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     auto FromPtrType = FromType->getAs<PointerType>();
2664     DestRecordType = Context.getAddrSpaceQualType(
2665         DestRecordType, FromPtrType
2666                             ? FromType->getPointeeType().getAddressSpace()
2667                             : FromType.getAddressSpace());
2668 
2669     if (FromPtrType) {
2670       DestType = Context.getPointerType(DestRecordType);
2671       FromRecordType = FromPtrType->getPointeeType();
2672       PointerConversions = true;
2673     } else {
2674       DestType = DestRecordType;
2675       FromRecordType = FromType;
2676     }
2677   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2678     if (Method->isStatic())
2679       return From;
2680 
2681     DestType = Method->getThisType();
2682     DestRecordType = DestType->getPointeeType();
2683 
2684     if (FromType->getAs<PointerType>()) {
2685       FromRecordType = FromType->getPointeeType();
2686       PointerConversions = true;
2687     } else {
2688       FromRecordType = FromType;
2689       DestType = DestRecordType;
2690     }
2691   } else {
2692     // No conversion necessary.
2693     return From;
2694   }
2695 
2696   if (DestType->isDependentType() || FromType->isDependentType())
2697     return From;
2698 
2699   // If the unqualified types are the same, no conversion is necessary.
2700   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2701     return From;
2702 
2703   SourceRange FromRange = From->getSourceRange();
2704   SourceLocation FromLoc = FromRange.getBegin();
2705 
2706   ExprValueKind VK = From->getValueKind();
2707 
2708   // C++ [class.member.lookup]p8:
2709   //   [...] Ambiguities can often be resolved by qualifying a name with its
2710   //   class name.
2711   //
2712   // If the member was a qualified name and the qualified referred to a
2713   // specific base subobject type, we'll cast to that intermediate type
2714   // first and then to the object in which the member is declared. That allows
2715   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2716   //
2717   //   class Base { public: int x; };
2718   //   class Derived1 : public Base { };
2719   //   class Derived2 : public Base { };
2720   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2721   //
2722   //   void VeryDerived::f() {
2723   //     x = 17; // error: ambiguous base subobjects
2724   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2725   //   }
2726   if (Qualifier && Qualifier->getAsType()) {
2727     QualType QType = QualType(Qualifier->getAsType(), 0);
2728     assert(QType->isRecordType() && "lookup done with non-record type");
2729 
2730     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2731 
2732     // In C++98, the qualifier type doesn't actually have to be a base
2733     // type of the object type, in which case we just ignore it.
2734     // Otherwise build the appropriate casts.
2735     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2736       CXXCastPath BasePath;
2737       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2738                                        FromLoc, FromRange, &BasePath))
2739         return ExprError();
2740 
2741       if (PointerConversions)
2742         QType = Context.getPointerType(QType);
2743       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2744                                VK, &BasePath).get();
2745 
2746       FromType = QType;
2747       FromRecordType = QRecordType;
2748 
2749       // If the qualifier type was the same as the destination type,
2750       // we're done.
2751       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2752         return From;
2753     }
2754   }
2755 
2756   bool IgnoreAccess = false;
2757 
2758   // If we actually found the member through a using declaration, cast
2759   // down to the using declaration's type.
2760   //
2761   // Pointer equality is fine here because only one declaration of a
2762   // class ever has member declarations.
2763   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2764     assert(isa<UsingShadowDecl>(FoundDecl));
2765     QualType URecordType = Context.getTypeDeclType(
2766                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2767 
2768     // We only need to do this if the naming-class to declaring-class
2769     // conversion is non-trivial.
2770     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2771       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2772       CXXCastPath BasePath;
2773       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2774                                        FromLoc, FromRange, &BasePath))
2775         return ExprError();
2776 
2777       QualType UType = URecordType;
2778       if (PointerConversions)
2779         UType = Context.getPointerType(UType);
2780       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2781                                VK, &BasePath).get();
2782       FromType = UType;
2783       FromRecordType = URecordType;
2784     }
2785 
2786     // We don't do access control for the conversion from the
2787     // declaring class to the true declaring class.
2788     IgnoreAccess = true;
2789   }
2790 
2791   CXXCastPath BasePath;
2792   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2793                                    FromLoc, FromRange, &BasePath,
2794                                    IgnoreAccess))
2795     return ExprError();
2796 
2797   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2798                            VK, &BasePath);
2799 }
2800 
2801 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2802                                       const LookupResult &R,
2803                                       bool HasTrailingLParen) {
2804   // Only when used directly as the postfix-expression of a call.
2805   if (!HasTrailingLParen)
2806     return false;
2807 
2808   // Never if a scope specifier was provided.
2809   if (SS.isSet())
2810     return false;
2811 
2812   // Only in C++ or ObjC++.
2813   if (!getLangOpts().CPlusPlus)
2814     return false;
2815 
2816   // Turn off ADL when we find certain kinds of declarations during
2817   // normal lookup:
2818   for (NamedDecl *D : R) {
2819     // C++0x [basic.lookup.argdep]p3:
2820     //     -- a declaration of a class member
2821     // Since using decls preserve this property, we check this on the
2822     // original decl.
2823     if (D->isCXXClassMember())
2824       return false;
2825 
2826     // C++0x [basic.lookup.argdep]p3:
2827     //     -- a block-scope function declaration that is not a
2828     //        using-declaration
2829     // NOTE: we also trigger this for function templates (in fact, we
2830     // don't check the decl type at all, since all other decl types
2831     // turn off ADL anyway).
2832     if (isa<UsingShadowDecl>(D))
2833       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2834     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2835       return false;
2836 
2837     // C++0x [basic.lookup.argdep]p3:
2838     //     -- a declaration that is neither a function or a function
2839     //        template
2840     // And also for builtin functions.
2841     if (isa<FunctionDecl>(D)) {
2842       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2843 
2844       // But also builtin functions.
2845       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2846         return false;
2847     } else if (!isa<FunctionTemplateDecl>(D))
2848       return false;
2849   }
2850 
2851   return true;
2852 }
2853 
2854 
2855 /// Diagnoses obvious problems with the use of the given declaration
2856 /// as an expression.  This is only actually called for lookups that
2857 /// were not overloaded, and it doesn't promise that the declaration
2858 /// will in fact be used.
2859 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2860   if (D->isInvalidDecl())
2861     return true;
2862 
2863   if (isa<TypedefNameDecl>(D)) {
2864     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2865     return true;
2866   }
2867 
2868   if (isa<ObjCInterfaceDecl>(D)) {
2869     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2870     return true;
2871   }
2872 
2873   if (isa<NamespaceDecl>(D)) {
2874     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2875     return true;
2876   }
2877 
2878   return false;
2879 }
2880 
2881 // Certain multiversion types should be treated as overloaded even when there is
2882 // only one result.
2883 static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
2884   assert(R.isSingleResult() && "Expected only a single result");
2885   const auto *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
2886   return FD &&
2887          (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion());
2888 }
2889 
2890 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2891                                           LookupResult &R, bool NeedsADL,
2892                                           bool AcceptInvalidDecl) {
2893   // If this is a single, fully-resolved result and we don't need ADL,
2894   // just build an ordinary singleton decl ref.
2895   if (!NeedsADL && R.isSingleResult() &&
2896       !R.getAsSingle<FunctionTemplateDecl>() &&
2897       !ShouldLookupResultBeMultiVersionOverload(R))
2898     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2899                                     R.getRepresentativeDecl(), nullptr,
2900                                     AcceptInvalidDecl);
2901 
2902   // We only need to check the declaration if there's exactly one
2903   // result, because in the overloaded case the results can only be
2904   // functions and function templates.
2905   if (R.isSingleResult() && !ShouldLookupResultBeMultiVersionOverload(R) &&
2906       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2907     return ExprError();
2908 
2909   // Otherwise, just build an unresolved lookup expression.  Suppress
2910   // any lookup-related diagnostics; we'll hash these out later, when
2911   // we've picked a target.
2912   R.suppressDiagnostics();
2913 
2914   UnresolvedLookupExpr *ULE
2915     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2916                                    SS.getWithLocInContext(Context),
2917                                    R.getLookupNameInfo(),
2918                                    NeedsADL, R.isOverloadedResult(),
2919                                    R.begin(), R.end());
2920 
2921   return ULE;
2922 }
2923 
2924 static void
2925 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2926                                    ValueDecl *var, DeclContext *DC);
2927 
2928 /// Complete semantic analysis for a reference to the given declaration.
2929 ExprResult Sema::BuildDeclarationNameExpr(
2930     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2931     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2932     bool AcceptInvalidDecl) {
2933   assert(D && "Cannot refer to a NULL declaration");
2934   assert(!isa<FunctionTemplateDecl>(D) &&
2935          "Cannot refer unambiguously to a function template");
2936 
2937   SourceLocation Loc = NameInfo.getLoc();
2938   if (CheckDeclInExpr(*this, Loc, D))
2939     return ExprError();
2940 
2941   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2942     // Specifically diagnose references to class templates that are missing
2943     // a template argument list.
2944     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2945     return ExprError();
2946   }
2947 
2948   // Make sure that we're referring to a value.
2949   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2950   if (!VD) {
2951     Diag(Loc, diag::err_ref_non_value)
2952       << D << SS.getRange();
2953     Diag(D->getLocation(), diag::note_declared_at);
2954     return ExprError();
2955   }
2956 
2957   // Check whether this declaration can be used. Note that we suppress
2958   // this check when we're going to perform argument-dependent lookup
2959   // on this function name, because this might not be the function
2960   // that overload resolution actually selects.
2961   if (DiagnoseUseOfDecl(VD, Loc))
2962     return ExprError();
2963 
2964   // Only create DeclRefExpr's for valid Decl's.
2965   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2966     return ExprError();
2967 
2968   // Handle members of anonymous structs and unions.  If we got here,
2969   // and the reference is to a class member indirect field, then this
2970   // must be the subject of a pointer-to-member expression.
2971   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2972     if (!indirectField->isCXXClassMember())
2973       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2974                                                       indirectField);
2975 
2976   {
2977     QualType type = VD->getType();
2978     if (type.isNull())
2979       return ExprError();
2980     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2981       // C++ [except.spec]p17:
2982       //   An exception-specification is considered to be needed when:
2983       //   - in an expression, the function is the unique lookup result or
2984       //     the selected member of a set of overloaded functions.
2985       ResolveExceptionSpec(Loc, FPT);
2986       type = VD->getType();
2987     }
2988     ExprValueKind valueKind = VK_RValue;
2989 
2990     switch (D->getKind()) {
2991     // Ignore all the non-ValueDecl kinds.
2992 #define ABSTRACT_DECL(kind)
2993 #define VALUE(type, base)
2994 #define DECL(type, base) \
2995     case Decl::type:
2996 #include "clang/AST/DeclNodes.inc"
2997       llvm_unreachable("invalid value decl kind");
2998 
2999     // These shouldn't make it here.
3000     case Decl::ObjCAtDefsField:
3001     case Decl::ObjCIvar:
3002       llvm_unreachable("forming non-member reference to ivar?");
3003 
3004     // Enum constants are always r-values and never references.
3005     // Unresolved using declarations are dependent.
3006     case Decl::EnumConstant:
3007     case Decl::UnresolvedUsingValue:
3008     case Decl::OMPDeclareReduction:
3009     case Decl::OMPDeclareMapper:
3010       valueKind = VK_RValue;
3011       break;
3012 
3013     // Fields and indirect fields that got here must be for
3014     // pointer-to-member expressions; we just call them l-values for
3015     // internal consistency, because this subexpression doesn't really
3016     // exist in the high-level semantics.
3017     case Decl::Field:
3018     case Decl::IndirectField:
3019       assert(getLangOpts().CPlusPlus &&
3020              "building reference to field in C?");
3021 
3022       // These can't have reference type in well-formed programs, but
3023       // for internal consistency we do this anyway.
3024       type = type.getNonReferenceType();
3025       valueKind = VK_LValue;
3026       break;
3027 
3028     // Non-type template parameters are either l-values or r-values
3029     // depending on the type.
3030     case Decl::NonTypeTemplateParm: {
3031       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
3032         type = reftype->getPointeeType();
3033         valueKind = VK_LValue; // even if the parameter is an r-value reference
3034         break;
3035       }
3036 
3037       // For non-references, we need to strip qualifiers just in case
3038       // the template parameter was declared as 'const int' or whatever.
3039       valueKind = VK_RValue;
3040       type = type.getUnqualifiedType();
3041       break;
3042     }
3043 
3044     case Decl::Var:
3045     case Decl::VarTemplateSpecialization:
3046     case Decl::VarTemplatePartialSpecialization:
3047     case Decl::Decomposition:
3048     case Decl::OMPCapturedExpr:
3049       // In C, "extern void blah;" is valid and is an r-value.
3050       if (!getLangOpts().CPlusPlus &&
3051           !type.hasQualifiers() &&
3052           type->isVoidType()) {
3053         valueKind = VK_RValue;
3054         break;
3055       }
3056       LLVM_FALLTHROUGH;
3057 
3058     case Decl::ImplicitParam:
3059     case Decl::ParmVar: {
3060       // These are always l-values.
3061       valueKind = VK_LValue;
3062       type = type.getNonReferenceType();
3063 
3064       // FIXME: Does the addition of const really only apply in
3065       // potentially-evaluated contexts? Since the variable isn't actually
3066       // captured in an unevaluated context, it seems that the answer is no.
3067       if (!isUnevaluatedContext()) {
3068         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
3069         if (!CapturedType.isNull())
3070           type = CapturedType;
3071       }
3072 
3073       break;
3074     }
3075 
3076     case Decl::Binding: {
3077       // These are always lvalues.
3078       valueKind = VK_LValue;
3079       type = type.getNonReferenceType();
3080       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
3081       // decides how that's supposed to work.
3082       auto *BD = cast<BindingDecl>(VD);
3083       if (BD->getDeclContext()->isFunctionOrMethod() &&
3084           BD->getDeclContext() != CurContext)
3085         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
3086       break;
3087     }
3088 
3089     case Decl::Function: {
3090       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
3091         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
3092           type = Context.BuiltinFnTy;
3093           valueKind = VK_RValue;
3094           break;
3095         }
3096       }
3097 
3098       const FunctionType *fty = type->castAs<FunctionType>();
3099 
3100       // If we're referring to a function with an __unknown_anytype
3101       // result type, make the entire expression __unknown_anytype.
3102       if (fty->getReturnType() == Context.UnknownAnyTy) {
3103         type = Context.UnknownAnyTy;
3104         valueKind = VK_RValue;
3105         break;
3106       }
3107 
3108       // Functions are l-values in C++.
3109       if (getLangOpts().CPlusPlus) {
3110         valueKind = VK_LValue;
3111         break;
3112       }
3113 
3114       // C99 DR 316 says that, if a function type comes from a
3115       // function definition (without a prototype), that type is only
3116       // used for checking compatibility. Therefore, when referencing
3117       // the function, we pretend that we don't have the full function
3118       // type.
3119       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3120           isa<FunctionProtoType>(fty))
3121         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3122                                               fty->getExtInfo());
3123 
3124       // Functions are r-values in C.
3125       valueKind = VK_RValue;
3126       break;
3127     }
3128 
3129     case Decl::CXXDeductionGuide:
3130       llvm_unreachable("building reference to deduction guide");
3131 
3132     case Decl::MSProperty:
3133       valueKind = VK_LValue;
3134       break;
3135 
3136     case Decl::CXXMethod:
3137       // If we're referring to a method with an __unknown_anytype
3138       // result type, make the entire expression __unknown_anytype.
3139       // This should only be possible with a type written directly.
3140       if (const FunctionProtoType *proto
3141             = dyn_cast<FunctionProtoType>(VD->getType()))
3142         if (proto->getReturnType() == Context.UnknownAnyTy) {
3143           type = Context.UnknownAnyTy;
3144           valueKind = VK_RValue;
3145           break;
3146         }
3147 
3148       // C++ methods are l-values if static, r-values if non-static.
3149       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3150         valueKind = VK_LValue;
3151         break;
3152       }
3153       LLVM_FALLTHROUGH;
3154 
3155     case Decl::CXXConversion:
3156     case Decl::CXXDestructor:
3157     case Decl::CXXConstructor:
3158       valueKind = VK_RValue;
3159       break;
3160     }
3161 
3162     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3163                             TemplateArgs);
3164   }
3165 }
3166 
3167 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3168                                     SmallString<32> &Target) {
3169   Target.resize(CharByteWidth * (Source.size() + 1));
3170   char *ResultPtr = &Target[0];
3171   const llvm::UTF8 *ErrorPtr;
3172   bool success =
3173       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3174   (void)success;
3175   assert(success);
3176   Target.resize(ResultPtr - &Target[0]);
3177 }
3178 
3179 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3180                                      PredefinedExpr::IdentKind IK) {
3181   // Pick the current block, lambda, captured statement or function.
3182   Decl *currentDecl = nullptr;
3183   if (const BlockScopeInfo *BSI = getCurBlock())
3184     currentDecl = BSI->TheDecl;
3185   else if (const LambdaScopeInfo *LSI = getCurLambda())
3186     currentDecl = LSI->CallOperator;
3187   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3188     currentDecl = CSI->TheCapturedDecl;
3189   else
3190     currentDecl = getCurFunctionOrMethodDecl();
3191 
3192   if (!currentDecl) {
3193     Diag(Loc, diag::ext_predef_outside_function);
3194     currentDecl = Context.getTranslationUnitDecl();
3195   }
3196 
3197   QualType ResTy;
3198   StringLiteral *SL = nullptr;
3199   if (cast<DeclContext>(currentDecl)->isDependentContext())
3200     ResTy = Context.DependentTy;
3201   else {
3202     // Pre-defined identifiers are of type char[x], where x is the length of
3203     // the string.
3204     auto Str = PredefinedExpr::ComputeName(IK, currentDecl);
3205     unsigned Length = Str.length();
3206 
3207     llvm::APInt LengthI(32, Length + 1);
3208     if (IK == PredefinedExpr::LFunction || IK == PredefinedExpr::LFuncSig) {
3209       ResTy =
3210           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3211       SmallString<32> RawChars;
3212       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3213                               Str, RawChars);
3214       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3215                                            /*IndexTypeQuals*/ 0);
3216       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3217                                  /*Pascal*/ false, ResTy, Loc);
3218     } else {
3219       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3220       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3221                                            /*IndexTypeQuals*/ 0);
3222       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3223                                  /*Pascal*/ false, ResTy, Loc);
3224     }
3225   }
3226 
3227   return PredefinedExpr::Create(Context, Loc, ResTy, IK, SL);
3228 }
3229 
3230 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3231   PredefinedExpr::IdentKind IK;
3232 
3233   switch (Kind) {
3234   default: llvm_unreachable("Unknown simple primary expr!");
3235   case tok::kw___func__: IK = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3236   case tok::kw___FUNCTION__: IK = PredefinedExpr::Function; break;
3237   case tok::kw___FUNCDNAME__: IK = PredefinedExpr::FuncDName; break; // [MS]
3238   case tok::kw___FUNCSIG__: IK = PredefinedExpr::FuncSig; break; // [MS]
3239   case tok::kw_L__FUNCTION__: IK = PredefinedExpr::LFunction; break; // [MS]
3240   case tok::kw_L__FUNCSIG__: IK = PredefinedExpr::LFuncSig; break; // [MS]
3241   case tok::kw___PRETTY_FUNCTION__: IK = PredefinedExpr::PrettyFunction; break;
3242   }
3243 
3244   return BuildPredefinedExpr(Loc, IK);
3245 }
3246 
3247 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3248   SmallString<16> CharBuffer;
3249   bool Invalid = false;
3250   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3251   if (Invalid)
3252     return ExprError();
3253 
3254   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3255                             PP, Tok.getKind());
3256   if (Literal.hadError())
3257     return ExprError();
3258 
3259   QualType Ty;
3260   if (Literal.isWide())
3261     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3262   else if (Literal.isUTF8() && getLangOpts().Char8)
3263     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3264   else if (Literal.isUTF16())
3265     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3266   else if (Literal.isUTF32())
3267     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3268   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3269     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3270   else
3271     Ty = Context.CharTy;  // 'x' -> char in C++
3272 
3273   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3274   if (Literal.isWide())
3275     Kind = CharacterLiteral::Wide;
3276   else if (Literal.isUTF16())
3277     Kind = CharacterLiteral::UTF16;
3278   else if (Literal.isUTF32())
3279     Kind = CharacterLiteral::UTF32;
3280   else if (Literal.isUTF8())
3281     Kind = CharacterLiteral::UTF8;
3282 
3283   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3284                                              Tok.getLocation());
3285 
3286   if (Literal.getUDSuffix().empty())
3287     return Lit;
3288 
3289   // We're building a user-defined literal.
3290   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3291   SourceLocation UDSuffixLoc =
3292     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3293 
3294   // Make sure we're allowed user-defined literals here.
3295   if (!UDLScope)
3296     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3297 
3298   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3299   //   operator "" X (ch)
3300   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3301                                         Lit, Tok.getLocation());
3302 }
3303 
3304 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3305   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3306   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3307                                 Context.IntTy, Loc);
3308 }
3309 
3310 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3311                                   QualType Ty, SourceLocation Loc) {
3312   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3313 
3314   using llvm::APFloat;
3315   APFloat Val(Format);
3316 
3317   APFloat::opStatus result = Literal.GetFloatValue(Val);
3318 
3319   // Overflow is always an error, but underflow is only an error if
3320   // we underflowed to zero (APFloat reports denormals as underflow).
3321   if ((result & APFloat::opOverflow) ||
3322       ((result & APFloat::opUnderflow) && Val.isZero())) {
3323     unsigned diagnostic;
3324     SmallString<20> buffer;
3325     if (result & APFloat::opOverflow) {
3326       diagnostic = diag::warn_float_overflow;
3327       APFloat::getLargest(Format).toString(buffer);
3328     } else {
3329       diagnostic = diag::warn_float_underflow;
3330       APFloat::getSmallest(Format).toString(buffer);
3331     }
3332 
3333     S.Diag(Loc, diagnostic)
3334       << Ty
3335       << StringRef(buffer.data(), buffer.size());
3336   }
3337 
3338   bool isExact = (result == APFloat::opOK);
3339   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3340 }
3341 
3342 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3343   assert(E && "Invalid expression");
3344 
3345   if (E->isValueDependent())
3346     return false;
3347 
3348   QualType QT = E->getType();
3349   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3350     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3351     return true;
3352   }
3353 
3354   llvm::APSInt ValueAPS;
3355   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3356 
3357   if (R.isInvalid())
3358     return true;
3359 
3360   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3361   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3362     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3363         << ValueAPS.toString(10) << ValueIsPositive;
3364     return true;
3365   }
3366 
3367   return false;
3368 }
3369 
3370 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3371   // Fast path for a single digit (which is quite common).  A single digit
3372   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3373   if (Tok.getLength() == 1) {
3374     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3375     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3376   }
3377 
3378   SmallString<128> SpellingBuffer;
3379   // NumericLiteralParser wants to overread by one character.  Add padding to
3380   // the buffer in case the token is copied to the buffer.  If getSpelling()
3381   // returns a StringRef to the memory buffer, it should have a null char at
3382   // the EOF, so it is also safe.
3383   SpellingBuffer.resize(Tok.getLength() + 1);
3384 
3385   // Get the spelling of the token, which eliminates trigraphs, etc.
3386   bool Invalid = false;
3387   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3388   if (Invalid)
3389     return ExprError();
3390 
3391   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3392   if (Literal.hadError)
3393     return ExprError();
3394 
3395   if (Literal.hasUDSuffix()) {
3396     // We're building a user-defined literal.
3397     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3398     SourceLocation UDSuffixLoc =
3399       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3400 
3401     // Make sure we're allowed user-defined literals here.
3402     if (!UDLScope)
3403       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3404 
3405     QualType CookedTy;
3406     if (Literal.isFloatingLiteral()) {
3407       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3408       // long double, the literal is treated as a call of the form
3409       //   operator "" X (f L)
3410       CookedTy = Context.LongDoubleTy;
3411     } else {
3412       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3413       // unsigned long long, the literal is treated as a call of the form
3414       //   operator "" X (n ULL)
3415       CookedTy = Context.UnsignedLongLongTy;
3416     }
3417 
3418     DeclarationName OpName =
3419       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3420     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3421     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3422 
3423     SourceLocation TokLoc = Tok.getLocation();
3424 
3425     // Perform literal operator lookup to determine if we're building a raw
3426     // literal or a cooked one.
3427     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3428     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3429                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3430                                   /*AllowStringTemplate*/ false,
3431                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3432     case LOLR_ErrorNoDiagnostic:
3433       // Lookup failure for imaginary constants isn't fatal, there's still the
3434       // GNU extension producing _Complex types.
3435       break;
3436     case LOLR_Error:
3437       return ExprError();
3438     case LOLR_Cooked: {
3439       Expr *Lit;
3440       if (Literal.isFloatingLiteral()) {
3441         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3442       } else {
3443         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3444         if (Literal.GetIntegerValue(ResultVal))
3445           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3446               << /* Unsigned */ 1;
3447         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3448                                      Tok.getLocation());
3449       }
3450       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3451     }
3452 
3453     case LOLR_Raw: {
3454       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3455       // literal is treated as a call of the form
3456       //   operator "" X ("n")
3457       unsigned Length = Literal.getUDSuffixOffset();
3458       QualType StrTy = Context.getConstantArrayType(
3459           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3460           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3461       Expr *Lit = StringLiteral::Create(
3462           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3463           /*Pascal*/false, StrTy, &TokLoc, 1);
3464       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3465     }
3466 
3467     case LOLR_Template: {
3468       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3469       // template), L is treated as a call fo the form
3470       //   operator "" X <'c1', 'c2', ... 'ck'>()
3471       // where n is the source character sequence c1 c2 ... ck.
3472       TemplateArgumentListInfo ExplicitArgs;
3473       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3474       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3475       llvm::APSInt Value(CharBits, CharIsUnsigned);
3476       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3477         Value = TokSpelling[I];
3478         TemplateArgument Arg(Context, Value, Context.CharTy);
3479         TemplateArgumentLocInfo ArgInfo;
3480         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3481       }
3482       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3483                                       &ExplicitArgs);
3484     }
3485     case LOLR_StringTemplate:
3486       llvm_unreachable("unexpected literal operator lookup result");
3487     }
3488   }
3489 
3490   Expr *Res;
3491 
3492   if (Literal.isFixedPointLiteral()) {
3493     QualType Ty;
3494 
3495     if (Literal.isAccum) {
3496       if (Literal.isHalf) {
3497         Ty = Context.ShortAccumTy;
3498       } else if (Literal.isLong) {
3499         Ty = Context.LongAccumTy;
3500       } else {
3501         Ty = Context.AccumTy;
3502       }
3503     } else if (Literal.isFract) {
3504       if (Literal.isHalf) {
3505         Ty = Context.ShortFractTy;
3506       } else if (Literal.isLong) {
3507         Ty = Context.LongFractTy;
3508       } else {
3509         Ty = Context.FractTy;
3510       }
3511     }
3512 
3513     if (Literal.isUnsigned) Ty = Context.getCorrespondingUnsignedType(Ty);
3514 
3515     bool isSigned = !Literal.isUnsigned;
3516     unsigned scale = Context.getFixedPointScale(Ty);
3517     unsigned bit_width = Context.getTypeInfo(Ty).Width;
3518 
3519     llvm::APInt Val(bit_width, 0, isSigned);
3520     bool Overflowed = Literal.GetFixedPointValue(Val, scale);
3521     bool ValIsZero = Val.isNullValue() && !Overflowed;
3522 
3523     auto MaxVal = Context.getFixedPointMax(Ty).getValue();
3524     if (Literal.isFract && Val == MaxVal + 1 && !ValIsZero)
3525       // Clause 6.4.4 - The value of a constant shall be in the range of
3526       // representable values for its type, with exception for constants of a
3527       // fract type with a value of exactly 1; such a constant shall denote
3528       // the maximal value for the type.
3529       --Val;
3530     else if (Val.ugt(MaxVal) || Overflowed)
3531       Diag(Tok.getLocation(), diag::err_too_large_for_fixed_point);
3532 
3533     Res = FixedPointLiteral::CreateFromRawInt(Context, Val, Ty,
3534                                               Tok.getLocation(), scale);
3535   } else if (Literal.isFloatingLiteral()) {
3536     QualType Ty;
3537     if (Literal.isHalf){
3538       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3539         Ty = Context.HalfTy;
3540       else {
3541         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3542         return ExprError();
3543       }
3544     } else if (Literal.isFloat)
3545       Ty = Context.FloatTy;
3546     else if (Literal.isLong)
3547       Ty = Context.LongDoubleTy;
3548     else if (Literal.isFloat16)
3549       Ty = Context.Float16Ty;
3550     else if (Literal.isFloat128)
3551       Ty = Context.Float128Ty;
3552     else
3553       Ty = Context.DoubleTy;
3554 
3555     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3556 
3557     if (Ty == Context.DoubleTy) {
3558       if (getLangOpts().SinglePrecisionConstants) {
3559         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3560         if (BTy->getKind() != BuiltinType::Float) {
3561           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3562         }
3563       } else if (getLangOpts().OpenCL &&
3564                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3565         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3566         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3567         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3568       }
3569     }
3570   } else if (!Literal.isIntegerLiteral()) {
3571     return ExprError();
3572   } else {
3573     QualType Ty;
3574 
3575     // 'long long' is a C99 or C++11 feature.
3576     if (!getLangOpts().C99 && Literal.isLongLong) {
3577       if (getLangOpts().CPlusPlus)
3578         Diag(Tok.getLocation(),
3579              getLangOpts().CPlusPlus11 ?
3580              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3581       else
3582         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3583     }
3584 
3585     // Get the value in the widest-possible width.
3586     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3587     llvm::APInt ResultVal(MaxWidth, 0);
3588 
3589     if (Literal.GetIntegerValue(ResultVal)) {
3590       // If this value didn't fit into uintmax_t, error and force to ull.
3591       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3592           << /* Unsigned */ 1;
3593       Ty = Context.UnsignedLongLongTy;
3594       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3595              "long long is not intmax_t?");
3596     } else {
3597       // If this value fits into a ULL, try to figure out what else it fits into
3598       // according to the rules of C99 6.4.4.1p5.
3599 
3600       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3601       // be an unsigned int.
3602       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3603 
3604       // Check from smallest to largest, picking the smallest type we can.
3605       unsigned Width = 0;
3606 
3607       // Microsoft specific integer suffixes are explicitly sized.
3608       if (Literal.MicrosoftInteger) {
3609         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3610           Width = 8;
3611           Ty = Context.CharTy;
3612         } else {
3613           Width = Literal.MicrosoftInteger;
3614           Ty = Context.getIntTypeForBitwidth(Width,
3615                                              /*Signed=*/!Literal.isUnsigned);
3616         }
3617       }
3618 
3619       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3620         // Are int/unsigned possibilities?
3621         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3622 
3623         // Does it fit in a unsigned int?
3624         if (ResultVal.isIntN(IntSize)) {
3625           // Does it fit in a signed int?
3626           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3627             Ty = Context.IntTy;
3628           else if (AllowUnsigned)
3629             Ty = Context.UnsignedIntTy;
3630           Width = IntSize;
3631         }
3632       }
3633 
3634       // Are long/unsigned long possibilities?
3635       if (Ty.isNull() && !Literal.isLongLong) {
3636         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3637 
3638         // Does it fit in a unsigned long?
3639         if (ResultVal.isIntN(LongSize)) {
3640           // Does it fit in a signed long?
3641           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3642             Ty = Context.LongTy;
3643           else if (AllowUnsigned)
3644             Ty = Context.UnsignedLongTy;
3645           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3646           // is compatible.
3647           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3648             const unsigned LongLongSize =
3649                 Context.getTargetInfo().getLongLongWidth();
3650             Diag(Tok.getLocation(),
3651                  getLangOpts().CPlusPlus
3652                      ? Literal.isLong
3653                            ? diag::warn_old_implicitly_unsigned_long_cxx
3654                            : /*C++98 UB*/ diag::
3655                                  ext_old_implicitly_unsigned_long_cxx
3656                      : diag::warn_old_implicitly_unsigned_long)
3657                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3658                                             : /*will be ill-formed*/ 1);
3659             Ty = Context.UnsignedLongTy;
3660           }
3661           Width = LongSize;
3662         }
3663       }
3664 
3665       // Check long long if needed.
3666       if (Ty.isNull()) {
3667         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3668 
3669         // Does it fit in a unsigned long long?
3670         if (ResultVal.isIntN(LongLongSize)) {
3671           // Does it fit in a signed long long?
3672           // To be compatible with MSVC, hex integer literals ending with the
3673           // LL or i64 suffix are always signed in Microsoft mode.
3674           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3675               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3676             Ty = Context.LongLongTy;
3677           else if (AllowUnsigned)
3678             Ty = Context.UnsignedLongLongTy;
3679           Width = LongLongSize;
3680         }
3681       }
3682 
3683       // If we still couldn't decide a type, we probably have something that
3684       // does not fit in a signed long long, but has no U suffix.
3685       if (Ty.isNull()) {
3686         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3687         Ty = Context.UnsignedLongLongTy;
3688         Width = Context.getTargetInfo().getLongLongWidth();
3689       }
3690 
3691       if (ResultVal.getBitWidth() != Width)
3692         ResultVal = ResultVal.trunc(Width);
3693     }
3694     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3695   }
3696 
3697   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3698   if (Literal.isImaginary) {
3699     Res = new (Context) ImaginaryLiteral(Res,
3700                                         Context.getComplexType(Res->getType()));
3701 
3702     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3703   }
3704   return Res;
3705 }
3706 
3707 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3708   assert(E && "ActOnParenExpr() missing expr");
3709   return new (Context) ParenExpr(L, R, E);
3710 }
3711 
3712 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3713                                          SourceLocation Loc,
3714                                          SourceRange ArgRange) {
3715   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3716   // scalar or vector data type argument..."
3717   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3718   // type (C99 6.2.5p18) or void.
3719   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3720     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3721       << T << ArgRange;
3722     return true;
3723   }
3724 
3725   assert((T->isVoidType() || !T->isIncompleteType()) &&
3726          "Scalar types should always be complete");
3727   return false;
3728 }
3729 
3730 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3731                                            SourceLocation Loc,
3732                                            SourceRange ArgRange,
3733                                            UnaryExprOrTypeTrait TraitKind) {
3734   // Invalid types must be hard errors for SFINAE in C++.
3735   if (S.LangOpts.CPlusPlus)
3736     return true;
3737 
3738   // C99 6.5.3.4p1:
3739   if (T->isFunctionType() &&
3740       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf ||
3741        TraitKind == UETT_PreferredAlignOf)) {
3742     // sizeof(function)/alignof(function) is allowed as an extension.
3743     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3744       << TraitKind << ArgRange;
3745     return false;
3746   }
3747 
3748   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3749   // this is an error (OpenCL v1.1 s6.3.k)
3750   if (T->isVoidType()) {
3751     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3752                                         : diag::ext_sizeof_alignof_void_type;
3753     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3754     return false;
3755   }
3756 
3757   return true;
3758 }
3759 
3760 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3761                                              SourceLocation Loc,
3762                                              SourceRange ArgRange,
3763                                              UnaryExprOrTypeTrait TraitKind) {
3764   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3765   // runtime doesn't allow it.
3766   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3767     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3768       << T << (TraitKind == UETT_SizeOf)
3769       << ArgRange;
3770     return true;
3771   }
3772 
3773   return false;
3774 }
3775 
3776 /// Check whether E is a pointer from a decayed array type (the decayed
3777 /// pointer type is equal to T) and emit a warning if it is.
3778 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3779                                      Expr *E) {
3780   // Don't warn if the operation changed the type.
3781   if (T != E->getType())
3782     return;
3783 
3784   // Now look for array decays.
3785   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3786   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3787     return;
3788 
3789   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3790                                              << ICE->getType()
3791                                              << ICE->getSubExpr()->getType();
3792 }
3793 
3794 /// Check the constraints on expression operands to unary type expression
3795 /// and type traits.
3796 ///
3797 /// Completes any types necessary and validates the constraints on the operand
3798 /// expression. The logic mostly mirrors the type-based overload, but may modify
3799 /// the expression as it completes the type for that expression through template
3800 /// instantiation, etc.
3801 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3802                                             UnaryExprOrTypeTrait ExprKind) {
3803   QualType ExprTy = E->getType();
3804   assert(!ExprTy->isReferenceType());
3805 
3806   if (ExprKind == UETT_VecStep)
3807     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3808                                         E->getSourceRange());
3809 
3810   // Whitelist some types as extensions
3811   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3812                                       E->getSourceRange(), ExprKind))
3813     return false;
3814 
3815   // 'alignof' applied to an expression only requires the base element type of
3816   // the expression to be complete. 'sizeof' requires the expression's type to
3817   // be complete (and will attempt to complete it if it's an array of unknown
3818   // bound).
3819   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
3820     if (RequireCompleteType(E->getExprLoc(),
3821                             Context.getBaseElementType(E->getType()),
3822                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3823                             E->getSourceRange()))
3824       return true;
3825   } else {
3826     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3827                                 ExprKind, E->getSourceRange()))
3828       return true;
3829   }
3830 
3831   // Completing the expression's type may have changed it.
3832   ExprTy = E->getType();
3833   assert(!ExprTy->isReferenceType());
3834 
3835   if (ExprTy->isFunctionType()) {
3836     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3837       << ExprKind << E->getSourceRange();
3838     return true;
3839   }
3840 
3841   // The operand for sizeof and alignof is in an unevaluated expression context,
3842   // so side effects could result in unintended consequences.
3843   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf ||
3844        ExprKind == UETT_PreferredAlignOf) &&
3845       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3846     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3847 
3848   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3849                                        E->getSourceRange(), ExprKind))
3850     return true;
3851 
3852   if (ExprKind == UETT_SizeOf) {
3853     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3854       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3855         QualType OType = PVD->getOriginalType();
3856         QualType Type = PVD->getType();
3857         if (Type->isPointerType() && OType->isArrayType()) {
3858           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3859             << Type << OType;
3860           Diag(PVD->getLocation(), diag::note_declared_at);
3861         }
3862       }
3863     }
3864 
3865     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3866     // decays into a pointer and returns an unintended result. This is most
3867     // likely a typo for "sizeof(array) op x".
3868     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3869       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3870                                BO->getLHS());
3871       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3872                                BO->getRHS());
3873     }
3874   }
3875 
3876   return false;
3877 }
3878 
3879 /// Check the constraints on operands to unary expression and type
3880 /// traits.
3881 ///
3882 /// This will complete any types necessary, and validate the various constraints
3883 /// on those operands.
3884 ///
3885 /// The UsualUnaryConversions() function is *not* called by this routine.
3886 /// C99 6.3.2.1p[2-4] all state:
3887 ///   Except when it is the operand of the sizeof operator ...
3888 ///
3889 /// C++ [expr.sizeof]p4
3890 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3891 ///   standard conversions are not applied to the operand of sizeof.
3892 ///
3893 /// This policy is followed for all of the unary trait expressions.
3894 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3895                                             SourceLocation OpLoc,
3896                                             SourceRange ExprRange,
3897                                             UnaryExprOrTypeTrait ExprKind) {
3898   if (ExprType->isDependentType())
3899     return false;
3900 
3901   // C++ [expr.sizeof]p2:
3902   //     When applied to a reference or a reference type, the result
3903   //     is the size of the referenced type.
3904   // C++11 [expr.alignof]p3:
3905   //     When alignof is applied to a reference type, the result
3906   //     shall be the alignment of the referenced type.
3907   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3908     ExprType = Ref->getPointeeType();
3909 
3910   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3911   //   When alignof or _Alignof is applied to an array type, the result
3912   //   is the alignment of the element type.
3913   if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf ||
3914       ExprKind == UETT_OpenMPRequiredSimdAlign)
3915     ExprType = Context.getBaseElementType(ExprType);
3916 
3917   if (ExprKind == UETT_VecStep)
3918     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3919 
3920   // Whitelist some types as extensions
3921   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3922                                       ExprKind))
3923     return false;
3924 
3925   if (RequireCompleteType(OpLoc, ExprType,
3926                           diag::err_sizeof_alignof_incomplete_type,
3927                           ExprKind, ExprRange))
3928     return true;
3929 
3930   if (ExprType->isFunctionType()) {
3931     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3932       << ExprKind << ExprRange;
3933     return true;
3934   }
3935 
3936   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3937                                        ExprKind))
3938     return true;
3939 
3940   return false;
3941 }
3942 
3943 static bool CheckAlignOfExpr(Sema &S, Expr *E, UnaryExprOrTypeTrait ExprKind) {
3944   E = E->IgnoreParens();
3945 
3946   // Cannot know anything else if the expression is dependent.
3947   if (E->isTypeDependent())
3948     return false;
3949 
3950   if (E->getObjectKind() == OK_BitField) {
3951     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3952        << 1 << E->getSourceRange();
3953     return true;
3954   }
3955 
3956   ValueDecl *D = nullptr;
3957   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3958     D = DRE->getDecl();
3959   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3960     D = ME->getMemberDecl();
3961   }
3962 
3963   // If it's a field, require the containing struct to have a
3964   // complete definition so that we can compute the layout.
3965   //
3966   // This can happen in C++11 onwards, either by naming the member
3967   // in a way that is not transformed into a member access expression
3968   // (in an unevaluated operand, for instance), or by naming the member
3969   // in a trailing-return-type.
3970   //
3971   // For the record, since __alignof__ on expressions is a GCC
3972   // extension, GCC seems to permit this but always gives the
3973   // nonsensical answer 0.
3974   //
3975   // We don't really need the layout here --- we could instead just
3976   // directly check for all the appropriate alignment-lowing
3977   // attributes --- but that would require duplicating a lot of
3978   // logic that just isn't worth duplicating for such a marginal
3979   // use-case.
3980   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3981     // Fast path this check, since we at least know the record has a
3982     // definition if we can find a member of it.
3983     if (!FD->getParent()->isCompleteDefinition()) {
3984       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3985         << E->getSourceRange();
3986       return true;
3987     }
3988 
3989     // Otherwise, if it's a field, and the field doesn't have
3990     // reference type, then it must have a complete type (or be a
3991     // flexible array member, which we explicitly want to
3992     // white-list anyway), which makes the following checks trivial.
3993     if (!FD->getType()->isReferenceType())
3994       return false;
3995   }
3996 
3997   return S.CheckUnaryExprOrTypeTraitOperand(E, ExprKind);
3998 }
3999 
4000 bool Sema::CheckVecStepExpr(Expr *E) {
4001   E = E->IgnoreParens();
4002 
4003   // Cannot know anything else if the expression is dependent.
4004   if (E->isTypeDependent())
4005     return false;
4006 
4007   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
4008 }
4009 
4010 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
4011                                         CapturingScopeInfo *CSI) {
4012   assert(T->isVariablyModifiedType());
4013   assert(CSI != nullptr);
4014 
4015   // We're going to walk down into the type and look for VLA expressions.
4016   do {
4017     const Type *Ty = T.getTypePtr();
4018     switch (Ty->getTypeClass()) {
4019 #define TYPE(Class, Base)
4020 #define ABSTRACT_TYPE(Class, Base)
4021 #define NON_CANONICAL_TYPE(Class, Base)
4022 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
4023 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
4024 #include "clang/AST/TypeNodes.def"
4025       T = QualType();
4026       break;
4027     // These types are never variably-modified.
4028     case Type::Builtin:
4029     case Type::Complex:
4030     case Type::Vector:
4031     case Type::ExtVector:
4032     case Type::Record:
4033     case Type::Enum:
4034     case Type::Elaborated:
4035     case Type::TemplateSpecialization:
4036     case Type::ObjCObject:
4037     case Type::ObjCInterface:
4038     case Type::ObjCObjectPointer:
4039     case Type::ObjCTypeParam:
4040     case Type::Pipe:
4041       llvm_unreachable("type class is never variably-modified!");
4042     case Type::Adjusted:
4043       T = cast<AdjustedType>(Ty)->getOriginalType();
4044       break;
4045     case Type::Decayed:
4046       T = cast<DecayedType>(Ty)->getPointeeType();
4047       break;
4048     case Type::Pointer:
4049       T = cast<PointerType>(Ty)->getPointeeType();
4050       break;
4051     case Type::BlockPointer:
4052       T = cast<BlockPointerType>(Ty)->getPointeeType();
4053       break;
4054     case Type::LValueReference:
4055     case Type::RValueReference:
4056       T = cast<ReferenceType>(Ty)->getPointeeType();
4057       break;
4058     case Type::MemberPointer:
4059       T = cast<MemberPointerType>(Ty)->getPointeeType();
4060       break;
4061     case Type::ConstantArray:
4062     case Type::IncompleteArray:
4063       // Losing element qualification here is fine.
4064       T = cast<ArrayType>(Ty)->getElementType();
4065       break;
4066     case Type::VariableArray: {
4067       // Losing element qualification here is fine.
4068       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
4069 
4070       // Unknown size indication requires no size computation.
4071       // Otherwise, evaluate and record it.
4072       if (auto Size = VAT->getSizeExpr()) {
4073         if (!CSI->isVLATypeCaptured(VAT)) {
4074           RecordDecl *CapRecord = nullptr;
4075           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
4076             CapRecord = LSI->Lambda;
4077           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
4078             CapRecord = CRSI->TheRecordDecl;
4079           }
4080           if (CapRecord) {
4081             auto ExprLoc = Size->getExprLoc();
4082             auto SizeType = Context.getSizeType();
4083             // Build the non-static data member.
4084             auto Field =
4085                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
4086                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
4087                                   /*BW*/ nullptr, /*Mutable*/ false,
4088                                   /*InitStyle*/ ICIS_NoInit);
4089             Field->setImplicit(true);
4090             Field->setAccess(AS_private);
4091             Field->setCapturedVLAType(VAT);
4092             CapRecord->addDecl(Field);
4093 
4094             CSI->addVLATypeCapture(ExprLoc, SizeType);
4095           }
4096         }
4097       }
4098       T = VAT->getElementType();
4099       break;
4100     }
4101     case Type::FunctionProto:
4102     case Type::FunctionNoProto:
4103       T = cast<FunctionType>(Ty)->getReturnType();
4104       break;
4105     case Type::Paren:
4106     case Type::TypeOf:
4107     case Type::UnaryTransform:
4108     case Type::Attributed:
4109     case Type::SubstTemplateTypeParm:
4110     case Type::PackExpansion:
4111       // Keep walking after single level desugaring.
4112       T = T.getSingleStepDesugaredType(Context);
4113       break;
4114     case Type::Typedef:
4115       T = cast<TypedefType>(Ty)->desugar();
4116       break;
4117     case Type::Decltype:
4118       T = cast<DecltypeType>(Ty)->desugar();
4119       break;
4120     case Type::Auto:
4121     case Type::DeducedTemplateSpecialization:
4122       T = cast<DeducedType>(Ty)->getDeducedType();
4123       break;
4124     case Type::TypeOfExpr:
4125       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
4126       break;
4127     case Type::Atomic:
4128       T = cast<AtomicType>(Ty)->getValueType();
4129       break;
4130     }
4131   } while (!T.isNull() && T->isVariablyModifiedType());
4132 }
4133 
4134 /// Build a sizeof or alignof expression given a type operand.
4135 ExprResult
4136 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
4137                                      SourceLocation OpLoc,
4138                                      UnaryExprOrTypeTrait ExprKind,
4139                                      SourceRange R) {
4140   if (!TInfo)
4141     return ExprError();
4142 
4143   QualType T = TInfo->getType();
4144 
4145   if (!T->isDependentType() &&
4146       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
4147     return ExprError();
4148 
4149   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
4150     if (auto *TT = T->getAs<TypedefType>()) {
4151       for (auto I = FunctionScopes.rbegin(),
4152                 E = std::prev(FunctionScopes.rend());
4153            I != E; ++I) {
4154         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
4155         if (CSI == nullptr)
4156           break;
4157         DeclContext *DC = nullptr;
4158         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
4159           DC = LSI->CallOperator;
4160         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
4161           DC = CRSI->TheCapturedDecl;
4162         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4163           DC = BSI->TheDecl;
4164         if (DC) {
4165           if (DC->containsDecl(TT->getDecl()))
4166             break;
4167           captureVariablyModifiedType(Context, T, CSI);
4168         }
4169       }
4170     }
4171   }
4172 
4173   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4174   return new (Context) UnaryExprOrTypeTraitExpr(
4175       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4176 }
4177 
4178 /// Build a sizeof or alignof expression given an expression
4179 /// operand.
4180 ExprResult
4181 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4182                                      UnaryExprOrTypeTrait ExprKind) {
4183   ExprResult PE = CheckPlaceholderExpr(E);
4184   if (PE.isInvalid())
4185     return ExprError();
4186 
4187   E = PE.get();
4188 
4189   // Verify that the operand is valid.
4190   bool isInvalid = false;
4191   if (E->isTypeDependent()) {
4192     // Delay type-checking for type-dependent expressions.
4193   } else if (ExprKind == UETT_AlignOf || ExprKind == UETT_PreferredAlignOf) {
4194     isInvalid = CheckAlignOfExpr(*this, E, ExprKind);
4195   } else if (ExprKind == UETT_VecStep) {
4196     isInvalid = CheckVecStepExpr(E);
4197   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4198       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4199       isInvalid = true;
4200   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4201     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4202     isInvalid = true;
4203   } else {
4204     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4205   }
4206 
4207   if (isInvalid)
4208     return ExprError();
4209 
4210   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4211     PE = TransformToPotentiallyEvaluated(E);
4212     if (PE.isInvalid()) return ExprError();
4213     E = PE.get();
4214   }
4215 
4216   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4217   return new (Context) UnaryExprOrTypeTraitExpr(
4218       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4219 }
4220 
4221 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4222 /// expr and the same for @c alignof and @c __alignof
4223 /// Note that the ArgRange is invalid if isType is false.
4224 ExprResult
4225 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4226                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4227                                     void *TyOrEx, SourceRange ArgRange) {
4228   // If error parsing type, ignore.
4229   if (!TyOrEx) return ExprError();
4230 
4231   if (IsType) {
4232     TypeSourceInfo *TInfo;
4233     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4234     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4235   }
4236 
4237   Expr *ArgEx = (Expr *)TyOrEx;
4238   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4239   return Result;
4240 }
4241 
4242 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4243                                      bool IsReal) {
4244   if (V.get()->isTypeDependent())
4245     return S.Context.DependentTy;
4246 
4247   // _Real and _Imag are only l-values for normal l-values.
4248   if (V.get()->getObjectKind() != OK_Ordinary) {
4249     V = S.DefaultLvalueConversion(V.get());
4250     if (V.isInvalid())
4251       return QualType();
4252   }
4253 
4254   // These operators return the element type of a complex type.
4255   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4256     return CT->getElementType();
4257 
4258   // Otherwise they pass through real integer and floating point types here.
4259   if (V.get()->getType()->isArithmeticType())
4260     return V.get()->getType();
4261 
4262   // Test for placeholders.
4263   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4264   if (PR.isInvalid()) return QualType();
4265   if (PR.get() != V.get()) {
4266     V = PR;
4267     return CheckRealImagOperand(S, V, Loc, IsReal);
4268   }
4269 
4270   // Reject anything else.
4271   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4272     << (IsReal ? "__real" : "__imag");
4273   return QualType();
4274 }
4275 
4276 
4277 
4278 ExprResult
4279 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4280                           tok::TokenKind Kind, Expr *Input) {
4281   UnaryOperatorKind Opc;
4282   switch (Kind) {
4283   default: llvm_unreachable("Unknown unary op!");
4284   case tok::plusplus:   Opc = UO_PostInc; break;
4285   case tok::minusminus: Opc = UO_PostDec; break;
4286   }
4287 
4288   // Since this might is a postfix expression, get rid of ParenListExprs.
4289   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4290   if (Result.isInvalid()) return ExprError();
4291   Input = Result.get();
4292 
4293   return BuildUnaryOp(S, OpLoc, Opc, Input);
4294 }
4295 
4296 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4297 ///
4298 /// \return true on error
4299 static bool checkArithmeticOnObjCPointer(Sema &S,
4300                                          SourceLocation opLoc,
4301                                          Expr *op) {
4302   assert(op->getType()->isObjCObjectPointerType());
4303   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4304       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4305     return false;
4306 
4307   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4308     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4309     << op->getSourceRange();
4310   return true;
4311 }
4312 
4313 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4314   auto *BaseNoParens = Base->IgnoreParens();
4315   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4316     return MSProp->getPropertyDecl()->getType()->isArrayType();
4317   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4318 }
4319 
4320 ExprResult
4321 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4322                               Expr *idx, SourceLocation rbLoc) {
4323   if (base && !base->getType().isNull() &&
4324       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4325     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4326                                     /*Length=*/nullptr, rbLoc);
4327 
4328   // Since this might be a postfix expression, get rid of ParenListExprs.
4329   if (isa<ParenListExpr>(base)) {
4330     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4331     if (result.isInvalid()) return ExprError();
4332     base = result.get();
4333   }
4334 
4335   // Handle any non-overload placeholder types in the base and index
4336   // expressions.  We can't handle overloads here because the other
4337   // operand might be an overloadable type, in which case the overload
4338   // resolution for the operator overload should get the first crack
4339   // at the overload.
4340   bool IsMSPropertySubscript = false;
4341   if (base->getType()->isNonOverloadPlaceholderType()) {
4342     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4343     if (!IsMSPropertySubscript) {
4344       ExprResult result = CheckPlaceholderExpr(base);
4345       if (result.isInvalid())
4346         return ExprError();
4347       base = result.get();
4348     }
4349   }
4350   if (idx->getType()->isNonOverloadPlaceholderType()) {
4351     ExprResult result = CheckPlaceholderExpr(idx);
4352     if (result.isInvalid()) return ExprError();
4353     idx = result.get();
4354   }
4355 
4356   // Build an unanalyzed expression if either operand is type-dependent.
4357   if (getLangOpts().CPlusPlus &&
4358       (base->isTypeDependent() || idx->isTypeDependent())) {
4359     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4360                                             VK_LValue, OK_Ordinary, rbLoc);
4361   }
4362 
4363   // MSDN, property (C++)
4364   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4365   // This attribute can also be used in the declaration of an empty array in a
4366   // class or structure definition. For example:
4367   // __declspec(property(get=GetX, put=PutX)) int x[];
4368   // The above statement indicates that x[] can be used with one or more array
4369   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4370   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4371   if (IsMSPropertySubscript) {
4372     // Build MS property subscript expression if base is MS property reference
4373     // or MS property subscript.
4374     return new (Context) MSPropertySubscriptExpr(
4375         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4376   }
4377 
4378   // Use C++ overloaded-operator rules if either operand has record
4379   // type.  The spec says to do this if either type is *overloadable*,
4380   // but enum types can't declare subscript operators or conversion
4381   // operators, so there's nothing interesting for overload resolution
4382   // to do if there aren't any record types involved.
4383   //
4384   // ObjC pointers have their own subscripting logic that is not tied
4385   // to overload resolution and so should not take this path.
4386   if (getLangOpts().CPlusPlus &&
4387       (base->getType()->isRecordType() ||
4388        (!base->getType()->isObjCObjectPointerType() &&
4389         idx->getType()->isRecordType()))) {
4390     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4391   }
4392 
4393   ExprResult Res = CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4394 
4395   if (!Res.isInvalid() && isa<ArraySubscriptExpr>(Res.get()))
4396     CheckSubscriptAccessOfNoDeref(cast<ArraySubscriptExpr>(Res.get()));
4397 
4398   return Res;
4399 }
4400 
4401 void Sema::CheckAddressOfNoDeref(const Expr *E) {
4402   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4403   const Expr *StrippedExpr = E->IgnoreParenImpCasts();
4404 
4405   // For expressions like `&(*s).b`, the base is recorded and what should be
4406   // checked.
4407   const MemberExpr *Member = nullptr;
4408   while ((Member = dyn_cast<MemberExpr>(StrippedExpr)) && !Member->isArrow())
4409     StrippedExpr = Member->getBase()->IgnoreParenImpCasts();
4410 
4411   LastRecord.PossibleDerefs.erase(StrippedExpr);
4412 }
4413 
4414 void Sema::CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E) {
4415   QualType ResultTy = E->getType();
4416   ExpressionEvaluationContextRecord &LastRecord = ExprEvalContexts.back();
4417 
4418   // Bail if the element is an array since it is not memory access.
4419   if (isa<ArrayType>(ResultTy))
4420     return;
4421 
4422   if (ResultTy->hasAttr(attr::NoDeref)) {
4423     LastRecord.PossibleDerefs.insert(E);
4424     return;
4425   }
4426 
4427   // Check if the base type is a pointer to a member access of a struct
4428   // marked with noderef.
4429   const Expr *Base = E->getBase();
4430   QualType BaseTy = Base->getType();
4431   if (!(isa<ArrayType>(BaseTy) || isa<PointerType>(BaseTy)))
4432     // Not a pointer access
4433     return;
4434 
4435   const MemberExpr *Member = nullptr;
4436   while ((Member = dyn_cast<MemberExpr>(Base->IgnoreParenCasts())) &&
4437          Member->isArrow())
4438     Base = Member->getBase();
4439 
4440   if (const auto *Ptr = dyn_cast<PointerType>(Base->getType())) {
4441     if (Ptr->getPointeeType()->hasAttr(attr::NoDeref))
4442       LastRecord.PossibleDerefs.insert(E);
4443   }
4444 }
4445 
4446 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4447                                           Expr *LowerBound,
4448                                           SourceLocation ColonLoc, Expr *Length,
4449                                           SourceLocation RBLoc) {
4450   if (Base->getType()->isPlaceholderType() &&
4451       !Base->getType()->isSpecificPlaceholderType(
4452           BuiltinType::OMPArraySection)) {
4453     ExprResult Result = CheckPlaceholderExpr(Base);
4454     if (Result.isInvalid())
4455       return ExprError();
4456     Base = Result.get();
4457   }
4458   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4459     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4460     if (Result.isInvalid())
4461       return ExprError();
4462     Result = DefaultLvalueConversion(Result.get());
4463     if (Result.isInvalid())
4464       return ExprError();
4465     LowerBound = Result.get();
4466   }
4467   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4468     ExprResult Result = CheckPlaceholderExpr(Length);
4469     if (Result.isInvalid())
4470       return ExprError();
4471     Result = DefaultLvalueConversion(Result.get());
4472     if (Result.isInvalid())
4473       return ExprError();
4474     Length = Result.get();
4475   }
4476 
4477   // Build an unanalyzed expression if either operand is type-dependent.
4478   if (Base->isTypeDependent() ||
4479       (LowerBound &&
4480        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4481       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4482     return new (Context)
4483         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4484                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4485   }
4486 
4487   // Perform default conversions.
4488   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4489   QualType ResultTy;
4490   if (OriginalTy->isAnyPointerType()) {
4491     ResultTy = OriginalTy->getPointeeType();
4492   } else if (OriginalTy->isArrayType()) {
4493     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4494   } else {
4495     return ExprError(
4496         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4497         << Base->getSourceRange());
4498   }
4499   // C99 6.5.2.1p1
4500   if (LowerBound) {
4501     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4502                                                       LowerBound);
4503     if (Res.isInvalid())
4504       return ExprError(Diag(LowerBound->getExprLoc(),
4505                             diag::err_omp_typecheck_section_not_integer)
4506                        << 0 << LowerBound->getSourceRange());
4507     LowerBound = Res.get();
4508 
4509     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4510         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4511       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4512           << 0 << LowerBound->getSourceRange();
4513   }
4514   if (Length) {
4515     auto Res =
4516         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4517     if (Res.isInvalid())
4518       return ExprError(Diag(Length->getExprLoc(),
4519                             diag::err_omp_typecheck_section_not_integer)
4520                        << 1 << Length->getSourceRange());
4521     Length = Res.get();
4522 
4523     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4524         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4525       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4526           << 1 << Length->getSourceRange();
4527   }
4528 
4529   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4530   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4531   // type. Note that functions are not objects, and that (in C99 parlance)
4532   // incomplete types are not object types.
4533   if (ResultTy->isFunctionType()) {
4534     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4535         << ResultTy << Base->getSourceRange();
4536     return ExprError();
4537   }
4538 
4539   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4540                           diag::err_omp_section_incomplete_type, Base))
4541     return ExprError();
4542 
4543   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4544     Expr::EvalResult Result;
4545     if (LowerBound->EvaluateAsInt(Result, Context)) {
4546       // OpenMP 4.5, [2.4 Array Sections]
4547       // The array section must be a subset of the original array.
4548       llvm::APSInt LowerBoundValue = Result.Val.getInt();
4549       if (LowerBoundValue.isNegative()) {
4550         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4551             << LowerBound->getSourceRange();
4552         return ExprError();
4553       }
4554     }
4555   }
4556 
4557   if (Length) {
4558     Expr::EvalResult Result;
4559     if (Length->EvaluateAsInt(Result, Context)) {
4560       // OpenMP 4.5, [2.4 Array Sections]
4561       // The length must evaluate to non-negative integers.
4562       llvm::APSInt LengthValue = Result.Val.getInt();
4563       if (LengthValue.isNegative()) {
4564         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4565             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4566             << Length->getSourceRange();
4567         return ExprError();
4568       }
4569     }
4570   } else if (ColonLoc.isValid() &&
4571              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4572                                       !OriginalTy->isVariableArrayType()))) {
4573     // OpenMP 4.5, [2.4 Array Sections]
4574     // When the size of the array dimension is not known, the length must be
4575     // specified explicitly.
4576     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4577         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4578     return ExprError();
4579   }
4580 
4581   if (!Base->getType()->isSpecificPlaceholderType(
4582           BuiltinType::OMPArraySection)) {
4583     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4584     if (Result.isInvalid())
4585       return ExprError();
4586     Base = Result.get();
4587   }
4588   return new (Context)
4589       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4590                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4591 }
4592 
4593 ExprResult
4594 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4595                                       Expr *Idx, SourceLocation RLoc) {
4596   Expr *LHSExp = Base;
4597   Expr *RHSExp = Idx;
4598 
4599   ExprValueKind VK = VK_LValue;
4600   ExprObjectKind OK = OK_Ordinary;
4601 
4602   // Per C++ core issue 1213, the result is an xvalue if either operand is
4603   // a non-lvalue array, and an lvalue otherwise.
4604   if (getLangOpts().CPlusPlus11) {
4605     for (auto *Op : {LHSExp, RHSExp}) {
4606       Op = Op->IgnoreImplicit();
4607       if (Op->getType()->isArrayType() && !Op->isLValue())
4608         VK = VK_XValue;
4609     }
4610   }
4611 
4612   // Perform default conversions.
4613   if (!LHSExp->getType()->getAs<VectorType>()) {
4614     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4615     if (Result.isInvalid())
4616       return ExprError();
4617     LHSExp = Result.get();
4618   }
4619   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4620   if (Result.isInvalid())
4621     return ExprError();
4622   RHSExp = Result.get();
4623 
4624   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4625 
4626   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4627   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4628   // in the subscript position. As a result, we need to derive the array base
4629   // and index from the expression types.
4630   Expr *BaseExpr, *IndexExpr;
4631   QualType ResultType;
4632   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4633     BaseExpr = LHSExp;
4634     IndexExpr = RHSExp;
4635     ResultType = Context.DependentTy;
4636   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4637     BaseExpr = LHSExp;
4638     IndexExpr = RHSExp;
4639     ResultType = PTy->getPointeeType();
4640   } else if (const ObjCObjectPointerType *PTy =
4641                LHSTy->getAs<ObjCObjectPointerType>()) {
4642     BaseExpr = LHSExp;
4643     IndexExpr = RHSExp;
4644 
4645     // Use custom logic if this should be the pseudo-object subscript
4646     // expression.
4647     if (!LangOpts.isSubscriptPointerArithmetic())
4648       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4649                                           nullptr);
4650 
4651     ResultType = PTy->getPointeeType();
4652   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4653      // Handle the uncommon case of "123[Ptr]".
4654     BaseExpr = RHSExp;
4655     IndexExpr = LHSExp;
4656     ResultType = PTy->getPointeeType();
4657   } else if (const ObjCObjectPointerType *PTy =
4658                RHSTy->getAs<ObjCObjectPointerType>()) {
4659      // Handle the uncommon case of "123[Ptr]".
4660     BaseExpr = RHSExp;
4661     IndexExpr = LHSExp;
4662     ResultType = PTy->getPointeeType();
4663     if (!LangOpts.isSubscriptPointerArithmetic()) {
4664       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4665         << ResultType << BaseExpr->getSourceRange();
4666       return ExprError();
4667     }
4668   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4669     BaseExpr = LHSExp;    // vectors: V[123]
4670     IndexExpr = RHSExp;
4671     // We apply C++ DR1213 to vector subscripting too.
4672     if (getLangOpts().CPlusPlus11 && LHSExp->getValueKind() == VK_RValue) {
4673       ExprResult Materialized = TemporaryMaterializationConversion(LHSExp);
4674       if (Materialized.isInvalid())
4675         return ExprError();
4676       LHSExp = Materialized.get();
4677     }
4678     VK = LHSExp->getValueKind();
4679     if (VK != VK_RValue)
4680       OK = OK_VectorComponent;
4681 
4682     ResultType = VTy->getElementType();
4683     QualType BaseType = BaseExpr->getType();
4684     Qualifiers BaseQuals = BaseType.getQualifiers();
4685     Qualifiers MemberQuals = ResultType.getQualifiers();
4686     Qualifiers Combined = BaseQuals + MemberQuals;
4687     if (Combined != MemberQuals)
4688       ResultType = Context.getQualifiedType(ResultType, Combined);
4689   } else if (LHSTy->isArrayType()) {
4690     // If we see an array that wasn't promoted by
4691     // DefaultFunctionArrayLvalueConversion, it must be an array that
4692     // wasn't promoted because of the C90 rule that doesn't
4693     // allow promoting non-lvalue arrays.  Warn, then
4694     // force the promotion here.
4695     Diag(LHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4696         << LHSExp->getSourceRange();
4697     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4698                                CK_ArrayToPointerDecay).get();
4699     LHSTy = LHSExp->getType();
4700 
4701     BaseExpr = LHSExp;
4702     IndexExpr = RHSExp;
4703     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4704   } else if (RHSTy->isArrayType()) {
4705     // Same as previous, except for 123[f().a] case
4706     Diag(RHSExp->getBeginLoc(), diag::ext_subscript_non_lvalue)
4707         << RHSExp->getSourceRange();
4708     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4709                                CK_ArrayToPointerDecay).get();
4710     RHSTy = RHSExp->getType();
4711 
4712     BaseExpr = RHSExp;
4713     IndexExpr = LHSExp;
4714     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4715   } else {
4716     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4717        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4718   }
4719   // C99 6.5.2.1p1
4720   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4721     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4722                      << IndexExpr->getSourceRange());
4723 
4724   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4725        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4726          && !IndexExpr->isTypeDependent())
4727     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4728 
4729   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4730   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4731   // type. Note that Functions are not objects, and that (in C99 parlance)
4732   // incomplete types are not object types.
4733   if (ResultType->isFunctionType()) {
4734     Diag(BaseExpr->getBeginLoc(), diag::err_subscript_function_type)
4735         << ResultType << BaseExpr->getSourceRange();
4736     return ExprError();
4737   }
4738 
4739   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4740     // GNU extension: subscripting on pointer to void
4741     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4742       << BaseExpr->getSourceRange();
4743 
4744     // C forbids expressions of unqualified void type from being l-values.
4745     // See IsCForbiddenLValueType.
4746     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4747   } else if (!ResultType->isDependentType() &&
4748       RequireCompleteType(LLoc, ResultType,
4749                           diag::err_subscript_incomplete_type, BaseExpr))
4750     return ExprError();
4751 
4752   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4753          !ResultType.isCForbiddenLValueType());
4754 
4755   return new (Context)
4756       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4757 }
4758 
4759 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4760                                   ParmVarDecl *Param) {
4761   if (Param->hasUnparsedDefaultArg()) {
4762     Diag(CallLoc,
4763          diag::err_use_of_default_argument_to_function_declared_later) <<
4764       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4765     Diag(UnparsedDefaultArgLocs[Param],
4766          diag::note_default_argument_declared_here);
4767     return true;
4768   }
4769 
4770   if (Param->hasUninstantiatedDefaultArg()) {
4771     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4772 
4773     EnterExpressionEvaluationContext EvalContext(
4774         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4775 
4776     // Instantiate the expression.
4777     //
4778     // FIXME: Pass in a correct Pattern argument, otherwise
4779     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4780     //
4781     // template<typename T>
4782     // struct A {
4783     //   static int FooImpl();
4784     //
4785     //   template<typename Tp>
4786     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4787     //   // template argument list [[T], [Tp]], should be [[Tp]].
4788     //   friend A<Tp> Foo(int a);
4789     // };
4790     //
4791     // template<typename T>
4792     // A<T> Foo(int a = A<T>::FooImpl());
4793     MultiLevelTemplateArgumentList MutiLevelArgList
4794       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4795 
4796     InstantiatingTemplate Inst(*this, CallLoc, Param,
4797                                MutiLevelArgList.getInnermost());
4798     if (Inst.isInvalid())
4799       return true;
4800     if (Inst.isAlreadyInstantiating()) {
4801       Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4802       Param->setInvalidDecl();
4803       return true;
4804     }
4805 
4806     ExprResult Result;
4807     {
4808       // C++ [dcl.fct.default]p5:
4809       //   The names in the [default argument] expression are bound, and
4810       //   the semantic constraints are checked, at the point where the
4811       //   default argument expression appears.
4812       ContextRAII SavedContext(*this, FD);
4813       LocalInstantiationScope Local(*this);
4814       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4815                                 /*DirectInit*/false);
4816     }
4817     if (Result.isInvalid())
4818       return true;
4819 
4820     // Check the expression as an initializer for the parameter.
4821     InitializedEntity Entity
4822       = InitializedEntity::InitializeParameter(Context, Param);
4823     InitializationKind Kind = InitializationKind::CreateCopy(
4824         Param->getLocation(),
4825         /*FIXME:EqualLoc*/ UninstExpr->getBeginLoc());
4826     Expr *ResultE = Result.getAs<Expr>();
4827 
4828     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4829     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4830     if (Result.isInvalid())
4831       return true;
4832 
4833     Result =
4834         ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
4835                             /*DiscardedValue*/ false);
4836     if (Result.isInvalid())
4837       return true;
4838 
4839     // Remember the instantiated default argument.
4840     Param->setDefaultArg(Result.getAs<Expr>());
4841     if (ASTMutationListener *L = getASTMutationListener()) {
4842       L->DefaultArgumentInstantiated(Param);
4843     }
4844   }
4845 
4846   // If the default argument expression is not set yet, we are building it now.
4847   if (!Param->hasInit()) {
4848     Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
4849     Param->setInvalidDecl();
4850     return true;
4851   }
4852 
4853   // If the default expression creates temporaries, we need to
4854   // push them to the current stack of expression temporaries so they'll
4855   // be properly destroyed.
4856   // FIXME: We should really be rebuilding the default argument with new
4857   // bound temporaries; see the comment in PR5810.
4858   // We don't need to do that with block decls, though, because
4859   // blocks in default argument expression can never capture anything.
4860   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4861     // Set the "needs cleanups" bit regardless of whether there are
4862     // any explicit objects.
4863     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4864 
4865     // Append all the objects to the cleanup list.  Right now, this
4866     // should always be a no-op, because blocks in default argument
4867     // expressions should never be able to capture anything.
4868     assert(!Init->getNumObjects() &&
4869            "default argument expression has capturing blocks?");
4870   }
4871 
4872   // We already type-checked the argument, so we know it works.
4873   // Just mark all of the declarations in this potentially-evaluated expression
4874   // as being "referenced".
4875   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4876                                    /*SkipLocalVariables=*/true);
4877   return false;
4878 }
4879 
4880 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4881                                         FunctionDecl *FD, ParmVarDecl *Param) {
4882   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4883     return ExprError();
4884   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4885 }
4886 
4887 Sema::VariadicCallType
4888 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4889                           Expr *Fn) {
4890   if (Proto && Proto->isVariadic()) {
4891     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4892       return VariadicConstructor;
4893     else if (Fn && Fn->getType()->isBlockPointerType())
4894       return VariadicBlock;
4895     else if (FDecl) {
4896       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4897         if (Method->isInstance())
4898           return VariadicMethod;
4899     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4900       return VariadicMethod;
4901     return VariadicFunction;
4902   }
4903   return VariadicDoesNotApply;
4904 }
4905 
4906 namespace {
4907 class FunctionCallCCC : public FunctionCallFilterCCC {
4908 public:
4909   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4910                   unsigned NumArgs, MemberExpr *ME)
4911       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4912         FunctionName(FuncName) {}
4913 
4914   bool ValidateCandidate(const TypoCorrection &candidate) override {
4915     if (!candidate.getCorrectionSpecifier() ||
4916         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4917       return false;
4918     }
4919 
4920     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4921   }
4922 
4923 private:
4924   const IdentifierInfo *const FunctionName;
4925 };
4926 }
4927 
4928 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4929                                                FunctionDecl *FDecl,
4930                                                ArrayRef<Expr *> Args) {
4931   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4932   DeclarationName FuncName = FDecl->getDeclName();
4933   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getBeginLoc();
4934 
4935   if (TypoCorrection Corrected = S.CorrectTypo(
4936           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4937           S.getScopeForContext(S.CurContext), nullptr,
4938           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4939                                              Args.size(), ME),
4940           Sema::CTK_ErrorRecovery)) {
4941     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4942       if (Corrected.isOverloaded()) {
4943         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4944         OverloadCandidateSet::iterator Best;
4945         for (NamedDecl *CD : Corrected) {
4946           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4947             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4948                                    OCS);
4949         }
4950         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4951         case OR_Success:
4952           ND = Best->FoundDecl;
4953           Corrected.setCorrectionDecl(ND);
4954           break;
4955         default:
4956           break;
4957         }
4958       }
4959       ND = ND->getUnderlyingDecl();
4960       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4961         return Corrected;
4962     }
4963   }
4964   return TypoCorrection();
4965 }
4966 
4967 /// ConvertArgumentsForCall - Converts the arguments specified in
4968 /// Args/NumArgs to the parameter types of the function FDecl with
4969 /// function prototype Proto. Call is the call expression itself, and
4970 /// Fn is the function expression. For a C++ member function, this
4971 /// routine does not attempt to convert the object argument. Returns
4972 /// true if the call is ill-formed.
4973 bool
4974 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4975                               FunctionDecl *FDecl,
4976                               const FunctionProtoType *Proto,
4977                               ArrayRef<Expr *> Args,
4978                               SourceLocation RParenLoc,
4979                               bool IsExecConfig) {
4980   // Bail out early if calling a builtin with custom typechecking.
4981   if (FDecl)
4982     if (unsigned ID = FDecl->getBuiltinID())
4983       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4984         return false;
4985 
4986   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4987   // assignment, to the types of the corresponding parameter, ...
4988   unsigned NumParams = Proto->getNumParams();
4989   bool Invalid = false;
4990   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4991   unsigned FnKind = Fn->getType()->isBlockPointerType()
4992                        ? 1 /* block */
4993                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4994                                        : 0 /* function */);
4995 
4996   // If too few arguments are available (and we don't have default
4997   // arguments for the remaining parameters), don't make the call.
4998   if (Args.size() < NumParams) {
4999     if (Args.size() < MinArgs) {
5000       TypoCorrection TC;
5001       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5002         unsigned diag_id =
5003             MinArgs == NumParams && !Proto->isVariadic()
5004                 ? diag::err_typecheck_call_too_few_args_suggest
5005                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
5006         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
5007                                         << static_cast<unsigned>(Args.size())
5008                                         << TC.getCorrectionRange());
5009       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
5010         Diag(RParenLoc,
5011              MinArgs == NumParams && !Proto->isVariadic()
5012                  ? diag::err_typecheck_call_too_few_args_one
5013                  : diag::err_typecheck_call_too_few_args_at_least_one)
5014             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
5015       else
5016         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
5017                             ? diag::err_typecheck_call_too_few_args
5018                             : diag::err_typecheck_call_too_few_args_at_least)
5019             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
5020             << Fn->getSourceRange();
5021 
5022       // Emit the location of the prototype.
5023       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5024         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5025 
5026       return true;
5027     }
5028     // We reserve space for the default arguments when we create
5029     // the call expression, before calling ConvertArgumentsForCall.
5030     assert((Call->getNumArgs() == NumParams) &&
5031            "We should have reserved space for the default arguments before!");
5032   }
5033 
5034   // If too many are passed and not variadic, error on the extras and drop
5035   // them.
5036   if (Args.size() > NumParams) {
5037     if (!Proto->isVariadic()) {
5038       TypoCorrection TC;
5039       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
5040         unsigned diag_id =
5041             MinArgs == NumParams && !Proto->isVariadic()
5042                 ? diag::err_typecheck_call_too_many_args_suggest
5043                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
5044         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
5045                                         << static_cast<unsigned>(Args.size())
5046                                         << TC.getCorrectionRange());
5047       } else if (NumParams == 1 && FDecl &&
5048                  FDecl->getParamDecl(0)->getDeclName())
5049         Diag(Args[NumParams]->getBeginLoc(),
5050              MinArgs == NumParams
5051                  ? diag::err_typecheck_call_too_many_args_one
5052                  : diag::err_typecheck_call_too_many_args_at_most_one)
5053             << FnKind << FDecl->getParamDecl(0)
5054             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
5055             << SourceRange(Args[NumParams]->getBeginLoc(),
5056                            Args.back()->getEndLoc());
5057       else
5058         Diag(Args[NumParams]->getBeginLoc(),
5059              MinArgs == NumParams
5060                  ? diag::err_typecheck_call_too_many_args
5061                  : diag::err_typecheck_call_too_many_args_at_most)
5062             << FnKind << NumParams << static_cast<unsigned>(Args.size())
5063             << Fn->getSourceRange()
5064             << SourceRange(Args[NumParams]->getBeginLoc(),
5065                            Args.back()->getEndLoc());
5066 
5067       // Emit the location of the prototype.
5068       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
5069         Diag(FDecl->getBeginLoc(), diag::note_callee_decl) << FDecl;
5070 
5071       // This deletes the extra arguments.
5072       Call->shrinkNumArgs(NumParams);
5073       return true;
5074     }
5075   }
5076   SmallVector<Expr *, 8> AllArgs;
5077   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
5078 
5079   Invalid = GatherArgumentsForCall(Call->getBeginLoc(), FDecl, Proto, 0, Args,
5080                                    AllArgs, CallType);
5081   if (Invalid)
5082     return true;
5083   unsigned TotalNumArgs = AllArgs.size();
5084   for (unsigned i = 0; i < TotalNumArgs; ++i)
5085     Call->setArg(i, AllArgs[i]);
5086 
5087   return false;
5088 }
5089 
5090 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
5091                                   const FunctionProtoType *Proto,
5092                                   unsigned FirstParam, ArrayRef<Expr *> Args,
5093                                   SmallVectorImpl<Expr *> &AllArgs,
5094                                   VariadicCallType CallType, bool AllowExplicit,
5095                                   bool IsListInitialization) {
5096   unsigned NumParams = Proto->getNumParams();
5097   bool Invalid = false;
5098   size_t ArgIx = 0;
5099   // Continue to check argument types (even if we have too few/many args).
5100   for (unsigned i = FirstParam; i < NumParams; i++) {
5101     QualType ProtoArgType = Proto->getParamType(i);
5102 
5103     Expr *Arg;
5104     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
5105     if (ArgIx < Args.size()) {
5106       Arg = Args[ArgIx++];
5107 
5108       if (RequireCompleteType(Arg->getBeginLoc(), ProtoArgType,
5109                               diag::err_call_incomplete_argument, Arg))
5110         return true;
5111 
5112       // Strip the unbridged-cast placeholder expression off, if applicable.
5113       bool CFAudited = false;
5114       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
5115           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5116           (!Param || !Param->hasAttr<CFConsumedAttr>()))
5117         Arg = stripARCUnbridgedCast(Arg);
5118       else if (getLangOpts().ObjCAutoRefCount &&
5119                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
5120                (!Param || !Param->hasAttr<CFConsumedAttr>()))
5121         CFAudited = true;
5122 
5123       if (Proto->getExtParameterInfo(i).isNoEscape())
5124         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
5125           BE->getBlockDecl()->setDoesNotEscape();
5126 
5127       InitializedEntity Entity =
5128           Param ? InitializedEntity::InitializeParameter(Context, Param,
5129                                                          ProtoArgType)
5130                 : InitializedEntity::InitializeParameter(
5131                       Context, ProtoArgType, Proto->isParamConsumed(i));
5132 
5133       // Remember that parameter belongs to a CF audited API.
5134       if (CFAudited)
5135         Entity.setParameterCFAudited();
5136 
5137       ExprResult ArgE = PerformCopyInitialization(
5138           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
5139       if (ArgE.isInvalid())
5140         return true;
5141 
5142       Arg = ArgE.getAs<Expr>();
5143     } else {
5144       assert(Param && "can't use default arguments without a known callee");
5145 
5146       ExprResult ArgExpr =
5147         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
5148       if (ArgExpr.isInvalid())
5149         return true;
5150 
5151       Arg = ArgExpr.getAs<Expr>();
5152     }
5153 
5154     // Check for array bounds violations for each argument to the call. This
5155     // check only triggers warnings when the argument isn't a more complex Expr
5156     // with its own checking, such as a BinaryOperator.
5157     CheckArrayAccess(Arg);
5158 
5159     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
5160     CheckStaticArrayArgument(CallLoc, Param, Arg);
5161 
5162     AllArgs.push_back(Arg);
5163   }
5164 
5165   // If this is a variadic call, handle args passed through "...".
5166   if (CallType != VariadicDoesNotApply) {
5167     // Assume that extern "C" functions with variadic arguments that
5168     // return __unknown_anytype aren't *really* variadic.
5169     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
5170         FDecl->isExternC()) {
5171       for (Expr *A : Args.slice(ArgIx)) {
5172         QualType paramType; // ignored
5173         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
5174         Invalid |= arg.isInvalid();
5175         AllArgs.push_back(arg.get());
5176       }
5177 
5178     // Otherwise do argument promotion, (C99 6.5.2.2p7).
5179     } else {
5180       for (Expr *A : Args.slice(ArgIx)) {
5181         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
5182         Invalid |= Arg.isInvalid();
5183         AllArgs.push_back(Arg.get());
5184       }
5185     }
5186 
5187     // Check for array bounds violations.
5188     for (Expr *A : Args.slice(ArgIx))
5189       CheckArrayAccess(A);
5190   }
5191   return Invalid;
5192 }
5193 
5194 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
5195   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
5196   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
5197     TL = DTL.getOriginalLoc();
5198   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
5199     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
5200       << ATL.getLocalSourceRange();
5201 }
5202 
5203 /// CheckStaticArrayArgument - If the given argument corresponds to a static
5204 /// array parameter, check that it is non-null, and that if it is formed by
5205 /// array-to-pointer decay, the underlying array is sufficiently large.
5206 ///
5207 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
5208 /// array type derivation, then for each call to the function, the value of the
5209 /// corresponding actual argument shall provide access to the first element of
5210 /// an array with at least as many elements as specified by the size expression.
5211 void
5212 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
5213                                ParmVarDecl *Param,
5214                                const Expr *ArgExpr) {
5215   // Static array parameters are not supported in C++.
5216   if (!Param || getLangOpts().CPlusPlus)
5217     return;
5218 
5219   QualType OrigTy = Param->getOriginalType();
5220 
5221   const ArrayType *AT = Context.getAsArrayType(OrigTy);
5222   if (!AT || AT->getSizeModifier() != ArrayType::Static)
5223     return;
5224 
5225   if (ArgExpr->isNullPointerConstant(Context,
5226                                      Expr::NPC_NeverValueDependent)) {
5227     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
5228     DiagnoseCalleeStaticArrayParam(*this, Param);
5229     return;
5230   }
5231 
5232   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
5233   if (!CAT)
5234     return;
5235 
5236   const ConstantArrayType *ArgCAT =
5237     Context.getAsConstantArrayType(ArgExpr->IgnoreParenCasts()->getType());
5238   if (!ArgCAT)
5239     return;
5240 
5241   if (getASTContext().hasSameUnqualifiedType(CAT->getElementType(),
5242                                              ArgCAT->getElementType())) {
5243     if (ArgCAT->getSize().ult(CAT->getSize())) {
5244       Diag(CallLoc, diag::warn_static_array_too_small)
5245           << ArgExpr->getSourceRange()
5246           << (unsigned)ArgCAT->getSize().getZExtValue()
5247           << (unsigned)CAT->getSize().getZExtValue() << 0;
5248       DiagnoseCalleeStaticArrayParam(*this, Param);
5249     }
5250     return;
5251   }
5252 
5253   Optional<CharUnits> ArgSize =
5254       getASTContext().getTypeSizeInCharsIfKnown(ArgCAT);
5255   Optional<CharUnits> ParmSize = getASTContext().getTypeSizeInCharsIfKnown(CAT);
5256   if (ArgSize && ParmSize && *ArgSize < *ParmSize) {
5257     Diag(CallLoc, diag::warn_static_array_too_small)
5258         << ArgExpr->getSourceRange() << (unsigned)ArgSize->getQuantity()
5259         << (unsigned)ParmSize->getQuantity() << 1;
5260     DiagnoseCalleeStaticArrayParam(*this, Param);
5261   }
5262 }
5263 
5264 /// Given a function expression of unknown-any type, try to rebuild it
5265 /// to have a function type.
5266 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
5267 
5268 /// Is the given type a placeholder that we need to lower out
5269 /// immediately during argument processing?
5270 static bool isPlaceholderToRemoveAsArg(QualType type) {
5271   // Placeholders are never sugared.
5272   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
5273   if (!placeholder) return false;
5274 
5275   switch (placeholder->getKind()) {
5276   // Ignore all the non-placeholder types.
5277 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5278   case BuiltinType::Id:
5279 #include "clang/Basic/OpenCLImageTypes.def"
5280 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
5281   case BuiltinType::Id:
5282 #include "clang/Basic/OpenCLExtensionTypes.def"
5283 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5284 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5285 #include "clang/AST/BuiltinTypes.def"
5286     return false;
5287 
5288   // We cannot lower out overload sets; they might validly be resolved
5289   // by the call machinery.
5290   case BuiltinType::Overload:
5291     return false;
5292 
5293   // Unbridged casts in ARC can be handled in some call positions and
5294   // should be left in place.
5295   case BuiltinType::ARCUnbridgedCast:
5296     return false;
5297 
5298   // Pseudo-objects should be converted as soon as possible.
5299   case BuiltinType::PseudoObject:
5300     return true;
5301 
5302   // The debugger mode could theoretically but currently does not try
5303   // to resolve unknown-typed arguments based on known parameter types.
5304   case BuiltinType::UnknownAny:
5305     return true;
5306 
5307   // These are always invalid as call arguments and should be reported.
5308   case BuiltinType::BoundMember:
5309   case BuiltinType::BuiltinFn:
5310   case BuiltinType::OMPArraySection:
5311     return true;
5312 
5313   }
5314   llvm_unreachable("bad builtin type kind");
5315 }
5316 
5317 /// Check an argument list for placeholders that we won't try to
5318 /// handle later.
5319 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5320   // Apply this processing to all the arguments at once instead of
5321   // dying at the first failure.
5322   bool hasInvalid = false;
5323   for (size_t i = 0, e = args.size(); i != e; i++) {
5324     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5325       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5326       if (result.isInvalid()) hasInvalid = true;
5327       else args[i] = result.get();
5328     } else if (hasInvalid) {
5329       (void)S.CorrectDelayedTyposInExpr(args[i]);
5330     }
5331   }
5332   return hasInvalid;
5333 }
5334 
5335 /// If a builtin function has a pointer argument with no explicit address
5336 /// space, then it should be able to accept a pointer to any address
5337 /// space as input.  In order to do this, we need to replace the
5338 /// standard builtin declaration with one that uses the same address space
5339 /// as the call.
5340 ///
5341 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5342 ///                  it does not contain any pointer arguments without
5343 ///                  an address space qualifer.  Otherwise the rewritten
5344 ///                  FunctionDecl is returned.
5345 /// TODO: Handle pointer return types.
5346 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5347                                                 const FunctionDecl *FDecl,
5348                                                 MultiExprArg ArgExprs) {
5349 
5350   QualType DeclType = FDecl->getType();
5351   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5352 
5353   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5354       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5355     return nullptr;
5356 
5357   bool NeedsNewDecl = false;
5358   unsigned i = 0;
5359   SmallVector<QualType, 8> OverloadParams;
5360 
5361   for (QualType ParamType : FT->param_types()) {
5362 
5363     // Convert array arguments to pointer to simplify type lookup.
5364     ExprResult ArgRes =
5365         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5366     if (ArgRes.isInvalid())
5367       return nullptr;
5368     Expr *Arg = ArgRes.get();
5369     QualType ArgType = Arg->getType();
5370     if (!ParamType->isPointerType() ||
5371         ParamType.getQualifiers().hasAddressSpace() ||
5372         !ArgType->isPointerType() ||
5373         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5374       OverloadParams.push_back(ParamType);
5375       continue;
5376     }
5377 
5378     QualType PointeeType = ParamType->getPointeeType();
5379     if (PointeeType.getQualifiers().hasAddressSpace())
5380       continue;
5381 
5382     NeedsNewDecl = true;
5383     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5384 
5385     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5386     OverloadParams.push_back(Context.getPointerType(PointeeType));
5387   }
5388 
5389   if (!NeedsNewDecl)
5390     return nullptr;
5391 
5392   FunctionProtoType::ExtProtoInfo EPI;
5393   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5394                                                 OverloadParams, EPI);
5395   DeclContext *Parent = Context.getTranslationUnitDecl();
5396   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5397                                                     FDecl->getLocation(),
5398                                                     FDecl->getLocation(),
5399                                                     FDecl->getIdentifier(),
5400                                                     OverloadTy,
5401                                                     /*TInfo=*/nullptr,
5402                                                     SC_Extern, false,
5403                                                     /*hasPrototype=*/true);
5404   SmallVector<ParmVarDecl*, 16> Params;
5405   FT = cast<FunctionProtoType>(OverloadTy);
5406   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5407     QualType ParamType = FT->getParamType(i);
5408     ParmVarDecl *Parm =
5409         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5410                                 SourceLocation(), nullptr, ParamType,
5411                                 /*TInfo=*/nullptr, SC_None, nullptr);
5412     Parm->setScopeInfo(0, i);
5413     Params.push_back(Parm);
5414   }
5415   OverloadDecl->setParams(Params);
5416   return OverloadDecl;
5417 }
5418 
5419 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5420                                     FunctionDecl *Callee,
5421                                     MultiExprArg ArgExprs) {
5422   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5423   // similar attributes) really don't like it when functions are called with an
5424   // invalid number of args.
5425   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5426                          /*PartialOverloading=*/false) &&
5427       !Callee->isVariadic())
5428     return;
5429   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5430     return;
5431 
5432   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5433     S.Diag(Fn->getBeginLoc(),
5434            isa<CXXMethodDecl>(Callee)
5435                ? diag::err_ovl_no_viable_member_function_in_call
5436                : diag::err_ovl_no_viable_function_in_call)
5437         << Callee << Callee->getSourceRange();
5438     S.Diag(Callee->getLocation(),
5439            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5440         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5441     return;
5442   }
5443 }
5444 
5445 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5446     const UnresolvedMemberExpr *const UME, Sema &S) {
5447 
5448   const auto GetFunctionLevelDCIfCXXClass =
5449       [](Sema &S) -> const CXXRecordDecl * {
5450     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5451     if (!DC || !DC->getParent())
5452       return nullptr;
5453 
5454     // If the call to some member function was made from within a member
5455     // function body 'M' return return 'M's parent.
5456     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5457       return MD->getParent()->getCanonicalDecl();
5458     // else the call was made from within a default member initializer of a
5459     // class, so return the class.
5460     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5461       return RD->getCanonicalDecl();
5462     return nullptr;
5463   };
5464   // If our DeclContext is neither a member function nor a class (in the
5465   // case of a lambda in a default member initializer), we can't have an
5466   // enclosing 'this'.
5467 
5468   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5469   if (!CurParentClass)
5470     return false;
5471 
5472   // The naming class for implicit member functions call is the class in which
5473   // name lookup starts.
5474   const CXXRecordDecl *const NamingClass =
5475       UME->getNamingClass()->getCanonicalDecl();
5476   assert(NamingClass && "Must have naming class even for implicit access");
5477 
5478   // If the unresolved member functions were found in a 'naming class' that is
5479   // related (either the same or derived from) to the class that contains the
5480   // member function that itself contained the implicit member access.
5481 
5482   return CurParentClass == NamingClass ||
5483          CurParentClass->isDerivedFrom(NamingClass);
5484 }
5485 
5486 static void
5487 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5488     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5489 
5490   if (!UME)
5491     return;
5492 
5493   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5494   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5495   // already been captured, or if this is an implicit member function call (if
5496   // it isn't, an attempt to capture 'this' should already have been made).
5497   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5498       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5499     return;
5500 
5501   // Check if the naming class in which the unresolved members were found is
5502   // related (same as or is a base of) to the enclosing class.
5503 
5504   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5505     return;
5506 
5507 
5508   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5509   // If the enclosing function is not dependent, then this lambda is
5510   // capture ready, so if we can capture this, do so.
5511   if (!EnclosingFunctionCtx->isDependentContext()) {
5512     // If the current lambda and all enclosing lambdas can capture 'this' -
5513     // then go ahead and capture 'this' (since our unresolved overload set
5514     // contains at least one non-static member function).
5515     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5516       S.CheckCXXThisCapture(CallLoc);
5517   } else if (S.CurContext->isDependentContext()) {
5518     // ... since this is an implicit member reference, that might potentially
5519     // involve a 'this' capture, mark 'this' for potential capture in
5520     // enclosing lambdas.
5521     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5522       CurLSI->addPotentialThisCapture(CallLoc);
5523   }
5524 }
5525 
5526 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5527 /// This provides the location of the left/right parens and a list of comma
5528 /// locations.
5529 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5530                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5531                                Expr *ExecConfig, bool IsExecConfig) {
5532   // Since this might be a postfix expression, get rid of ParenListExprs.
5533   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5534   if (Result.isInvalid()) return ExprError();
5535   Fn = Result.get();
5536 
5537   if (checkArgsForPlaceholders(*this, ArgExprs))
5538     return ExprError();
5539 
5540   if (getLangOpts().CPlusPlus) {
5541     // If this is a pseudo-destructor expression, build the call immediately.
5542     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5543       if (!ArgExprs.empty()) {
5544         // Pseudo-destructor calls should not have any arguments.
5545         Diag(Fn->getBeginLoc(), diag::err_pseudo_dtor_call_with_args)
5546             << FixItHint::CreateRemoval(
5547                    SourceRange(ArgExprs.front()->getBeginLoc(),
5548                                ArgExprs.back()->getEndLoc()));
5549       }
5550 
5551       return CallExpr::Create(Context, Fn, /*Args=*/{}, Context.VoidTy,
5552                               VK_RValue, RParenLoc);
5553     }
5554     if (Fn->getType() == Context.PseudoObjectTy) {
5555       ExprResult result = CheckPlaceholderExpr(Fn);
5556       if (result.isInvalid()) return ExprError();
5557       Fn = result.get();
5558     }
5559 
5560     // Determine whether this is a dependent call inside a C++ template,
5561     // in which case we won't do any semantic analysis now.
5562     if (Fn->isTypeDependent() || Expr::hasAnyTypeDependentArguments(ArgExprs)) {
5563       if (ExecConfig) {
5564         return CUDAKernelCallExpr::Create(
5565             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5566             Context.DependentTy, VK_RValue, RParenLoc);
5567       } else {
5568 
5569         tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5570             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5571             Fn->getBeginLoc());
5572 
5573         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5574                                 VK_RValue, RParenLoc);
5575       }
5576     }
5577 
5578     // Determine whether this is a call to an object (C++ [over.call.object]).
5579     if (Fn->getType()->isRecordType())
5580       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5581                                           RParenLoc);
5582 
5583     if (Fn->getType() == Context.UnknownAnyTy) {
5584       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5585       if (result.isInvalid()) return ExprError();
5586       Fn = result.get();
5587     }
5588 
5589     if (Fn->getType() == Context.BoundMemberTy) {
5590       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5591                                        RParenLoc);
5592     }
5593   }
5594 
5595   // Check for overloaded calls.  This can happen even in C due to extensions.
5596   if (Fn->getType() == Context.OverloadTy) {
5597     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5598 
5599     // We aren't supposed to apply this logic if there's an '&' involved.
5600     if (!find.HasFormOfMemberPointer) {
5601       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5602         return CallExpr::Create(Context, Fn, ArgExprs, Context.DependentTy,
5603                                 VK_RValue, RParenLoc);
5604       OverloadExpr *ovl = find.Expression;
5605       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5606         return BuildOverloadedCallExpr(
5607             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5608             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5609       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5610                                        RParenLoc);
5611     }
5612   }
5613 
5614   // If we're directly calling a function, get the appropriate declaration.
5615   if (Fn->getType() == Context.UnknownAnyTy) {
5616     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5617     if (result.isInvalid()) return ExprError();
5618     Fn = result.get();
5619   }
5620 
5621   Expr *NakedFn = Fn->IgnoreParens();
5622 
5623   bool CallingNDeclIndirectly = false;
5624   NamedDecl *NDecl = nullptr;
5625   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5626     if (UnOp->getOpcode() == UO_AddrOf) {
5627       CallingNDeclIndirectly = true;
5628       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5629     }
5630   }
5631 
5632   if (isa<DeclRefExpr>(NakedFn)) {
5633     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5634 
5635     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5636     if (FDecl && FDecl->getBuiltinID()) {
5637       // Rewrite the function decl for this builtin by replacing parameters
5638       // with no explicit address space with the address space of the arguments
5639       // in ArgExprs.
5640       if ((FDecl =
5641                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5642         NDecl = FDecl;
5643         Fn = DeclRefExpr::Create(
5644             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5645             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5646       }
5647     }
5648   } else if (isa<MemberExpr>(NakedFn))
5649     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5650 
5651   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5652     if (CallingNDeclIndirectly && !checkAddressOfFunctionIsAvailable(
5653                                       FD, /*Complain=*/true, Fn->getBeginLoc()))
5654       return ExprError();
5655 
5656     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5657       return ExprError();
5658 
5659     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5660   }
5661 
5662   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5663                                ExecConfig, IsExecConfig);
5664 }
5665 
5666 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5667 ///
5668 /// __builtin_astype( value, dst type )
5669 ///
5670 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5671                                  SourceLocation BuiltinLoc,
5672                                  SourceLocation RParenLoc) {
5673   ExprValueKind VK = VK_RValue;
5674   ExprObjectKind OK = OK_Ordinary;
5675   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5676   QualType SrcTy = E->getType();
5677   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5678     return ExprError(Diag(BuiltinLoc,
5679                           diag::err_invalid_astype_of_different_size)
5680                      << DstTy
5681                      << SrcTy
5682                      << E->getSourceRange());
5683   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5684 }
5685 
5686 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5687 /// provided arguments.
5688 ///
5689 /// __builtin_convertvector( value, dst type )
5690 ///
5691 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5692                                         SourceLocation BuiltinLoc,
5693                                         SourceLocation RParenLoc) {
5694   TypeSourceInfo *TInfo;
5695   GetTypeFromParser(ParsedDestTy, &TInfo);
5696   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5697 }
5698 
5699 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5700 /// i.e. an expression not of \p OverloadTy.  The expression should
5701 /// unary-convert to an expression of function-pointer or
5702 /// block-pointer type.
5703 ///
5704 /// \param NDecl the declaration being called, if available
5705 ExprResult Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5706                                        SourceLocation LParenLoc,
5707                                        ArrayRef<Expr *> Args,
5708                                        SourceLocation RParenLoc, Expr *Config,
5709                                        bool IsExecConfig, ADLCallKind UsesADL) {
5710   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5711   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5712 
5713   // Functions with 'interrupt' attribute cannot be called directly.
5714   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5715     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5716     return ExprError();
5717   }
5718 
5719   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5720   // so there's some risk when calling out to non-interrupt handler functions
5721   // that the callee might not preserve them. This is easy to diagnose here,
5722   // but can be very challenging to debug.
5723   if (auto *Caller = getCurFunctionDecl())
5724     if (Caller->hasAttr<ARMInterruptAttr>()) {
5725       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5726       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5727         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5728     }
5729 
5730   // Promote the function operand.
5731   // We special-case function promotion here because we only allow promoting
5732   // builtin functions to function pointers in the callee of a call.
5733   ExprResult Result;
5734   QualType ResultTy;
5735   if (BuiltinID &&
5736       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5737     // Extract the return type from the (builtin) function pointer type.
5738     // FIXME Several builtins still have setType in
5739     // Sema::CheckBuiltinFunctionCall. One should review their definitions in
5740     // Builtins.def to ensure they are correct before removing setType calls.
5741     QualType FnPtrTy = Context.getPointerType(FDecl->getType());
5742     Result = ImpCastExprToType(Fn, FnPtrTy, CK_BuiltinFnToFnPtr).get();
5743     ResultTy = FDecl->getCallResultType();
5744   } else {
5745     Result = CallExprUnaryConversions(Fn);
5746     ResultTy = Context.BoolTy;
5747   }
5748   if (Result.isInvalid())
5749     return ExprError();
5750   Fn = Result.get();
5751 
5752   // Check for a valid function type, but only if it is not a builtin which
5753   // requires custom type checking. These will be handled by
5754   // CheckBuiltinFunctionCall below just after creation of the call expression.
5755   const FunctionType *FuncT = nullptr;
5756   if (!BuiltinID || !Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
5757    retry:
5758     if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5759       // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5760       // have type pointer to function".
5761       FuncT = PT->getPointeeType()->getAs<FunctionType>();
5762       if (!FuncT)
5763         return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5764                            << Fn->getType() << Fn->getSourceRange());
5765     } else if (const BlockPointerType *BPT =
5766                  Fn->getType()->getAs<BlockPointerType>()) {
5767       FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5768     } else {
5769       // Handle calls to expressions of unknown-any type.
5770       if (Fn->getType() == Context.UnknownAnyTy) {
5771         ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5772         if (rewrite.isInvalid()) return ExprError();
5773         Fn = rewrite.get();
5774         goto retry;
5775       }
5776 
5777     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5778       << Fn->getType() << Fn->getSourceRange());
5779     }
5780   }
5781 
5782   // Get the number of parameters in the function prototype, if any.
5783   // We will allocate space for max(Args.size(), NumParams) arguments
5784   // in the call expression.
5785   const auto *Proto = dyn_cast_or_null<FunctionProtoType>(FuncT);
5786   unsigned NumParams = Proto ? Proto->getNumParams() : 0;
5787 
5788   CallExpr *TheCall;
5789   if (Config) {
5790     assert(UsesADL == ADLCallKind::NotADL &&
5791            "CUDAKernelCallExpr should not use ADL");
5792     TheCall =
5793         CUDAKernelCallExpr::Create(Context, Fn, cast<CallExpr>(Config), Args,
5794                                    ResultTy, VK_RValue, RParenLoc, NumParams);
5795   } else {
5796     TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5797                                RParenLoc, NumParams, UsesADL);
5798   }
5799 
5800   if (!getLangOpts().CPlusPlus) {
5801     // Forget about the nulled arguments since typo correction
5802     // do not handle them well.
5803     TheCall->shrinkNumArgs(Args.size());
5804     // C cannot always handle TypoExpr nodes in builtin calls and direct
5805     // function calls as their argument checking don't necessarily handle
5806     // dependent types properly, so make sure any TypoExprs have been
5807     // dealt with.
5808     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5809     if (!Result.isUsable()) return ExprError();
5810     CallExpr *TheOldCall = TheCall;
5811     TheCall = dyn_cast<CallExpr>(Result.get());
5812     bool CorrectedTypos = TheCall != TheOldCall;
5813     if (!TheCall) return Result;
5814     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5815 
5816     // A new call expression node was created if some typos were corrected.
5817     // However it may not have been constructed with enough storage. In this
5818     // case, rebuild the node with enough storage. The waste of space is
5819     // immaterial since this only happens when some typos were corrected.
5820     if (CorrectedTypos && Args.size() < NumParams) {
5821       if (Config)
5822         TheCall = CUDAKernelCallExpr::Create(
5823             Context, Fn, cast<CallExpr>(Config), Args, ResultTy, VK_RValue,
5824             RParenLoc, NumParams);
5825       else
5826         TheCall = CallExpr::Create(Context, Fn, Args, ResultTy, VK_RValue,
5827                                    RParenLoc, NumParams, UsesADL);
5828     }
5829     // We can now handle the nulled arguments for the default arguments.
5830     TheCall->setNumArgsUnsafe(std::max<unsigned>(Args.size(), NumParams));
5831   }
5832 
5833   // Bail out early if calling a builtin with custom type checking.
5834   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5835     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5836 
5837   if (getLangOpts().CUDA) {
5838     if (Config) {
5839       // CUDA: Kernel calls must be to global functions
5840       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5841         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5842             << FDecl << Fn->getSourceRange());
5843 
5844       // CUDA: Kernel function must have 'void' return type
5845       if (!FuncT->getReturnType()->isVoidType())
5846         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5847             << Fn->getType() << Fn->getSourceRange());
5848     } else {
5849       // CUDA: Calls to global functions must be configured
5850       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5851         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5852             << FDecl << Fn->getSourceRange());
5853     }
5854   }
5855 
5856   // Check for a valid return type
5857   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getBeginLoc(), TheCall,
5858                           FDecl))
5859     return ExprError();
5860 
5861   // We know the result type of the call, set it.
5862   TheCall->setType(FuncT->getCallResultType(Context));
5863   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5864 
5865   if (Proto) {
5866     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5867                                 IsExecConfig))
5868       return ExprError();
5869   } else {
5870     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5871 
5872     if (FDecl) {
5873       // Check if we have too few/too many template arguments, based
5874       // on our knowledge of the function definition.
5875       const FunctionDecl *Def = nullptr;
5876       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5877         Proto = Def->getType()->getAs<FunctionProtoType>();
5878        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5879           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5880           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5881       }
5882 
5883       // If the function we're calling isn't a function prototype, but we have
5884       // a function prototype from a prior declaratiom, use that prototype.
5885       if (!FDecl->hasPrototype())
5886         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5887     }
5888 
5889     // Promote the arguments (C99 6.5.2.2p6).
5890     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5891       Expr *Arg = Args[i];
5892 
5893       if (Proto && i < Proto->getNumParams()) {
5894         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5895             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5896         ExprResult ArgE =
5897             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5898         if (ArgE.isInvalid())
5899           return true;
5900 
5901         Arg = ArgE.getAs<Expr>();
5902 
5903       } else {
5904         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5905 
5906         if (ArgE.isInvalid())
5907           return true;
5908 
5909         Arg = ArgE.getAs<Expr>();
5910       }
5911 
5912       if (RequireCompleteType(Arg->getBeginLoc(), Arg->getType(),
5913                               diag::err_call_incomplete_argument, Arg))
5914         return ExprError();
5915 
5916       TheCall->setArg(i, Arg);
5917     }
5918   }
5919 
5920   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5921     if (!Method->isStatic())
5922       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5923         << Fn->getSourceRange());
5924 
5925   // Check for sentinels
5926   if (NDecl)
5927     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5928 
5929   // Do special checking on direct calls to functions.
5930   if (FDecl) {
5931     if (CheckFunctionCall(FDecl, TheCall, Proto))
5932       return ExprError();
5933 
5934     if (BuiltinID)
5935       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5936   } else if (NDecl) {
5937     if (CheckPointerCall(NDecl, TheCall, Proto))
5938       return ExprError();
5939   } else {
5940     if (CheckOtherCall(TheCall, Proto))
5941       return ExprError();
5942   }
5943 
5944   return MaybeBindToTemporary(TheCall);
5945 }
5946 
5947 ExprResult
5948 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5949                            SourceLocation RParenLoc, Expr *InitExpr) {
5950   assert(Ty && "ActOnCompoundLiteral(): missing type");
5951   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5952 
5953   TypeSourceInfo *TInfo;
5954   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5955   if (!TInfo)
5956     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5957 
5958   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5959 }
5960 
5961 ExprResult
5962 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5963                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5964   QualType literalType = TInfo->getType();
5965 
5966   if (literalType->isArrayType()) {
5967     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5968           diag::err_illegal_decl_array_incomplete_type,
5969           SourceRange(LParenLoc,
5970                       LiteralExpr->getSourceRange().getEnd())))
5971       return ExprError();
5972     if (literalType->isVariableArrayType())
5973       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5974         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5975   } else if (!literalType->isDependentType() &&
5976              RequireCompleteType(LParenLoc, literalType,
5977                diag::err_typecheck_decl_incomplete_type,
5978                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5979     return ExprError();
5980 
5981   InitializedEntity Entity
5982     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5983   InitializationKind Kind
5984     = InitializationKind::CreateCStyleCast(LParenLoc,
5985                                            SourceRange(LParenLoc, RParenLoc),
5986                                            /*InitList=*/true);
5987   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5988   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5989                                       &literalType);
5990   if (Result.isInvalid())
5991     return ExprError();
5992   LiteralExpr = Result.get();
5993 
5994   bool isFileScope = !CurContext->isFunctionOrMethod();
5995 
5996   // In C, compound literals are l-values for some reason.
5997   // For GCC compatibility, in C++, file-scope array compound literals with
5998   // constant initializers are also l-values, and compound literals are
5999   // otherwise prvalues.
6000   //
6001   // (GCC also treats C++ list-initialized file-scope array prvalues with
6002   // constant initializers as l-values, but that's non-conforming, so we don't
6003   // follow it there.)
6004   //
6005   // FIXME: It would be better to handle the lvalue cases as materializing and
6006   // lifetime-extending a temporary object, but our materialized temporaries
6007   // representation only supports lifetime extension from a variable, not "out
6008   // of thin air".
6009   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
6010   // is bound to the result of applying array-to-pointer decay to the compound
6011   // literal.
6012   // FIXME: GCC supports compound literals of reference type, which should
6013   // obviously have a value kind derived from the kind of reference involved.
6014   ExprValueKind VK =
6015       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
6016           ? VK_RValue
6017           : VK_LValue;
6018 
6019   if (isFileScope)
6020     if (auto ILE = dyn_cast<InitListExpr>(LiteralExpr))
6021       for (unsigned i = 0, j = ILE->getNumInits(); i != j; i++) {
6022         Expr *Init = ILE->getInit(i);
6023         ILE->setInit(i, ConstantExpr::Create(Context, Init));
6024       }
6025 
6026   Expr *E = new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
6027                                               VK, LiteralExpr, isFileScope);
6028   if (isFileScope) {
6029     if (!LiteralExpr->isTypeDependent() &&
6030         !LiteralExpr->isValueDependent() &&
6031         !literalType->isDependentType()) // C99 6.5.2.5p3
6032       if (CheckForConstantInitializer(LiteralExpr, literalType))
6033         return ExprError();
6034   } else if (literalType.getAddressSpace() != LangAS::opencl_private &&
6035              literalType.getAddressSpace() != LangAS::Default) {
6036     // Embedded-C extensions to C99 6.5.2.5:
6037     //   "If the compound literal occurs inside the body of a function, the
6038     //   type name shall not be qualified by an address-space qualifier."
6039     Diag(LParenLoc, diag::err_compound_literal_with_address_space)
6040       << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd());
6041     return ExprError();
6042   }
6043 
6044   return MaybeBindToTemporary(E);
6045 }
6046 
6047 ExprResult
6048 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
6049                     SourceLocation RBraceLoc) {
6050   // Immediately handle non-overload placeholders.  Overloads can be
6051   // resolved contextually, but everything else here can't.
6052   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
6053     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
6054       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
6055 
6056       // Ignore failures; dropping the entire initializer list because
6057       // of one failure would be terrible for indexing/etc.
6058       if (result.isInvalid()) continue;
6059 
6060       InitArgList[I] = result.get();
6061     }
6062   }
6063 
6064   // Semantic analysis for initializers is done by ActOnDeclarator() and
6065   // CheckInitializer() - it requires knowledge of the object being initialized.
6066 
6067   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
6068                                                RBraceLoc);
6069   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
6070   return E;
6071 }
6072 
6073 /// Do an explicit extend of the given block pointer if we're in ARC.
6074 void Sema::maybeExtendBlockObject(ExprResult &E) {
6075   assert(E.get()->getType()->isBlockPointerType());
6076   assert(E.get()->isRValue());
6077 
6078   // Only do this in an r-value context.
6079   if (!getLangOpts().ObjCAutoRefCount) return;
6080 
6081   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
6082                                CK_ARCExtendBlockObject, E.get(),
6083                                /*base path*/ nullptr, VK_RValue);
6084   Cleanup.setExprNeedsCleanups(true);
6085 }
6086 
6087 /// Prepare a conversion of the given expression to an ObjC object
6088 /// pointer type.
6089 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
6090   QualType type = E.get()->getType();
6091   if (type->isObjCObjectPointerType()) {
6092     return CK_BitCast;
6093   } else if (type->isBlockPointerType()) {
6094     maybeExtendBlockObject(E);
6095     return CK_BlockPointerToObjCPointerCast;
6096   } else {
6097     assert(type->isPointerType());
6098     return CK_CPointerToObjCPointerCast;
6099   }
6100 }
6101 
6102 /// Prepares for a scalar cast, performing all the necessary stages
6103 /// except the final cast and returning the kind required.
6104 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
6105   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
6106   // Also, callers should have filtered out the invalid cases with
6107   // pointers.  Everything else should be possible.
6108 
6109   QualType SrcTy = Src.get()->getType();
6110   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
6111     return CK_NoOp;
6112 
6113   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
6114   case Type::STK_MemberPointer:
6115     llvm_unreachable("member pointer type in C");
6116 
6117   case Type::STK_CPointer:
6118   case Type::STK_BlockPointer:
6119   case Type::STK_ObjCObjectPointer:
6120     switch (DestTy->getScalarTypeKind()) {
6121     case Type::STK_CPointer: {
6122       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
6123       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
6124       if (SrcAS != DestAS)
6125         return CK_AddressSpaceConversion;
6126       if (Context.hasCvrSimilarType(SrcTy, DestTy))
6127         return CK_NoOp;
6128       return CK_BitCast;
6129     }
6130     case Type::STK_BlockPointer:
6131       return (SrcKind == Type::STK_BlockPointer
6132                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
6133     case Type::STK_ObjCObjectPointer:
6134       if (SrcKind == Type::STK_ObjCObjectPointer)
6135         return CK_BitCast;
6136       if (SrcKind == Type::STK_CPointer)
6137         return CK_CPointerToObjCPointerCast;
6138       maybeExtendBlockObject(Src);
6139       return CK_BlockPointerToObjCPointerCast;
6140     case Type::STK_Bool:
6141       return CK_PointerToBoolean;
6142     case Type::STK_Integral:
6143       return CK_PointerToIntegral;
6144     case Type::STK_Floating:
6145     case Type::STK_FloatingComplex:
6146     case Type::STK_IntegralComplex:
6147     case Type::STK_MemberPointer:
6148     case Type::STK_FixedPoint:
6149       llvm_unreachable("illegal cast from pointer");
6150     }
6151     llvm_unreachable("Should have returned before this");
6152 
6153   case Type::STK_FixedPoint:
6154     switch (DestTy->getScalarTypeKind()) {
6155     case Type::STK_FixedPoint:
6156       return CK_FixedPointCast;
6157     case Type::STK_Bool:
6158       return CK_FixedPointToBoolean;
6159     case Type::STK_Integral:
6160       return CK_FixedPointToIntegral;
6161     case Type::STK_Floating:
6162     case Type::STK_IntegralComplex:
6163     case Type::STK_FloatingComplex:
6164       Diag(Src.get()->getExprLoc(),
6165            diag::err_unimplemented_conversion_with_fixed_point_type)
6166           << DestTy;
6167       return CK_IntegralCast;
6168     case Type::STK_CPointer:
6169     case Type::STK_ObjCObjectPointer:
6170     case Type::STK_BlockPointer:
6171     case Type::STK_MemberPointer:
6172       llvm_unreachable("illegal cast to pointer type");
6173     }
6174     llvm_unreachable("Should have returned before this");
6175 
6176   case Type::STK_Bool: // casting from bool is like casting from an integer
6177   case Type::STK_Integral:
6178     switch (DestTy->getScalarTypeKind()) {
6179     case Type::STK_CPointer:
6180     case Type::STK_ObjCObjectPointer:
6181     case Type::STK_BlockPointer:
6182       if (Src.get()->isNullPointerConstant(Context,
6183                                            Expr::NPC_ValueDependentIsNull))
6184         return CK_NullToPointer;
6185       return CK_IntegralToPointer;
6186     case Type::STK_Bool:
6187       return CK_IntegralToBoolean;
6188     case Type::STK_Integral:
6189       return CK_IntegralCast;
6190     case Type::STK_Floating:
6191       return CK_IntegralToFloating;
6192     case Type::STK_IntegralComplex:
6193       Src = ImpCastExprToType(Src.get(),
6194                       DestTy->castAs<ComplexType>()->getElementType(),
6195                       CK_IntegralCast);
6196       return CK_IntegralRealToComplex;
6197     case Type::STK_FloatingComplex:
6198       Src = ImpCastExprToType(Src.get(),
6199                       DestTy->castAs<ComplexType>()->getElementType(),
6200                       CK_IntegralToFloating);
6201       return CK_FloatingRealToComplex;
6202     case Type::STK_MemberPointer:
6203       llvm_unreachable("member pointer type in C");
6204     case Type::STK_FixedPoint:
6205       return CK_IntegralToFixedPoint;
6206     }
6207     llvm_unreachable("Should have returned before this");
6208 
6209   case Type::STK_Floating:
6210     switch (DestTy->getScalarTypeKind()) {
6211     case Type::STK_Floating:
6212       return CK_FloatingCast;
6213     case Type::STK_Bool:
6214       return CK_FloatingToBoolean;
6215     case Type::STK_Integral:
6216       return CK_FloatingToIntegral;
6217     case Type::STK_FloatingComplex:
6218       Src = ImpCastExprToType(Src.get(),
6219                               DestTy->castAs<ComplexType>()->getElementType(),
6220                               CK_FloatingCast);
6221       return CK_FloatingRealToComplex;
6222     case Type::STK_IntegralComplex:
6223       Src = ImpCastExprToType(Src.get(),
6224                               DestTy->castAs<ComplexType>()->getElementType(),
6225                               CK_FloatingToIntegral);
6226       return CK_IntegralRealToComplex;
6227     case Type::STK_CPointer:
6228     case Type::STK_ObjCObjectPointer:
6229     case Type::STK_BlockPointer:
6230       llvm_unreachable("valid float->pointer cast?");
6231     case Type::STK_MemberPointer:
6232       llvm_unreachable("member pointer type in C");
6233     case Type::STK_FixedPoint:
6234       Diag(Src.get()->getExprLoc(),
6235            diag::err_unimplemented_conversion_with_fixed_point_type)
6236           << SrcTy;
6237       return CK_IntegralCast;
6238     }
6239     llvm_unreachable("Should have returned before this");
6240 
6241   case Type::STK_FloatingComplex:
6242     switch (DestTy->getScalarTypeKind()) {
6243     case Type::STK_FloatingComplex:
6244       return CK_FloatingComplexCast;
6245     case Type::STK_IntegralComplex:
6246       return CK_FloatingComplexToIntegralComplex;
6247     case Type::STK_Floating: {
6248       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6249       if (Context.hasSameType(ET, DestTy))
6250         return CK_FloatingComplexToReal;
6251       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
6252       return CK_FloatingCast;
6253     }
6254     case Type::STK_Bool:
6255       return CK_FloatingComplexToBoolean;
6256     case Type::STK_Integral:
6257       Src = ImpCastExprToType(Src.get(),
6258                               SrcTy->castAs<ComplexType>()->getElementType(),
6259                               CK_FloatingComplexToReal);
6260       return CK_FloatingToIntegral;
6261     case Type::STK_CPointer:
6262     case Type::STK_ObjCObjectPointer:
6263     case Type::STK_BlockPointer:
6264       llvm_unreachable("valid complex float->pointer cast?");
6265     case Type::STK_MemberPointer:
6266       llvm_unreachable("member pointer type in C");
6267     case Type::STK_FixedPoint:
6268       Diag(Src.get()->getExprLoc(),
6269            diag::err_unimplemented_conversion_with_fixed_point_type)
6270           << SrcTy;
6271       return CK_IntegralCast;
6272     }
6273     llvm_unreachable("Should have returned before this");
6274 
6275   case Type::STK_IntegralComplex:
6276     switch (DestTy->getScalarTypeKind()) {
6277     case Type::STK_FloatingComplex:
6278       return CK_IntegralComplexToFloatingComplex;
6279     case Type::STK_IntegralComplex:
6280       return CK_IntegralComplexCast;
6281     case Type::STK_Integral: {
6282       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
6283       if (Context.hasSameType(ET, DestTy))
6284         return CK_IntegralComplexToReal;
6285       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
6286       return CK_IntegralCast;
6287     }
6288     case Type::STK_Bool:
6289       return CK_IntegralComplexToBoolean;
6290     case Type::STK_Floating:
6291       Src = ImpCastExprToType(Src.get(),
6292                               SrcTy->castAs<ComplexType>()->getElementType(),
6293                               CK_IntegralComplexToReal);
6294       return CK_IntegralToFloating;
6295     case Type::STK_CPointer:
6296     case Type::STK_ObjCObjectPointer:
6297     case Type::STK_BlockPointer:
6298       llvm_unreachable("valid complex int->pointer cast?");
6299     case Type::STK_MemberPointer:
6300       llvm_unreachable("member pointer type in C");
6301     case Type::STK_FixedPoint:
6302       Diag(Src.get()->getExprLoc(),
6303            diag::err_unimplemented_conversion_with_fixed_point_type)
6304           << SrcTy;
6305       return CK_IntegralCast;
6306     }
6307     llvm_unreachable("Should have returned before this");
6308   }
6309 
6310   llvm_unreachable("Unhandled scalar cast");
6311 }
6312 
6313 static bool breakDownVectorType(QualType type, uint64_t &len,
6314                                 QualType &eltType) {
6315   // Vectors are simple.
6316   if (const VectorType *vecType = type->getAs<VectorType>()) {
6317     len = vecType->getNumElements();
6318     eltType = vecType->getElementType();
6319     assert(eltType->isScalarType());
6320     return true;
6321   }
6322 
6323   // We allow lax conversion to and from non-vector types, but only if
6324   // they're real types (i.e. non-complex, non-pointer scalar types).
6325   if (!type->isRealType()) return false;
6326 
6327   len = 1;
6328   eltType = type;
6329   return true;
6330 }
6331 
6332 /// Are the two types lax-compatible vector types?  That is, given
6333 /// that one of them is a vector, do they have equal storage sizes,
6334 /// where the storage size is the number of elements times the element
6335 /// size?
6336 ///
6337 /// This will also return false if either of the types is neither a
6338 /// vector nor a real type.
6339 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
6340   assert(destTy->isVectorType() || srcTy->isVectorType());
6341 
6342   // Disallow lax conversions between scalars and ExtVectors (these
6343   // conversions are allowed for other vector types because common headers
6344   // depend on them).  Most scalar OP ExtVector cases are handled by the
6345   // splat path anyway, which does what we want (convert, not bitcast).
6346   // What this rules out for ExtVectors is crazy things like char4*float.
6347   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
6348   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
6349 
6350   uint64_t srcLen, destLen;
6351   QualType srcEltTy, destEltTy;
6352   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
6353   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
6354 
6355   // ASTContext::getTypeSize will return the size rounded up to a
6356   // power of 2, so instead of using that, we need to use the raw
6357   // element size multiplied by the element count.
6358   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
6359   uint64_t destEltSize = Context.getTypeSize(destEltTy);
6360 
6361   return (srcLen * srcEltSize == destLen * destEltSize);
6362 }
6363 
6364 /// Is this a legal conversion between two types, one of which is
6365 /// known to be a vector type?
6366 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
6367   assert(destTy->isVectorType() || srcTy->isVectorType());
6368 
6369   if (!Context.getLangOpts().LaxVectorConversions)
6370     return false;
6371   return areLaxCompatibleVectorTypes(srcTy, destTy);
6372 }
6373 
6374 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
6375                            CastKind &Kind) {
6376   assert(VectorTy->isVectorType() && "Not a vector type!");
6377 
6378   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6379     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6380       return Diag(R.getBegin(),
6381                   Ty->isVectorType() ?
6382                   diag::err_invalid_conversion_between_vectors :
6383                   diag::err_invalid_conversion_between_vector_and_integer)
6384         << VectorTy << Ty << R;
6385   } else
6386     return Diag(R.getBegin(),
6387                 diag::err_invalid_conversion_between_vector_and_scalar)
6388       << VectorTy << Ty << R;
6389 
6390   Kind = CK_BitCast;
6391   return false;
6392 }
6393 
6394 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6395   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6396 
6397   if (DestElemTy == SplattedExpr->getType())
6398     return SplattedExpr;
6399 
6400   assert(DestElemTy->isFloatingType() ||
6401          DestElemTy->isIntegralOrEnumerationType());
6402 
6403   CastKind CK;
6404   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6405     // OpenCL requires that we convert `true` boolean expressions to -1, but
6406     // only when splatting vectors.
6407     if (DestElemTy->isFloatingType()) {
6408       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6409       // in two steps: boolean to signed integral, then to floating.
6410       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6411                                                  CK_BooleanToSignedIntegral);
6412       SplattedExpr = CastExprRes.get();
6413       CK = CK_IntegralToFloating;
6414     } else {
6415       CK = CK_BooleanToSignedIntegral;
6416     }
6417   } else {
6418     ExprResult CastExprRes = SplattedExpr;
6419     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6420     if (CastExprRes.isInvalid())
6421       return ExprError();
6422     SplattedExpr = CastExprRes.get();
6423   }
6424   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6425 }
6426 
6427 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6428                                     Expr *CastExpr, CastKind &Kind) {
6429   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6430 
6431   QualType SrcTy = CastExpr->getType();
6432 
6433   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6434   // an ExtVectorType.
6435   // In OpenCL, casts between vectors of different types are not allowed.
6436   // (See OpenCL 6.2).
6437   if (SrcTy->isVectorType()) {
6438     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6439         (getLangOpts().OpenCL &&
6440          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6441       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6442         << DestTy << SrcTy << R;
6443       return ExprError();
6444     }
6445     Kind = CK_BitCast;
6446     return CastExpr;
6447   }
6448 
6449   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6450   // conversion will take place first from scalar to elt type, and then
6451   // splat from elt type to vector.
6452   if (SrcTy->isPointerType())
6453     return Diag(R.getBegin(),
6454                 diag::err_invalid_conversion_between_vector_and_scalar)
6455       << DestTy << SrcTy << R;
6456 
6457   Kind = CK_VectorSplat;
6458   return prepareVectorSplat(DestTy, CastExpr);
6459 }
6460 
6461 ExprResult
6462 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6463                     Declarator &D, ParsedType &Ty,
6464                     SourceLocation RParenLoc, Expr *CastExpr) {
6465   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6466          "ActOnCastExpr(): missing type or expr");
6467 
6468   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6469   if (D.isInvalidType())
6470     return ExprError();
6471 
6472   if (getLangOpts().CPlusPlus) {
6473     // Check that there are no default arguments (C++ only).
6474     CheckExtraCXXDefaultArguments(D);
6475   } else {
6476     // Make sure any TypoExprs have been dealt with.
6477     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6478     if (!Res.isUsable())
6479       return ExprError();
6480     CastExpr = Res.get();
6481   }
6482 
6483   checkUnusedDeclAttributes(D);
6484 
6485   QualType castType = castTInfo->getType();
6486   Ty = CreateParsedType(castType, castTInfo);
6487 
6488   bool isVectorLiteral = false;
6489 
6490   // Check for an altivec or OpenCL literal,
6491   // i.e. all the elements are integer constants.
6492   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6493   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6494   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6495        && castType->isVectorType() && (PE || PLE)) {
6496     if (PLE && PLE->getNumExprs() == 0) {
6497       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6498       return ExprError();
6499     }
6500     if (PE || PLE->getNumExprs() == 1) {
6501       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6502       if (!E->getType()->isVectorType())
6503         isVectorLiteral = true;
6504     }
6505     else
6506       isVectorLiteral = true;
6507   }
6508 
6509   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6510   // then handle it as such.
6511   if (isVectorLiteral)
6512     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6513 
6514   // If the Expr being casted is a ParenListExpr, handle it specially.
6515   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6516   // sequence of BinOp comma operators.
6517   if (isa<ParenListExpr>(CastExpr)) {
6518     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6519     if (Result.isInvalid()) return ExprError();
6520     CastExpr = Result.get();
6521   }
6522 
6523   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6524       !getSourceManager().isInSystemMacro(LParenLoc))
6525     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6526 
6527   CheckTollFreeBridgeCast(castType, CastExpr);
6528 
6529   CheckObjCBridgeRelatedCast(castType, CastExpr);
6530 
6531   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6532 
6533   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6534 }
6535 
6536 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6537                                     SourceLocation RParenLoc, Expr *E,
6538                                     TypeSourceInfo *TInfo) {
6539   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6540          "Expected paren or paren list expression");
6541 
6542   Expr **exprs;
6543   unsigned numExprs;
6544   Expr *subExpr;
6545   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6546   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6547     LiteralLParenLoc = PE->getLParenLoc();
6548     LiteralRParenLoc = PE->getRParenLoc();
6549     exprs = PE->getExprs();
6550     numExprs = PE->getNumExprs();
6551   } else { // isa<ParenExpr> by assertion at function entrance
6552     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6553     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6554     subExpr = cast<ParenExpr>(E)->getSubExpr();
6555     exprs = &subExpr;
6556     numExprs = 1;
6557   }
6558 
6559   QualType Ty = TInfo->getType();
6560   assert(Ty->isVectorType() && "Expected vector type");
6561 
6562   SmallVector<Expr *, 8> initExprs;
6563   const VectorType *VTy = Ty->getAs<VectorType>();
6564   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6565 
6566   // '(...)' form of vector initialization in AltiVec: the number of
6567   // initializers must be one or must match the size of the vector.
6568   // If a single value is specified in the initializer then it will be
6569   // replicated to all the components of the vector
6570   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6571     // The number of initializers must be one or must match the size of the
6572     // vector. If a single value is specified in the initializer then it will
6573     // be replicated to all the components of the vector
6574     if (numExprs == 1) {
6575       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6576       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6577       if (Literal.isInvalid())
6578         return ExprError();
6579       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6580                                   PrepareScalarCast(Literal, ElemTy));
6581       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6582     }
6583     else if (numExprs < numElems) {
6584       Diag(E->getExprLoc(),
6585            diag::err_incorrect_number_of_vector_initializers);
6586       return ExprError();
6587     }
6588     else
6589       initExprs.append(exprs, exprs + numExprs);
6590   }
6591   else {
6592     // For OpenCL, when the number of initializers is a single value,
6593     // it will be replicated to all components of the vector.
6594     if (getLangOpts().OpenCL &&
6595         VTy->getVectorKind() == VectorType::GenericVector &&
6596         numExprs == 1) {
6597         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6598         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6599         if (Literal.isInvalid())
6600           return ExprError();
6601         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6602                                     PrepareScalarCast(Literal, ElemTy));
6603         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6604     }
6605 
6606     initExprs.append(exprs, exprs + numExprs);
6607   }
6608   // FIXME: This means that pretty-printing the final AST will produce curly
6609   // braces instead of the original commas.
6610   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6611                                                    initExprs, LiteralRParenLoc);
6612   initE->setType(Ty);
6613   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6614 }
6615 
6616 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6617 /// the ParenListExpr into a sequence of comma binary operators.
6618 ExprResult
6619 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6620   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6621   if (!E)
6622     return OrigExpr;
6623 
6624   ExprResult Result(E->getExpr(0));
6625 
6626   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6627     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6628                         E->getExpr(i));
6629 
6630   if (Result.isInvalid()) return ExprError();
6631 
6632   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6633 }
6634 
6635 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6636                                     SourceLocation R,
6637                                     MultiExprArg Val) {
6638   return ParenListExpr::Create(Context, L, Val, R);
6639 }
6640 
6641 /// Emit a specialized diagnostic when one expression is a null pointer
6642 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6643 /// emitted.
6644 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6645                                       SourceLocation QuestionLoc) {
6646   Expr *NullExpr = LHSExpr;
6647   Expr *NonPointerExpr = RHSExpr;
6648   Expr::NullPointerConstantKind NullKind =
6649       NullExpr->isNullPointerConstant(Context,
6650                                       Expr::NPC_ValueDependentIsNotNull);
6651 
6652   if (NullKind == Expr::NPCK_NotNull) {
6653     NullExpr = RHSExpr;
6654     NonPointerExpr = LHSExpr;
6655     NullKind =
6656         NullExpr->isNullPointerConstant(Context,
6657                                         Expr::NPC_ValueDependentIsNotNull);
6658   }
6659 
6660   if (NullKind == Expr::NPCK_NotNull)
6661     return false;
6662 
6663   if (NullKind == Expr::NPCK_ZeroExpression)
6664     return false;
6665 
6666   if (NullKind == Expr::NPCK_ZeroLiteral) {
6667     // In this case, check to make sure that we got here from a "NULL"
6668     // string in the source code.
6669     NullExpr = NullExpr->IgnoreParenImpCasts();
6670     SourceLocation loc = NullExpr->getExprLoc();
6671     if (!findMacroSpelling(loc, "NULL"))
6672       return false;
6673   }
6674 
6675   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6676   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6677       << NonPointerExpr->getType() << DiagType
6678       << NonPointerExpr->getSourceRange();
6679   return true;
6680 }
6681 
6682 /// Return false if the condition expression is valid, true otherwise.
6683 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6684   QualType CondTy = Cond->getType();
6685 
6686   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6687   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6688     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6689       << CondTy << Cond->getSourceRange();
6690     return true;
6691   }
6692 
6693   // C99 6.5.15p2
6694   if (CondTy->isScalarType()) return false;
6695 
6696   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6697     << CondTy << Cond->getSourceRange();
6698   return true;
6699 }
6700 
6701 /// Handle when one or both operands are void type.
6702 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6703                                          ExprResult &RHS) {
6704     Expr *LHSExpr = LHS.get();
6705     Expr *RHSExpr = RHS.get();
6706 
6707     if (!LHSExpr->getType()->isVoidType())
6708       S.Diag(RHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6709           << RHSExpr->getSourceRange();
6710     if (!RHSExpr->getType()->isVoidType())
6711       S.Diag(LHSExpr->getBeginLoc(), diag::ext_typecheck_cond_one_void)
6712           << LHSExpr->getSourceRange();
6713     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6714     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6715     return S.Context.VoidTy;
6716 }
6717 
6718 /// Return false if the NullExpr can be promoted to PointerTy,
6719 /// true otherwise.
6720 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6721                                         QualType PointerTy) {
6722   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6723       !NullExpr.get()->isNullPointerConstant(S.Context,
6724                                             Expr::NPC_ValueDependentIsNull))
6725     return true;
6726 
6727   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6728   return false;
6729 }
6730 
6731 /// Checks compatibility between two pointers and return the resulting
6732 /// type.
6733 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6734                                                      ExprResult &RHS,
6735                                                      SourceLocation Loc) {
6736   QualType LHSTy = LHS.get()->getType();
6737   QualType RHSTy = RHS.get()->getType();
6738 
6739   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6740     // Two identical pointers types are always compatible.
6741     return LHSTy;
6742   }
6743 
6744   QualType lhptee, rhptee;
6745 
6746   // Get the pointee types.
6747   bool IsBlockPointer = false;
6748   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6749     lhptee = LHSBTy->getPointeeType();
6750     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6751     IsBlockPointer = true;
6752   } else {
6753     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6754     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6755   }
6756 
6757   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6758   // differently qualified versions of compatible types, the result type is
6759   // a pointer to an appropriately qualified version of the composite
6760   // type.
6761 
6762   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6763   // clause doesn't make sense for our extensions. E.g. address space 2 should
6764   // be incompatible with address space 3: they may live on different devices or
6765   // anything.
6766   Qualifiers lhQual = lhptee.getQualifiers();
6767   Qualifiers rhQual = rhptee.getQualifiers();
6768 
6769   LangAS ResultAddrSpace = LangAS::Default;
6770   LangAS LAddrSpace = lhQual.getAddressSpace();
6771   LangAS RAddrSpace = rhQual.getAddressSpace();
6772 
6773   // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6774   // spaces is disallowed.
6775   if (lhQual.isAddressSpaceSupersetOf(rhQual))
6776     ResultAddrSpace = LAddrSpace;
6777   else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6778     ResultAddrSpace = RAddrSpace;
6779   else {
6780     S.Diag(Loc, diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6781         << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6782         << RHS.get()->getSourceRange();
6783     return QualType();
6784   }
6785 
6786   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6787   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6788   lhQual.removeCVRQualifiers();
6789   rhQual.removeCVRQualifiers();
6790 
6791   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6792   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6793   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6794   // qual types are compatible iff
6795   //  * corresponded types are compatible
6796   //  * CVR qualifiers are equal
6797   //  * address spaces are equal
6798   // Thus for conditional operator we merge CVR and address space unqualified
6799   // pointees and if there is a composite type we return a pointer to it with
6800   // merged qualifiers.
6801   LHSCastKind =
6802       LAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6803   RHSCastKind =
6804       RAddrSpace == ResultAddrSpace ? CK_BitCast : CK_AddressSpaceConversion;
6805   lhQual.removeAddressSpace();
6806   rhQual.removeAddressSpace();
6807 
6808   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6809   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6810 
6811   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6812 
6813   if (CompositeTy.isNull()) {
6814     // In this situation, we assume void* type. No especially good
6815     // reason, but this is what gcc does, and we do have to pick
6816     // to get a consistent AST.
6817     QualType incompatTy;
6818     incompatTy = S.Context.getPointerType(
6819         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6820     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6821     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6822 
6823     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6824     // for casts between types with incompatible address space qualifiers.
6825     // For the following code the compiler produces casts between global and
6826     // local address spaces of the corresponded innermost pointees:
6827     // local int *global *a;
6828     // global int *global *b;
6829     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6830     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6831         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6832         << RHS.get()->getSourceRange();
6833 
6834     return incompatTy;
6835   }
6836 
6837   // The pointer types are compatible.
6838   // In case of OpenCL ResultTy should have the address space qualifier
6839   // which is a superset of address spaces of both the 2nd and the 3rd
6840   // operands of the conditional operator.
6841   QualType ResultTy = [&, ResultAddrSpace]() {
6842     if (S.getLangOpts().OpenCL) {
6843       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6844       CompositeQuals.setAddressSpace(ResultAddrSpace);
6845       return S.Context
6846           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6847           .withCVRQualifiers(MergedCVRQual);
6848     }
6849     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6850   }();
6851   if (IsBlockPointer)
6852     ResultTy = S.Context.getBlockPointerType(ResultTy);
6853   else
6854     ResultTy = S.Context.getPointerType(ResultTy);
6855 
6856   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6857   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6858   return ResultTy;
6859 }
6860 
6861 /// Return the resulting type when the operands are both block pointers.
6862 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6863                                                           ExprResult &LHS,
6864                                                           ExprResult &RHS,
6865                                                           SourceLocation Loc) {
6866   QualType LHSTy = LHS.get()->getType();
6867   QualType RHSTy = RHS.get()->getType();
6868 
6869   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6870     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6871       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6872       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6873       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6874       return destType;
6875     }
6876     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6877       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6878       << RHS.get()->getSourceRange();
6879     return QualType();
6880   }
6881 
6882   // We have 2 block pointer types.
6883   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6884 }
6885 
6886 /// Return the resulting type when the operands are both pointers.
6887 static QualType
6888 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6889                                             ExprResult &RHS,
6890                                             SourceLocation Loc) {
6891   // get the pointer types
6892   QualType LHSTy = LHS.get()->getType();
6893   QualType RHSTy = RHS.get()->getType();
6894 
6895   // get the "pointed to" types
6896   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6897   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6898 
6899   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6900   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6901     // Figure out necessary qualifiers (C99 6.5.15p6)
6902     QualType destPointee
6903       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6904     QualType destType = S.Context.getPointerType(destPointee);
6905     // Add qualifiers if necessary.
6906     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6907     // Promote to void*.
6908     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6909     return destType;
6910   }
6911   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6912     QualType destPointee
6913       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6914     QualType destType = S.Context.getPointerType(destPointee);
6915     // Add qualifiers if necessary.
6916     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6917     // Promote to void*.
6918     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6919     return destType;
6920   }
6921 
6922   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6923 }
6924 
6925 /// Return false if the first expression is not an integer and the second
6926 /// expression is not a pointer, true otherwise.
6927 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6928                                         Expr* PointerExpr, SourceLocation Loc,
6929                                         bool IsIntFirstExpr) {
6930   if (!PointerExpr->getType()->isPointerType() ||
6931       !Int.get()->getType()->isIntegerType())
6932     return false;
6933 
6934   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6935   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6936 
6937   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6938     << Expr1->getType() << Expr2->getType()
6939     << Expr1->getSourceRange() << Expr2->getSourceRange();
6940   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6941                             CK_IntegralToPointer);
6942   return true;
6943 }
6944 
6945 /// Simple conversion between integer and floating point types.
6946 ///
6947 /// Used when handling the OpenCL conditional operator where the
6948 /// condition is a vector while the other operands are scalar.
6949 ///
6950 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6951 /// types are either integer or floating type. Between the two
6952 /// operands, the type with the higher rank is defined as the "result
6953 /// type". The other operand needs to be promoted to the same type. No
6954 /// other type promotion is allowed. We cannot use
6955 /// UsualArithmeticConversions() for this purpose, since it always
6956 /// promotes promotable types.
6957 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6958                                             ExprResult &RHS,
6959                                             SourceLocation QuestionLoc) {
6960   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6961   if (LHS.isInvalid())
6962     return QualType();
6963   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6964   if (RHS.isInvalid())
6965     return QualType();
6966 
6967   // For conversion purposes, we ignore any qualifiers.
6968   // For example, "const float" and "float" are equivalent.
6969   QualType LHSType =
6970     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6971   QualType RHSType =
6972     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6973 
6974   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6975     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6976       << LHSType << LHS.get()->getSourceRange();
6977     return QualType();
6978   }
6979 
6980   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6981     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6982       << RHSType << RHS.get()->getSourceRange();
6983     return QualType();
6984   }
6985 
6986   // If both types are identical, no conversion is needed.
6987   if (LHSType == RHSType)
6988     return LHSType;
6989 
6990   // Now handle "real" floating types (i.e. float, double, long double).
6991   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6992     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6993                                  /*IsCompAssign = */ false);
6994 
6995   // Finally, we have two differing integer types.
6996   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6997   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6998 }
6999 
7000 /// Convert scalar operands to a vector that matches the
7001 ///        condition in length.
7002 ///
7003 /// Used when handling the OpenCL conditional operator where the
7004 /// condition is a vector while the other operands are scalar.
7005 ///
7006 /// We first compute the "result type" for the scalar operands
7007 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
7008 /// into a vector of that type where the length matches the condition
7009 /// vector type. s6.11.6 requires that the element types of the result
7010 /// and the condition must have the same number of bits.
7011 static QualType
7012 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
7013                               QualType CondTy, SourceLocation QuestionLoc) {
7014   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
7015   if (ResTy.isNull()) return QualType();
7016 
7017   const VectorType *CV = CondTy->getAs<VectorType>();
7018   assert(CV);
7019 
7020   // Determine the vector result type
7021   unsigned NumElements = CV->getNumElements();
7022   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
7023 
7024   // Ensure that all types have the same number of bits
7025   if (S.Context.getTypeSize(CV->getElementType())
7026       != S.Context.getTypeSize(ResTy)) {
7027     // Since VectorTy is created internally, it does not pretty print
7028     // with an OpenCL name. Instead, we just print a description.
7029     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
7030     SmallString<64> Str;
7031     llvm::raw_svector_ostream OS(Str);
7032     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
7033     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7034       << CondTy << OS.str();
7035     return QualType();
7036   }
7037 
7038   // Convert operands to the vector result type
7039   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
7040   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
7041 
7042   return VectorTy;
7043 }
7044 
7045 /// Return false if this is a valid OpenCL condition vector
7046 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
7047                                        SourceLocation QuestionLoc) {
7048   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
7049   // integral type.
7050   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
7051   assert(CondTy);
7052   QualType EleTy = CondTy->getElementType();
7053   if (EleTy->isIntegerType()) return false;
7054 
7055   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
7056     << Cond->getType() << Cond->getSourceRange();
7057   return true;
7058 }
7059 
7060 /// Return false if the vector condition type and the vector
7061 ///        result type are compatible.
7062 ///
7063 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
7064 /// number of elements, and their element types have the same number
7065 /// of bits.
7066 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
7067                               SourceLocation QuestionLoc) {
7068   const VectorType *CV = CondTy->getAs<VectorType>();
7069   const VectorType *RV = VecResTy->getAs<VectorType>();
7070   assert(CV && RV);
7071 
7072   if (CV->getNumElements() != RV->getNumElements()) {
7073     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
7074       << CondTy << VecResTy;
7075     return true;
7076   }
7077 
7078   QualType CVE = CV->getElementType();
7079   QualType RVE = RV->getElementType();
7080 
7081   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
7082     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
7083       << CondTy << VecResTy;
7084     return true;
7085   }
7086 
7087   return false;
7088 }
7089 
7090 /// Return the resulting type for the conditional operator in
7091 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
7092 ///        s6.3.i) when the condition is a vector type.
7093 static QualType
7094 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
7095                              ExprResult &LHS, ExprResult &RHS,
7096                              SourceLocation QuestionLoc) {
7097   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
7098   if (Cond.isInvalid())
7099     return QualType();
7100   QualType CondTy = Cond.get()->getType();
7101 
7102   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
7103     return QualType();
7104 
7105   // If either operand is a vector then find the vector type of the
7106   // result as specified in OpenCL v1.1 s6.3.i.
7107   if (LHS.get()->getType()->isVectorType() ||
7108       RHS.get()->getType()->isVectorType()) {
7109     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
7110                                               /*isCompAssign*/false,
7111                                               /*AllowBothBool*/true,
7112                                               /*AllowBoolConversions*/false);
7113     if (VecResTy.isNull()) return QualType();
7114     // The result type must match the condition type as specified in
7115     // OpenCL v1.1 s6.11.6.
7116     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
7117       return QualType();
7118     return VecResTy;
7119   }
7120 
7121   // Both operands are scalar.
7122   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
7123 }
7124 
7125 /// Return true if the Expr is block type
7126 static bool checkBlockType(Sema &S, const Expr *E) {
7127   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7128     QualType Ty = CE->getCallee()->getType();
7129     if (Ty->isBlockPointerType()) {
7130       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
7131       return true;
7132     }
7133   }
7134   return false;
7135 }
7136 
7137 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
7138 /// In that case, LHS = cond.
7139 /// C99 6.5.15
7140 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
7141                                         ExprResult &RHS, ExprValueKind &VK,
7142                                         ExprObjectKind &OK,
7143                                         SourceLocation QuestionLoc) {
7144 
7145   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
7146   if (!LHSResult.isUsable()) return QualType();
7147   LHS = LHSResult;
7148 
7149   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
7150   if (!RHSResult.isUsable()) return QualType();
7151   RHS = RHSResult;
7152 
7153   // C++ is sufficiently different to merit its own checker.
7154   if (getLangOpts().CPlusPlus)
7155     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
7156 
7157   VK = VK_RValue;
7158   OK = OK_Ordinary;
7159 
7160   // The OpenCL operator with a vector condition is sufficiently
7161   // different to merit its own checker.
7162   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
7163     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
7164 
7165   // First, check the condition.
7166   Cond = UsualUnaryConversions(Cond.get());
7167   if (Cond.isInvalid())
7168     return QualType();
7169   if (checkCondition(*this, Cond.get(), QuestionLoc))
7170     return QualType();
7171 
7172   // Now check the two expressions.
7173   if (LHS.get()->getType()->isVectorType() ||
7174       RHS.get()->getType()->isVectorType())
7175     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
7176                                /*AllowBothBool*/true,
7177                                /*AllowBoolConversions*/false);
7178 
7179   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
7180   if (LHS.isInvalid() || RHS.isInvalid())
7181     return QualType();
7182 
7183   QualType LHSTy = LHS.get()->getType();
7184   QualType RHSTy = RHS.get()->getType();
7185 
7186   // Diagnose attempts to convert between __float128 and long double where
7187   // such conversions currently can't be handled.
7188   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
7189     Diag(QuestionLoc,
7190          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
7191       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7192     return QualType();
7193   }
7194 
7195   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
7196   // selection operator (?:).
7197   if (getLangOpts().OpenCL &&
7198       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
7199     return QualType();
7200   }
7201 
7202   // If both operands have arithmetic type, do the usual arithmetic conversions
7203   // to find a common type: C99 6.5.15p3,5.
7204   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
7205     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
7206     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
7207 
7208     return ResTy;
7209   }
7210 
7211   // If both operands are the same structure or union type, the result is that
7212   // type.
7213   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
7214     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
7215       if (LHSRT->getDecl() == RHSRT->getDecl())
7216         // "If both the operands have structure or union type, the result has
7217         // that type."  This implies that CV qualifiers are dropped.
7218         return LHSTy.getUnqualifiedType();
7219     // FIXME: Type of conditional expression must be complete in C mode.
7220   }
7221 
7222   // C99 6.5.15p5: "If both operands have void type, the result has void type."
7223   // The following || allows only one side to be void (a GCC-ism).
7224   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
7225     return checkConditionalVoidType(*this, LHS, RHS);
7226   }
7227 
7228   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
7229   // the type of the other operand."
7230   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
7231   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
7232 
7233   // All objective-c pointer type analysis is done here.
7234   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
7235                                                         QuestionLoc);
7236   if (LHS.isInvalid() || RHS.isInvalid())
7237     return QualType();
7238   if (!compositeType.isNull())
7239     return compositeType;
7240 
7241 
7242   // Handle block pointer types.
7243   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
7244     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
7245                                                      QuestionLoc);
7246 
7247   // Check constraints for C object pointers types (C99 6.5.15p3,6).
7248   if (LHSTy->isPointerType() && RHSTy->isPointerType())
7249     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
7250                                                        QuestionLoc);
7251 
7252   // GCC compatibility: soften pointer/integer mismatch.  Note that
7253   // null pointers have been filtered out by this point.
7254   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
7255       /*isIntFirstExpr=*/true))
7256     return RHSTy;
7257   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
7258       /*isIntFirstExpr=*/false))
7259     return LHSTy;
7260 
7261   // Emit a better diagnostic if one of the expressions is a null pointer
7262   // constant and the other is not a pointer type. In this case, the user most
7263   // likely forgot to take the address of the other expression.
7264   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
7265     return QualType();
7266 
7267   // Otherwise, the operands are not compatible.
7268   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
7269     << LHSTy << RHSTy << LHS.get()->getSourceRange()
7270     << RHS.get()->getSourceRange();
7271   return QualType();
7272 }
7273 
7274 /// FindCompositeObjCPointerType - Helper method to find composite type of
7275 /// two objective-c pointer types of the two input expressions.
7276 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
7277                                             SourceLocation QuestionLoc) {
7278   QualType LHSTy = LHS.get()->getType();
7279   QualType RHSTy = RHS.get()->getType();
7280 
7281   // Handle things like Class and struct objc_class*.  Here we case the result
7282   // to the pseudo-builtin, because that will be implicitly cast back to the
7283   // redefinition type if an attempt is made to access its fields.
7284   if (LHSTy->isObjCClassType() &&
7285       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
7286     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7287     return LHSTy;
7288   }
7289   if (RHSTy->isObjCClassType() &&
7290       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
7291     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7292     return RHSTy;
7293   }
7294   // And the same for struct objc_object* / id
7295   if (LHSTy->isObjCIdType() &&
7296       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
7297     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
7298     return LHSTy;
7299   }
7300   if (RHSTy->isObjCIdType() &&
7301       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
7302     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
7303     return RHSTy;
7304   }
7305   // And the same for struct objc_selector* / SEL
7306   if (Context.isObjCSelType(LHSTy) &&
7307       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
7308     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
7309     return LHSTy;
7310   }
7311   if (Context.isObjCSelType(RHSTy) &&
7312       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
7313     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
7314     return RHSTy;
7315   }
7316   // Check constraints for Objective-C object pointers types.
7317   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
7318 
7319     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
7320       // Two identical object pointer types are always compatible.
7321       return LHSTy;
7322     }
7323     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
7324     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
7325     QualType compositeType = LHSTy;
7326 
7327     // If both operands are interfaces and either operand can be
7328     // assigned to the other, use that type as the composite
7329     // type. This allows
7330     //   xxx ? (A*) a : (B*) b
7331     // where B is a subclass of A.
7332     //
7333     // Additionally, as for assignment, if either type is 'id'
7334     // allow silent coercion. Finally, if the types are
7335     // incompatible then make sure to use 'id' as the composite
7336     // type so the result is acceptable for sending messages to.
7337 
7338     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
7339     // It could return the composite type.
7340     if (!(compositeType =
7341           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
7342       // Nothing more to do.
7343     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
7344       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
7345     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
7346       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
7347     } else if ((LHSTy->isObjCQualifiedIdType() ||
7348                 RHSTy->isObjCQualifiedIdType()) &&
7349                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
7350       // Need to handle "id<xx>" explicitly.
7351       // GCC allows qualified id and any Objective-C type to devolve to
7352       // id. Currently localizing to here until clear this should be
7353       // part of ObjCQualifiedIdTypesAreCompatible.
7354       compositeType = Context.getObjCIdType();
7355     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
7356       compositeType = Context.getObjCIdType();
7357     } else {
7358       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
7359       << LHSTy << RHSTy
7360       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7361       QualType incompatTy = Context.getObjCIdType();
7362       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
7363       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
7364       return incompatTy;
7365     }
7366     // The object pointer types are compatible.
7367     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
7368     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
7369     return compositeType;
7370   }
7371   // Check Objective-C object pointer types and 'void *'
7372   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
7373     if (getLangOpts().ObjCAutoRefCount) {
7374       // ARC forbids the implicit conversion of object pointers to 'void *',
7375       // so these types are not compatible.
7376       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7377           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7378       LHS = RHS = true;
7379       return QualType();
7380     }
7381     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7382     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7383     QualType destPointee
7384     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7385     QualType destType = Context.getPointerType(destPointee);
7386     // Add qualifiers if necessary.
7387     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7388     // Promote to void*.
7389     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7390     return destType;
7391   }
7392   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7393     if (getLangOpts().ObjCAutoRefCount) {
7394       // ARC forbids the implicit conversion of object pointers to 'void *',
7395       // so these types are not compatible.
7396       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7397           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7398       LHS = RHS = true;
7399       return QualType();
7400     }
7401     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7402     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7403     QualType destPointee
7404     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7405     QualType destType = Context.getPointerType(destPointee);
7406     // Add qualifiers if necessary.
7407     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7408     // Promote to void*.
7409     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7410     return destType;
7411   }
7412   return QualType();
7413 }
7414 
7415 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7416 /// ParenRange in parentheses.
7417 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7418                                const PartialDiagnostic &Note,
7419                                SourceRange ParenRange) {
7420   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7421   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7422       EndLoc.isValid()) {
7423     Self.Diag(Loc, Note)
7424       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7425       << FixItHint::CreateInsertion(EndLoc, ")");
7426   } else {
7427     // We can't display the parentheses, so just show the bare note.
7428     Self.Diag(Loc, Note) << ParenRange;
7429   }
7430 }
7431 
7432 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7433   return BinaryOperator::isAdditiveOp(Opc) ||
7434          BinaryOperator::isMultiplicativeOp(Opc) ||
7435          BinaryOperator::isShiftOp(Opc);
7436 }
7437 
7438 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7439 /// expression, either using a built-in or overloaded operator,
7440 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7441 /// expression.
7442 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7443                                    Expr **RHSExprs) {
7444   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7445   E = E->IgnoreImpCasts();
7446   E = E->IgnoreConversionOperator();
7447   E = E->IgnoreImpCasts();
7448   if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
7449     E = MTE->GetTemporaryExpr();
7450     E = E->IgnoreImpCasts();
7451   }
7452 
7453   // Built-in binary operator.
7454   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7455     if (IsArithmeticOp(OP->getOpcode())) {
7456       *Opcode = OP->getOpcode();
7457       *RHSExprs = OP->getRHS();
7458       return true;
7459     }
7460   }
7461 
7462   // Overloaded operator.
7463   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7464     if (Call->getNumArgs() != 2)
7465       return false;
7466 
7467     // Make sure this is really a binary operator that is safe to pass into
7468     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7469     OverloadedOperatorKind OO = Call->getOperator();
7470     if (OO < OO_Plus || OO > OO_Arrow ||
7471         OO == OO_PlusPlus || OO == OO_MinusMinus)
7472       return false;
7473 
7474     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7475     if (IsArithmeticOp(OpKind)) {
7476       *Opcode = OpKind;
7477       *RHSExprs = Call->getArg(1);
7478       return true;
7479     }
7480   }
7481 
7482   return false;
7483 }
7484 
7485 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7486 /// or is a logical expression such as (x==y) which has int type, but is
7487 /// commonly interpreted as boolean.
7488 static bool ExprLooksBoolean(Expr *E) {
7489   E = E->IgnoreParenImpCasts();
7490 
7491   if (E->getType()->isBooleanType())
7492     return true;
7493   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7494     return OP->isComparisonOp() || OP->isLogicalOp();
7495   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7496     return OP->getOpcode() == UO_LNot;
7497   if (E->getType()->isPointerType())
7498     return true;
7499   // FIXME: What about overloaded operator calls returning "unspecified boolean
7500   // type"s (commonly pointer-to-members)?
7501 
7502   return false;
7503 }
7504 
7505 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7506 /// and binary operator are mixed in a way that suggests the programmer assumed
7507 /// the conditional operator has higher precedence, for example:
7508 /// "int x = a + someBinaryCondition ? 1 : 2".
7509 static void DiagnoseConditionalPrecedence(Sema &Self,
7510                                           SourceLocation OpLoc,
7511                                           Expr *Condition,
7512                                           Expr *LHSExpr,
7513                                           Expr *RHSExpr) {
7514   BinaryOperatorKind CondOpcode;
7515   Expr *CondRHS;
7516 
7517   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7518     return;
7519   if (!ExprLooksBoolean(CondRHS))
7520     return;
7521 
7522   // The condition is an arithmetic binary expression, with a right-
7523   // hand side that looks boolean, so warn.
7524 
7525   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7526       << Condition->getSourceRange()
7527       << BinaryOperator::getOpcodeStr(CondOpcode);
7528 
7529   SuggestParentheses(
7530       Self, OpLoc,
7531       Self.PDiag(diag::note_precedence_silence)
7532           << BinaryOperator::getOpcodeStr(CondOpcode),
7533       SourceRange(Condition->getBeginLoc(), Condition->getEndLoc()));
7534 
7535   SuggestParentheses(Self, OpLoc,
7536                      Self.PDiag(diag::note_precedence_conditional_first),
7537                      SourceRange(CondRHS->getBeginLoc(), RHSExpr->getEndLoc()));
7538 }
7539 
7540 /// Compute the nullability of a conditional expression.
7541 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7542                                               QualType LHSTy, QualType RHSTy,
7543                                               ASTContext &Ctx) {
7544   if (!ResTy->isAnyPointerType())
7545     return ResTy;
7546 
7547   auto GetNullability = [&Ctx](QualType Ty) {
7548     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7549     if (Kind)
7550       return *Kind;
7551     return NullabilityKind::Unspecified;
7552   };
7553 
7554   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7555   NullabilityKind MergedKind;
7556 
7557   // Compute nullability of a binary conditional expression.
7558   if (IsBin) {
7559     if (LHSKind == NullabilityKind::NonNull)
7560       MergedKind = NullabilityKind::NonNull;
7561     else
7562       MergedKind = RHSKind;
7563   // Compute nullability of a normal conditional expression.
7564   } else {
7565     if (LHSKind == NullabilityKind::Nullable ||
7566         RHSKind == NullabilityKind::Nullable)
7567       MergedKind = NullabilityKind::Nullable;
7568     else if (LHSKind == NullabilityKind::NonNull)
7569       MergedKind = RHSKind;
7570     else if (RHSKind == NullabilityKind::NonNull)
7571       MergedKind = LHSKind;
7572     else
7573       MergedKind = NullabilityKind::Unspecified;
7574   }
7575 
7576   // Return if ResTy already has the correct nullability.
7577   if (GetNullability(ResTy) == MergedKind)
7578     return ResTy;
7579 
7580   // Strip all nullability from ResTy.
7581   while (ResTy->getNullability(Ctx))
7582     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7583 
7584   // Create a new AttributedType with the new nullability kind.
7585   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7586   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7587 }
7588 
7589 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7590 /// in the case of a the GNU conditional expr extension.
7591 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7592                                     SourceLocation ColonLoc,
7593                                     Expr *CondExpr, Expr *LHSExpr,
7594                                     Expr *RHSExpr) {
7595   if (!getLangOpts().CPlusPlus) {
7596     // C cannot handle TypoExpr nodes in the condition because it
7597     // doesn't handle dependent types properly, so make sure any TypoExprs have
7598     // been dealt with before checking the operands.
7599     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7600     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7601     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7602 
7603     if (!CondResult.isUsable())
7604       return ExprError();
7605 
7606     if (LHSExpr) {
7607       if (!LHSResult.isUsable())
7608         return ExprError();
7609     }
7610 
7611     if (!RHSResult.isUsable())
7612       return ExprError();
7613 
7614     CondExpr = CondResult.get();
7615     LHSExpr = LHSResult.get();
7616     RHSExpr = RHSResult.get();
7617   }
7618 
7619   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7620   // was the condition.
7621   OpaqueValueExpr *opaqueValue = nullptr;
7622   Expr *commonExpr = nullptr;
7623   if (!LHSExpr) {
7624     commonExpr = CondExpr;
7625     // Lower out placeholder types first.  This is important so that we don't
7626     // try to capture a placeholder. This happens in few cases in C++; such
7627     // as Objective-C++'s dictionary subscripting syntax.
7628     if (commonExpr->hasPlaceholderType()) {
7629       ExprResult result = CheckPlaceholderExpr(commonExpr);
7630       if (!result.isUsable()) return ExprError();
7631       commonExpr = result.get();
7632     }
7633     // We usually want to apply unary conversions *before* saving, except
7634     // in the special case of a C++ l-value conditional.
7635     if (!(getLangOpts().CPlusPlus
7636           && !commonExpr->isTypeDependent()
7637           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7638           && commonExpr->isGLValue()
7639           && commonExpr->isOrdinaryOrBitFieldObject()
7640           && RHSExpr->isOrdinaryOrBitFieldObject()
7641           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7642       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7643       if (commonRes.isInvalid())
7644         return ExprError();
7645       commonExpr = commonRes.get();
7646     }
7647 
7648     // If the common expression is a class or array prvalue, materialize it
7649     // so that we can safely refer to it multiple times.
7650     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7651                                    commonExpr->getType()->isArrayType())) {
7652       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7653       if (MatExpr.isInvalid())
7654         return ExprError();
7655       commonExpr = MatExpr.get();
7656     }
7657 
7658     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7659                                                 commonExpr->getType(),
7660                                                 commonExpr->getValueKind(),
7661                                                 commonExpr->getObjectKind(),
7662                                                 commonExpr);
7663     LHSExpr = CondExpr = opaqueValue;
7664   }
7665 
7666   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7667   ExprValueKind VK = VK_RValue;
7668   ExprObjectKind OK = OK_Ordinary;
7669   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7670   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7671                                              VK, OK, QuestionLoc);
7672   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7673       RHS.isInvalid())
7674     return ExprError();
7675 
7676   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7677                                 RHS.get());
7678 
7679   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7680 
7681   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7682                                          Context);
7683 
7684   if (!commonExpr)
7685     return new (Context)
7686         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7687                             RHS.get(), result, VK, OK);
7688 
7689   return new (Context) BinaryConditionalOperator(
7690       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7691       ColonLoc, result, VK, OK);
7692 }
7693 
7694 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7695 // being closely modeled after the C99 spec:-). The odd characteristic of this
7696 // routine is it effectively iqnores the qualifiers on the top level pointee.
7697 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7698 // FIXME: add a couple examples in this comment.
7699 static Sema::AssignConvertType
7700 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7701   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7702   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7703 
7704   // get the "pointed to" type (ignoring qualifiers at the top level)
7705   const Type *lhptee, *rhptee;
7706   Qualifiers lhq, rhq;
7707   std::tie(lhptee, lhq) =
7708       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7709   std::tie(rhptee, rhq) =
7710       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7711 
7712   Sema::AssignConvertType ConvTy = Sema::Compatible;
7713 
7714   // C99 6.5.16.1p1: This following citation is common to constraints
7715   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7716   // qualifiers of the type *pointed to* by the right;
7717 
7718   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7719   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7720       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7721     // Ignore lifetime for further calculation.
7722     lhq.removeObjCLifetime();
7723     rhq.removeObjCLifetime();
7724   }
7725 
7726   if (!lhq.compatiblyIncludes(rhq)) {
7727     // Treat address-space mismatches as fatal.  TODO: address subspaces
7728     if (!lhq.isAddressSpaceSupersetOf(rhq))
7729       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7730 
7731     // It's okay to add or remove GC or lifetime qualifiers when converting to
7732     // and from void*.
7733     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7734                         .compatiblyIncludes(
7735                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7736              && (lhptee->isVoidType() || rhptee->isVoidType()))
7737       ; // keep old
7738 
7739     // Treat lifetime mismatches as fatal.
7740     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7741       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7742 
7743     // For GCC/MS compatibility, other qualifier mismatches are treated
7744     // as still compatible in C.
7745     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7746   }
7747 
7748   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7749   // incomplete type and the other is a pointer to a qualified or unqualified
7750   // version of void...
7751   if (lhptee->isVoidType()) {
7752     if (rhptee->isIncompleteOrObjectType())
7753       return ConvTy;
7754 
7755     // As an extension, we allow cast to/from void* to function pointer.
7756     assert(rhptee->isFunctionType());
7757     return Sema::FunctionVoidPointer;
7758   }
7759 
7760   if (rhptee->isVoidType()) {
7761     if (lhptee->isIncompleteOrObjectType())
7762       return ConvTy;
7763 
7764     // As an extension, we allow cast to/from void* to function pointer.
7765     assert(lhptee->isFunctionType());
7766     return Sema::FunctionVoidPointer;
7767   }
7768 
7769   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7770   // unqualified versions of compatible types, ...
7771   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7772   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7773     // Check if the pointee types are compatible ignoring the sign.
7774     // We explicitly check for char so that we catch "char" vs
7775     // "unsigned char" on systems where "char" is unsigned.
7776     if (lhptee->isCharType())
7777       ltrans = S.Context.UnsignedCharTy;
7778     else if (lhptee->hasSignedIntegerRepresentation())
7779       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7780 
7781     if (rhptee->isCharType())
7782       rtrans = S.Context.UnsignedCharTy;
7783     else if (rhptee->hasSignedIntegerRepresentation())
7784       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7785 
7786     if (ltrans == rtrans) {
7787       // Types are compatible ignoring the sign. Qualifier incompatibility
7788       // takes priority over sign incompatibility because the sign
7789       // warning can be disabled.
7790       if (ConvTy != Sema::Compatible)
7791         return ConvTy;
7792 
7793       return Sema::IncompatiblePointerSign;
7794     }
7795 
7796     // If we are a multi-level pointer, it's possible that our issue is simply
7797     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7798     // the eventual target type is the same and the pointers have the same
7799     // level of indirection, this must be the issue.
7800     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7801       do {
7802         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7803         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7804       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7805 
7806       if (lhptee == rhptee)
7807         return Sema::IncompatibleNestedPointerQualifiers;
7808     }
7809 
7810     // General pointer incompatibility takes priority over qualifiers.
7811     return Sema::IncompatiblePointer;
7812   }
7813   if (!S.getLangOpts().CPlusPlus &&
7814       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7815     return Sema::IncompatiblePointer;
7816   return ConvTy;
7817 }
7818 
7819 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7820 /// block pointer types are compatible or whether a block and normal pointer
7821 /// are compatible. It is more restrict than comparing two function pointer
7822 // types.
7823 static Sema::AssignConvertType
7824 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7825                                     QualType RHSType) {
7826   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7827   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7828 
7829   QualType lhptee, rhptee;
7830 
7831   // get the "pointed to" type (ignoring qualifiers at the top level)
7832   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7833   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7834 
7835   // In C++, the types have to match exactly.
7836   if (S.getLangOpts().CPlusPlus)
7837     return Sema::IncompatibleBlockPointer;
7838 
7839   Sema::AssignConvertType ConvTy = Sema::Compatible;
7840 
7841   // For blocks we enforce that qualifiers are identical.
7842   Qualifiers LQuals = lhptee.getLocalQualifiers();
7843   Qualifiers RQuals = rhptee.getLocalQualifiers();
7844   if (S.getLangOpts().OpenCL) {
7845     LQuals.removeAddressSpace();
7846     RQuals.removeAddressSpace();
7847   }
7848   if (LQuals != RQuals)
7849     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7850 
7851   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7852   // assignment.
7853   // The current behavior is similar to C++ lambdas. A block might be
7854   // assigned to a variable iff its return type and parameters are compatible
7855   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7856   // an assignment. Presumably it should behave in way that a function pointer
7857   // assignment does in C, so for each parameter and return type:
7858   //  * CVR and address space of LHS should be a superset of CVR and address
7859   //  space of RHS.
7860   //  * unqualified types should be compatible.
7861   if (S.getLangOpts().OpenCL) {
7862     if (!S.Context.typesAreBlockPointerCompatible(
7863             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7864             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7865       return Sema::IncompatibleBlockPointer;
7866   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7867     return Sema::IncompatibleBlockPointer;
7868 
7869   return ConvTy;
7870 }
7871 
7872 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7873 /// for assignment compatibility.
7874 static Sema::AssignConvertType
7875 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7876                                    QualType RHSType) {
7877   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7878   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7879 
7880   if (LHSType->isObjCBuiltinType()) {
7881     // Class is not compatible with ObjC object pointers.
7882     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7883         !RHSType->isObjCQualifiedClassType())
7884       return Sema::IncompatiblePointer;
7885     return Sema::Compatible;
7886   }
7887   if (RHSType->isObjCBuiltinType()) {
7888     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7889         !LHSType->isObjCQualifiedClassType())
7890       return Sema::IncompatiblePointer;
7891     return Sema::Compatible;
7892   }
7893   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7894   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7895 
7896   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7897       // make an exception for id<P>
7898       !LHSType->isObjCQualifiedIdType())
7899     return Sema::CompatiblePointerDiscardsQualifiers;
7900 
7901   if (S.Context.typesAreCompatible(LHSType, RHSType))
7902     return Sema::Compatible;
7903   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7904     return Sema::IncompatibleObjCQualifiedId;
7905   return Sema::IncompatiblePointer;
7906 }
7907 
7908 Sema::AssignConvertType
7909 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7910                                  QualType LHSType, QualType RHSType) {
7911   // Fake up an opaque expression.  We don't actually care about what
7912   // cast operations are required, so if CheckAssignmentConstraints
7913   // adds casts to this they'll be wasted, but fortunately that doesn't
7914   // usually happen on valid code.
7915   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7916   ExprResult RHSPtr = &RHSExpr;
7917   CastKind K;
7918 
7919   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7920 }
7921 
7922 /// This helper function returns true if QT is a vector type that has element
7923 /// type ElementType.
7924 static bool isVector(QualType QT, QualType ElementType) {
7925   if (const VectorType *VT = QT->getAs<VectorType>())
7926     return VT->getElementType() == ElementType;
7927   return false;
7928 }
7929 
7930 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7931 /// has code to accommodate several GCC extensions when type checking
7932 /// pointers. Here are some objectionable examples that GCC considers warnings:
7933 ///
7934 ///  int a, *pint;
7935 ///  short *pshort;
7936 ///  struct foo *pfoo;
7937 ///
7938 ///  pint = pshort; // warning: assignment from incompatible pointer type
7939 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7940 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7941 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7942 ///
7943 /// As a result, the code for dealing with pointers is more complex than the
7944 /// C99 spec dictates.
7945 ///
7946 /// Sets 'Kind' for any result kind except Incompatible.
7947 Sema::AssignConvertType
7948 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7949                                  CastKind &Kind, bool ConvertRHS) {
7950   QualType RHSType = RHS.get()->getType();
7951   QualType OrigLHSType = LHSType;
7952 
7953   // Get canonical types.  We're not formatting these types, just comparing
7954   // them.
7955   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7956   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7957 
7958   // Common case: no conversion required.
7959   if (LHSType == RHSType) {
7960     Kind = CK_NoOp;
7961     return Compatible;
7962   }
7963 
7964   // If we have an atomic type, try a non-atomic assignment, then just add an
7965   // atomic qualification step.
7966   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7967     Sema::AssignConvertType result =
7968       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7969     if (result != Compatible)
7970       return result;
7971     if (Kind != CK_NoOp && ConvertRHS)
7972       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7973     Kind = CK_NonAtomicToAtomic;
7974     return Compatible;
7975   }
7976 
7977   // If the left-hand side is a reference type, then we are in a
7978   // (rare!) case where we've allowed the use of references in C,
7979   // e.g., as a parameter type in a built-in function. In this case,
7980   // just make sure that the type referenced is compatible with the
7981   // right-hand side type. The caller is responsible for adjusting
7982   // LHSType so that the resulting expression does not have reference
7983   // type.
7984   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7985     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7986       Kind = CK_LValueBitCast;
7987       return Compatible;
7988     }
7989     return Incompatible;
7990   }
7991 
7992   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7993   // to the same ExtVector type.
7994   if (LHSType->isExtVectorType()) {
7995     if (RHSType->isExtVectorType())
7996       return Incompatible;
7997     if (RHSType->isArithmeticType()) {
7998       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7999       if (ConvertRHS)
8000         RHS = prepareVectorSplat(LHSType, RHS.get());
8001       Kind = CK_VectorSplat;
8002       return Compatible;
8003     }
8004   }
8005 
8006   // Conversions to or from vector type.
8007   if (LHSType->isVectorType() || RHSType->isVectorType()) {
8008     if (LHSType->isVectorType() && RHSType->isVectorType()) {
8009       // Allow assignments of an AltiVec vector type to an equivalent GCC
8010       // vector type and vice versa
8011       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8012         Kind = CK_BitCast;
8013         return Compatible;
8014       }
8015 
8016       // If we are allowing lax vector conversions, and LHS and RHS are both
8017       // vectors, the total size only needs to be the same. This is a bitcast;
8018       // no bits are changed but the result type is different.
8019       if (isLaxVectorConversion(RHSType, LHSType)) {
8020         Kind = CK_BitCast;
8021         return IncompatibleVectors;
8022       }
8023     }
8024 
8025     // When the RHS comes from another lax conversion (e.g. binops between
8026     // scalars and vectors) the result is canonicalized as a vector. When the
8027     // LHS is also a vector, the lax is allowed by the condition above. Handle
8028     // the case where LHS is a scalar.
8029     if (LHSType->isScalarType()) {
8030       const VectorType *VecType = RHSType->getAs<VectorType>();
8031       if (VecType && VecType->getNumElements() == 1 &&
8032           isLaxVectorConversion(RHSType, LHSType)) {
8033         ExprResult *VecExpr = &RHS;
8034         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
8035         Kind = CK_BitCast;
8036         return Compatible;
8037       }
8038     }
8039 
8040     return Incompatible;
8041   }
8042 
8043   // Diagnose attempts to convert between __float128 and long double where
8044   // such conversions currently can't be handled.
8045   if (unsupportedTypeConversion(*this, LHSType, RHSType))
8046     return Incompatible;
8047 
8048   // Disallow assigning a _Complex to a real type in C++ mode since it simply
8049   // discards the imaginary part.
8050   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
8051       !LHSType->getAs<ComplexType>())
8052     return Incompatible;
8053 
8054   // Arithmetic conversions.
8055   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
8056       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
8057     if (ConvertRHS)
8058       Kind = PrepareScalarCast(RHS, LHSType);
8059     return Compatible;
8060   }
8061 
8062   // Conversions to normal pointers.
8063   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
8064     // U* -> T*
8065     if (isa<PointerType>(RHSType)) {
8066       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8067       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
8068       if (AddrSpaceL != AddrSpaceR)
8069         Kind = CK_AddressSpaceConversion;
8070       else if (Context.hasCvrSimilarType(RHSType, LHSType))
8071         Kind = CK_NoOp;
8072       else
8073         Kind = CK_BitCast;
8074       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
8075     }
8076 
8077     // int -> T*
8078     if (RHSType->isIntegerType()) {
8079       Kind = CK_IntegralToPointer; // FIXME: null?
8080       return IntToPointer;
8081     }
8082 
8083     // C pointers are not compatible with ObjC object pointers,
8084     // with two exceptions:
8085     if (isa<ObjCObjectPointerType>(RHSType)) {
8086       //  - conversions to void*
8087       if (LHSPointer->getPointeeType()->isVoidType()) {
8088         Kind = CK_BitCast;
8089         return Compatible;
8090       }
8091 
8092       //  - conversions from 'Class' to the redefinition type
8093       if (RHSType->isObjCClassType() &&
8094           Context.hasSameType(LHSType,
8095                               Context.getObjCClassRedefinitionType())) {
8096         Kind = CK_BitCast;
8097         return Compatible;
8098       }
8099 
8100       Kind = CK_BitCast;
8101       return IncompatiblePointer;
8102     }
8103 
8104     // U^ -> void*
8105     if (RHSType->getAs<BlockPointerType>()) {
8106       if (LHSPointer->getPointeeType()->isVoidType()) {
8107         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
8108         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8109                                 ->getPointeeType()
8110                                 .getAddressSpace();
8111         Kind =
8112             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8113         return Compatible;
8114       }
8115     }
8116 
8117     return Incompatible;
8118   }
8119 
8120   // Conversions to block pointers.
8121   if (isa<BlockPointerType>(LHSType)) {
8122     // U^ -> T^
8123     if (RHSType->isBlockPointerType()) {
8124       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
8125                               ->getPointeeType()
8126                               .getAddressSpace();
8127       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
8128                               ->getPointeeType()
8129                               .getAddressSpace();
8130       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
8131       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
8132     }
8133 
8134     // int or null -> T^
8135     if (RHSType->isIntegerType()) {
8136       Kind = CK_IntegralToPointer; // FIXME: null
8137       return IntToBlockPointer;
8138     }
8139 
8140     // id -> T^
8141     if (getLangOpts().ObjC && RHSType->isObjCIdType()) {
8142       Kind = CK_AnyPointerToBlockPointerCast;
8143       return Compatible;
8144     }
8145 
8146     // void* -> T^
8147     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
8148       if (RHSPT->getPointeeType()->isVoidType()) {
8149         Kind = CK_AnyPointerToBlockPointerCast;
8150         return Compatible;
8151       }
8152 
8153     return Incompatible;
8154   }
8155 
8156   // Conversions to Objective-C pointers.
8157   if (isa<ObjCObjectPointerType>(LHSType)) {
8158     // A* -> B*
8159     if (RHSType->isObjCObjectPointerType()) {
8160       Kind = CK_BitCast;
8161       Sema::AssignConvertType result =
8162         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
8163       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8164           result == Compatible &&
8165           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
8166         result = IncompatibleObjCWeakRef;
8167       return result;
8168     }
8169 
8170     // int or null -> A*
8171     if (RHSType->isIntegerType()) {
8172       Kind = CK_IntegralToPointer; // FIXME: null
8173       return IntToPointer;
8174     }
8175 
8176     // In general, C pointers are not compatible with ObjC object pointers,
8177     // with two exceptions:
8178     if (isa<PointerType>(RHSType)) {
8179       Kind = CK_CPointerToObjCPointerCast;
8180 
8181       //  - conversions from 'void*'
8182       if (RHSType->isVoidPointerType()) {
8183         return Compatible;
8184       }
8185 
8186       //  - conversions to 'Class' from its redefinition type
8187       if (LHSType->isObjCClassType() &&
8188           Context.hasSameType(RHSType,
8189                               Context.getObjCClassRedefinitionType())) {
8190         return Compatible;
8191       }
8192 
8193       return IncompatiblePointer;
8194     }
8195 
8196     // Only under strict condition T^ is compatible with an Objective-C pointer.
8197     if (RHSType->isBlockPointerType() &&
8198         LHSType->isBlockCompatibleObjCPointerType(Context)) {
8199       if (ConvertRHS)
8200         maybeExtendBlockObject(RHS);
8201       Kind = CK_BlockPointerToObjCPointerCast;
8202       return Compatible;
8203     }
8204 
8205     return Incompatible;
8206   }
8207 
8208   // Conversions from pointers that are not covered by the above.
8209   if (isa<PointerType>(RHSType)) {
8210     // T* -> _Bool
8211     if (LHSType == Context.BoolTy) {
8212       Kind = CK_PointerToBoolean;
8213       return Compatible;
8214     }
8215 
8216     // T* -> int
8217     if (LHSType->isIntegerType()) {
8218       Kind = CK_PointerToIntegral;
8219       return PointerToInt;
8220     }
8221 
8222     return Incompatible;
8223   }
8224 
8225   // Conversions from Objective-C pointers that are not covered by the above.
8226   if (isa<ObjCObjectPointerType>(RHSType)) {
8227     // T* -> _Bool
8228     if (LHSType == Context.BoolTy) {
8229       Kind = CK_PointerToBoolean;
8230       return Compatible;
8231     }
8232 
8233     // T* -> int
8234     if (LHSType->isIntegerType()) {
8235       Kind = CK_PointerToIntegral;
8236       return PointerToInt;
8237     }
8238 
8239     return Incompatible;
8240   }
8241 
8242   // struct A -> struct B
8243   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
8244     if (Context.typesAreCompatible(LHSType, RHSType)) {
8245       Kind = CK_NoOp;
8246       return Compatible;
8247     }
8248   }
8249 
8250   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
8251     Kind = CK_IntToOCLSampler;
8252     return Compatible;
8253   }
8254 
8255   return Incompatible;
8256 }
8257 
8258 /// Constructs a transparent union from an expression that is
8259 /// used to initialize the transparent union.
8260 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
8261                                       ExprResult &EResult, QualType UnionType,
8262                                       FieldDecl *Field) {
8263   // Build an initializer list that designates the appropriate member
8264   // of the transparent union.
8265   Expr *E = EResult.get();
8266   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
8267                                                    E, SourceLocation());
8268   Initializer->setType(UnionType);
8269   Initializer->setInitializedFieldInUnion(Field);
8270 
8271   // Build a compound literal constructing a value of the transparent
8272   // union type from this initializer list.
8273   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
8274   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
8275                                         VK_RValue, Initializer, false);
8276 }
8277 
8278 Sema::AssignConvertType
8279 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
8280                                                ExprResult &RHS) {
8281   QualType RHSType = RHS.get()->getType();
8282 
8283   // If the ArgType is a Union type, we want to handle a potential
8284   // transparent_union GCC extension.
8285   const RecordType *UT = ArgType->getAsUnionType();
8286   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
8287     return Incompatible;
8288 
8289   // The field to initialize within the transparent union.
8290   RecordDecl *UD = UT->getDecl();
8291   FieldDecl *InitField = nullptr;
8292   // It's compatible if the expression matches any of the fields.
8293   for (auto *it : UD->fields()) {
8294     if (it->getType()->isPointerType()) {
8295       // If the transparent union contains a pointer type, we allow:
8296       // 1) void pointer
8297       // 2) null pointer constant
8298       if (RHSType->isPointerType())
8299         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
8300           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
8301           InitField = it;
8302           break;
8303         }
8304 
8305       if (RHS.get()->isNullPointerConstant(Context,
8306                                            Expr::NPC_ValueDependentIsNull)) {
8307         RHS = ImpCastExprToType(RHS.get(), it->getType(),
8308                                 CK_NullToPointer);
8309         InitField = it;
8310         break;
8311       }
8312     }
8313 
8314     CastKind Kind;
8315     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
8316           == Compatible) {
8317       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
8318       InitField = it;
8319       break;
8320     }
8321   }
8322 
8323   if (!InitField)
8324     return Incompatible;
8325 
8326   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
8327   return Compatible;
8328 }
8329 
8330 Sema::AssignConvertType
8331 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
8332                                        bool Diagnose,
8333                                        bool DiagnoseCFAudited,
8334                                        bool ConvertRHS) {
8335   // We need to be able to tell the caller whether we diagnosed a problem, if
8336   // they ask us to issue diagnostics.
8337   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
8338 
8339   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
8340   // we can't avoid *all* modifications at the moment, so we need some somewhere
8341   // to put the updated value.
8342   ExprResult LocalRHS = CallerRHS;
8343   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
8344 
8345   if (const auto *LHSPtrType = LHSType->getAs<PointerType>()) {
8346     if (const auto *RHSPtrType = RHS.get()->getType()->getAs<PointerType>()) {
8347       if (RHSPtrType->getPointeeType()->hasAttr(attr::NoDeref) &&
8348           !LHSPtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
8349         Diag(RHS.get()->getExprLoc(),
8350              diag::warn_noderef_to_dereferenceable_pointer)
8351             << RHS.get()->getSourceRange();
8352       }
8353     }
8354   }
8355 
8356   if (getLangOpts().CPlusPlus) {
8357     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
8358       // C++ 5.17p3: If the left operand is not of class type, the
8359       // expression is implicitly converted (C++ 4) to the
8360       // cv-unqualified type of the left operand.
8361       QualType RHSType = RHS.get()->getType();
8362       if (Diagnose) {
8363         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8364                                         AA_Assigning);
8365       } else {
8366         ImplicitConversionSequence ICS =
8367             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8368                                   /*SuppressUserConversions=*/false,
8369                                   /*AllowExplicit=*/false,
8370                                   /*InOverloadResolution=*/false,
8371                                   /*CStyle=*/false,
8372                                   /*AllowObjCWritebackConversion=*/false);
8373         if (ICS.isFailure())
8374           return Incompatible;
8375         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
8376                                         ICS, AA_Assigning);
8377       }
8378       if (RHS.isInvalid())
8379         return Incompatible;
8380       Sema::AssignConvertType result = Compatible;
8381       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8382           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
8383         result = IncompatibleObjCWeakRef;
8384       return result;
8385     }
8386 
8387     // FIXME: Currently, we fall through and treat C++ classes like C
8388     // structures.
8389     // FIXME: We also fall through for atomics; not sure what should
8390     // happen there, though.
8391   } else if (RHS.get()->getType() == Context.OverloadTy) {
8392     // As a set of extensions to C, we support overloading on functions. These
8393     // functions need to be resolved here.
8394     DeclAccessPair DAP;
8395     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
8396             RHS.get(), LHSType, /*Complain=*/false, DAP))
8397       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8398     else
8399       return Incompatible;
8400   }
8401 
8402   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8403   // a null pointer constant.
8404   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8405        LHSType->isBlockPointerType()) &&
8406       RHS.get()->isNullPointerConstant(Context,
8407                                        Expr::NPC_ValueDependentIsNull)) {
8408     if (Diagnose || ConvertRHS) {
8409       CastKind Kind;
8410       CXXCastPath Path;
8411       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8412                              /*IgnoreBaseAccess=*/false, Diagnose);
8413       if (ConvertRHS)
8414         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8415     }
8416     return Compatible;
8417   }
8418 
8419   // OpenCL queue_t type assignment.
8420   if (LHSType->isQueueT() && RHS.get()->isNullPointerConstant(
8421                                  Context, Expr::NPC_ValueDependentIsNull)) {
8422     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8423     return Compatible;
8424   }
8425 
8426   // This check seems unnatural, however it is necessary to ensure the proper
8427   // conversion of functions/arrays. If the conversion were done for all
8428   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8429   // expressions that suppress this implicit conversion (&, sizeof).
8430   //
8431   // Suppress this for references: C++ 8.5.3p5.
8432   if (!LHSType->isReferenceType()) {
8433     // FIXME: We potentially allocate here even if ConvertRHS is false.
8434     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8435     if (RHS.isInvalid())
8436       return Incompatible;
8437   }
8438   CastKind Kind;
8439   Sema::AssignConvertType result =
8440     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8441 
8442   // C99 6.5.16.1p2: The value of the right operand is converted to the
8443   // type of the assignment expression.
8444   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8445   // so that we can use references in built-in functions even in C.
8446   // The getNonReferenceType() call makes sure that the resulting expression
8447   // does not have reference type.
8448   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8449     QualType Ty = LHSType.getNonLValueExprType(Context);
8450     Expr *E = RHS.get();
8451 
8452     // Check for various Objective-C errors. If we are not reporting
8453     // diagnostics and just checking for errors, e.g., during overload
8454     // resolution, return Incompatible to indicate the failure.
8455     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8456         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8457                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8458       if (!Diagnose)
8459         return Incompatible;
8460     }
8461     if (getLangOpts().ObjC &&
8462         (CheckObjCBridgeRelatedConversions(E->getBeginLoc(), LHSType,
8463                                            E->getType(), E, Diagnose) ||
8464          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8465       if (!Diagnose)
8466         return Incompatible;
8467       // Replace the expression with a corrected version and continue so we
8468       // can find further errors.
8469       RHS = E;
8470       return Compatible;
8471     }
8472 
8473     if (ConvertRHS)
8474       RHS = ImpCastExprToType(E, Ty, Kind);
8475   }
8476 
8477   return result;
8478 }
8479 
8480 namespace {
8481 /// The original operand to an operator, prior to the application of the usual
8482 /// arithmetic conversions and converting the arguments of a builtin operator
8483 /// candidate.
8484 struct OriginalOperand {
8485   explicit OriginalOperand(Expr *Op) : Orig(Op), Conversion(nullptr) {
8486     if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Op))
8487       Op = MTE->GetTemporaryExpr();
8488     if (auto *BTE = dyn_cast<CXXBindTemporaryExpr>(Op))
8489       Op = BTE->getSubExpr();
8490     if (auto *ICE = dyn_cast<ImplicitCastExpr>(Op)) {
8491       Orig = ICE->getSubExprAsWritten();
8492       Conversion = ICE->getConversionFunction();
8493     }
8494   }
8495 
8496   QualType getType() const { return Orig->getType(); }
8497 
8498   Expr *Orig;
8499   NamedDecl *Conversion;
8500 };
8501 }
8502 
8503 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8504                                ExprResult &RHS) {
8505   OriginalOperand OrigLHS(LHS.get()), OrigRHS(RHS.get());
8506 
8507   Diag(Loc, diag::err_typecheck_invalid_operands)
8508     << OrigLHS.getType() << OrigRHS.getType()
8509     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8510 
8511   // If a user-defined conversion was applied to either of the operands prior
8512   // to applying the built-in operator rules, tell the user about it.
8513   if (OrigLHS.Conversion) {
8514     Diag(OrigLHS.Conversion->getLocation(),
8515          diag::note_typecheck_invalid_operands_converted)
8516       << 0 << LHS.get()->getType();
8517   }
8518   if (OrigRHS.Conversion) {
8519     Diag(OrigRHS.Conversion->getLocation(),
8520          diag::note_typecheck_invalid_operands_converted)
8521       << 1 << RHS.get()->getType();
8522   }
8523 
8524   return QualType();
8525 }
8526 
8527 // Diagnose cases where a scalar was implicitly converted to a vector and
8528 // diagnose the underlying types. Otherwise, diagnose the error
8529 // as invalid vector logical operands for non-C++ cases.
8530 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8531                                             ExprResult &RHS) {
8532   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8533   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8534 
8535   bool LHSNatVec = LHSType->isVectorType();
8536   bool RHSNatVec = RHSType->isVectorType();
8537 
8538   if (!(LHSNatVec && RHSNatVec)) {
8539     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8540     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8541     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8542         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8543         << Vector->getSourceRange();
8544     return QualType();
8545   }
8546 
8547   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8548       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8549       << RHS.get()->getSourceRange();
8550 
8551   return QualType();
8552 }
8553 
8554 /// Try to convert a value of non-vector type to a vector type by converting
8555 /// the type to the element type of the vector and then performing a splat.
8556 /// If the language is OpenCL, we only use conversions that promote scalar
8557 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8558 /// for float->int.
8559 ///
8560 /// OpenCL V2.0 6.2.6.p2:
8561 /// An error shall occur if any scalar operand type has greater rank
8562 /// than the type of the vector element.
8563 ///
8564 /// \param scalar - if non-null, actually perform the conversions
8565 /// \return true if the operation fails (but without diagnosing the failure)
8566 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8567                                      QualType scalarTy,
8568                                      QualType vectorEltTy,
8569                                      QualType vectorTy,
8570                                      unsigned &DiagID) {
8571   // The conversion to apply to the scalar before splatting it,
8572   // if necessary.
8573   CastKind scalarCast = CK_NoOp;
8574 
8575   if (vectorEltTy->isIntegralType(S.Context)) {
8576     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8577         (scalarTy->isIntegerType() &&
8578          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8579       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8580       return true;
8581     }
8582     if (!scalarTy->isIntegralType(S.Context))
8583       return true;
8584     scalarCast = CK_IntegralCast;
8585   } else if (vectorEltTy->isRealFloatingType()) {
8586     if (scalarTy->isRealFloatingType()) {
8587       if (S.getLangOpts().OpenCL &&
8588           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8589         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8590         return true;
8591       }
8592       scalarCast = CK_FloatingCast;
8593     }
8594     else if (scalarTy->isIntegralType(S.Context))
8595       scalarCast = CK_IntegralToFloating;
8596     else
8597       return true;
8598   } else {
8599     return true;
8600   }
8601 
8602   // Adjust scalar if desired.
8603   if (scalar) {
8604     if (scalarCast != CK_NoOp)
8605       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8606     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8607   }
8608   return false;
8609 }
8610 
8611 /// Convert vector E to a vector with the same number of elements but different
8612 /// element type.
8613 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8614   const auto *VecTy = E->getType()->getAs<VectorType>();
8615   assert(VecTy && "Expression E must be a vector");
8616   QualType NewVecTy = S.Context.getVectorType(ElementType,
8617                                               VecTy->getNumElements(),
8618                                               VecTy->getVectorKind());
8619 
8620   // Look through the implicit cast. Return the subexpression if its type is
8621   // NewVecTy.
8622   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8623     if (ICE->getSubExpr()->getType() == NewVecTy)
8624       return ICE->getSubExpr();
8625 
8626   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8627   return S.ImpCastExprToType(E, NewVecTy, Cast);
8628 }
8629 
8630 /// Test if a (constant) integer Int can be casted to another integer type
8631 /// IntTy without losing precision.
8632 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8633                                       QualType OtherIntTy) {
8634   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8635 
8636   // Reject cases where the value of the Int is unknown as that would
8637   // possibly cause truncation, but accept cases where the scalar can be
8638   // demoted without loss of precision.
8639   Expr::EvalResult EVResult;
8640   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8641   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8642   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8643   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8644 
8645   if (CstInt) {
8646     // If the scalar is constant and is of a higher order and has more active
8647     // bits that the vector element type, reject it.
8648     llvm::APSInt Result = EVResult.Val.getInt();
8649     unsigned NumBits = IntSigned
8650                            ? (Result.isNegative() ? Result.getMinSignedBits()
8651                                                   : Result.getActiveBits())
8652                            : Result.getActiveBits();
8653     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8654       return true;
8655 
8656     // If the signedness of the scalar type and the vector element type
8657     // differs and the number of bits is greater than that of the vector
8658     // element reject it.
8659     return (IntSigned != OtherIntSigned &&
8660             NumBits > S.Context.getIntWidth(OtherIntTy));
8661   }
8662 
8663   // Reject cases where the value of the scalar is not constant and it's
8664   // order is greater than that of the vector element type.
8665   return (Order < 0);
8666 }
8667 
8668 /// Test if a (constant) integer Int can be casted to floating point type
8669 /// FloatTy without losing precision.
8670 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8671                                      QualType FloatTy) {
8672   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8673 
8674   // Determine if the integer constant can be expressed as a floating point
8675   // number of the appropriate type.
8676   Expr::EvalResult EVResult;
8677   bool CstInt = Int->get()->EvaluateAsInt(EVResult, S.Context);
8678 
8679   uint64_t Bits = 0;
8680   if (CstInt) {
8681     // Reject constants that would be truncated if they were converted to
8682     // the floating point type. Test by simple to/from conversion.
8683     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8684     //        could be avoided if there was a convertFromAPInt method
8685     //        which could signal back if implicit truncation occurred.
8686     llvm::APSInt Result = EVResult.Val.getInt();
8687     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8688     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8689                            llvm::APFloat::rmTowardZero);
8690     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8691                              !IntTy->hasSignedIntegerRepresentation());
8692     bool Ignored = false;
8693     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8694                            &Ignored);
8695     if (Result != ConvertBack)
8696       return true;
8697   } else {
8698     // Reject types that cannot be fully encoded into the mantissa of
8699     // the float.
8700     Bits = S.Context.getTypeSize(IntTy);
8701     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8702         S.Context.getFloatTypeSemantics(FloatTy));
8703     if (Bits > FloatPrec)
8704       return true;
8705   }
8706 
8707   return false;
8708 }
8709 
8710 /// Attempt to convert and splat Scalar into a vector whose types matches
8711 /// Vector following GCC conversion rules. The rule is that implicit
8712 /// conversion can occur when Scalar can be casted to match Vector's element
8713 /// type without causing truncation of Scalar.
8714 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8715                                         ExprResult *Vector) {
8716   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8717   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8718   const VectorType *VT = VectorTy->getAs<VectorType>();
8719 
8720   assert(!isa<ExtVectorType>(VT) &&
8721          "ExtVectorTypes should not be handled here!");
8722 
8723   QualType VectorEltTy = VT->getElementType();
8724 
8725   // Reject cases where the vector element type or the scalar element type are
8726   // not integral or floating point types.
8727   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8728     return true;
8729 
8730   // The conversion to apply to the scalar before splatting it,
8731   // if necessary.
8732   CastKind ScalarCast = CK_NoOp;
8733 
8734   // Accept cases where the vector elements are integers and the scalar is
8735   // an integer.
8736   // FIXME: Notionally if the scalar was a floating point value with a precise
8737   //        integral representation, we could cast it to an appropriate integer
8738   //        type and then perform the rest of the checks here. GCC will perform
8739   //        this conversion in some cases as determined by the input language.
8740   //        We should accept it on a language independent basis.
8741   if (VectorEltTy->isIntegralType(S.Context) &&
8742       ScalarTy->isIntegralType(S.Context) &&
8743       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8744 
8745     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8746       return true;
8747 
8748     ScalarCast = CK_IntegralCast;
8749   } else if (VectorEltTy->isRealFloatingType()) {
8750     if (ScalarTy->isRealFloatingType()) {
8751 
8752       // Reject cases where the scalar type is not a constant and has a higher
8753       // Order than the vector element type.
8754       llvm::APFloat Result(0.0);
8755       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8756       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8757       if (!CstScalar && Order < 0)
8758         return true;
8759 
8760       // If the scalar cannot be safely casted to the vector element type,
8761       // reject it.
8762       if (CstScalar) {
8763         bool Truncated = false;
8764         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8765                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8766         if (Truncated)
8767           return true;
8768       }
8769 
8770       ScalarCast = CK_FloatingCast;
8771     } else if (ScalarTy->isIntegralType(S.Context)) {
8772       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8773         return true;
8774 
8775       ScalarCast = CK_IntegralToFloating;
8776     } else
8777       return true;
8778   }
8779 
8780   // Adjust scalar if desired.
8781   if (Scalar) {
8782     if (ScalarCast != CK_NoOp)
8783       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8784     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8785   }
8786   return false;
8787 }
8788 
8789 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8790                                    SourceLocation Loc, bool IsCompAssign,
8791                                    bool AllowBothBool,
8792                                    bool AllowBoolConversions) {
8793   if (!IsCompAssign) {
8794     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8795     if (LHS.isInvalid())
8796       return QualType();
8797   }
8798   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8799   if (RHS.isInvalid())
8800     return QualType();
8801 
8802   // For conversion purposes, we ignore any qualifiers.
8803   // For example, "const float" and "float" are equivalent.
8804   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8805   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8806 
8807   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8808   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8809   assert(LHSVecType || RHSVecType);
8810 
8811   // AltiVec-style "vector bool op vector bool" combinations are allowed
8812   // for some operators but not others.
8813   if (!AllowBothBool &&
8814       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8815       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8816     return InvalidOperands(Loc, LHS, RHS);
8817 
8818   // If the vector types are identical, return.
8819   if (Context.hasSameType(LHSType, RHSType))
8820     return LHSType;
8821 
8822   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8823   if (LHSVecType && RHSVecType &&
8824       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8825     if (isa<ExtVectorType>(LHSVecType)) {
8826       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8827       return LHSType;
8828     }
8829 
8830     if (!IsCompAssign)
8831       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8832     return RHSType;
8833   }
8834 
8835   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8836   // can be mixed, with the result being the non-bool type.  The non-bool
8837   // operand must have integer element type.
8838   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8839       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8840       (Context.getTypeSize(LHSVecType->getElementType()) ==
8841        Context.getTypeSize(RHSVecType->getElementType()))) {
8842     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8843         LHSVecType->getElementType()->isIntegerType() &&
8844         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8845       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8846       return LHSType;
8847     }
8848     if (!IsCompAssign &&
8849         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8850         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8851         RHSVecType->getElementType()->isIntegerType()) {
8852       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8853       return RHSType;
8854     }
8855   }
8856 
8857   // If there's a vector type and a scalar, try to convert the scalar to
8858   // the vector element type and splat.
8859   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8860   if (!RHSVecType) {
8861     if (isa<ExtVectorType>(LHSVecType)) {
8862       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8863                                     LHSVecType->getElementType(), LHSType,
8864                                     DiagID))
8865         return LHSType;
8866     } else {
8867       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8868         return LHSType;
8869     }
8870   }
8871   if (!LHSVecType) {
8872     if (isa<ExtVectorType>(RHSVecType)) {
8873       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8874                                     LHSType, RHSVecType->getElementType(),
8875                                     RHSType, DiagID))
8876         return RHSType;
8877     } else {
8878       if (LHS.get()->getValueKind() == VK_LValue ||
8879           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8880         return RHSType;
8881     }
8882   }
8883 
8884   // FIXME: The code below also handles conversion between vectors and
8885   // non-scalars, we should break this down into fine grained specific checks
8886   // and emit proper diagnostics.
8887   QualType VecType = LHSVecType ? LHSType : RHSType;
8888   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8889   QualType OtherType = LHSVecType ? RHSType : LHSType;
8890   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8891   if (isLaxVectorConversion(OtherType, VecType)) {
8892     // If we're allowing lax vector conversions, only the total (data) size
8893     // needs to be the same. For non compound assignment, if one of the types is
8894     // scalar, the result is always the vector type.
8895     if (!IsCompAssign) {
8896       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8897       return VecType;
8898     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8899     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8900     // type. Note that this is already done by non-compound assignments in
8901     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8902     // <1 x T> -> T. The result is also a vector type.
8903     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8904                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8905       ExprResult *RHSExpr = &RHS;
8906       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8907       return VecType;
8908     }
8909   }
8910 
8911   // Okay, the expression is invalid.
8912 
8913   // If there's a non-vector, non-real operand, diagnose that.
8914   if ((!RHSVecType && !RHSType->isRealType()) ||
8915       (!LHSVecType && !LHSType->isRealType())) {
8916     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8917       << LHSType << RHSType
8918       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8919     return QualType();
8920   }
8921 
8922   // OpenCL V1.1 6.2.6.p1:
8923   // If the operands are of more than one vector type, then an error shall
8924   // occur. Implicit conversions between vector types are not permitted, per
8925   // section 6.2.1.
8926   if (getLangOpts().OpenCL &&
8927       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8928       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8929     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8930                                                            << RHSType;
8931     return QualType();
8932   }
8933 
8934 
8935   // If there is a vector type that is not a ExtVector and a scalar, we reach
8936   // this point if scalar could not be converted to the vector's element type
8937   // without truncation.
8938   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8939       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8940     QualType Scalar = LHSVecType ? RHSType : LHSType;
8941     QualType Vector = LHSVecType ? LHSType : RHSType;
8942     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8943     Diag(Loc,
8944          diag::err_typecheck_vector_not_convertable_implict_truncation)
8945         << ScalarOrVector << Scalar << Vector;
8946 
8947     return QualType();
8948   }
8949 
8950   // Otherwise, use the generic diagnostic.
8951   Diag(Loc, DiagID)
8952     << LHSType << RHSType
8953     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8954   return QualType();
8955 }
8956 
8957 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8958 // expression.  These are mainly cases where the null pointer is used as an
8959 // integer instead of a pointer.
8960 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8961                                 SourceLocation Loc, bool IsCompare) {
8962   // The canonical way to check for a GNU null is with isNullPointerConstant,
8963   // but we use a bit of a hack here for speed; this is a relatively
8964   // hot path, and isNullPointerConstant is slow.
8965   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8966   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8967 
8968   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8969 
8970   // Avoid analyzing cases where the result will either be invalid (and
8971   // diagnosed as such) or entirely valid and not something to warn about.
8972   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8973       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8974     return;
8975 
8976   // Comparison operations would not make sense with a null pointer no matter
8977   // what the other expression is.
8978   if (!IsCompare) {
8979     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8980         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8981         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8982     return;
8983   }
8984 
8985   // The rest of the operations only make sense with a null pointer
8986   // if the other expression is a pointer.
8987   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8988       NonNullType->canDecayToPointerType())
8989     return;
8990 
8991   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8992       << LHSNull /* LHS is NULL */ << NonNullType
8993       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8994 }
8995 
8996 static void DiagnoseDivisionSizeofPointer(Sema &S, Expr *LHS, Expr *RHS,
8997                                           SourceLocation Loc) {
8998   const auto *LUE = dyn_cast<UnaryExprOrTypeTraitExpr>(LHS);
8999   const auto *RUE = dyn_cast<UnaryExprOrTypeTraitExpr>(RHS);
9000   if (!LUE || !RUE)
9001     return;
9002   if (LUE->getKind() != UETT_SizeOf || LUE->isArgumentType() ||
9003       RUE->getKind() != UETT_SizeOf)
9004     return;
9005 
9006   QualType LHSTy = LUE->getArgumentExpr()->IgnoreParens()->getType();
9007   QualType RHSTy;
9008 
9009   if (RUE->isArgumentType())
9010     RHSTy = RUE->getArgumentType();
9011   else
9012     RHSTy = RUE->getArgumentExpr()->IgnoreParens()->getType();
9013 
9014   if (!LHSTy->isPointerType() || RHSTy->isPointerType())
9015     return;
9016   if (LHSTy->getPointeeType() != RHSTy)
9017     return;
9018 
9019   S.Diag(Loc, diag::warn_division_sizeof_ptr) << LHS << LHS->getSourceRange();
9020 }
9021 
9022 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
9023                                                ExprResult &RHS,
9024                                                SourceLocation Loc, bool IsDiv) {
9025   // Check for division/remainder by zero.
9026   Expr::EvalResult RHSValue;
9027   if (!RHS.get()->isValueDependent() &&
9028       RHS.get()->EvaluateAsInt(RHSValue, S.Context) &&
9029       RHSValue.Val.getInt() == 0)
9030     S.DiagRuntimeBehavior(Loc, RHS.get(),
9031                           S.PDiag(diag::warn_remainder_division_by_zero)
9032                             << IsDiv << RHS.get()->getSourceRange());
9033 }
9034 
9035 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
9036                                            SourceLocation Loc,
9037                                            bool IsCompAssign, bool IsDiv) {
9038   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9039 
9040   if (LHS.get()->getType()->isVectorType() ||
9041       RHS.get()->getType()->isVectorType())
9042     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9043                                /*AllowBothBool*/getLangOpts().AltiVec,
9044                                /*AllowBoolConversions*/false);
9045 
9046   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9047   if (LHS.isInvalid() || RHS.isInvalid())
9048     return QualType();
9049 
9050 
9051   if (compType.isNull() || !compType->isArithmeticType())
9052     return InvalidOperands(Loc, LHS, RHS);
9053   if (IsDiv) {
9054     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
9055     DiagnoseDivisionSizeofPointer(*this, LHS.get(), RHS.get(), Loc);
9056   }
9057   return compType;
9058 }
9059 
9060 QualType Sema::CheckRemainderOperands(
9061   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9062   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9063 
9064   if (LHS.get()->getType()->isVectorType() ||
9065       RHS.get()->getType()->isVectorType()) {
9066     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9067         RHS.get()->getType()->hasIntegerRepresentation())
9068       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9069                                  /*AllowBothBool*/getLangOpts().AltiVec,
9070                                  /*AllowBoolConversions*/false);
9071     return InvalidOperands(Loc, LHS, RHS);
9072   }
9073 
9074   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
9075   if (LHS.isInvalid() || RHS.isInvalid())
9076     return QualType();
9077 
9078   if (compType.isNull() || !compType->isIntegerType())
9079     return InvalidOperands(Loc, LHS, RHS);
9080   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
9081   return compType;
9082 }
9083 
9084 /// Diagnose invalid arithmetic on two void pointers.
9085 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
9086                                                 Expr *LHSExpr, Expr *RHSExpr) {
9087   S.Diag(Loc, S.getLangOpts().CPlusPlus
9088                 ? diag::err_typecheck_pointer_arith_void_type
9089                 : diag::ext_gnu_void_ptr)
9090     << 1 /* two pointers */ << LHSExpr->getSourceRange()
9091                             << RHSExpr->getSourceRange();
9092 }
9093 
9094 /// Diagnose invalid arithmetic on a void pointer.
9095 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
9096                                             Expr *Pointer) {
9097   S.Diag(Loc, S.getLangOpts().CPlusPlus
9098                 ? diag::err_typecheck_pointer_arith_void_type
9099                 : diag::ext_gnu_void_ptr)
9100     << 0 /* one pointer */ << Pointer->getSourceRange();
9101 }
9102 
9103 /// Diagnose invalid arithmetic on a null pointer.
9104 ///
9105 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
9106 /// idiom, which we recognize as a GNU extension.
9107 ///
9108 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
9109                                             Expr *Pointer, bool IsGNUIdiom) {
9110   if (IsGNUIdiom)
9111     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
9112       << Pointer->getSourceRange();
9113   else
9114     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
9115       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
9116 }
9117 
9118 /// Diagnose invalid arithmetic on two function pointers.
9119 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
9120                                                     Expr *LHS, Expr *RHS) {
9121   assert(LHS->getType()->isAnyPointerType());
9122   assert(RHS->getType()->isAnyPointerType());
9123   S.Diag(Loc, S.getLangOpts().CPlusPlus
9124                 ? diag::err_typecheck_pointer_arith_function_type
9125                 : diag::ext_gnu_ptr_func_arith)
9126     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
9127     // We only show the second type if it differs from the first.
9128     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
9129                                                    RHS->getType())
9130     << RHS->getType()->getPointeeType()
9131     << LHS->getSourceRange() << RHS->getSourceRange();
9132 }
9133 
9134 /// Diagnose invalid arithmetic on a function pointer.
9135 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
9136                                                 Expr *Pointer) {
9137   assert(Pointer->getType()->isAnyPointerType());
9138   S.Diag(Loc, S.getLangOpts().CPlusPlus
9139                 ? diag::err_typecheck_pointer_arith_function_type
9140                 : diag::ext_gnu_ptr_func_arith)
9141     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
9142     << 0 /* one pointer, so only one type */
9143     << Pointer->getSourceRange();
9144 }
9145 
9146 /// Emit error if Operand is incomplete pointer type
9147 ///
9148 /// \returns True if pointer has incomplete type
9149 static bool checkArithmeticIncompletePointerType(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   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
9156   QualType PointeeTy = ResType->getPointeeType();
9157   return S.RequireCompleteType(Loc, PointeeTy,
9158                                diag::err_typecheck_arithmetic_incomplete_type,
9159                                PointeeTy, Operand->getSourceRange());
9160 }
9161 
9162 /// Check the validity of an arithmetic pointer operand.
9163 ///
9164 /// If the operand has pointer type, this code will check for pointer types
9165 /// which are invalid in arithmetic operations. These will be diagnosed
9166 /// appropriately, including whether or not the use is supported as an
9167 /// extension.
9168 ///
9169 /// \returns True when the operand is valid to use (even if as an extension).
9170 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
9171                                             Expr *Operand) {
9172   QualType ResType = Operand->getType();
9173   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9174     ResType = ResAtomicType->getValueType();
9175 
9176   if (!ResType->isAnyPointerType()) return true;
9177 
9178   QualType PointeeTy = ResType->getPointeeType();
9179   if (PointeeTy->isVoidType()) {
9180     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
9181     return !S.getLangOpts().CPlusPlus;
9182   }
9183   if (PointeeTy->isFunctionType()) {
9184     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
9185     return !S.getLangOpts().CPlusPlus;
9186   }
9187 
9188   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
9189 
9190   return true;
9191 }
9192 
9193 /// Check the validity of a binary arithmetic operation w.r.t. pointer
9194 /// operands.
9195 ///
9196 /// This routine will diagnose any invalid arithmetic on pointer operands much
9197 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
9198 /// for emitting a single diagnostic even for operations where both LHS and RHS
9199 /// are (potentially problematic) pointers.
9200 ///
9201 /// \returns True when the operand is valid to use (even if as an extension).
9202 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
9203                                                 Expr *LHSExpr, Expr *RHSExpr) {
9204   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
9205   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
9206   if (!isLHSPointer && !isRHSPointer) return true;
9207 
9208   QualType LHSPointeeTy, RHSPointeeTy;
9209   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
9210   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
9211 
9212   // if both are pointers check if operation is valid wrt address spaces
9213   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
9214     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
9215     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
9216     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
9217       S.Diag(Loc,
9218              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9219           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
9220           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9221       return false;
9222     }
9223   }
9224 
9225   // Check for arithmetic on pointers to incomplete types.
9226   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
9227   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
9228   if (isLHSVoidPtr || isRHSVoidPtr) {
9229     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
9230     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
9231     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
9232 
9233     return !S.getLangOpts().CPlusPlus;
9234   }
9235 
9236   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
9237   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
9238   if (isLHSFuncPtr || isRHSFuncPtr) {
9239     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
9240     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
9241                                                                 RHSExpr);
9242     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
9243 
9244     return !S.getLangOpts().CPlusPlus;
9245   }
9246 
9247   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
9248     return false;
9249   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
9250     return false;
9251 
9252   return true;
9253 }
9254 
9255 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
9256 /// literal.
9257 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
9258                                   Expr *LHSExpr, Expr *RHSExpr) {
9259   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
9260   Expr* IndexExpr = RHSExpr;
9261   if (!StrExpr) {
9262     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
9263     IndexExpr = LHSExpr;
9264   }
9265 
9266   bool IsStringPlusInt = StrExpr &&
9267       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
9268   if (!IsStringPlusInt || IndexExpr->isValueDependent())
9269     return;
9270 
9271   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9272   Self.Diag(OpLoc, diag::warn_string_plus_int)
9273       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
9274 
9275   // Only print a fixit for "str" + int, not for int + "str".
9276   if (IndexExpr == RHSExpr) {
9277     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9278     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9279         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9280         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9281         << FixItHint::CreateInsertion(EndLoc, "]");
9282   } else
9283     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9284 }
9285 
9286 /// Emit a warning when adding a char literal to a string.
9287 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
9288                                    Expr *LHSExpr, Expr *RHSExpr) {
9289   const Expr *StringRefExpr = LHSExpr;
9290   const CharacterLiteral *CharExpr =
9291       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
9292 
9293   if (!CharExpr) {
9294     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
9295     StringRefExpr = RHSExpr;
9296   }
9297 
9298   if (!CharExpr || !StringRefExpr)
9299     return;
9300 
9301   const QualType StringType = StringRefExpr->getType();
9302 
9303   // Return if not a PointerType.
9304   if (!StringType->isAnyPointerType())
9305     return;
9306 
9307   // Return if not a CharacterType.
9308   if (!StringType->getPointeeType()->isAnyCharacterType())
9309     return;
9310 
9311   ASTContext &Ctx = Self.getASTContext();
9312   SourceRange DiagRange(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
9313 
9314   const QualType CharType = CharExpr->getType();
9315   if (!CharType->isAnyCharacterType() &&
9316       CharType->isIntegerType() &&
9317       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
9318     Self.Diag(OpLoc, diag::warn_string_plus_char)
9319         << DiagRange << Ctx.CharTy;
9320   } else {
9321     Self.Diag(OpLoc, diag::warn_string_plus_char)
9322         << DiagRange << CharExpr->getType();
9323   }
9324 
9325   // Only print a fixit for str + char, not for char + str.
9326   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
9327     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getEndLoc());
9328     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
9329         << FixItHint::CreateInsertion(LHSExpr->getBeginLoc(), "&")
9330         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
9331         << FixItHint::CreateInsertion(EndLoc, "]");
9332   } else {
9333     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
9334   }
9335 }
9336 
9337 /// Emit error when two pointers are incompatible.
9338 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
9339                                            Expr *LHSExpr, Expr *RHSExpr) {
9340   assert(LHSExpr->getType()->isAnyPointerType());
9341   assert(RHSExpr->getType()->isAnyPointerType());
9342   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
9343     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
9344     << RHSExpr->getSourceRange();
9345 }
9346 
9347 // C99 6.5.6
9348 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
9349                                      SourceLocation Loc, BinaryOperatorKind Opc,
9350                                      QualType* CompLHSTy) {
9351   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9352 
9353   if (LHS.get()->getType()->isVectorType() ||
9354       RHS.get()->getType()->isVectorType()) {
9355     QualType compType = CheckVectorOperands(
9356         LHS, RHS, Loc, CompLHSTy,
9357         /*AllowBothBool*/getLangOpts().AltiVec,
9358         /*AllowBoolConversions*/getLangOpts().ZVector);
9359     if (CompLHSTy) *CompLHSTy = compType;
9360     return compType;
9361   }
9362 
9363   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9364   if (LHS.isInvalid() || RHS.isInvalid())
9365     return QualType();
9366 
9367   // Diagnose "string literal" '+' int and string '+' "char literal".
9368   if (Opc == BO_Add) {
9369     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
9370     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
9371   }
9372 
9373   // handle the common case first (both operands are arithmetic).
9374   if (!compType.isNull() && compType->isArithmeticType()) {
9375     if (CompLHSTy) *CompLHSTy = compType;
9376     return compType;
9377   }
9378 
9379   // Type-checking.  Ultimately the pointer's going to be in PExp;
9380   // note that we bias towards the LHS being the pointer.
9381   Expr *PExp = LHS.get(), *IExp = RHS.get();
9382 
9383   bool isObjCPointer;
9384   if (PExp->getType()->isPointerType()) {
9385     isObjCPointer = false;
9386   } else if (PExp->getType()->isObjCObjectPointerType()) {
9387     isObjCPointer = true;
9388   } else {
9389     std::swap(PExp, IExp);
9390     if (PExp->getType()->isPointerType()) {
9391       isObjCPointer = false;
9392     } else if (PExp->getType()->isObjCObjectPointerType()) {
9393       isObjCPointer = true;
9394     } else {
9395       return InvalidOperands(Loc, LHS, RHS);
9396     }
9397   }
9398   assert(PExp->getType()->isAnyPointerType());
9399 
9400   if (!IExp->getType()->isIntegerType())
9401     return InvalidOperands(Loc, LHS, RHS);
9402 
9403   // Adding to a null pointer results in undefined behavior.
9404   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
9405           Context, Expr::NPC_ValueDependentIsNotNull)) {
9406     // In C++ adding zero to a null pointer is defined.
9407     Expr::EvalResult KnownVal;
9408     if (!getLangOpts().CPlusPlus ||
9409         (!IExp->isValueDependent() &&
9410          (!IExp->EvaluateAsInt(KnownVal, Context) ||
9411           KnownVal.Val.getInt() != 0))) {
9412       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
9413       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
9414           Context, BO_Add, PExp, IExp);
9415       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
9416     }
9417   }
9418 
9419   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
9420     return QualType();
9421 
9422   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
9423     return QualType();
9424 
9425   // Check array bounds for pointer arithemtic
9426   CheckArrayAccess(PExp, IExp);
9427 
9428   if (CompLHSTy) {
9429     QualType LHSTy = Context.isPromotableBitField(LHS.get());
9430     if (LHSTy.isNull()) {
9431       LHSTy = LHS.get()->getType();
9432       if (LHSTy->isPromotableIntegerType())
9433         LHSTy = Context.getPromotedIntegerType(LHSTy);
9434     }
9435     *CompLHSTy = LHSTy;
9436   }
9437 
9438   return PExp->getType();
9439 }
9440 
9441 // C99 6.5.6
9442 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
9443                                         SourceLocation Loc,
9444                                         QualType* CompLHSTy) {
9445   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9446 
9447   if (LHS.get()->getType()->isVectorType() ||
9448       RHS.get()->getType()->isVectorType()) {
9449     QualType compType = CheckVectorOperands(
9450         LHS, RHS, Loc, CompLHSTy,
9451         /*AllowBothBool*/getLangOpts().AltiVec,
9452         /*AllowBoolConversions*/getLangOpts().ZVector);
9453     if (CompLHSTy) *CompLHSTy = compType;
9454     return compType;
9455   }
9456 
9457   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9458   if (LHS.isInvalid() || RHS.isInvalid())
9459     return QualType();
9460 
9461   // Enforce type constraints: C99 6.5.6p3.
9462 
9463   // Handle the common case first (both operands are arithmetic).
9464   if (!compType.isNull() && compType->isArithmeticType()) {
9465     if (CompLHSTy) *CompLHSTy = compType;
9466     return compType;
9467   }
9468 
9469   // Either ptr - int   or   ptr - ptr.
9470   if (LHS.get()->getType()->isAnyPointerType()) {
9471     QualType lpointee = LHS.get()->getType()->getPointeeType();
9472 
9473     // Diagnose bad cases where we step over interface counts.
9474     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9475         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9476       return QualType();
9477 
9478     // The result type of a pointer-int computation is the pointer type.
9479     if (RHS.get()->getType()->isIntegerType()) {
9480       // Subtracting from a null pointer should produce a warning.
9481       // The last argument to the diagnose call says this doesn't match the
9482       // GNU int-to-pointer idiom.
9483       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9484                                            Expr::NPC_ValueDependentIsNotNull)) {
9485         // In C++ adding zero to a null pointer is defined.
9486         Expr::EvalResult KnownVal;
9487         if (!getLangOpts().CPlusPlus ||
9488             (!RHS.get()->isValueDependent() &&
9489              (!RHS.get()->EvaluateAsInt(KnownVal, Context) ||
9490               KnownVal.Val.getInt() != 0))) {
9491           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9492         }
9493       }
9494 
9495       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9496         return QualType();
9497 
9498       // Check array bounds for pointer arithemtic
9499       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9500                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9501 
9502       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9503       return LHS.get()->getType();
9504     }
9505 
9506     // Handle pointer-pointer subtractions.
9507     if (const PointerType *RHSPTy
9508           = RHS.get()->getType()->getAs<PointerType>()) {
9509       QualType rpointee = RHSPTy->getPointeeType();
9510 
9511       if (getLangOpts().CPlusPlus) {
9512         // Pointee types must be the same: C++ [expr.add]
9513         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9514           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9515         }
9516       } else {
9517         // Pointee types must be compatible C99 6.5.6p3
9518         if (!Context.typesAreCompatible(
9519                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9520                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9521           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9522           return QualType();
9523         }
9524       }
9525 
9526       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9527                                                LHS.get(), RHS.get()))
9528         return QualType();
9529 
9530       // FIXME: Add warnings for nullptr - ptr.
9531 
9532       // The pointee type may have zero size.  As an extension, a structure or
9533       // union may have zero size or an array may have zero length.  In this
9534       // case subtraction does not make sense.
9535       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9536         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9537         if (ElementSize.isZero()) {
9538           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9539             << rpointee.getUnqualifiedType()
9540             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9541         }
9542       }
9543 
9544       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9545       return Context.getPointerDiffType();
9546     }
9547   }
9548 
9549   return InvalidOperands(Loc, LHS, RHS);
9550 }
9551 
9552 static bool isScopedEnumerationType(QualType T) {
9553   if (const EnumType *ET = T->getAs<EnumType>())
9554     return ET->getDecl()->isScoped();
9555   return false;
9556 }
9557 
9558 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9559                                    SourceLocation Loc, BinaryOperatorKind Opc,
9560                                    QualType LHSType) {
9561   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9562   // so skip remaining warnings as we don't want to modify values within Sema.
9563   if (S.getLangOpts().OpenCL)
9564     return;
9565 
9566   // Check right/shifter operand
9567   Expr::EvalResult RHSResult;
9568   if (RHS.get()->isValueDependent() ||
9569       !RHS.get()->EvaluateAsInt(RHSResult, S.Context))
9570     return;
9571   llvm::APSInt Right = RHSResult.Val.getInt();
9572 
9573   if (Right.isNegative()) {
9574     S.DiagRuntimeBehavior(Loc, RHS.get(),
9575                           S.PDiag(diag::warn_shift_negative)
9576                             << RHS.get()->getSourceRange());
9577     return;
9578   }
9579   llvm::APInt LeftBits(Right.getBitWidth(),
9580                        S.Context.getTypeSize(LHS.get()->getType()));
9581   if (Right.uge(LeftBits)) {
9582     S.DiagRuntimeBehavior(Loc, RHS.get(),
9583                           S.PDiag(diag::warn_shift_gt_typewidth)
9584                             << RHS.get()->getSourceRange());
9585     return;
9586   }
9587   if (Opc != BO_Shl)
9588     return;
9589 
9590   // When left shifting an ICE which is signed, we can check for overflow which
9591   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9592   // integers have defined behavior modulo one more than the maximum value
9593   // representable in the result type, so never warn for those.
9594   Expr::EvalResult LHSResult;
9595   if (LHS.get()->isValueDependent() ||
9596       LHSType->hasUnsignedIntegerRepresentation() ||
9597       !LHS.get()->EvaluateAsInt(LHSResult, S.Context))
9598     return;
9599   llvm::APSInt Left = LHSResult.Val.getInt();
9600 
9601   // If LHS does not have a signed type and non-negative value
9602   // then, the behavior is undefined. Warn about it.
9603   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9604     S.DiagRuntimeBehavior(Loc, LHS.get(),
9605                           S.PDiag(diag::warn_shift_lhs_negative)
9606                             << LHS.get()->getSourceRange());
9607     return;
9608   }
9609 
9610   llvm::APInt ResultBits =
9611       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9612   if (LeftBits.uge(ResultBits))
9613     return;
9614   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9615   Result = Result.shl(Right);
9616 
9617   // Print the bit representation of the signed integer as an unsigned
9618   // hexadecimal number.
9619   SmallString<40> HexResult;
9620   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9621 
9622   // If we are only missing a sign bit, this is less likely to result in actual
9623   // bugs -- if the result is cast back to an unsigned type, it will have the
9624   // expected value. Thus we place this behind a different warning that can be
9625   // turned off separately if needed.
9626   if (LeftBits == ResultBits - 1) {
9627     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9628         << HexResult << LHSType
9629         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9630     return;
9631   }
9632 
9633   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9634     << HexResult.str() << Result.getMinSignedBits() << LHSType
9635     << Left.getBitWidth() << LHS.get()->getSourceRange()
9636     << RHS.get()->getSourceRange();
9637 }
9638 
9639 /// Return the resulting type when a vector is shifted
9640 ///        by a scalar or vector shift amount.
9641 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9642                                  SourceLocation Loc, bool IsCompAssign) {
9643   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9644   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9645       !LHS.get()->getType()->isVectorType()) {
9646     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9647       << RHS.get()->getType() << LHS.get()->getType()
9648       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9649     return QualType();
9650   }
9651 
9652   if (!IsCompAssign) {
9653     LHS = S.UsualUnaryConversions(LHS.get());
9654     if (LHS.isInvalid()) return QualType();
9655   }
9656 
9657   RHS = S.UsualUnaryConversions(RHS.get());
9658   if (RHS.isInvalid()) return QualType();
9659 
9660   QualType LHSType = LHS.get()->getType();
9661   // Note that LHS might be a scalar because the routine calls not only in
9662   // OpenCL case.
9663   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9664   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9665 
9666   // Note that RHS might not be a vector.
9667   QualType RHSType = RHS.get()->getType();
9668   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9669   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9670 
9671   // The operands need to be integers.
9672   if (!LHSEleType->isIntegerType()) {
9673     S.Diag(Loc, diag::err_typecheck_expect_int)
9674       << LHS.get()->getType() << LHS.get()->getSourceRange();
9675     return QualType();
9676   }
9677 
9678   if (!RHSEleType->isIntegerType()) {
9679     S.Diag(Loc, diag::err_typecheck_expect_int)
9680       << RHS.get()->getType() << RHS.get()->getSourceRange();
9681     return QualType();
9682   }
9683 
9684   if (!LHSVecTy) {
9685     assert(RHSVecTy);
9686     if (IsCompAssign)
9687       return RHSType;
9688     if (LHSEleType != RHSEleType) {
9689       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9690       LHSEleType = RHSEleType;
9691     }
9692     QualType VecTy =
9693         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9694     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9695     LHSType = VecTy;
9696   } else if (RHSVecTy) {
9697     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9698     // are applied component-wise. So if RHS is a vector, then ensure
9699     // that the number of elements is the same as LHS...
9700     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9701       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9702         << LHS.get()->getType() << RHS.get()->getType()
9703         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9704       return QualType();
9705     }
9706     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9707       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9708       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9709       if (LHSBT != RHSBT &&
9710           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9711         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9712             << LHS.get()->getType() << RHS.get()->getType()
9713             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9714       }
9715     }
9716   } else {
9717     // ...else expand RHS to match the number of elements in LHS.
9718     QualType VecTy =
9719       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9720     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9721   }
9722 
9723   return LHSType;
9724 }
9725 
9726 // C99 6.5.7
9727 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9728                                   SourceLocation Loc, BinaryOperatorKind Opc,
9729                                   bool IsCompAssign) {
9730   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9731 
9732   // Vector shifts promote their scalar inputs to vector type.
9733   if (LHS.get()->getType()->isVectorType() ||
9734       RHS.get()->getType()->isVectorType()) {
9735     if (LangOpts.ZVector) {
9736       // The shift operators for the z vector extensions work basically
9737       // like general shifts, except that neither the LHS nor the RHS is
9738       // allowed to be a "vector bool".
9739       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9740         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9741           return InvalidOperands(Loc, LHS, RHS);
9742       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9743         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9744           return InvalidOperands(Loc, LHS, RHS);
9745     }
9746     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9747   }
9748 
9749   // Shifts don't perform usual arithmetic conversions, they just do integer
9750   // promotions on each operand. C99 6.5.7p3
9751 
9752   // For the LHS, do usual unary conversions, but then reset them away
9753   // if this is a compound assignment.
9754   ExprResult OldLHS = LHS;
9755   LHS = UsualUnaryConversions(LHS.get());
9756   if (LHS.isInvalid())
9757     return QualType();
9758   QualType LHSType = LHS.get()->getType();
9759   if (IsCompAssign) LHS = OldLHS;
9760 
9761   // The RHS is simpler.
9762   RHS = UsualUnaryConversions(RHS.get());
9763   if (RHS.isInvalid())
9764     return QualType();
9765   QualType RHSType = RHS.get()->getType();
9766 
9767   // C99 6.5.7p2: Each of the operands shall have integer type.
9768   if (!LHSType->hasIntegerRepresentation() ||
9769       !RHSType->hasIntegerRepresentation())
9770     return InvalidOperands(Loc, LHS, RHS);
9771 
9772   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9773   // hasIntegerRepresentation() above instead of this.
9774   if (isScopedEnumerationType(LHSType) ||
9775       isScopedEnumerationType(RHSType)) {
9776     return InvalidOperands(Loc, LHS, RHS);
9777   }
9778   // Sanity-check shift operands
9779   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9780 
9781   // "The type of the result is that of the promoted left operand."
9782   return LHSType;
9783 }
9784 
9785 /// If two different enums are compared, raise a warning.
9786 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9787                                 Expr *RHS) {
9788   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9789   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9790 
9791   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9792   if (!LHSEnumType)
9793     return;
9794   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9795   if (!RHSEnumType)
9796     return;
9797 
9798   // Ignore anonymous enums.
9799   if (!LHSEnumType->getDecl()->getIdentifier() &&
9800       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9801     return;
9802   if (!RHSEnumType->getDecl()->getIdentifier() &&
9803       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9804     return;
9805 
9806   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9807     return;
9808 
9809   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9810       << LHSStrippedType << RHSStrippedType
9811       << LHS->getSourceRange() << RHS->getSourceRange();
9812 }
9813 
9814 /// Diagnose bad pointer comparisons.
9815 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9816                                               ExprResult &LHS, ExprResult &RHS,
9817                                               bool IsError) {
9818   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9819                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9820     << LHS.get()->getType() << RHS.get()->getType()
9821     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9822 }
9823 
9824 /// Returns false if the pointers are converted to a composite type,
9825 /// true otherwise.
9826 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9827                                            ExprResult &LHS, ExprResult &RHS) {
9828   // C++ [expr.rel]p2:
9829   //   [...] Pointer conversions (4.10) and qualification
9830   //   conversions (4.4) are performed on pointer operands (or on
9831   //   a pointer operand and a null pointer constant) to bring
9832   //   them to their composite pointer type. [...]
9833   //
9834   // C++ [expr.eq]p1 uses the same notion for (in)equality
9835   // comparisons of pointers.
9836 
9837   QualType LHSType = LHS.get()->getType();
9838   QualType RHSType = RHS.get()->getType();
9839   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9840          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9841 
9842   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9843   if (T.isNull()) {
9844     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9845         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9846       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9847     else
9848       S.InvalidOperands(Loc, LHS, RHS);
9849     return true;
9850   }
9851 
9852   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9853   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9854   return false;
9855 }
9856 
9857 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9858                                                     ExprResult &LHS,
9859                                                     ExprResult &RHS,
9860                                                     bool IsError) {
9861   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9862                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9863     << LHS.get()->getType() << RHS.get()->getType()
9864     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9865 }
9866 
9867 static bool isObjCObjectLiteral(ExprResult &E) {
9868   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9869   case Stmt::ObjCArrayLiteralClass:
9870   case Stmt::ObjCDictionaryLiteralClass:
9871   case Stmt::ObjCStringLiteralClass:
9872   case Stmt::ObjCBoxedExprClass:
9873     return true;
9874   default:
9875     // Note that ObjCBoolLiteral is NOT an object literal!
9876     return false;
9877   }
9878 }
9879 
9880 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9881   const ObjCObjectPointerType *Type =
9882     LHS->getType()->getAs<ObjCObjectPointerType>();
9883 
9884   // If this is not actually an Objective-C object, bail out.
9885   if (!Type)
9886     return false;
9887 
9888   // Get the LHS object's interface type.
9889   QualType InterfaceType = Type->getPointeeType();
9890 
9891   // If the RHS isn't an Objective-C object, bail out.
9892   if (!RHS->getType()->isObjCObjectPointerType())
9893     return false;
9894 
9895   // Try to find the -isEqual: method.
9896   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9897   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9898                                                       InterfaceType,
9899                                                       /*instance=*/true);
9900   if (!Method) {
9901     if (Type->isObjCIdType()) {
9902       // For 'id', just check the global pool.
9903       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9904                                                   /*receiverId=*/true);
9905     } else {
9906       // Check protocols.
9907       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9908                                              /*instance=*/true);
9909     }
9910   }
9911 
9912   if (!Method)
9913     return false;
9914 
9915   QualType T = Method->parameters()[0]->getType();
9916   if (!T->isObjCObjectPointerType())
9917     return false;
9918 
9919   QualType R = Method->getReturnType();
9920   if (!R->isScalarType())
9921     return false;
9922 
9923   return true;
9924 }
9925 
9926 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9927   FromE = FromE->IgnoreParenImpCasts();
9928   switch (FromE->getStmtClass()) {
9929     default:
9930       break;
9931     case Stmt::ObjCStringLiteralClass:
9932       // "string literal"
9933       return LK_String;
9934     case Stmt::ObjCArrayLiteralClass:
9935       // "array literal"
9936       return LK_Array;
9937     case Stmt::ObjCDictionaryLiteralClass:
9938       // "dictionary literal"
9939       return LK_Dictionary;
9940     case Stmt::BlockExprClass:
9941       return LK_Block;
9942     case Stmt::ObjCBoxedExprClass: {
9943       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9944       switch (Inner->getStmtClass()) {
9945         case Stmt::IntegerLiteralClass:
9946         case Stmt::FloatingLiteralClass:
9947         case Stmt::CharacterLiteralClass:
9948         case Stmt::ObjCBoolLiteralExprClass:
9949         case Stmt::CXXBoolLiteralExprClass:
9950           // "numeric literal"
9951           return LK_Numeric;
9952         case Stmt::ImplicitCastExprClass: {
9953           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9954           // Boolean literals can be represented by implicit casts.
9955           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9956             return LK_Numeric;
9957           break;
9958         }
9959         default:
9960           break;
9961       }
9962       return LK_Boxed;
9963     }
9964   }
9965   return LK_None;
9966 }
9967 
9968 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9969                                           ExprResult &LHS, ExprResult &RHS,
9970                                           BinaryOperator::Opcode Opc){
9971   Expr *Literal;
9972   Expr *Other;
9973   if (isObjCObjectLiteral(LHS)) {
9974     Literal = LHS.get();
9975     Other = RHS.get();
9976   } else {
9977     Literal = RHS.get();
9978     Other = LHS.get();
9979   }
9980 
9981   // Don't warn on comparisons against nil.
9982   Other = Other->IgnoreParenCasts();
9983   if (Other->isNullPointerConstant(S.getASTContext(),
9984                                    Expr::NPC_ValueDependentIsNotNull))
9985     return;
9986 
9987   // This should be kept in sync with warn_objc_literal_comparison.
9988   // LK_String should always be after the other literals, since it has its own
9989   // warning flag.
9990   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9991   assert(LiteralKind != Sema::LK_Block);
9992   if (LiteralKind == Sema::LK_None) {
9993     llvm_unreachable("Unknown Objective-C object literal kind");
9994   }
9995 
9996   if (LiteralKind == Sema::LK_String)
9997     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9998       << Literal->getSourceRange();
9999   else
10000     S.Diag(Loc, diag::warn_objc_literal_comparison)
10001       << LiteralKind << Literal->getSourceRange();
10002 
10003   if (BinaryOperator::isEqualityOp(Opc) &&
10004       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
10005     SourceLocation Start = LHS.get()->getBeginLoc();
10006     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getEndLoc());
10007     CharSourceRange OpRange =
10008       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
10009 
10010     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
10011       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
10012       << FixItHint::CreateReplacement(OpRange, " isEqual:")
10013       << FixItHint::CreateInsertion(End, "]");
10014   }
10015 }
10016 
10017 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
10018 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
10019                                            ExprResult &RHS, SourceLocation Loc,
10020                                            BinaryOperatorKind Opc) {
10021   // Check that left hand side is !something.
10022   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
10023   if (!UO || UO->getOpcode() != UO_LNot) return;
10024 
10025   // Only check if the right hand side is non-bool arithmetic type.
10026   if (RHS.get()->isKnownToHaveBooleanValue()) return;
10027 
10028   // Make sure that the something in !something is not bool.
10029   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
10030   if (SubExpr->isKnownToHaveBooleanValue()) return;
10031 
10032   // Emit warning.
10033   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
10034   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
10035       << Loc << IsBitwiseOp;
10036 
10037   // First note suggest !(x < y)
10038   SourceLocation FirstOpen = SubExpr->getBeginLoc();
10039   SourceLocation FirstClose = RHS.get()->getEndLoc();
10040   FirstClose = S.getLocForEndOfToken(FirstClose);
10041   if (FirstClose.isInvalid())
10042     FirstOpen = SourceLocation();
10043   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
10044       << IsBitwiseOp
10045       << FixItHint::CreateInsertion(FirstOpen, "(")
10046       << FixItHint::CreateInsertion(FirstClose, ")");
10047 
10048   // Second note suggests (!x) < y
10049   SourceLocation SecondOpen = LHS.get()->getBeginLoc();
10050   SourceLocation SecondClose = LHS.get()->getEndLoc();
10051   SecondClose = S.getLocForEndOfToken(SecondClose);
10052   if (SecondClose.isInvalid())
10053     SecondOpen = SourceLocation();
10054   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
10055       << FixItHint::CreateInsertion(SecondOpen, "(")
10056       << FixItHint::CreateInsertion(SecondClose, ")");
10057 }
10058 
10059 // Get the decl for a simple expression: a reference to a variable,
10060 // an implicit C++ field reference, or an implicit ObjC ivar reference.
10061 static ValueDecl *getCompareDecl(Expr *E) {
10062   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
10063     return DR->getDecl();
10064   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
10065     if (Ivar->isFreeIvar())
10066       return Ivar->getDecl();
10067   }
10068   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
10069     if (Mem->isImplicitAccess())
10070       return Mem->getMemberDecl();
10071   }
10072   return nullptr;
10073 }
10074 
10075 /// Diagnose some forms of syntactically-obvious tautological comparison.
10076 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
10077                                            Expr *LHS, Expr *RHS,
10078                                            BinaryOperatorKind Opc) {
10079   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
10080   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
10081 
10082   QualType LHSType = LHS->getType();
10083   QualType RHSType = RHS->getType();
10084   if (LHSType->hasFloatingRepresentation() ||
10085       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
10086       LHS->getBeginLoc().isMacroID() || RHS->getBeginLoc().isMacroID() ||
10087       S.inTemplateInstantiation())
10088     return;
10089 
10090   // Comparisons between two array types are ill-formed for operator<=>, so
10091   // we shouldn't emit any additional warnings about it.
10092   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
10093     return;
10094 
10095   // For non-floating point types, check for self-comparisons of the form
10096   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10097   // often indicate logic errors in the program.
10098   //
10099   // NOTE: Don't warn about comparison expressions resulting from macro
10100   // expansion. Also don't warn about comparisons which are only self
10101   // comparisons within a template instantiation. The warnings should catch
10102   // obvious cases in the definition of the template anyways. The idea is to
10103   // warn when the typed comparison operator will always evaluate to the same
10104   // result.
10105   ValueDecl *DL = getCompareDecl(LHSStripped);
10106   ValueDecl *DR = getCompareDecl(RHSStripped);
10107   if (DL && DR && declaresSameEntity(DL, DR)) {
10108     StringRef Result;
10109     switch (Opc) {
10110     case BO_EQ: case BO_LE: case BO_GE:
10111       Result = "true";
10112       break;
10113     case BO_NE: case BO_LT: case BO_GT:
10114       Result = "false";
10115       break;
10116     case BO_Cmp:
10117       Result = "'std::strong_ordering::equal'";
10118       break;
10119     default:
10120       break;
10121     }
10122     S.DiagRuntimeBehavior(Loc, nullptr,
10123                           S.PDiag(diag::warn_comparison_always)
10124                               << 0 /*self-comparison*/ << !Result.empty()
10125                               << Result);
10126   } else if (DL && DR &&
10127              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
10128              !DL->isWeak() && !DR->isWeak()) {
10129     // What is it always going to evaluate to?
10130     StringRef Result;
10131     switch(Opc) {
10132     case BO_EQ: // e.g. array1 == array2
10133       Result = "false";
10134       break;
10135     case BO_NE: // e.g. array1 != array2
10136       Result = "true";
10137       break;
10138     default: // e.g. array1 <= array2
10139       // The best we can say is 'a constant'
10140       break;
10141     }
10142     S.DiagRuntimeBehavior(Loc, nullptr,
10143                           S.PDiag(diag::warn_comparison_always)
10144                               << 1 /*array comparison*/
10145                               << !Result.empty() << Result);
10146   }
10147 
10148   if (isa<CastExpr>(LHSStripped))
10149     LHSStripped = LHSStripped->IgnoreParenCasts();
10150   if (isa<CastExpr>(RHSStripped))
10151     RHSStripped = RHSStripped->IgnoreParenCasts();
10152 
10153   // Warn about comparisons against a string constant (unless the other
10154   // operand is null); the user probably wants strcmp.
10155   Expr *LiteralString = nullptr;
10156   Expr *LiteralStringStripped = nullptr;
10157   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
10158       !RHSStripped->isNullPointerConstant(S.Context,
10159                                           Expr::NPC_ValueDependentIsNull)) {
10160     LiteralString = LHS;
10161     LiteralStringStripped = LHSStripped;
10162   } else if ((isa<StringLiteral>(RHSStripped) ||
10163               isa<ObjCEncodeExpr>(RHSStripped)) &&
10164              !LHSStripped->isNullPointerConstant(S.Context,
10165                                           Expr::NPC_ValueDependentIsNull)) {
10166     LiteralString = RHS;
10167     LiteralStringStripped = RHSStripped;
10168   }
10169 
10170   if (LiteralString) {
10171     S.DiagRuntimeBehavior(Loc, nullptr,
10172                           S.PDiag(diag::warn_stringcompare)
10173                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
10174                               << LiteralString->getSourceRange());
10175   }
10176 }
10177 
10178 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
10179   switch (CK) {
10180   default: {
10181 #ifndef NDEBUG
10182     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
10183                  << "\n";
10184 #endif
10185     llvm_unreachable("unhandled cast kind");
10186   }
10187   case CK_UserDefinedConversion:
10188     return ICK_Identity;
10189   case CK_LValueToRValue:
10190     return ICK_Lvalue_To_Rvalue;
10191   case CK_ArrayToPointerDecay:
10192     return ICK_Array_To_Pointer;
10193   case CK_FunctionToPointerDecay:
10194     return ICK_Function_To_Pointer;
10195   case CK_IntegralCast:
10196     return ICK_Integral_Conversion;
10197   case CK_FloatingCast:
10198     return ICK_Floating_Conversion;
10199   case CK_IntegralToFloating:
10200   case CK_FloatingToIntegral:
10201     return ICK_Floating_Integral;
10202   case CK_IntegralComplexCast:
10203   case CK_FloatingComplexCast:
10204   case CK_FloatingComplexToIntegralComplex:
10205   case CK_IntegralComplexToFloatingComplex:
10206     return ICK_Complex_Conversion;
10207   case CK_FloatingComplexToReal:
10208   case CK_FloatingRealToComplex:
10209   case CK_IntegralComplexToReal:
10210   case CK_IntegralRealToComplex:
10211     return ICK_Complex_Real;
10212   }
10213 }
10214 
10215 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
10216                                              QualType FromType,
10217                                              SourceLocation Loc) {
10218   // Check for a narrowing implicit conversion.
10219   StandardConversionSequence SCS;
10220   SCS.setAsIdentityConversion();
10221   SCS.setToType(0, FromType);
10222   SCS.setToType(1, ToType);
10223   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
10224     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
10225 
10226   APValue PreNarrowingValue;
10227   QualType PreNarrowingType;
10228   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
10229                                PreNarrowingType,
10230                                /*IgnoreFloatToIntegralConversion*/ true)) {
10231   case NK_Dependent_Narrowing:
10232     // Implicit conversion to a narrower type, but the expression is
10233     // value-dependent so we can't tell whether it's actually narrowing.
10234   case NK_Not_Narrowing:
10235     return false;
10236 
10237   case NK_Constant_Narrowing:
10238     // Implicit conversion to a narrower type, and the value is not a constant
10239     // expression.
10240     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10241         << /*Constant*/ 1
10242         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
10243     return true;
10244 
10245   case NK_Variable_Narrowing:
10246     // Implicit conversion to a narrower type, and the value is not a constant
10247     // expression.
10248   case NK_Type_Narrowing:
10249     S.Diag(E->getBeginLoc(), diag::err_spaceship_argument_narrowing)
10250         << /*Constant*/ 0 << FromType << ToType;
10251     // TODO: It's not a constant expression, but what if the user intended it
10252     // to be? Can we produce notes to help them figure out why it isn't?
10253     return true;
10254   }
10255   llvm_unreachable("unhandled case in switch");
10256 }
10257 
10258 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
10259                                                          ExprResult &LHS,
10260                                                          ExprResult &RHS,
10261                                                          SourceLocation Loc) {
10262   using CCT = ComparisonCategoryType;
10263 
10264   QualType LHSType = LHS.get()->getType();
10265   QualType RHSType = RHS.get()->getType();
10266   // Dig out the original argument type and expression before implicit casts
10267   // were applied. These are the types/expressions we need to check the
10268   // [expr.spaceship] requirements against.
10269   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
10270   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
10271   QualType LHSStrippedType = LHSStripped.get()->getType();
10272   QualType RHSStrippedType = RHSStripped.get()->getType();
10273 
10274   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
10275   // other is not, the program is ill-formed.
10276   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
10277     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10278     return QualType();
10279   }
10280 
10281   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
10282                     RHSStrippedType->isEnumeralType();
10283   if (NumEnumArgs == 1) {
10284     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
10285     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
10286     if (OtherTy->hasFloatingRepresentation()) {
10287       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
10288       return QualType();
10289     }
10290   }
10291   if (NumEnumArgs == 2) {
10292     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
10293     // type E, the operator yields the result of converting the operands
10294     // to the underlying type of E and applying <=> to the converted operands.
10295     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
10296       S.InvalidOperands(Loc, LHS, RHS);
10297       return QualType();
10298     }
10299     QualType IntType =
10300         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
10301     assert(IntType->isArithmeticType());
10302 
10303     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
10304     // promote the boolean type, and all other promotable integer types, to
10305     // avoid this.
10306     if (IntType->isPromotableIntegerType())
10307       IntType = S.Context.getPromotedIntegerType(IntType);
10308 
10309     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
10310     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
10311     LHSType = RHSType = IntType;
10312   }
10313 
10314   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
10315   // usual arithmetic conversions are applied to the operands.
10316   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10317   if (LHS.isInvalid() || RHS.isInvalid())
10318     return QualType();
10319   if (Type.isNull())
10320     return S.InvalidOperands(Loc, LHS, RHS);
10321   assert(Type->isArithmeticType() || Type->isEnumeralType());
10322 
10323   bool HasNarrowing = checkThreeWayNarrowingConversion(
10324       S, Type, LHS.get(), LHSType, LHS.get()->getBeginLoc());
10325   HasNarrowing |= checkThreeWayNarrowingConversion(S, Type, RHS.get(), RHSType,
10326                                                    RHS.get()->getBeginLoc());
10327   if (HasNarrowing)
10328     return QualType();
10329 
10330   assert(!Type.isNull() && "composite type for <=> has not been set");
10331 
10332   auto TypeKind = [&]() {
10333     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
10334       if (CT->getElementType()->hasFloatingRepresentation())
10335         return CCT::WeakEquality;
10336       return CCT::StrongEquality;
10337     }
10338     if (Type->isIntegralOrEnumerationType())
10339       return CCT::StrongOrdering;
10340     if (Type->hasFloatingRepresentation())
10341       return CCT::PartialOrdering;
10342     llvm_unreachable("other types are unimplemented");
10343   }();
10344 
10345   return S.CheckComparisonCategoryType(TypeKind, Loc);
10346 }
10347 
10348 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
10349                                                  ExprResult &RHS,
10350                                                  SourceLocation Loc,
10351                                                  BinaryOperatorKind Opc) {
10352   if (Opc == BO_Cmp)
10353     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
10354 
10355   // C99 6.5.8p3 / C99 6.5.9p4
10356   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
10357   if (LHS.isInvalid() || RHS.isInvalid())
10358     return QualType();
10359   if (Type.isNull())
10360     return S.InvalidOperands(Loc, LHS, RHS);
10361   assert(Type->isArithmeticType() || Type->isEnumeralType());
10362 
10363   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
10364 
10365   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
10366     return S.InvalidOperands(Loc, LHS, RHS);
10367 
10368   // Check for comparisons of floating point operands using != and ==.
10369   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
10370     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
10371 
10372   // The result of comparisons is 'bool' in C++, 'int' in C.
10373   return S.Context.getLogicalOperationType();
10374 }
10375 
10376 // C99 6.5.8, C++ [expr.rel]
10377 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
10378                                     SourceLocation Loc,
10379                                     BinaryOperatorKind Opc) {
10380   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
10381   bool IsThreeWay = Opc == BO_Cmp;
10382   auto IsAnyPointerType = [](ExprResult E) {
10383     QualType Ty = E.get()->getType();
10384     return Ty->isPointerType() || Ty->isMemberPointerType();
10385   };
10386 
10387   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
10388   // type, array-to-pointer, ..., conversions are performed on both operands to
10389   // bring them to their composite type.
10390   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
10391   // any type-related checks.
10392   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
10393     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
10394     if (LHS.isInvalid())
10395       return QualType();
10396     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
10397     if (RHS.isInvalid())
10398       return QualType();
10399   } else {
10400     LHS = DefaultLvalueConversion(LHS.get());
10401     if (LHS.isInvalid())
10402       return QualType();
10403     RHS = DefaultLvalueConversion(RHS.get());
10404     if (RHS.isInvalid())
10405       return QualType();
10406   }
10407 
10408   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
10409 
10410   // Handle vector comparisons separately.
10411   if (LHS.get()->getType()->isVectorType() ||
10412       RHS.get()->getType()->isVectorType())
10413     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
10414 
10415   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10416   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10417 
10418   QualType LHSType = LHS.get()->getType();
10419   QualType RHSType = RHS.get()->getType();
10420   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
10421       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
10422     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
10423 
10424   const Expr::NullPointerConstantKind LHSNullKind =
10425       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10426   const Expr::NullPointerConstantKind RHSNullKind =
10427       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
10428   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
10429   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
10430 
10431   auto computeResultTy = [&]() {
10432     if (Opc != BO_Cmp)
10433       return Context.getLogicalOperationType();
10434     assert(getLangOpts().CPlusPlus);
10435     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
10436 
10437     QualType CompositeTy = LHS.get()->getType();
10438     assert(!CompositeTy->isReferenceType());
10439 
10440     auto buildResultTy = [&](ComparisonCategoryType Kind) {
10441       return CheckComparisonCategoryType(Kind, Loc);
10442     };
10443 
10444     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
10445     // pointer type, a pointer-to-member type, or std::nullptr_t, the
10446     // result is of type std::strong_equality
10447     if (CompositeTy->isFunctionPointerType() ||
10448         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
10449       // FIXME: consider making the function pointer case produce
10450       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
10451       // and direction polls
10452       return buildResultTy(ComparisonCategoryType::StrongEquality);
10453 
10454     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
10455     // pointer type, p <=> q is of type std::strong_ordering.
10456     if (CompositeTy->isPointerType()) {
10457       // P0946R0: Comparisons between a null pointer constant and an object
10458       // pointer result in std::strong_equality
10459       if (LHSIsNull != RHSIsNull)
10460         return buildResultTy(ComparisonCategoryType::StrongEquality);
10461       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10462     }
10463     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10464     // TODO: Extend support for operator<=> to ObjC types.
10465     return InvalidOperands(Loc, LHS, RHS);
10466   };
10467 
10468 
10469   if (!IsRelational && LHSIsNull != RHSIsNull) {
10470     bool IsEquality = Opc == BO_EQ;
10471     if (RHSIsNull)
10472       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10473                                    RHS.get()->getSourceRange());
10474     else
10475       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10476                                    LHS.get()->getSourceRange());
10477   }
10478 
10479   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10480       (RHSType->isIntegerType() && !RHSIsNull)) {
10481     // Skip normal pointer conversion checks in this case; we have better
10482     // diagnostics for this below.
10483   } else if (getLangOpts().CPlusPlus) {
10484     // Equality comparison of a function pointer to a void pointer is invalid,
10485     // but we allow it as an extension.
10486     // FIXME: If we really want to allow this, should it be part of composite
10487     // pointer type computation so it works in conditionals too?
10488     if (!IsRelational &&
10489         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10490          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10491       // This is a gcc extension compatibility comparison.
10492       // In a SFINAE context, we treat this as a hard error to maintain
10493       // conformance with the C++ standard.
10494       diagnoseFunctionPointerToVoidComparison(
10495           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10496 
10497       if (isSFINAEContext())
10498         return QualType();
10499 
10500       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10501       return computeResultTy();
10502     }
10503 
10504     // C++ [expr.eq]p2:
10505     //   If at least one operand is a pointer [...] bring them to their
10506     //   composite pointer type.
10507     // C++ [expr.spaceship]p6
10508     //  If at least one of the operands is of pointer type, [...] bring them
10509     //  to their composite pointer type.
10510     // C++ [expr.rel]p2:
10511     //   If both operands are pointers, [...] bring them to their composite
10512     //   pointer type.
10513     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10514             (IsRelational ? 2 : 1) &&
10515         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10516                                          RHSType->isObjCObjectPointerType()))) {
10517       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10518         return QualType();
10519       return computeResultTy();
10520     }
10521   } else if (LHSType->isPointerType() &&
10522              RHSType->isPointerType()) { // C99 6.5.8p2
10523     // All of the following pointer-related warnings are GCC extensions, except
10524     // when handling null pointer constants.
10525     QualType LCanPointeeTy =
10526       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10527     QualType RCanPointeeTy =
10528       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10529 
10530     // C99 6.5.9p2 and C99 6.5.8p2
10531     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10532                                    RCanPointeeTy.getUnqualifiedType())) {
10533       // Valid unless a relational comparison of function pointers
10534       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10535         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10536           << LHSType << RHSType << LHS.get()->getSourceRange()
10537           << RHS.get()->getSourceRange();
10538       }
10539     } else if (!IsRelational &&
10540                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10541       // Valid unless comparison between non-null pointer and function pointer
10542       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10543           && !LHSIsNull && !RHSIsNull)
10544         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10545                                                 /*isError*/false);
10546     } else {
10547       // Invalid
10548       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10549     }
10550     if (LCanPointeeTy != RCanPointeeTy) {
10551       // Treat NULL constant as a special case in OpenCL.
10552       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10553         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10554         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10555           Diag(Loc,
10556                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10557               << LHSType << RHSType << 0 /* comparison */
10558               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10559         }
10560       }
10561       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10562       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10563       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10564                                                : CK_BitCast;
10565       if (LHSIsNull && !RHSIsNull)
10566         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10567       else
10568         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10569     }
10570     return computeResultTy();
10571   }
10572 
10573   if (getLangOpts().CPlusPlus) {
10574     // C++ [expr.eq]p4:
10575     //   Two operands of type std::nullptr_t or one operand of type
10576     //   std::nullptr_t and the other a null pointer constant compare equal.
10577     if (!IsRelational && LHSIsNull && RHSIsNull) {
10578       if (LHSType->isNullPtrType()) {
10579         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10580         return computeResultTy();
10581       }
10582       if (RHSType->isNullPtrType()) {
10583         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10584         return computeResultTy();
10585       }
10586     }
10587 
10588     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10589     // These aren't covered by the composite pointer type rules.
10590     if (!IsRelational && RHSType->isNullPtrType() &&
10591         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10592       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10593       return computeResultTy();
10594     }
10595     if (!IsRelational && LHSType->isNullPtrType() &&
10596         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10597       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10598       return computeResultTy();
10599     }
10600 
10601     if (IsRelational &&
10602         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10603          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10604       // HACK: Relational comparison of nullptr_t against a pointer type is
10605       // invalid per DR583, but we allow it within std::less<> and friends,
10606       // since otherwise common uses of it break.
10607       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10608       // friends to have std::nullptr_t overload candidates.
10609       DeclContext *DC = CurContext;
10610       if (isa<FunctionDecl>(DC))
10611         DC = DC->getParent();
10612       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10613         if (CTSD->isInStdNamespace() &&
10614             llvm::StringSwitch<bool>(CTSD->getName())
10615                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10616                 .Default(false)) {
10617           if (RHSType->isNullPtrType())
10618             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10619           else
10620             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10621           return computeResultTy();
10622         }
10623       }
10624     }
10625 
10626     // C++ [expr.eq]p2:
10627     //   If at least one operand is a pointer to member, [...] bring them to
10628     //   their composite pointer type.
10629     if (!IsRelational &&
10630         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10631       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10632         return QualType();
10633       else
10634         return computeResultTy();
10635     }
10636   }
10637 
10638   // Handle block pointer types.
10639   if (!IsRelational && LHSType->isBlockPointerType() &&
10640       RHSType->isBlockPointerType()) {
10641     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10642     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10643 
10644     if (!LHSIsNull && !RHSIsNull &&
10645         !Context.typesAreCompatible(lpointee, rpointee)) {
10646       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10647         << LHSType << RHSType << LHS.get()->getSourceRange()
10648         << RHS.get()->getSourceRange();
10649     }
10650     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10651     return computeResultTy();
10652   }
10653 
10654   // Allow block pointers to be compared with null pointer constants.
10655   if (!IsRelational
10656       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10657           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10658     if (!LHSIsNull && !RHSIsNull) {
10659       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10660              ->getPointeeType()->isVoidType())
10661             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10662                 ->getPointeeType()->isVoidType())))
10663         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10664           << LHSType << RHSType << LHS.get()->getSourceRange()
10665           << RHS.get()->getSourceRange();
10666     }
10667     if (LHSIsNull && !RHSIsNull)
10668       LHS = ImpCastExprToType(LHS.get(), RHSType,
10669                               RHSType->isPointerType() ? CK_BitCast
10670                                 : CK_AnyPointerToBlockPointerCast);
10671     else
10672       RHS = ImpCastExprToType(RHS.get(), LHSType,
10673                               LHSType->isPointerType() ? CK_BitCast
10674                                 : CK_AnyPointerToBlockPointerCast);
10675     return computeResultTy();
10676   }
10677 
10678   if (LHSType->isObjCObjectPointerType() ||
10679       RHSType->isObjCObjectPointerType()) {
10680     const PointerType *LPT = LHSType->getAs<PointerType>();
10681     const PointerType *RPT = RHSType->getAs<PointerType>();
10682     if (LPT || RPT) {
10683       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10684       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10685 
10686       if (!LPtrToVoid && !RPtrToVoid &&
10687           !Context.typesAreCompatible(LHSType, RHSType)) {
10688         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10689                                           /*isError*/false);
10690       }
10691       if (LHSIsNull && !RHSIsNull) {
10692         Expr *E = LHS.get();
10693         if (getLangOpts().ObjCAutoRefCount)
10694           CheckObjCConversion(SourceRange(), RHSType, E,
10695                               CCK_ImplicitConversion);
10696         LHS = ImpCastExprToType(E, RHSType,
10697                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10698       }
10699       else {
10700         Expr *E = RHS.get();
10701         if (getLangOpts().ObjCAutoRefCount)
10702           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10703                               /*Diagnose=*/true,
10704                               /*DiagnoseCFAudited=*/false, Opc);
10705         RHS = ImpCastExprToType(E, LHSType,
10706                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10707       }
10708       return computeResultTy();
10709     }
10710     if (LHSType->isObjCObjectPointerType() &&
10711         RHSType->isObjCObjectPointerType()) {
10712       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10713         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10714                                           /*isError*/false);
10715       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10716         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10717 
10718       if (LHSIsNull && !RHSIsNull)
10719         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10720       else
10721         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10722       return computeResultTy();
10723     }
10724 
10725     if (!IsRelational && LHSType->isBlockPointerType() &&
10726         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10727       LHS = ImpCastExprToType(LHS.get(), RHSType,
10728                               CK_BlockPointerToObjCPointerCast);
10729       return computeResultTy();
10730     } else if (!IsRelational &&
10731                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10732                RHSType->isBlockPointerType()) {
10733       RHS = ImpCastExprToType(RHS.get(), LHSType,
10734                               CK_BlockPointerToObjCPointerCast);
10735       return computeResultTy();
10736     }
10737   }
10738   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10739       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10740     unsigned DiagID = 0;
10741     bool isError = false;
10742     if (LangOpts.DebuggerSupport) {
10743       // Under a debugger, allow the comparison of pointers to integers,
10744       // since users tend to want to compare addresses.
10745     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10746                (RHSIsNull && RHSType->isIntegerType())) {
10747       if (IsRelational) {
10748         isError = getLangOpts().CPlusPlus;
10749         DiagID =
10750           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10751                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10752       }
10753     } else if (getLangOpts().CPlusPlus) {
10754       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10755       isError = true;
10756     } else if (IsRelational)
10757       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10758     else
10759       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10760 
10761     if (DiagID) {
10762       Diag(Loc, DiagID)
10763         << LHSType << RHSType << LHS.get()->getSourceRange()
10764         << RHS.get()->getSourceRange();
10765       if (isError)
10766         return QualType();
10767     }
10768 
10769     if (LHSType->isIntegerType())
10770       LHS = ImpCastExprToType(LHS.get(), RHSType,
10771                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10772     else
10773       RHS = ImpCastExprToType(RHS.get(), LHSType,
10774                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10775     return computeResultTy();
10776   }
10777 
10778   // Handle block pointers.
10779   if (!IsRelational && RHSIsNull
10780       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10781     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10782     return computeResultTy();
10783   }
10784   if (!IsRelational && LHSIsNull
10785       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10786     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10787     return computeResultTy();
10788   }
10789 
10790   if (getLangOpts().OpenCLVersion >= 200) {
10791     if (LHSType->isClkEventT() && RHSType->isClkEventT()) {
10792       return computeResultTy();
10793     }
10794 
10795     if (LHSType->isQueueT() && RHSType->isQueueT()) {
10796       return computeResultTy();
10797     }
10798 
10799     if (LHSIsNull && RHSType->isQueueT()) {
10800       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10801       return computeResultTy();
10802     }
10803 
10804     if (LHSType->isQueueT() && RHSIsNull) {
10805       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10806       return computeResultTy();
10807     }
10808   }
10809 
10810   return InvalidOperands(Loc, LHS, RHS);
10811 }
10812 
10813 // Return a signed ext_vector_type that is of identical size and number of
10814 // elements. For floating point vectors, return an integer type of identical
10815 // size and number of elements. In the non ext_vector_type case, search from
10816 // the largest type to the smallest type to avoid cases where long long == long,
10817 // where long gets picked over long long.
10818 QualType Sema::GetSignedVectorType(QualType V) {
10819   const VectorType *VTy = V->getAs<VectorType>();
10820   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10821 
10822   if (isa<ExtVectorType>(VTy)) {
10823     if (TypeSize == Context.getTypeSize(Context.CharTy))
10824       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10825     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10826       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10827     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10828       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10829     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10830       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10831     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10832            "Unhandled vector element size in vector compare");
10833     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10834   }
10835 
10836   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10837     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10838                                  VectorType::GenericVector);
10839   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10840     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10841                                  VectorType::GenericVector);
10842   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10843     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10844                                  VectorType::GenericVector);
10845   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10846     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10847                                  VectorType::GenericVector);
10848   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10849          "Unhandled vector element size in vector compare");
10850   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10851                                VectorType::GenericVector);
10852 }
10853 
10854 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10855 /// operates on extended vector types.  Instead of producing an IntTy result,
10856 /// like a scalar comparison, a vector comparison produces a vector of integer
10857 /// types.
10858 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10859                                           SourceLocation Loc,
10860                                           BinaryOperatorKind Opc) {
10861   // Check to make sure we're operating on vectors of the same type and width,
10862   // Allowing one side to be a scalar of element type.
10863   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10864                               /*AllowBothBool*/true,
10865                               /*AllowBoolConversions*/getLangOpts().ZVector);
10866   if (vType.isNull())
10867     return vType;
10868 
10869   QualType LHSType = LHS.get()->getType();
10870 
10871   // If AltiVec, the comparison results in a numeric type, i.e.
10872   // bool for C++, int for C
10873   if (getLangOpts().AltiVec &&
10874       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10875     return Context.getLogicalOperationType();
10876 
10877   // For non-floating point types, check for self-comparisons of the form
10878   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10879   // often indicate logic errors in the program.
10880   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10881 
10882   // Check for comparisons of floating point operands using != and ==.
10883   if (BinaryOperator::isEqualityOp(Opc) &&
10884       LHSType->hasFloatingRepresentation()) {
10885     assert(RHS.get()->getType()->hasFloatingRepresentation());
10886     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10887   }
10888 
10889   // Return a signed type for the vector.
10890   return GetSignedVectorType(vType);
10891 }
10892 
10893 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10894                                           SourceLocation Loc) {
10895   // Ensure that either both operands are of the same vector type, or
10896   // one operand is of a vector type and the other is of its element type.
10897   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10898                                        /*AllowBothBool*/true,
10899                                        /*AllowBoolConversions*/false);
10900   if (vType.isNull())
10901     return InvalidOperands(Loc, LHS, RHS);
10902   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10903       vType->hasFloatingRepresentation())
10904     return InvalidOperands(Loc, LHS, RHS);
10905   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10906   //        usage of the logical operators && and || with vectors in C. This
10907   //        check could be notionally dropped.
10908   if (!getLangOpts().CPlusPlus &&
10909       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10910     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10911 
10912   return GetSignedVectorType(LHS.get()->getType());
10913 }
10914 
10915 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10916                                            SourceLocation Loc,
10917                                            BinaryOperatorKind Opc) {
10918   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10919 
10920   bool IsCompAssign =
10921       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10922 
10923   if (LHS.get()->getType()->isVectorType() ||
10924       RHS.get()->getType()->isVectorType()) {
10925     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10926         RHS.get()->getType()->hasIntegerRepresentation())
10927       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10928                         /*AllowBothBool*/true,
10929                         /*AllowBoolConversions*/getLangOpts().ZVector);
10930     return InvalidOperands(Loc, LHS, RHS);
10931   }
10932 
10933   if (Opc == BO_And)
10934     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10935 
10936   ExprResult LHSResult = LHS, RHSResult = RHS;
10937   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10938                                                  IsCompAssign);
10939   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10940     return QualType();
10941   LHS = LHSResult.get();
10942   RHS = RHSResult.get();
10943 
10944   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10945     return compType;
10946   return InvalidOperands(Loc, LHS, RHS);
10947 }
10948 
10949 // C99 6.5.[13,14]
10950 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10951                                            SourceLocation Loc,
10952                                            BinaryOperatorKind Opc) {
10953   // Check vector operands differently.
10954   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10955     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10956 
10957   // Diagnose cases where the user write a logical and/or but probably meant a
10958   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10959   // is a constant.
10960   if (LHS.get()->getType()->isIntegerType() &&
10961       !LHS.get()->getType()->isBooleanType() &&
10962       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10963       // Don't warn in macros or template instantiations.
10964       !Loc.isMacroID() && !inTemplateInstantiation()) {
10965     // If the RHS can be constant folded, and if it constant folds to something
10966     // that isn't 0 or 1 (which indicate a potential logical operation that
10967     // happened to fold to true/false) then warn.
10968     // Parens on the RHS are ignored.
10969     Expr::EvalResult EVResult;
10970     if (RHS.get()->EvaluateAsInt(EVResult, Context)) {
10971       llvm::APSInt Result = EVResult.Val.getInt();
10972       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10973            !RHS.get()->getExprLoc().isMacroID()) ||
10974           (Result != 0 && Result != 1)) {
10975         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10976           << RHS.get()->getSourceRange()
10977           << (Opc == BO_LAnd ? "&&" : "||");
10978         // Suggest replacing the logical operator with the bitwise version
10979         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10980             << (Opc == BO_LAnd ? "&" : "|")
10981             << FixItHint::CreateReplacement(SourceRange(
10982                                                  Loc, getLocForEndOfToken(Loc)),
10983                                             Opc == BO_LAnd ? "&" : "|");
10984         if (Opc == BO_LAnd)
10985           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10986           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10987               << FixItHint::CreateRemoval(
10988                      SourceRange(getLocForEndOfToken(LHS.get()->getEndLoc()),
10989                                  RHS.get()->getEndLoc()));
10990       }
10991     }
10992   }
10993 
10994   if (!Context.getLangOpts().CPlusPlus) {
10995     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10996     // not operate on the built-in scalar and vector float types.
10997     if (Context.getLangOpts().OpenCL &&
10998         Context.getLangOpts().OpenCLVersion < 120) {
10999       if (LHS.get()->getType()->isFloatingType() ||
11000           RHS.get()->getType()->isFloatingType())
11001         return InvalidOperands(Loc, LHS, RHS);
11002     }
11003 
11004     LHS = UsualUnaryConversions(LHS.get());
11005     if (LHS.isInvalid())
11006       return QualType();
11007 
11008     RHS = UsualUnaryConversions(RHS.get());
11009     if (RHS.isInvalid())
11010       return QualType();
11011 
11012     if (!LHS.get()->getType()->isScalarType() ||
11013         !RHS.get()->getType()->isScalarType())
11014       return InvalidOperands(Loc, LHS, RHS);
11015 
11016     return Context.IntTy;
11017   }
11018 
11019   // The following is safe because we only use this method for
11020   // non-overloadable operands.
11021 
11022   // C++ [expr.log.and]p1
11023   // C++ [expr.log.or]p1
11024   // The operands are both contextually converted to type bool.
11025   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
11026   if (LHSRes.isInvalid())
11027     return InvalidOperands(Loc, LHS, RHS);
11028   LHS = LHSRes;
11029 
11030   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
11031   if (RHSRes.isInvalid())
11032     return InvalidOperands(Loc, LHS, RHS);
11033   RHS = RHSRes;
11034 
11035   // C++ [expr.log.and]p2
11036   // C++ [expr.log.or]p2
11037   // The result is a bool.
11038   return Context.BoolTy;
11039 }
11040 
11041 static bool IsReadonlyMessage(Expr *E, Sema &S) {
11042   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11043   if (!ME) return false;
11044   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
11045   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
11046       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
11047   if (!Base) return false;
11048   return Base->getMethodDecl() != nullptr;
11049 }
11050 
11051 /// Is the given expression (which must be 'const') a reference to a
11052 /// variable which was originally non-const, but which has become
11053 /// 'const' due to being captured within a block?
11054 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
11055 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
11056   assert(E->isLValue() && E->getType().isConstQualified());
11057   E = E->IgnoreParens();
11058 
11059   // Must be a reference to a declaration from an enclosing scope.
11060   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
11061   if (!DRE) return NCCK_None;
11062   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
11063 
11064   // The declaration must be a variable which is not declared 'const'.
11065   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
11066   if (!var) return NCCK_None;
11067   if (var->getType().isConstQualified()) return NCCK_None;
11068   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
11069 
11070   // Decide whether the first capture was for a block or a lambda.
11071   DeclContext *DC = S.CurContext, *Prev = nullptr;
11072   // Decide whether the first capture was for a block or a lambda.
11073   while (DC) {
11074     // For init-capture, it is possible that the variable belongs to the
11075     // template pattern of the current context.
11076     if (auto *FD = dyn_cast<FunctionDecl>(DC))
11077       if (var->isInitCapture() &&
11078           FD->getTemplateInstantiationPattern() == var->getDeclContext())
11079         break;
11080     if (DC == var->getDeclContext())
11081       break;
11082     Prev = DC;
11083     DC = DC->getParent();
11084   }
11085   // Unless we have an init-capture, we've gone one step too far.
11086   if (!var->isInitCapture())
11087     DC = Prev;
11088   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
11089 }
11090 
11091 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
11092   Ty = Ty.getNonReferenceType();
11093   if (IsDereference && Ty->isPointerType())
11094     Ty = Ty->getPointeeType();
11095   return !Ty.isConstQualified();
11096 }
11097 
11098 // Update err_typecheck_assign_const and note_typecheck_assign_const
11099 // when this enum is changed.
11100 enum {
11101   ConstFunction,
11102   ConstVariable,
11103   ConstMember,
11104   ConstMethod,
11105   NestedConstMember,
11106   ConstUnknown,  // Keep as last element
11107 };
11108 
11109 /// Emit the "read-only variable not assignable" error and print notes to give
11110 /// more information about why the variable is not assignable, such as pointing
11111 /// to the declaration of a const variable, showing that a method is const, or
11112 /// that the function is returning a const reference.
11113 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
11114                                     SourceLocation Loc) {
11115   SourceRange ExprRange = E->getSourceRange();
11116 
11117   // Only emit one error on the first const found.  All other consts will emit
11118   // a note to the error.
11119   bool DiagnosticEmitted = false;
11120 
11121   // Track if the current expression is the result of a dereference, and if the
11122   // next checked expression is the result of a dereference.
11123   bool IsDereference = false;
11124   bool NextIsDereference = false;
11125 
11126   // Loop to process MemberExpr chains.
11127   while (true) {
11128     IsDereference = NextIsDereference;
11129 
11130     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
11131     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
11132       NextIsDereference = ME->isArrow();
11133       const ValueDecl *VD = ME->getMemberDecl();
11134       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
11135         // Mutable fields can be modified even if the class is const.
11136         if (Field->isMutable()) {
11137           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
11138           break;
11139         }
11140 
11141         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
11142           if (!DiagnosticEmitted) {
11143             S.Diag(Loc, diag::err_typecheck_assign_const)
11144                 << ExprRange << ConstMember << false /*static*/ << Field
11145                 << Field->getType();
11146             DiagnosticEmitted = true;
11147           }
11148           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11149               << ConstMember << false /*static*/ << Field << Field->getType()
11150               << Field->getSourceRange();
11151         }
11152         E = ME->getBase();
11153         continue;
11154       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
11155         if (VDecl->getType().isConstQualified()) {
11156           if (!DiagnosticEmitted) {
11157             S.Diag(Loc, diag::err_typecheck_assign_const)
11158                 << ExprRange << ConstMember << true /*static*/ << VDecl
11159                 << VDecl->getType();
11160             DiagnosticEmitted = true;
11161           }
11162           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11163               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
11164               << VDecl->getSourceRange();
11165         }
11166         // Static fields do not inherit constness from parents.
11167         break;
11168       }
11169       break; // End MemberExpr
11170     } else if (const ArraySubscriptExpr *ASE =
11171                    dyn_cast<ArraySubscriptExpr>(E)) {
11172       E = ASE->getBase()->IgnoreParenImpCasts();
11173       continue;
11174     } else if (const ExtVectorElementExpr *EVE =
11175                    dyn_cast<ExtVectorElementExpr>(E)) {
11176       E = EVE->getBase()->IgnoreParenImpCasts();
11177       continue;
11178     }
11179     break;
11180   }
11181 
11182   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11183     // Function calls
11184     const FunctionDecl *FD = CE->getDirectCallee();
11185     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
11186       if (!DiagnosticEmitted) {
11187         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11188                                                       << ConstFunction << FD;
11189         DiagnosticEmitted = true;
11190       }
11191       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
11192              diag::note_typecheck_assign_const)
11193           << ConstFunction << FD << FD->getReturnType()
11194           << FD->getReturnTypeSourceRange();
11195     }
11196   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11197     // Point to variable declaration.
11198     if (const ValueDecl *VD = DRE->getDecl()) {
11199       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
11200         if (!DiagnosticEmitted) {
11201           S.Diag(Loc, diag::err_typecheck_assign_const)
11202               << ExprRange << ConstVariable << VD << VD->getType();
11203           DiagnosticEmitted = true;
11204         }
11205         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
11206             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
11207       }
11208     }
11209   } else if (isa<CXXThisExpr>(E)) {
11210     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
11211       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
11212         if (MD->isConst()) {
11213           if (!DiagnosticEmitted) {
11214             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
11215                                                           << ConstMethod << MD;
11216             DiagnosticEmitted = true;
11217           }
11218           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
11219               << ConstMethod << MD << MD->getSourceRange();
11220         }
11221       }
11222     }
11223   }
11224 
11225   if (DiagnosticEmitted)
11226     return;
11227 
11228   // Can't determine a more specific message, so display the generic error.
11229   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
11230 }
11231 
11232 enum OriginalExprKind {
11233   OEK_Variable,
11234   OEK_Member,
11235   OEK_LValue
11236 };
11237 
11238 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
11239                                          const RecordType *Ty,
11240                                          SourceLocation Loc, SourceRange Range,
11241                                          OriginalExprKind OEK,
11242                                          bool &DiagnosticEmitted) {
11243   std::vector<const RecordType *> RecordTypeList;
11244   RecordTypeList.push_back(Ty);
11245   unsigned NextToCheckIndex = 0;
11246   // We walk the record hierarchy breadth-first to ensure that we print
11247   // diagnostics in field nesting order.
11248   while (RecordTypeList.size() > NextToCheckIndex) {
11249     bool IsNested = NextToCheckIndex > 0;
11250     for (const FieldDecl *Field :
11251          RecordTypeList[NextToCheckIndex]->getDecl()->fields()) {
11252       // First, check every field for constness.
11253       QualType FieldTy = Field->getType();
11254       if (FieldTy.isConstQualified()) {
11255         if (!DiagnosticEmitted) {
11256           S.Diag(Loc, diag::err_typecheck_assign_const)
11257               << Range << NestedConstMember << OEK << VD
11258               << IsNested << Field;
11259           DiagnosticEmitted = true;
11260         }
11261         S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
11262             << NestedConstMember << IsNested << Field
11263             << FieldTy << Field->getSourceRange();
11264       }
11265 
11266       // Then we append it to the list to check next in order.
11267       FieldTy = FieldTy.getCanonicalType();
11268       if (const auto *FieldRecTy = FieldTy->getAs<RecordType>()) {
11269         if (llvm::find(RecordTypeList, FieldRecTy) == RecordTypeList.end())
11270           RecordTypeList.push_back(FieldRecTy);
11271       }
11272     }
11273     ++NextToCheckIndex;
11274   }
11275 }
11276 
11277 /// Emit an error for the case where a record we are trying to assign to has a
11278 /// const-qualified field somewhere in its hierarchy.
11279 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
11280                                          SourceLocation Loc) {
11281   QualType Ty = E->getType();
11282   assert(Ty->isRecordType() && "lvalue was not record?");
11283   SourceRange Range = E->getSourceRange();
11284   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
11285   bool DiagEmitted = false;
11286 
11287   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
11288     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
11289             Range, OEK_Member, DiagEmitted);
11290   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
11291     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
11292             Range, OEK_Variable, DiagEmitted);
11293   else
11294     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
11295             Range, OEK_LValue, DiagEmitted);
11296   if (!DiagEmitted)
11297     DiagnoseConstAssignment(S, E, Loc);
11298 }
11299 
11300 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
11301 /// emit an error and return true.  If so, return false.
11302 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
11303   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
11304 
11305   S.CheckShadowingDeclModification(E, Loc);
11306 
11307   SourceLocation OrigLoc = Loc;
11308   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
11309                                                               &Loc);
11310   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
11311     IsLV = Expr::MLV_InvalidMessageExpression;
11312   if (IsLV == Expr::MLV_Valid)
11313     return false;
11314 
11315   unsigned DiagID = 0;
11316   bool NeedType = false;
11317   switch (IsLV) { // C99 6.5.16p2
11318   case Expr::MLV_ConstQualified:
11319     // Use a specialized diagnostic when we're assigning to an object
11320     // from an enclosing function or block.
11321     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
11322       if (NCCK == NCCK_Block)
11323         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
11324       else
11325         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
11326       break;
11327     }
11328 
11329     // In ARC, use some specialized diagnostics for occasions where we
11330     // infer 'const'.  These are always pseudo-strong variables.
11331     if (S.getLangOpts().ObjCAutoRefCount) {
11332       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
11333       if (declRef && isa<VarDecl>(declRef->getDecl())) {
11334         VarDecl *var = cast<VarDecl>(declRef->getDecl());
11335 
11336         // Use the normal diagnostic if it's pseudo-__strong but the
11337         // user actually wrote 'const'.
11338         if (var->isARCPseudoStrong() &&
11339             (!var->getTypeSourceInfo() ||
11340              !var->getTypeSourceInfo()->getType().isConstQualified())) {
11341           // There are three pseudo-strong cases:
11342           //  - self
11343           ObjCMethodDecl *method = S.getCurMethodDecl();
11344           if (method && var == method->getSelfDecl()) {
11345             DiagID = method->isClassMethod()
11346               ? diag::err_typecheck_arc_assign_self_class_method
11347               : diag::err_typecheck_arc_assign_self;
11348 
11349           //  - Objective-C externally_retained attribute.
11350           } else if (var->hasAttr<ObjCExternallyRetainedAttr>() ||
11351                      isa<ParmVarDecl>(var)) {
11352             DiagID = diag::err_typecheck_arc_assign_externally_retained;
11353 
11354           //  - fast enumeration variables
11355           } else {
11356             DiagID = diag::err_typecheck_arr_assign_enumeration;
11357           }
11358 
11359           SourceRange Assign;
11360           if (Loc != OrigLoc)
11361             Assign = SourceRange(OrigLoc, OrigLoc);
11362           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11363           // We need to preserve the AST regardless, so migration tool
11364           // can do its job.
11365           return false;
11366         }
11367       }
11368     }
11369 
11370     // If none of the special cases above are triggered, then this is a
11371     // simple const assignment.
11372     if (DiagID == 0) {
11373       DiagnoseConstAssignment(S, E, Loc);
11374       return true;
11375     }
11376 
11377     break;
11378   case Expr::MLV_ConstAddrSpace:
11379     DiagnoseConstAssignment(S, E, Loc);
11380     return true;
11381   case Expr::MLV_ConstQualifiedField:
11382     DiagnoseRecursiveConstFields(S, E, Loc);
11383     return true;
11384   case Expr::MLV_ArrayType:
11385   case Expr::MLV_ArrayTemporary:
11386     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
11387     NeedType = true;
11388     break;
11389   case Expr::MLV_NotObjectType:
11390     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
11391     NeedType = true;
11392     break;
11393   case Expr::MLV_LValueCast:
11394     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
11395     break;
11396   case Expr::MLV_Valid:
11397     llvm_unreachable("did not take early return for MLV_Valid");
11398   case Expr::MLV_InvalidExpression:
11399   case Expr::MLV_MemberFunction:
11400   case Expr::MLV_ClassTemporary:
11401     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
11402     break;
11403   case Expr::MLV_IncompleteType:
11404   case Expr::MLV_IncompleteVoidType:
11405     return S.RequireCompleteType(Loc, E->getType(),
11406              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
11407   case Expr::MLV_DuplicateVectorComponents:
11408     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
11409     break;
11410   case Expr::MLV_NoSetterProperty:
11411     llvm_unreachable("readonly properties should be processed differently");
11412   case Expr::MLV_InvalidMessageExpression:
11413     DiagID = diag::err_readonly_message_assignment;
11414     break;
11415   case Expr::MLV_SubObjCPropertySetting:
11416     DiagID = diag::err_no_subobject_property_setting;
11417     break;
11418   }
11419 
11420   SourceRange Assign;
11421   if (Loc != OrigLoc)
11422     Assign = SourceRange(OrigLoc, OrigLoc);
11423   if (NeedType)
11424     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
11425   else
11426     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
11427   return true;
11428 }
11429 
11430 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
11431                                          SourceLocation Loc,
11432                                          Sema &Sema) {
11433   if (Sema.inTemplateInstantiation())
11434     return;
11435   if (Sema.isUnevaluatedContext())
11436     return;
11437   if (Loc.isInvalid() || Loc.isMacroID())
11438     return;
11439   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
11440     return;
11441 
11442   // C / C++ fields
11443   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
11444   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
11445   if (ML && MR) {
11446     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
11447       return;
11448     const ValueDecl *LHSDecl =
11449         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
11450     const ValueDecl *RHSDecl =
11451         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
11452     if (LHSDecl != RHSDecl)
11453       return;
11454     if (LHSDecl->getType().isVolatileQualified())
11455       return;
11456     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11457       if (RefTy->getPointeeType().isVolatileQualified())
11458         return;
11459 
11460     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
11461   }
11462 
11463   // Objective-C instance variables
11464   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
11465   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
11466   if (OL && OR && OL->getDecl() == OR->getDecl()) {
11467     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
11468     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
11469     if (RL && RR && RL->getDecl() == RR->getDecl())
11470       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
11471   }
11472 }
11473 
11474 // C99 6.5.16.1
11475 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
11476                                        SourceLocation Loc,
11477                                        QualType CompoundType) {
11478   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
11479 
11480   // Verify that LHS is a modifiable lvalue, and emit error if not.
11481   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
11482     return QualType();
11483 
11484   QualType LHSType = LHSExpr->getType();
11485   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11486                                              CompoundType;
11487   // OpenCL v1.2 s6.1.1.1 p2:
11488   // The half data type can only be used to declare a pointer to a buffer that
11489   // contains half values
11490   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11491     LHSType->isHalfType()) {
11492     Diag(Loc, diag::err_opencl_half_load_store) << 1
11493         << LHSType.getUnqualifiedType();
11494     return QualType();
11495   }
11496 
11497   AssignConvertType ConvTy;
11498   if (CompoundType.isNull()) {
11499     Expr *RHSCheck = RHS.get();
11500 
11501     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11502 
11503     QualType LHSTy(LHSType);
11504     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11505     if (RHS.isInvalid())
11506       return QualType();
11507     // Special case of NSObject attributes on c-style pointer types.
11508     if (ConvTy == IncompatiblePointer &&
11509         ((Context.isObjCNSObjectType(LHSType) &&
11510           RHSType->isObjCObjectPointerType()) ||
11511          (Context.isObjCNSObjectType(RHSType) &&
11512           LHSType->isObjCObjectPointerType())))
11513       ConvTy = Compatible;
11514 
11515     if (ConvTy == Compatible &&
11516         LHSType->isObjCObjectType())
11517         Diag(Loc, diag::err_objc_object_assignment)
11518           << LHSType;
11519 
11520     // If the RHS is a unary plus or minus, check to see if they = and + are
11521     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11522     // instead of "x += 4".
11523     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11524       RHSCheck = ICE->getSubExpr();
11525     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11526       if ((UO->getOpcode() == UO_Plus || UO->getOpcode() == UO_Minus) &&
11527           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11528           // Only if the two operators are exactly adjacent.
11529           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11530           // And there is a space or other character before the subexpr of the
11531           // unary +/-.  We don't want to warn on "x=-1".
11532           Loc.getLocWithOffset(2) != UO->getSubExpr()->getBeginLoc() &&
11533           UO->getSubExpr()->getBeginLoc().isFileID()) {
11534         Diag(Loc, diag::warn_not_compound_assign)
11535           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11536           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11537       }
11538     }
11539 
11540     if (ConvTy == Compatible) {
11541       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11542         // Warn about retain cycles where a block captures the LHS, but
11543         // not if the LHS is a simple variable into which the block is
11544         // being stored...unless that variable can be captured by reference!
11545         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11546         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11547         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11548           checkRetainCycles(LHSExpr, RHS.get());
11549       }
11550 
11551       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11552           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11553         // It is safe to assign a weak reference into a strong variable.
11554         // Although this code can still have problems:
11555         //   id x = self.weakProp;
11556         //   id y = self.weakProp;
11557         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11558         // paths through the function. This should be revisited if
11559         // -Wrepeated-use-of-weak is made flow-sensitive.
11560         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11561         // variable, which will be valid for the current autorelease scope.
11562         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11563                              RHS.get()->getBeginLoc()))
11564           getCurFunction()->markSafeWeakUse(RHS.get());
11565 
11566       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11567         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11568       }
11569     }
11570   } else {
11571     // Compound assignment "x += y"
11572     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11573   }
11574 
11575   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11576                                RHS.get(), AA_Assigning))
11577     return QualType();
11578 
11579   CheckForNullPointerDereference(*this, LHSExpr);
11580 
11581   // C99 6.5.16p3: The type of an assignment expression is the type of the
11582   // left operand unless the left operand has qualified type, in which case
11583   // it is the unqualified version of the type of the left operand.
11584   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11585   // is converted to the type of the assignment expression (above).
11586   // C++ 5.17p1: the type of the assignment expression is that of its left
11587   // operand.
11588   return (getLangOpts().CPlusPlus
11589           ? LHSType : LHSType.getUnqualifiedType());
11590 }
11591 
11592 // Only ignore explicit casts to void.
11593 static bool IgnoreCommaOperand(const Expr *E) {
11594   E = E->IgnoreParens();
11595 
11596   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11597     if (CE->getCastKind() == CK_ToVoid) {
11598       return true;
11599     }
11600 
11601     // static_cast<void> on a dependent type will not show up as CK_ToVoid.
11602     if (CE->getCastKind() == CK_Dependent && E->getType()->isVoidType() &&
11603         CE->getSubExpr()->getType()->isDependentType()) {
11604       return true;
11605     }
11606   }
11607 
11608   return false;
11609 }
11610 
11611 // Look for instances where it is likely the comma operator is confused with
11612 // another operator.  There is a whitelist of acceptable expressions for the
11613 // left hand side of the comma operator, otherwise emit a warning.
11614 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11615   // No warnings in macros
11616   if (Loc.isMacroID())
11617     return;
11618 
11619   // Don't warn in template instantiations.
11620   if (inTemplateInstantiation())
11621     return;
11622 
11623   // Scope isn't fine-grained enough to whitelist the specific cases, so
11624   // instead, skip more than needed, then call back into here with the
11625   // CommaVisitor in SemaStmt.cpp.
11626   // The whitelisted locations are the initialization and increment portions
11627   // of a for loop.  The additional checks are on the condition of
11628   // if statements, do/while loops, and for loops.
11629   // Differences in scope flags for C89 mode requires the extra logic.
11630   const unsigned ForIncrementFlags =
11631       getLangOpts().C99 || getLangOpts().CPlusPlus
11632           ? Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope
11633           : Scope::ContinueScope | Scope::BreakScope;
11634   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11635   const unsigned ScopeFlags = getCurScope()->getFlags();
11636   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11637       (ScopeFlags & ForInitFlags) == ForInitFlags)
11638     return;
11639 
11640   // If there are multiple comma operators used together, get the RHS of the
11641   // of the comma operator as the LHS.
11642   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11643     if (BO->getOpcode() != BO_Comma)
11644       break;
11645     LHS = BO->getRHS();
11646   }
11647 
11648   // Only allow some expressions on LHS to not warn.
11649   if (IgnoreCommaOperand(LHS))
11650     return;
11651 
11652   Diag(Loc, diag::warn_comma_operator);
11653   Diag(LHS->getBeginLoc(), diag::note_cast_to_void)
11654       << LHS->getSourceRange()
11655       << FixItHint::CreateInsertion(LHS->getBeginLoc(),
11656                                     LangOpts.CPlusPlus ? "static_cast<void>("
11657                                                        : "(void)(")
11658       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getEndLoc()),
11659                                     ")");
11660 }
11661 
11662 // C99 6.5.17
11663 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11664                                    SourceLocation Loc) {
11665   LHS = S.CheckPlaceholderExpr(LHS.get());
11666   RHS = S.CheckPlaceholderExpr(RHS.get());
11667   if (LHS.isInvalid() || RHS.isInvalid())
11668     return QualType();
11669 
11670   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11671   // operands, but not unary promotions.
11672   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11673 
11674   // So we treat the LHS as a ignored value, and in C++ we allow the
11675   // containing site to determine what should be done with the RHS.
11676   LHS = S.IgnoredValueConversions(LHS.get());
11677   if (LHS.isInvalid())
11678     return QualType();
11679 
11680   S.DiagnoseUnusedExprResult(LHS.get());
11681 
11682   if (!S.getLangOpts().CPlusPlus) {
11683     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11684     if (RHS.isInvalid())
11685       return QualType();
11686     if (!RHS.get()->getType()->isVoidType())
11687       S.RequireCompleteType(Loc, RHS.get()->getType(),
11688                             diag::err_incomplete_type);
11689   }
11690 
11691   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11692     S.DiagnoseCommaOperator(LHS.get(), Loc);
11693 
11694   return RHS.get()->getType();
11695 }
11696 
11697 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11698 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11699 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11700                                                ExprValueKind &VK,
11701                                                ExprObjectKind &OK,
11702                                                SourceLocation OpLoc,
11703                                                bool IsInc, bool IsPrefix) {
11704   if (Op->isTypeDependent())
11705     return S.Context.DependentTy;
11706 
11707   QualType ResType = Op->getType();
11708   // Atomic types can be used for increment / decrement where the non-atomic
11709   // versions can, so ignore the _Atomic() specifier for the purpose of
11710   // checking.
11711   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11712     ResType = ResAtomicType->getValueType();
11713 
11714   assert(!ResType.isNull() && "no type for increment/decrement expression");
11715 
11716   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11717     // Decrement of bool is not allowed.
11718     if (!IsInc) {
11719       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11720       return QualType();
11721     }
11722     // Increment of bool sets it to true, but is deprecated.
11723     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11724                                               : diag::warn_increment_bool)
11725       << Op->getSourceRange();
11726   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11727     // Error on enum increments and decrements in C++ mode
11728     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11729     return QualType();
11730   } else if (ResType->isRealType()) {
11731     // OK!
11732   } else if (ResType->isPointerType()) {
11733     // C99 6.5.2.4p2, 6.5.6p2
11734     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11735       return QualType();
11736   } else if (ResType->isObjCObjectPointerType()) {
11737     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11738     // Otherwise, we just need a complete type.
11739     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11740         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11741       return QualType();
11742   } else if (ResType->isAnyComplexType()) {
11743     // C99 does not support ++/-- on complex types, we allow as an extension.
11744     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11745       << ResType << Op->getSourceRange();
11746   } else if (ResType->isPlaceholderType()) {
11747     ExprResult PR = S.CheckPlaceholderExpr(Op);
11748     if (PR.isInvalid()) return QualType();
11749     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11750                                           IsInc, IsPrefix);
11751   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11752     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11753   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11754              (ResType->getAs<VectorType>()->getVectorKind() !=
11755               VectorType::AltiVecBool)) {
11756     // The z vector extensions allow ++ and -- for non-bool vectors.
11757   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11758             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11759     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11760   } else {
11761     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11762       << ResType << int(IsInc) << Op->getSourceRange();
11763     return QualType();
11764   }
11765   // At this point, we know we have a real, complex or pointer type.
11766   // Now make sure the operand is a modifiable lvalue.
11767   if (CheckForModifiableLvalue(Op, OpLoc, S))
11768     return QualType();
11769   // In C++, a prefix increment is the same type as the operand. Otherwise
11770   // (in C or with postfix), the increment is the unqualified type of the
11771   // operand.
11772   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11773     VK = VK_LValue;
11774     OK = Op->getObjectKind();
11775     return ResType;
11776   } else {
11777     VK = VK_RValue;
11778     return ResType.getUnqualifiedType();
11779   }
11780 }
11781 
11782 
11783 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11784 /// This routine allows us to typecheck complex/recursive expressions
11785 /// where the declaration is needed for type checking. We only need to
11786 /// handle cases when the expression references a function designator
11787 /// or is an lvalue. Here are some examples:
11788 ///  - &(x) => x
11789 ///  - &*****f => f for f a function designator.
11790 ///  - &s.xx => s
11791 ///  - &s.zz[1].yy -> s, if zz is an array
11792 ///  - *(x + 1) -> x, if x is an array
11793 ///  - &"123"[2] -> 0
11794 ///  - & __real__ x -> x
11795 static ValueDecl *getPrimaryDecl(Expr *E) {
11796   switch (E->getStmtClass()) {
11797   case Stmt::DeclRefExprClass:
11798     return cast<DeclRefExpr>(E)->getDecl();
11799   case Stmt::MemberExprClass:
11800     // If this is an arrow operator, the address is an offset from
11801     // the base's value, so the object the base refers to is
11802     // irrelevant.
11803     if (cast<MemberExpr>(E)->isArrow())
11804       return nullptr;
11805     // Otherwise, the expression refers to a part of the base
11806     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11807   case Stmt::ArraySubscriptExprClass: {
11808     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11809     // promotion of register arrays earlier.
11810     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11811     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11812       if (ICE->getSubExpr()->getType()->isArrayType())
11813         return getPrimaryDecl(ICE->getSubExpr());
11814     }
11815     return nullptr;
11816   }
11817   case Stmt::UnaryOperatorClass: {
11818     UnaryOperator *UO = cast<UnaryOperator>(E);
11819 
11820     switch(UO->getOpcode()) {
11821     case UO_Real:
11822     case UO_Imag:
11823     case UO_Extension:
11824       return getPrimaryDecl(UO->getSubExpr());
11825     default:
11826       return nullptr;
11827     }
11828   }
11829   case Stmt::ParenExprClass:
11830     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11831   case Stmt::ImplicitCastExprClass:
11832     // If the result of an implicit cast is an l-value, we care about
11833     // the sub-expression; otherwise, the result here doesn't matter.
11834     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11835   default:
11836     return nullptr;
11837   }
11838 }
11839 
11840 namespace {
11841   enum {
11842     AO_Bit_Field = 0,
11843     AO_Vector_Element = 1,
11844     AO_Property_Expansion = 2,
11845     AO_Register_Variable = 3,
11846     AO_No_Error = 4
11847   };
11848 }
11849 /// Diagnose invalid operand for address of operations.
11850 ///
11851 /// \param Type The type of operand which cannot have its address taken.
11852 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11853                                          Expr *E, unsigned Type) {
11854   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11855 }
11856 
11857 /// CheckAddressOfOperand - The operand of & must be either a function
11858 /// designator or an lvalue designating an object. If it is an lvalue, the
11859 /// object cannot be declared with storage class register or be a bit field.
11860 /// Note: The usual conversions are *not* applied to the operand of the &
11861 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11862 /// In C++, the operand might be an overloaded function name, in which case
11863 /// we allow the '&' but retain the overloaded-function type.
11864 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11865   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11866     if (PTy->getKind() == BuiltinType::Overload) {
11867       Expr *E = OrigOp.get()->IgnoreParens();
11868       if (!isa<OverloadExpr>(E)) {
11869         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11870         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11871           << OrigOp.get()->getSourceRange();
11872         return QualType();
11873       }
11874 
11875       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11876       if (isa<UnresolvedMemberExpr>(Ovl))
11877         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11878           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11879             << OrigOp.get()->getSourceRange();
11880           return QualType();
11881         }
11882 
11883       return Context.OverloadTy;
11884     }
11885 
11886     if (PTy->getKind() == BuiltinType::UnknownAny)
11887       return Context.UnknownAnyTy;
11888 
11889     if (PTy->getKind() == BuiltinType::BoundMember) {
11890       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11891         << OrigOp.get()->getSourceRange();
11892       return QualType();
11893     }
11894 
11895     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11896     if (OrigOp.isInvalid()) return QualType();
11897   }
11898 
11899   if (OrigOp.get()->isTypeDependent())
11900     return Context.DependentTy;
11901 
11902   assert(!OrigOp.get()->getType()->isPlaceholderType());
11903 
11904   // Make sure to ignore parentheses in subsequent checks
11905   Expr *op = OrigOp.get()->IgnoreParens();
11906 
11907   // In OpenCL captures for blocks called as lambda functions
11908   // are located in the private address space. Blocks used in
11909   // enqueue_kernel can be located in a different address space
11910   // depending on a vendor implementation. Thus preventing
11911   // taking an address of the capture to avoid invalid AS casts.
11912   if (LangOpts.OpenCL) {
11913     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11914     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11915       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11916       return QualType();
11917     }
11918   }
11919 
11920   if (getLangOpts().C99) {
11921     // Implement C99-only parts of addressof rules.
11922     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11923       if (uOp->getOpcode() == UO_Deref)
11924         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11925         // (assuming the deref expression is valid).
11926         return uOp->getSubExpr()->getType();
11927     }
11928     // Technically, there should be a check for array subscript
11929     // expressions here, but the result of one is always an lvalue anyway.
11930   }
11931   ValueDecl *dcl = getPrimaryDecl(op);
11932 
11933   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11934     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11935                                            op->getBeginLoc()))
11936       return QualType();
11937 
11938   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11939   unsigned AddressOfError = AO_No_Error;
11940 
11941   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11942     bool sfinae = (bool)isSFINAEContext();
11943     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11944                                   : diag::ext_typecheck_addrof_temporary)
11945       << op->getType() << op->getSourceRange();
11946     if (sfinae)
11947       return QualType();
11948     // Materialize the temporary as an lvalue so that we can take its address.
11949     OrigOp = op =
11950         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11951   } else if (isa<ObjCSelectorExpr>(op)) {
11952     return Context.getPointerType(op->getType());
11953   } else if (lval == Expr::LV_MemberFunction) {
11954     // If it's an instance method, make a member pointer.
11955     // The expression must have exactly the form &A::foo.
11956 
11957     // If the underlying expression isn't a decl ref, give up.
11958     if (!isa<DeclRefExpr>(op)) {
11959       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11960         << OrigOp.get()->getSourceRange();
11961       return QualType();
11962     }
11963     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11964     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11965 
11966     // The id-expression was parenthesized.
11967     if (OrigOp.get() != DRE) {
11968       Diag(OpLoc, diag::err_parens_pointer_member_function)
11969         << OrigOp.get()->getSourceRange();
11970 
11971     // The method was named without a qualifier.
11972     } else if (!DRE->getQualifier()) {
11973       if (MD->getParent()->getName().empty())
11974         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11975           << op->getSourceRange();
11976       else {
11977         SmallString<32> Str;
11978         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11979         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11980           << op->getSourceRange()
11981           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11982       }
11983     }
11984 
11985     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11986     if (isa<CXXDestructorDecl>(MD))
11987       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11988 
11989     QualType MPTy = Context.getMemberPointerType(
11990         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11991     // Under the MS ABI, lock down the inheritance model now.
11992     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11993       (void)isCompleteType(OpLoc, MPTy);
11994     return MPTy;
11995   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11996     // C99 6.5.3.2p1
11997     // The operand must be either an l-value or a function designator
11998     if (!op->getType()->isFunctionType()) {
11999       // Use a special diagnostic for loads from property references.
12000       if (isa<PseudoObjectExpr>(op)) {
12001         AddressOfError = AO_Property_Expansion;
12002       } else {
12003         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
12004           << op->getType() << op->getSourceRange();
12005         return QualType();
12006       }
12007     }
12008   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
12009     // The operand cannot be a bit-field
12010     AddressOfError = AO_Bit_Field;
12011   } else if (op->getObjectKind() == OK_VectorComponent) {
12012     // The operand cannot be an element of a vector
12013     AddressOfError = AO_Vector_Element;
12014   } else if (dcl) { // C99 6.5.3.2p1
12015     // We have an lvalue with a decl. Make sure the decl is not declared
12016     // with the register storage-class specifier.
12017     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
12018       // in C++ it is not error to take address of a register
12019       // variable (c++03 7.1.1P3)
12020       if (vd->getStorageClass() == SC_Register &&
12021           !getLangOpts().CPlusPlus) {
12022         AddressOfError = AO_Register_Variable;
12023       }
12024     } else if (isa<MSPropertyDecl>(dcl)) {
12025       AddressOfError = AO_Property_Expansion;
12026     } else if (isa<FunctionTemplateDecl>(dcl)) {
12027       return Context.OverloadTy;
12028     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
12029       // Okay: we can take the address of a field.
12030       // Could be a pointer to member, though, if there is an explicit
12031       // scope qualifier for the class.
12032       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
12033         DeclContext *Ctx = dcl->getDeclContext();
12034         if (Ctx && Ctx->isRecord()) {
12035           if (dcl->getType()->isReferenceType()) {
12036             Diag(OpLoc,
12037                  diag::err_cannot_form_pointer_to_member_of_reference_type)
12038               << dcl->getDeclName() << dcl->getType();
12039             return QualType();
12040           }
12041 
12042           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
12043             Ctx = Ctx->getParent();
12044 
12045           QualType MPTy = Context.getMemberPointerType(
12046               op->getType(),
12047               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
12048           // Under the MS ABI, lock down the inheritance model now.
12049           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
12050             (void)isCompleteType(OpLoc, MPTy);
12051           return MPTy;
12052         }
12053       }
12054     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
12055                !isa<BindingDecl>(dcl))
12056       llvm_unreachable("Unknown/unexpected decl type");
12057   }
12058 
12059   if (AddressOfError != AO_No_Error) {
12060     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
12061     return QualType();
12062   }
12063 
12064   if (lval == Expr::LV_IncompleteVoidType) {
12065     // Taking the address of a void variable is technically illegal, but we
12066     // allow it in cases which are otherwise valid.
12067     // Example: "extern void x; void* y = &x;".
12068     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
12069   }
12070 
12071   // If the operand has type "type", the result has type "pointer to type".
12072   if (op->getType()->isObjCObjectType())
12073     return Context.getObjCObjectPointerType(op->getType());
12074 
12075   CheckAddressOfPackedMember(op);
12076 
12077   return Context.getPointerType(op->getType());
12078 }
12079 
12080 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
12081   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
12082   if (!DRE)
12083     return;
12084   const Decl *D = DRE->getDecl();
12085   if (!D)
12086     return;
12087   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
12088   if (!Param)
12089     return;
12090   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
12091     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
12092       return;
12093   if (FunctionScopeInfo *FD = S.getCurFunction())
12094     if (!FD->ModifiedNonNullParams.count(Param))
12095       FD->ModifiedNonNullParams.insert(Param);
12096 }
12097 
12098 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
12099 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
12100                                         SourceLocation OpLoc) {
12101   if (Op->isTypeDependent())
12102     return S.Context.DependentTy;
12103 
12104   ExprResult ConvResult = S.UsualUnaryConversions(Op);
12105   if (ConvResult.isInvalid())
12106     return QualType();
12107   Op = ConvResult.get();
12108   QualType OpTy = Op->getType();
12109   QualType Result;
12110 
12111   if (isa<CXXReinterpretCastExpr>(Op)) {
12112     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
12113     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
12114                                      Op->getSourceRange());
12115   }
12116 
12117   if (const PointerType *PT = OpTy->getAs<PointerType>())
12118   {
12119     Result = PT->getPointeeType();
12120   }
12121   else if (const ObjCObjectPointerType *OPT =
12122              OpTy->getAs<ObjCObjectPointerType>())
12123     Result = OPT->getPointeeType();
12124   else {
12125     ExprResult PR = S.CheckPlaceholderExpr(Op);
12126     if (PR.isInvalid()) return QualType();
12127     if (PR.get() != Op)
12128       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
12129   }
12130 
12131   if (Result.isNull()) {
12132     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
12133       << OpTy << Op->getSourceRange();
12134     return QualType();
12135   }
12136 
12137   // Note that per both C89 and C99, indirection is always legal, even if Result
12138   // is an incomplete type or void.  It would be possible to warn about
12139   // dereferencing a void pointer, but it's completely well-defined, and such a
12140   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
12141   // for pointers to 'void' but is fine for any other pointer type:
12142   //
12143   // C++ [expr.unary.op]p1:
12144   //   [...] the expression to which [the unary * operator] is applied shall
12145   //   be a pointer to an object type, or a pointer to a function type
12146   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
12147     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
12148       << OpTy << Op->getSourceRange();
12149 
12150   // Dereferences are usually l-values...
12151   VK = VK_LValue;
12152 
12153   // ...except that certain expressions are never l-values in C.
12154   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
12155     VK = VK_RValue;
12156 
12157   return Result;
12158 }
12159 
12160 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
12161   BinaryOperatorKind Opc;
12162   switch (Kind) {
12163   default: llvm_unreachable("Unknown binop!");
12164   case tok::periodstar:           Opc = BO_PtrMemD; break;
12165   case tok::arrowstar:            Opc = BO_PtrMemI; break;
12166   case tok::star:                 Opc = BO_Mul; break;
12167   case tok::slash:                Opc = BO_Div; break;
12168   case tok::percent:              Opc = BO_Rem; break;
12169   case tok::plus:                 Opc = BO_Add; break;
12170   case tok::minus:                Opc = BO_Sub; break;
12171   case tok::lessless:             Opc = BO_Shl; break;
12172   case tok::greatergreater:       Opc = BO_Shr; break;
12173   case tok::lessequal:            Opc = BO_LE; break;
12174   case tok::less:                 Opc = BO_LT; break;
12175   case tok::greaterequal:         Opc = BO_GE; break;
12176   case tok::greater:              Opc = BO_GT; break;
12177   case tok::exclaimequal:         Opc = BO_NE; break;
12178   case tok::equalequal:           Opc = BO_EQ; break;
12179   case tok::spaceship:            Opc = BO_Cmp; break;
12180   case tok::amp:                  Opc = BO_And; break;
12181   case tok::caret:                Opc = BO_Xor; break;
12182   case tok::pipe:                 Opc = BO_Or; break;
12183   case tok::ampamp:               Opc = BO_LAnd; break;
12184   case tok::pipepipe:             Opc = BO_LOr; break;
12185   case tok::equal:                Opc = BO_Assign; break;
12186   case tok::starequal:            Opc = BO_MulAssign; break;
12187   case tok::slashequal:           Opc = BO_DivAssign; break;
12188   case tok::percentequal:         Opc = BO_RemAssign; break;
12189   case tok::plusequal:            Opc = BO_AddAssign; break;
12190   case tok::minusequal:           Opc = BO_SubAssign; break;
12191   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
12192   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
12193   case tok::ampequal:             Opc = BO_AndAssign; break;
12194   case tok::caretequal:           Opc = BO_XorAssign; break;
12195   case tok::pipeequal:            Opc = BO_OrAssign; break;
12196   case tok::comma:                Opc = BO_Comma; break;
12197   }
12198   return Opc;
12199 }
12200 
12201 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
12202   tok::TokenKind Kind) {
12203   UnaryOperatorKind Opc;
12204   switch (Kind) {
12205   default: llvm_unreachable("Unknown unary op!");
12206   case tok::plusplus:     Opc = UO_PreInc; break;
12207   case tok::minusminus:   Opc = UO_PreDec; break;
12208   case tok::amp:          Opc = UO_AddrOf; break;
12209   case tok::star:         Opc = UO_Deref; break;
12210   case tok::plus:         Opc = UO_Plus; break;
12211   case tok::minus:        Opc = UO_Minus; break;
12212   case tok::tilde:        Opc = UO_Not; break;
12213   case tok::exclaim:      Opc = UO_LNot; break;
12214   case tok::kw___real:    Opc = UO_Real; break;
12215   case tok::kw___imag:    Opc = UO_Imag; break;
12216   case tok::kw___extension__: Opc = UO_Extension; break;
12217   }
12218   return Opc;
12219 }
12220 
12221 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
12222 /// This warning suppressed in the event of macro expansions.
12223 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
12224                                    SourceLocation OpLoc, bool IsBuiltin) {
12225   if (S.inTemplateInstantiation())
12226     return;
12227   if (S.isUnevaluatedContext())
12228     return;
12229   if (OpLoc.isInvalid() || OpLoc.isMacroID())
12230     return;
12231   LHSExpr = LHSExpr->IgnoreParenImpCasts();
12232   RHSExpr = RHSExpr->IgnoreParenImpCasts();
12233   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
12234   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
12235   if (!LHSDeclRef || !RHSDeclRef ||
12236       LHSDeclRef->getLocation().isMacroID() ||
12237       RHSDeclRef->getLocation().isMacroID())
12238     return;
12239   const ValueDecl *LHSDecl =
12240     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
12241   const ValueDecl *RHSDecl =
12242     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
12243   if (LHSDecl != RHSDecl)
12244     return;
12245   if (LHSDecl->getType().isVolatileQualified())
12246     return;
12247   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
12248     if (RefTy->getPointeeType().isVolatileQualified())
12249       return;
12250 
12251   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
12252                           : diag::warn_self_assignment_overloaded)
12253       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
12254       << RHSExpr->getSourceRange();
12255 }
12256 
12257 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
12258 /// is usually indicative of introspection within the Objective-C pointer.
12259 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
12260                                           SourceLocation OpLoc) {
12261   if (!S.getLangOpts().ObjC)
12262     return;
12263 
12264   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
12265   const Expr *LHS = L.get();
12266   const Expr *RHS = R.get();
12267 
12268   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12269     ObjCPointerExpr = LHS;
12270     OtherExpr = RHS;
12271   }
12272   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
12273     ObjCPointerExpr = RHS;
12274     OtherExpr = LHS;
12275   }
12276 
12277   // This warning is deliberately made very specific to reduce false
12278   // positives with logic that uses '&' for hashing.  This logic mainly
12279   // looks for code trying to introspect into tagged pointers, which
12280   // code should generally never do.
12281   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
12282     unsigned Diag = diag::warn_objc_pointer_masking;
12283     // Determine if we are introspecting the result of performSelectorXXX.
12284     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
12285     // Special case messages to -performSelector and friends, which
12286     // can return non-pointer values boxed in a pointer value.
12287     // Some clients may wish to silence warnings in this subcase.
12288     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
12289       Selector S = ME->getSelector();
12290       StringRef SelArg0 = S.getNameForSlot(0);
12291       if (SelArg0.startswith("performSelector"))
12292         Diag = diag::warn_objc_pointer_masking_performSelector;
12293     }
12294 
12295     S.Diag(OpLoc, Diag)
12296       << ObjCPointerExpr->getSourceRange();
12297   }
12298 }
12299 
12300 static NamedDecl *getDeclFromExpr(Expr *E) {
12301   if (!E)
12302     return nullptr;
12303   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
12304     return DRE->getDecl();
12305   if (auto *ME = dyn_cast<MemberExpr>(E))
12306     return ME->getMemberDecl();
12307   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
12308     return IRE->getDecl();
12309   return nullptr;
12310 }
12311 
12312 // This helper function promotes a binary operator's operands (which are of a
12313 // half vector type) to a vector of floats and then truncates the result to
12314 // a vector of either half or short.
12315 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
12316                                       BinaryOperatorKind Opc, QualType ResultTy,
12317                                       ExprValueKind VK, ExprObjectKind OK,
12318                                       bool IsCompAssign, SourceLocation OpLoc,
12319                                       FPOptions FPFeatures) {
12320   auto &Context = S.getASTContext();
12321   assert((isVector(ResultTy, Context.HalfTy) ||
12322           isVector(ResultTy, Context.ShortTy)) &&
12323          "Result must be a vector of half or short");
12324   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
12325          isVector(RHS.get()->getType(), Context.HalfTy) &&
12326          "both operands expected to be a half vector");
12327 
12328   RHS = convertVector(RHS.get(), Context.FloatTy, S);
12329   QualType BinOpResTy = RHS.get()->getType();
12330 
12331   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
12332   // change BinOpResTy to a vector of ints.
12333   if (isVector(ResultTy, Context.ShortTy))
12334     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
12335 
12336   if (IsCompAssign)
12337     return new (Context) CompoundAssignOperator(
12338         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
12339         OpLoc, FPFeatures);
12340 
12341   LHS = convertVector(LHS.get(), Context.FloatTy, S);
12342   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
12343                                           VK, OK, OpLoc, FPFeatures);
12344   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
12345 }
12346 
12347 static std::pair<ExprResult, ExprResult>
12348 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
12349                            Expr *RHSExpr) {
12350   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12351   if (!S.getLangOpts().CPlusPlus) {
12352     // C cannot handle TypoExpr nodes on either side of a binop because it
12353     // doesn't handle dependent types properly, so make sure any TypoExprs have
12354     // been dealt with before checking the operands.
12355     LHS = S.CorrectDelayedTyposInExpr(LHS);
12356     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
12357       if (Opc != BO_Assign)
12358         return ExprResult(E);
12359       // Avoid correcting the RHS to the same Expr as the LHS.
12360       Decl *D = getDeclFromExpr(E);
12361       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
12362     });
12363   }
12364   return std::make_pair(LHS, RHS);
12365 }
12366 
12367 /// Returns true if conversion between vectors of halfs and vectors of floats
12368 /// is needed.
12369 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
12370                                      QualType SrcType) {
12371   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
12372          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
12373          isVector(SrcType, Ctx.HalfTy);
12374 }
12375 
12376 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
12377 /// operator @p Opc at location @c TokLoc. This routine only supports
12378 /// built-in operations; ActOnBinOp handles overloaded operators.
12379 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
12380                                     BinaryOperatorKind Opc,
12381                                     Expr *LHSExpr, Expr *RHSExpr) {
12382   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
12383     // The syntax only allows initializer lists on the RHS of assignment,
12384     // so we don't need to worry about accepting invalid code for
12385     // non-assignment operators.
12386     // C++11 5.17p9:
12387     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
12388     //   of x = {} is x = T().
12389     InitializationKind Kind = InitializationKind::CreateDirectList(
12390         RHSExpr->getBeginLoc(), RHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12391     InitializedEntity Entity =
12392         InitializedEntity::InitializeTemporary(LHSExpr->getType());
12393     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
12394     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
12395     if (Init.isInvalid())
12396       return Init;
12397     RHSExpr = Init.get();
12398   }
12399 
12400   ExprResult LHS = LHSExpr, RHS = RHSExpr;
12401   QualType ResultTy;     // Result type of the binary operator.
12402   // The following two variables are used for compound assignment operators
12403   QualType CompLHSTy;    // Type of LHS after promotions for computation
12404   QualType CompResultTy; // Type of computation result
12405   ExprValueKind VK = VK_RValue;
12406   ExprObjectKind OK = OK_Ordinary;
12407   bool ConvertHalfVec = false;
12408 
12409   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12410   if (!LHS.isUsable() || !RHS.isUsable())
12411     return ExprError();
12412 
12413   if (getLangOpts().OpenCL) {
12414     QualType LHSTy = LHSExpr->getType();
12415     QualType RHSTy = RHSExpr->getType();
12416     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
12417     // the ATOMIC_VAR_INIT macro.
12418     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
12419       SourceRange SR(LHSExpr->getBeginLoc(), RHSExpr->getEndLoc());
12420       if (BO_Assign == Opc)
12421         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
12422       else
12423         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12424       return ExprError();
12425     }
12426 
12427     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12428     // only with a builtin functions and therefore should be disallowed here.
12429     if (LHSTy->isImageType() || RHSTy->isImageType() ||
12430         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
12431         LHSTy->isPipeType() || RHSTy->isPipeType() ||
12432         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
12433       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
12434       return ExprError();
12435     }
12436   }
12437 
12438   // Diagnose operations on the unsupported types for OpenMP device compilation.
12439   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
12440     if (Opc != BO_Assign && Opc != BO_Comma) {
12441       checkOpenMPDeviceExpr(LHSExpr);
12442       checkOpenMPDeviceExpr(RHSExpr);
12443     }
12444   }
12445 
12446   switch (Opc) {
12447   case BO_Assign:
12448     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
12449     if (getLangOpts().CPlusPlus &&
12450         LHS.get()->getObjectKind() != OK_ObjCProperty) {
12451       VK = LHS.get()->getValueKind();
12452       OK = LHS.get()->getObjectKind();
12453     }
12454     if (!ResultTy.isNull()) {
12455       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12456       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
12457 
12458       // Avoid copying a block to the heap if the block is assigned to a local
12459       // auto variable that is declared in the same scope as the block. This
12460       // optimization is unsafe if the local variable is declared in an outer
12461       // scope. For example:
12462       //
12463       // BlockTy b;
12464       // {
12465       //   b = ^{...};
12466       // }
12467       // // It is unsafe to invoke the block here if it wasn't copied to the
12468       // // heap.
12469       // b();
12470 
12471       if (auto *BE = dyn_cast<BlockExpr>(RHS.get()->IgnoreParens()))
12472         if (auto *DRE = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
12473           if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
12474             if (VD->hasLocalStorage() && getCurScope()->isDeclScope(VD))
12475               BE->getBlockDecl()->setCanAvoidCopyToHeap();
12476     }
12477     RecordModifiableNonNullParam(*this, LHS.get());
12478     break;
12479   case BO_PtrMemD:
12480   case BO_PtrMemI:
12481     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
12482                                             Opc == BO_PtrMemI);
12483     break;
12484   case BO_Mul:
12485   case BO_Div:
12486     ConvertHalfVec = true;
12487     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
12488                                            Opc == BO_Div);
12489     break;
12490   case BO_Rem:
12491     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
12492     break;
12493   case BO_Add:
12494     ConvertHalfVec = true;
12495     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
12496     break;
12497   case BO_Sub:
12498     ConvertHalfVec = true;
12499     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
12500     break;
12501   case BO_Shl:
12502   case BO_Shr:
12503     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
12504     break;
12505   case BO_LE:
12506   case BO_LT:
12507   case BO_GE:
12508   case BO_GT:
12509     ConvertHalfVec = true;
12510     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12511     break;
12512   case BO_EQ:
12513   case BO_NE:
12514     ConvertHalfVec = true;
12515     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12516     break;
12517   case BO_Cmp:
12518     ConvertHalfVec = true;
12519     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12520     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12521     break;
12522   case BO_And:
12523     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12524     LLVM_FALLTHROUGH;
12525   case BO_Xor:
12526   case BO_Or:
12527     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12528     break;
12529   case BO_LAnd:
12530   case BO_LOr:
12531     ConvertHalfVec = true;
12532     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12533     break;
12534   case BO_MulAssign:
12535   case BO_DivAssign:
12536     ConvertHalfVec = true;
12537     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12538                                                Opc == BO_DivAssign);
12539     CompLHSTy = CompResultTy;
12540     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12541       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12542     break;
12543   case BO_RemAssign:
12544     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12545     CompLHSTy = CompResultTy;
12546     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12547       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12548     break;
12549   case BO_AddAssign:
12550     ConvertHalfVec = true;
12551     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12552     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12553       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12554     break;
12555   case BO_SubAssign:
12556     ConvertHalfVec = true;
12557     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12558     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12559       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12560     break;
12561   case BO_ShlAssign:
12562   case BO_ShrAssign:
12563     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12564     CompLHSTy = CompResultTy;
12565     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12566       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12567     break;
12568   case BO_AndAssign:
12569   case BO_OrAssign: // fallthrough
12570     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12571     LLVM_FALLTHROUGH;
12572   case BO_XorAssign:
12573     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12574     CompLHSTy = CompResultTy;
12575     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12576       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12577     break;
12578   case BO_Comma:
12579     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12580     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12581       VK = RHS.get()->getValueKind();
12582       OK = RHS.get()->getObjectKind();
12583     }
12584     break;
12585   }
12586   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12587     return ExprError();
12588 
12589   // Some of the binary operations require promoting operands of half vector to
12590   // float vectors and truncating the result back to half vector. For now, we do
12591   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12592   // arm64).
12593   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12594          isVector(LHS.get()->getType(), Context.HalfTy) &&
12595          "both sides are half vectors or neither sides are");
12596   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12597                                             LHS.get()->getType());
12598 
12599   // Check for array bounds violations for both sides of the BinaryOperator
12600   CheckArrayAccess(LHS.get());
12601   CheckArrayAccess(RHS.get());
12602 
12603   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12604     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12605                                                  &Context.Idents.get("object_setClass"),
12606                                                  SourceLocation(), LookupOrdinaryName);
12607     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12608       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getEndLoc());
12609       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign)
12610           << FixItHint::CreateInsertion(LHS.get()->getBeginLoc(),
12611                                         "object_setClass(")
12612           << FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc),
12613                                           ",")
12614           << FixItHint::CreateInsertion(RHSLocEnd, ")");
12615     }
12616     else
12617       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12618   }
12619   else if (const ObjCIvarRefExpr *OIRE =
12620            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12621     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12622 
12623   // Opc is not a compound assignment if CompResultTy is null.
12624   if (CompResultTy.isNull()) {
12625     if (ConvertHalfVec)
12626       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12627                                  OpLoc, FPFeatures);
12628     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12629                                         OK, OpLoc, FPFeatures);
12630   }
12631 
12632   // Handle compound assignments.
12633   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12634       OK_ObjCProperty) {
12635     VK = VK_LValue;
12636     OK = LHS.get()->getObjectKind();
12637   }
12638 
12639   if (ConvertHalfVec)
12640     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12641                                OpLoc, FPFeatures);
12642 
12643   return new (Context) CompoundAssignOperator(
12644       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12645       OpLoc, FPFeatures);
12646 }
12647 
12648 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12649 /// operators are mixed in a way that suggests that the programmer forgot that
12650 /// comparison operators have higher precedence. The most typical example of
12651 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12652 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12653                                       SourceLocation OpLoc, Expr *LHSExpr,
12654                                       Expr *RHSExpr) {
12655   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12656   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12657 
12658   // Check that one of the sides is a comparison operator and the other isn't.
12659   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12660   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12661   if (isLeftComp == isRightComp)
12662     return;
12663 
12664   // Bitwise operations are sometimes used as eager logical ops.
12665   // Don't diagnose this.
12666   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12667   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12668   if (isLeftBitwise || isRightBitwise)
12669     return;
12670 
12671   SourceRange DiagRange = isLeftComp
12672                               ? SourceRange(LHSExpr->getBeginLoc(), OpLoc)
12673                               : SourceRange(OpLoc, RHSExpr->getEndLoc());
12674   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12675   SourceRange ParensRange =
12676       isLeftComp
12677           ? SourceRange(LHSBO->getRHS()->getBeginLoc(), RHSExpr->getEndLoc())
12678           : SourceRange(LHSExpr->getBeginLoc(), RHSBO->getLHS()->getEndLoc());
12679 
12680   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12681     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12682   SuggestParentheses(Self, OpLoc,
12683     Self.PDiag(diag::note_precedence_silence) << OpStr,
12684     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12685   SuggestParentheses(Self, OpLoc,
12686     Self.PDiag(diag::note_precedence_bitwise_first)
12687       << BinaryOperator::getOpcodeStr(Opc),
12688     ParensRange);
12689 }
12690 
12691 /// It accepts a '&&' expr that is inside a '||' one.
12692 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12693 /// in parentheses.
12694 static void
12695 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12696                                        BinaryOperator *Bop) {
12697   assert(Bop->getOpcode() == BO_LAnd);
12698   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12699       << Bop->getSourceRange() << OpLoc;
12700   SuggestParentheses(Self, Bop->getOperatorLoc(),
12701     Self.PDiag(diag::note_precedence_silence)
12702       << Bop->getOpcodeStr(),
12703     Bop->getSourceRange());
12704 }
12705 
12706 /// Returns true if the given expression can be evaluated as a constant
12707 /// 'true'.
12708 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12709   bool Res;
12710   return !E->isValueDependent() &&
12711          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12712 }
12713 
12714 /// Returns true if the given expression can be evaluated as a constant
12715 /// 'false'.
12716 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12717   bool Res;
12718   return !E->isValueDependent() &&
12719          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12720 }
12721 
12722 /// Look for '&&' in the left hand of a '||' expr.
12723 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12724                                              Expr *LHSExpr, Expr *RHSExpr) {
12725   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12726     if (Bop->getOpcode() == BO_LAnd) {
12727       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12728       if (EvaluatesAsFalse(S, RHSExpr))
12729         return;
12730       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12731       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12732         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12733     } else if (Bop->getOpcode() == BO_LOr) {
12734       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12735         // If it's "a || b && 1 || c" we didn't warn earlier for
12736         // "a || b && 1", but warn now.
12737         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12738           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12739       }
12740     }
12741   }
12742 }
12743 
12744 /// Look for '&&' in the right hand of a '||' expr.
12745 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12746                                              Expr *LHSExpr, Expr *RHSExpr) {
12747   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12748     if (Bop->getOpcode() == BO_LAnd) {
12749       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12750       if (EvaluatesAsFalse(S, LHSExpr))
12751         return;
12752       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12753       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12754         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12755     }
12756   }
12757 }
12758 
12759 /// Look for bitwise op in the left or right hand of a bitwise op with
12760 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12761 /// the '&' expression in parentheses.
12762 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12763                                          SourceLocation OpLoc, Expr *SubExpr) {
12764   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12765     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12766       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12767         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12768         << Bop->getSourceRange() << OpLoc;
12769       SuggestParentheses(S, Bop->getOperatorLoc(),
12770         S.PDiag(diag::note_precedence_silence)
12771           << Bop->getOpcodeStr(),
12772         Bop->getSourceRange());
12773     }
12774   }
12775 }
12776 
12777 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12778                                     Expr *SubExpr, StringRef Shift) {
12779   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12780     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12781       StringRef Op = Bop->getOpcodeStr();
12782       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12783           << Bop->getSourceRange() << OpLoc << Shift << Op;
12784       SuggestParentheses(S, Bop->getOperatorLoc(),
12785           S.PDiag(diag::note_precedence_silence) << Op,
12786           Bop->getSourceRange());
12787     }
12788   }
12789 }
12790 
12791 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12792                                  Expr *LHSExpr, Expr *RHSExpr) {
12793   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12794   if (!OCE)
12795     return;
12796 
12797   FunctionDecl *FD = OCE->getDirectCallee();
12798   if (!FD || !FD->isOverloadedOperator())
12799     return;
12800 
12801   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12802   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12803     return;
12804 
12805   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12806       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12807       << (Kind == OO_LessLess);
12808   SuggestParentheses(S, OCE->getOperatorLoc(),
12809                      S.PDiag(diag::note_precedence_silence)
12810                          << (Kind == OO_LessLess ? "<<" : ">>"),
12811                      OCE->getSourceRange());
12812   SuggestParentheses(
12813       S, OpLoc, S.PDiag(diag::note_evaluate_comparison_first),
12814       SourceRange(OCE->getArg(1)->getBeginLoc(), RHSExpr->getEndLoc()));
12815 }
12816 
12817 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12818 /// precedence.
12819 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12820                                     SourceLocation OpLoc, Expr *LHSExpr,
12821                                     Expr *RHSExpr){
12822   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12823   if (BinaryOperator::isBitwiseOp(Opc))
12824     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12825 
12826   // Diagnose "arg1 & arg2 | arg3"
12827   if ((Opc == BO_Or || Opc == BO_Xor) &&
12828       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12829     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12830     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12831   }
12832 
12833   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12834   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12835   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12836     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12837     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12838   }
12839 
12840   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12841       || Opc == BO_Shr) {
12842     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12843     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12844     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12845   }
12846 
12847   // Warn on overloaded shift operators and comparisons, such as:
12848   // cout << 5 == 4;
12849   if (BinaryOperator::isComparisonOp(Opc))
12850     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12851 }
12852 
12853 // Binary Operators.  'Tok' is the token for the operator.
12854 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12855                             tok::TokenKind Kind,
12856                             Expr *LHSExpr, Expr *RHSExpr) {
12857   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12858   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12859   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12860 
12861   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12862   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12863 
12864   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12865 }
12866 
12867 /// Build an overloaded binary operator expression in the given scope.
12868 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12869                                        BinaryOperatorKind Opc,
12870                                        Expr *LHS, Expr *RHS) {
12871   switch (Opc) {
12872   case BO_Assign:
12873   case BO_DivAssign:
12874   case BO_RemAssign:
12875   case BO_SubAssign:
12876   case BO_AndAssign:
12877   case BO_OrAssign:
12878   case BO_XorAssign:
12879     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12880     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12881     break;
12882   default:
12883     break;
12884   }
12885 
12886   // Find all of the overloaded operators visible from this
12887   // point. We perform both an operator-name lookup from the local
12888   // scope and an argument-dependent lookup based on the types of
12889   // the arguments.
12890   UnresolvedSet<16> Functions;
12891   OverloadedOperatorKind OverOp
12892     = BinaryOperator::getOverloadedOperator(Opc);
12893   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12894     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12895                                    RHS->getType(), Functions);
12896 
12897   // Build the (potentially-overloaded, potentially-dependent)
12898   // binary operation.
12899   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12900 }
12901 
12902 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12903                             BinaryOperatorKind Opc,
12904                             Expr *LHSExpr, Expr *RHSExpr) {
12905   ExprResult LHS, RHS;
12906   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12907   if (!LHS.isUsable() || !RHS.isUsable())
12908     return ExprError();
12909   LHSExpr = LHS.get();
12910   RHSExpr = RHS.get();
12911 
12912   // We want to end up calling one of checkPseudoObjectAssignment
12913   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12914   // both expressions are overloadable or either is type-dependent),
12915   // or CreateBuiltinBinOp (in any other case).  We also want to get
12916   // any placeholder types out of the way.
12917 
12918   // Handle pseudo-objects in the LHS.
12919   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12920     // Assignments with a pseudo-object l-value need special analysis.
12921     if (pty->getKind() == BuiltinType::PseudoObject &&
12922         BinaryOperator::isAssignmentOp(Opc))
12923       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12924 
12925     // Don't resolve overloads if the other type is overloadable.
12926     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12927       // We can't actually test that if we still have a placeholder,
12928       // though.  Fortunately, none of the exceptions we see in that
12929       // code below are valid when the LHS is an overload set.  Note
12930       // that an overload set can be dependently-typed, but it never
12931       // instantiates to having an overloadable type.
12932       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12933       if (resolvedRHS.isInvalid()) return ExprError();
12934       RHSExpr = resolvedRHS.get();
12935 
12936       if (RHSExpr->isTypeDependent() ||
12937           RHSExpr->getType()->isOverloadableType())
12938         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12939     }
12940 
12941     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12942     // template, diagnose the missing 'template' keyword instead of diagnosing
12943     // an invalid use of a bound member function.
12944     //
12945     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12946     // to C++1z [over.over]/1.4, but we already checked for that case above.
12947     if (Opc == BO_LT && inTemplateInstantiation() &&
12948         (pty->getKind() == BuiltinType::BoundMember ||
12949          pty->getKind() == BuiltinType::Overload)) {
12950       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12951       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12952           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12953             return isa<FunctionTemplateDecl>(ND);
12954           })) {
12955         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12956                                 : OE->getNameLoc(),
12957              diag::err_template_kw_missing)
12958           << OE->getName().getAsString() << "";
12959         return ExprError();
12960       }
12961     }
12962 
12963     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12964     if (LHS.isInvalid()) return ExprError();
12965     LHSExpr = LHS.get();
12966   }
12967 
12968   // Handle pseudo-objects in the RHS.
12969   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12970     // An overload in the RHS can potentially be resolved by the type
12971     // being assigned to.
12972     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12973       if (getLangOpts().CPlusPlus &&
12974           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12975            LHSExpr->getType()->isOverloadableType()))
12976         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12977 
12978       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12979     }
12980 
12981     // Don't resolve overloads if the other type is overloadable.
12982     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12983         LHSExpr->getType()->isOverloadableType())
12984       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12985 
12986     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12987     if (!resolvedRHS.isUsable()) return ExprError();
12988     RHSExpr = resolvedRHS.get();
12989   }
12990 
12991   if (getLangOpts().CPlusPlus) {
12992     // If either expression is type-dependent, always build an
12993     // overloaded op.
12994     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12995       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12996 
12997     // Otherwise, build an overloaded op if either expression has an
12998     // overloadable type.
12999     if (LHSExpr->getType()->isOverloadableType() ||
13000         RHSExpr->getType()->isOverloadableType())
13001       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
13002   }
13003 
13004   // Build a built-in binary operation.
13005   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
13006 }
13007 
13008 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
13009   if (T.isNull() || T->isDependentType())
13010     return false;
13011 
13012   if (!T->isPromotableIntegerType())
13013     return true;
13014 
13015   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
13016 }
13017 
13018 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
13019                                       UnaryOperatorKind Opc,
13020                                       Expr *InputExpr) {
13021   ExprResult Input = InputExpr;
13022   ExprValueKind VK = VK_RValue;
13023   ExprObjectKind OK = OK_Ordinary;
13024   QualType resultType;
13025   bool CanOverflow = false;
13026 
13027   bool ConvertHalfVec = false;
13028   if (getLangOpts().OpenCL) {
13029     QualType Ty = InputExpr->getType();
13030     // The only legal unary operation for atomics is '&'.
13031     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
13032     // OpenCL special types - image, sampler, pipe, and blocks are to be used
13033     // only with a builtin functions and therefore should be disallowed here.
13034         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
13035         || Ty->isBlockPointerType())) {
13036       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13037                        << InputExpr->getType()
13038                        << Input.get()->getSourceRange());
13039     }
13040   }
13041   // Diagnose operations on the unsupported types for OpenMP device compilation.
13042   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice) {
13043     if (UnaryOperator::isIncrementDecrementOp(Opc) ||
13044         UnaryOperator::isArithmeticOp(Opc))
13045       checkOpenMPDeviceExpr(InputExpr);
13046   }
13047 
13048   switch (Opc) {
13049   case UO_PreInc:
13050   case UO_PreDec:
13051   case UO_PostInc:
13052   case UO_PostDec:
13053     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
13054                                                 OpLoc,
13055                                                 Opc == UO_PreInc ||
13056                                                 Opc == UO_PostInc,
13057                                                 Opc == UO_PreInc ||
13058                                                 Opc == UO_PreDec);
13059     CanOverflow = isOverflowingIntegerType(Context, resultType);
13060     break;
13061   case UO_AddrOf:
13062     resultType = CheckAddressOfOperand(Input, OpLoc);
13063     CheckAddressOfNoDeref(InputExpr);
13064     RecordModifiableNonNullParam(*this, InputExpr);
13065     break;
13066   case UO_Deref: {
13067     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13068     if (Input.isInvalid()) return ExprError();
13069     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
13070     break;
13071   }
13072   case UO_Plus:
13073   case UO_Minus:
13074     CanOverflow = Opc == UO_Minus &&
13075                   isOverflowingIntegerType(Context, Input.get()->getType());
13076     Input = UsualUnaryConversions(Input.get());
13077     if (Input.isInvalid()) return ExprError();
13078     // Unary plus and minus require promoting an operand of half vector to a
13079     // float vector and truncating the result back to a half vector. For now, we
13080     // do this only when HalfArgsAndReturns is set (that is, when the target is
13081     // arm or arm64).
13082     ConvertHalfVec =
13083         needsConversionOfHalfVec(true, Context, Input.get()->getType());
13084 
13085     // If the operand is a half vector, promote it to a float vector.
13086     if (ConvertHalfVec)
13087       Input = convertVector(Input.get(), Context.FloatTy, *this);
13088     resultType = Input.get()->getType();
13089     if (resultType->isDependentType())
13090       break;
13091     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
13092       break;
13093     else if (resultType->isVectorType() &&
13094              // The z vector extensions don't allow + or - with bool vectors.
13095              (!Context.getLangOpts().ZVector ||
13096               resultType->getAs<VectorType>()->getVectorKind() !=
13097               VectorType::AltiVecBool))
13098       break;
13099     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
13100              Opc == UO_Plus &&
13101              resultType->isPointerType())
13102       break;
13103 
13104     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13105       << resultType << Input.get()->getSourceRange());
13106 
13107   case UO_Not: // bitwise complement
13108     Input = UsualUnaryConversions(Input.get());
13109     if (Input.isInvalid())
13110       return ExprError();
13111     resultType = Input.get()->getType();
13112 
13113     if (resultType->isDependentType())
13114       break;
13115     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
13116     if (resultType->isComplexType() || resultType->isComplexIntegerType())
13117       // C99 does not support '~' for complex conjugation.
13118       Diag(OpLoc, diag::ext_integer_complement_complex)
13119           << resultType << Input.get()->getSourceRange();
13120     else if (resultType->hasIntegerRepresentation())
13121       break;
13122     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
13123       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
13124       // on vector float types.
13125       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13126       if (!T->isIntegerType())
13127         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13128                           << resultType << Input.get()->getSourceRange());
13129     } else {
13130       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13131                        << resultType << Input.get()->getSourceRange());
13132     }
13133     break;
13134 
13135   case UO_LNot: // logical negation
13136     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
13137     Input = DefaultFunctionArrayLvalueConversion(Input.get());
13138     if (Input.isInvalid()) return ExprError();
13139     resultType = Input.get()->getType();
13140 
13141     // Though we still have to promote half FP to float...
13142     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
13143       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
13144       resultType = Context.FloatTy;
13145     }
13146 
13147     if (resultType->isDependentType())
13148       break;
13149     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
13150       // C99 6.5.3.3p1: ok, fallthrough;
13151       if (Context.getLangOpts().CPlusPlus) {
13152         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
13153         // operand contextually converted to bool.
13154         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
13155                                   ScalarTypeToBooleanCastKind(resultType));
13156       } else if (Context.getLangOpts().OpenCL &&
13157                  Context.getLangOpts().OpenCLVersion < 120) {
13158         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13159         // operate on scalar float types.
13160         if (!resultType->isIntegerType() && !resultType->isPointerType())
13161           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13162                            << resultType << Input.get()->getSourceRange());
13163       }
13164     } else if (resultType->isExtVectorType()) {
13165       if (Context.getLangOpts().OpenCL &&
13166           Context.getLangOpts().OpenCLVersion < 120) {
13167         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
13168         // operate on vector float types.
13169         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
13170         if (!T->isIntegerType())
13171           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13172                            << resultType << Input.get()->getSourceRange());
13173       }
13174       // Vector logical not returns the signed variant of the operand type.
13175       resultType = GetSignedVectorType(resultType);
13176       break;
13177     } else {
13178       // FIXME: GCC's vector extension permits the usage of '!' with a vector
13179       //        type in C++. We should allow that here too.
13180       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
13181         << resultType << Input.get()->getSourceRange());
13182     }
13183 
13184     // LNot always has type int. C99 6.5.3.3p5.
13185     // In C++, it's bool. C++ 5.3.1p8
13186     resultType = Context.getLogicalOperationType();
13187     break;
13188   case UO_Real:
13189   case UO_Imag:
13190     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
13191     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
13192     // complex l-values to ordinary l-values and all other values to r-values.
13193     if (Input.isInvalid()) return ExprError();
13194     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
13195       if (Input.get()->getValueKind() != VK_RValue &&
13196           Input.get()->getObjectKind() == OK_Ordinary)
13197         VK = Input.get()->getValueKind();
13198     } else if (!getLangOpts().CPlusPlus) {
13199       // In C, a volatile scalar is read by __imag. In C++, it is not.
13200       Input = DefaultLvalueConversion(Input.get());
13201     }
13202     break;
13203   case UO_Extension:
13204     resultType = Input.get()->getType();
13205     VK = Input.get()->getValueKind();
13206     OK = Input.get()->getObjectKind();
13207     break;
13208   case UO_Coawait:
13209     // It's unnecessary to represent the pass-through operator co_await in the
13210     // AST; just return the input expression instead.
13211     assert(!Input.get()->getType()->isDependentType() &&
13212                    "the co_await expression must be non-dependant before "
13213                    "building operator co_await");
13214     return Input;
13215   }
13216   if (resultType.isNull() || Input.isInvalid())
13217     return ExprError();
13218 
13219   // Check for array bounds violations in the operand of the UnaryOperator,
13220   // except for the '*' and '&' operators that have to be handled specially
13221   // by CheckArrayAccess (as there are special cases like &array[arraysize]
13222   // that are explicitly defined as valid by the standard).
13223   if (Opc != UO_AddrOf && Opc != UO_Deref)
13224     CheckArrayAccess(Input.get());
13225 
13226   auto *UO = new (Context)
13227       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
13228 
13229   if (Opc == UO_Deref && UO->getType()->hasAttr(attr::NoDeref) &&
13230       !isa<ArrayType>(UO->getType().getDesugaredType(Context)))
13231     ExprEvalContexts.back().PossibleDerefs.insert(UO);
13232 
13233   // Convert the result back to a half vector.
13234   if (ConvertHalfVec)
13235     return convertVector(UO, Context.HalfTy, *this);
13236   return UO;
13237 }
13238 
13239 /// Determine whether the given expression is a qualified member
13240 /// access expression, of a form that could be turned into a pointer to member
13241 /// with the address-of operator.
13242 bool Sema::isQualifiedMemberAccess(Expr *E) {
13243   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13244     if (!DRE->getQualifier())
13245       return false;
13246 
13247     ValueDecl *VD = DRE->getDecl();
13248     if (!VD->isCXXClassMember())
13249       return false;
13250 
13251     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
13252       return true;
13253     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
13254       return Method->isInstance();
13255 
13256     return false;
13257   }
13258 
13259   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13260     if (!ULE->getQualifier())
13261       return false;
13262 
13263     for (NamedDecl *D : ULE->decls()) {
13264       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
13265         if (Method->isInstance())
13266           return true;
13267       } else {
13268         // Overload set does not contain methods.
13269         break;
13270       }
13271     }
13272 
13273     return false;
13274   }
13275 
13276   return false;
13277 }
13278 
13279 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
13280                               UnaryOperatorKind Opc, Expr *Input) {
13281   // First things first: handle placeholders so that the
13282   // overloaded-operator check considers the right type.
13283   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
13284     // Increment and decrement of pseudo-object references.
13285     if (pty->getKind() == BuiltinType::PseudoObject &&
13286         UnaryOperator::isIncrementDecrementOp(Opc))
13287       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
13288 
13289     // extension is always a builtin operator.
13290     if (Opc == UO_Extension)
13291       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13292 
13293     // & gets special logic for several kinds of placeholder.
13294     // The builtin code knows what to do.
13295     if (Opc == UO_AddrOf &&
13296         (pty->getKind() == BuiltinType::Overload ||
13297          pty->getKind() == BuiltinType::UnknownAny ||
13298          pty->getKind() == BuiltinType::BoundMember))
13299       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13300 
13301     // Anything else needs to be handled now.
13302     ExprResult Result = CheckPlaceholderExpr(Input);
13303     if (Result.isInvalid()) return ExprError();
13304     Input = Result.get();
13305   }
13306 
13307   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
13308       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
13309       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
13310     // Find all of the overloaded operators visible from this
13311     // point. We perform both an operator-name lookup from the local
13312     // scope and an argument-dependent lookup based on the types of
13313     // the arguments.
13314     UnresolvedSet<16> Functions;
13315     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
13316     if (S && OverOp != OO_None)
13317       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
13318                                    Functions);
13319 
13320     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
13321   }
13322 
13323   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13324 }
13325 
13326 // Unary Operators.  'Tok' is the token for the operator.
13327 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
13328                               tok::TokenKind Op, Expr *Input) {
13329   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
13330 }
13331 
13332 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
13333 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
13334                                 LabelDecl *TheDecl) {
13335   TheDecl->markUsed(Context);
13336   // Create the AST node.  The address of a label always has type 'void*'.
13337   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
13338                                      Context.getPointerType(Context.VoidTy));
13339 }
13340 
13341 void Sema::ActOnStartStmtExpr() {
13342   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13343 }
13344 
13345 void Sema::ActOnStmtExprError() {
13346   // Note that function is also called by TreeTransform when leaving a
13347   // StmtExpr scope without rebuilding anything.
13348 
13349   DiscardCleanupsInEvaluationContext();
13350   PopExpressionEvaluationContext();
13351 }
13352 
13353 ExprResult
13354 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
13355                     SourceLocation RPLoc) { // "({..})"
13356   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
13357   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
13358 
13359   if (hasAnyUnrecoverableErrorsInThisFunction())
13360     DiscardCleanupsInEvaluationContext();
13361   assert(!Cleanup.exprNeedsCleanups() &&
13362          "cleanups within StmtExpr not correctly bound!");
13363   PopExpressionEvaluationContext();
13364 
13365   // FIXME: there are a variety of strange constraints to enforce here, for
13366   // example, it is not possible to goto into a stmt expression apparently.
13367   // More semantic analysis is needed.
13368 
13369   // If there are sub-stmts in the compound stmt, take the type of the last one
13370   // as the type of the stmtexpr.
13371   QualType Ty = Context.VoidTy;
13372   bool StmtExprMayBindToTemp = false;
13373   if (!Compound->body_empty()) {
13374     if (const auto *LastStmt = dyn_cast<ValueStmt>(Compound->body_back())) {
13375       if (const Expr *Value = LastStmt->getExprStmt()) {
13376         StmtExprMayBindToTemp = true;
13377         Ty = Value->getType();
13378       }
13379     }
13380   }
13381 
13382   // FIXME: Check that expression type is complete/non-abstract; statement
13383   // expressions are not lvalues.
13384   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
13385   if (StmtExprMayBindToTemp)
13386     return MaybeBindToTemporary(ResStmtExpr);
13387   return ResStmtExpr;
13388 }
13389 
13390 ExprResult Sema::ActOnStmtExprResult(ExprResult ER) {
13391   if (ER.isInvalid())
13392     return ExprError();
13393 
13394   // Do function/array conversion on the last expression, but not
13395   // lvalue-to-rvalue.  However, initialize an unqualified type.
13396   ER = DefaultFunctionArrayConversion(ER.get());
13397   if (ER.isInvalid())
13398     return ExprError();
13399   Expr *E = ER.get();
13400 
13401   if (E->isTypeDependent())
13402     return E;
13403 
13404   // In ARC, if the final expression ends in a consume, splice
13405   // the consume out and bind it later.  In the alternate case
13406   // (when dealing with a retainable type), the result
13407   // initialization will create a produce.  In both cases the
13408   // result will be +1, and we'll need to balance that out with
13409   // a bind.
13410   auto *Cast = dyn_cast<ImplicitCastExpr>(E);
13411   if (Cast && Cast->getCastKind() == CK_ARCConsumeObject)
13412     return Cast->getSubExpr();
13413 
13414   // FIXME: Provide a better location for the initialization.
13415   return PerformCopyInitialization(
13416       InitializedEntity::InitializeStmtExprResult(
13417           E->getBeginLoc(), E->getType().getUnqualifiedType()),
13418       SourceLocation(), E);
13419 }
13420 
13421 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
13422                                       TypeSourceInfo *TInfo,
13423                                       ArrayRef<OffsetOfComponent> Components,
13424                                       SourceLocation RParenLoc) {
13425   QualType ArgTy = TInfo->getType();
13426   bool Dependent = ArgTy->isDependentType();
13427   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
13428 
13429   // We must have at least one component that refers to the type, and the first
13430   // one is known to be a field designator.  Verify that the ArgTy represents
13431   // a struct/union/class.
13432   if (!Dependent && !ArgTy->isRecordType())
13433     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
13434                        << ArgTy << TypeRange);
13435 
13436   // Type must be complete per C99 7.17p3 because a declaring a variable
13437   // with an incomplete type would be ill-formed.
13438   if (!Dependent
13439       && RequireCompleteType(BuiltinLoc, ArgTy,
13440                              diag::err_offsetof_incomplete_type, TypeRange))
13441     return ExprError();
13442 
13443   bool DidWarnAboutNonPOD = false;
13444   QualType CurrentType = ArgTy;
13445   SmallVector<OffsetOfNode, 4> Comps;
13446   SmallVector<Expr*, 4> Exprs;
13447   for (const OffsetOfComponent &OC : Components) {
13448     if (OC.isBrackets) {
13449       // Offset of an array sub-field.  TODO: Should we allow vector elements?
13450       if (!CurrentType->isDependentType()) {
13451         const ArrayType *AT = Context.getAsArrayType(CurrentType);
13452         if(!AT)
13453           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
13454                            << CurrentType);
13455         CurrentType = AT->getElementType();
13456       } else
13457         CurrentType = Context.DependentTy;
13458 
13459       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
13460       if (IdxRval.isInvalid())
13461         return ExprError();
13462       Expr *Idx = IdxRval.get();
13463 
13464       // The expression must be an integral expression.
13465       // FIXME: An integral constant expression?
13466       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
13467           !Idx->getType()->isIntegerType())
13468         return ExprError(
13469             Diag(Idx->getBeginLoc(), diag::err_typecheck_subscript_not_integer)
13470             << Idx->getSourceRange());
13471 
13472       // Record this array index.
13473       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
13474       Exprs.push_back(Idx);
13475       continue;
13476     }
13477 
13478     // Offset of a field.
13479     if (CurrentType->isDependentType()) {
13480       // We have the offset of a field, but we can't look into the dependent
13481       // type. Just record the identifier of the field.
13482       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
13483       CurrentType = Context.DependentTy;
13484       continue;
13485     }
13486 
13487     // We need to have a complete type to look into.
13488     if (RequireCompleteType(OC.LocStart, CurrentType,
13489                             diag::err_offsetof_incomplete_type))
13490       return ExprError();
13491 
13492     // Look for the designated field.
13493     const RecordType *RC = CurrentType->getAs<RecordType>();
13494     if (!RC)
13495       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
13496                        << CurrentType);
13497     RecordDecl *RD = RC->getDecl();
13498 
13499     // C++ [lib.support.types]p5:
13500     //   The macro offsetof accepts a restricted set of type arguments in this
13501     //   International Standard. type shall be a POD structure or a POD union
13502     //   (clause 9).
13503     // C++11 [support.types]p4:
13504     //   If type is not a standard-layout class (Clause 9), the results are
13505     //   undefined.
13506     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13507       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13508       unsigned DiagID =
13509         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13510                             : diag::ext_offsetof_non_pod_type;
13511 
13512       if (!IsSafe && !DidWarnAboutNonPOD &&
13513           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13514                               PDiag(DiagID)
13515                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13516                               << CurrentType))
13517         DidWarnAboutNonPOD = true;
13518     }
13519 
13520     // Look for the field.
13521     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13522     LookupQualifiedName(R, RD);
13523     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13524     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13525     if (!MemberDecl) {
13526       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13527         MemberDecl = IndirectMemberDecl->getAnonField();
13528     }
13529 
13530     if (!MemberDecl)
13531       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13532                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13533                                                               OC.LocEnd));
13534 
13535     // C99 7.17p3:
13536     //   (If the specified member is a bit-field, the behavior is undefined.)
13537     //
13538     // We diagnose this as an error.
13539     if (MemberDecl->isBitField()) {
13540       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13541         << MemberDecl->getDeclName()
13542         << SourceRange(BuiltinLoc, RParenLoc);
13543       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13544       return ExprError();
13545     }
13546 
13547     RecordDecl *Parent = MemberDecl->getParent();
13548     if (IndirectMemberDecl)
13549       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13550 
13551     // If the member was found in a base class, introduce OffsetOfNodes for
13552     // the base class indirections.
13553     CXXBasePaths Paths;
13554     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13555                       Paths)) {
13556       if (Paths.getDetectedVirtual()) {
13557         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13558           << MemberDecl->getDeclName()
13559           << SourceRange(BuiltinLoc, RParenLoc);
13560         return ExprError();
13561       }
13562 
13563       CXXBasePath &Path = Paths.front();
13564       for (const CXXBasePathElement &B : Path)
13565         Comps.push_back(OffsetOfNode(B.Base));
13566     }
13567 
13568     if (IndirectMemberDecl) {
13569       for (auto *FI : IndirectMemberDecl->chain()) {
13570         assert(isa<FieldDecl>(FI));
13571         Comps.push_back(OffsetOfNode(OC.LocStart,
13572                                      cast<FieldDecl>(FI), OC.LocEnd));
13573       }
13574     } else
13575       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13576 
13577     CurrentType = MemberDecl->getType().getNonReferenceType();
13578   }
13579 
13580   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13581                               Comps, Exprs, RParenLoc);
13582 }
13583 
13584 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13585                                       SourceLocation BuiltinLoc,
13586                                       SourceLocation TypeLoc,
13587                                       ParsedType ParsedArgTy,
13588                                       ArrayRef<OffsetOfComponent> Components,
13589                                       SourceLocation RParenLoc) {
13590 
13591   TypeSourceInfo *ArgTInfo;
13592   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13593   if (ArgTy.isNull())
13594     return ExprError();
13595 
13596   if (!ArgTInfo)
13597     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13598 
13599   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13600 }
13601 
13602 
13603 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13604                                  Expr *CondExpr,
13605                                  Expr *LHSExpr, Expr *RHSExpr,
13606                                  SourceLocation RPLoc) {
13607   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13608 
13609   ExprValueKind VK = VK_RValue;
13610   ExprObjectKind OK = OK_Ordinary;
13611   QualType resType;
13612   bool ValueDependent = false;
13613   bool CondIsTrue = false;
13614   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13615     resType = Context.DependentTy;
13616     ValueDependent = true;
13617   } else {
13618     // The conditional expression is required to be a constant expression.
13619     llvm::APSInt condEval(32);
13620     ExprResult CondICE
13621       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13622           diag::err_typecheck_choose_expr_requires_constant, false);
13623     if (CondICE.isInvalid())
13624       return ExprError();
13625     CondExpr = CondICE.get();
13626     CondIsTrue = condEval.getZExtValue();
13627 
13628     // If the condition is > zero, then the AST type is the same as the LHSExpr.
13629     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13630 
13631     resType = ActiveExpr->getType();
13632     ValueDependent = ActiveExpr->isValueDependent();
13633     VK = ActiveExpr->getValueKind();
13634     OK = ActiveExpr->getObjectKind();
13635   }
13636 
13637   return new (Context)
13638       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13639                  CondIsTrue, resType->isDependentType(), ValueDependent);
13640 }
13641 
13642 //===----------------------------------------------------------------------===//
13643 // Clang Extensions.
13644 //===----------------------------------------------------------------------===//
13645 
13646 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13647 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13648   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13649 
13650   if (LangOpts.CPlusPlus) {
13651     Decl *ManglingContextDecl;
13652     if (MangleNumberingContext *MCtx =
13653             getCurrentMangleNumberContext(Block->getDeclContext(),
13654                                           ManglingContextDecl)) {
13655       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13656       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13657     }
13658   }
13659 
13660   PushBlockScope(CurScope, Block);
13661   CurContext->addDecl(Block);
13662   if (CurScope)
13663     PushDeclContext(CurScope, Block);
13664   else
13665     CurContext = Block;
13666 
13667   getCurBlock()->HasImplicitReturnType = true;
13668 
13669   // Enter a new evaluation context to insulate the block from any
13670   // cleanups from the enclosing full-expression.
13671   PushExpressionEvaluationContext(
13672       ExpressionEvaluationContext::PotentiallyEvaluated);
13673 }
13674 
13675 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13676                                Scope *CurScope) {
13677   assert(ParamInfo.getIdentifier() == nullptr &&
13678          "block-id should have no identifier!");
13679   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13680   BlockScopeInfo *CurBlock = getCurBlock();
13681 
13682   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13683   QualType T = Sig->getType();
13684 
13685   // FIXME: We should allow unexpanded parameter packs here, but that would,
13686   // in turn, make the block expression contain unexpanded parameter packs.
13687   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13688     // Drop the parameters.
13689     FunctionProtoType::ExtProtoInfo EPI;
13690     EPI.HasTrailingReturn = false;
13691     EPI.TypeQuals.addConst();
13692     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13693     Sig = Context.getTrivialTypeSourceInfo(T);
13694   }
13695 
13696   // GetTypeForDeclarator always produces a function type for a block
13697   // literal signature.  Furthermore, it is always a FunctionProtoType
13698   // unless the function was written with a typedef.
13699   assert(T->isFunctionType() &&
13700          "GetTypeForDeclarator made a non-function block signature");
13701 
13702   // Look for an explicit signature in that function type.
13703   FunctionProtoTypeLoc ExplicitSignature;
13704 
13705   if ((ExplicitSignature =
13706            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13707 
13708     // Check whether that explicit signature was synthesized by
13709     // GetTypeForDeclarator.  If so, don't save that as part of the
13710     // written signature.
13711     if (ExplicitSignature.getLocalRangeBegin() ==
13712         ExplicitSignature.getLocalRangeEnd()) {
13713       // This would be much cheaper if we stored TypeLocs instead of
13714       // TypeSourceInfos.
13715       TypeLoc Result = ExplicitSignature.getReturnLoc();
13716       unsigned Size = Result.getFullDataSize();
13717       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13718       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13719 
13720       ExplicitSignature = FunctionProtoTypeLoc();
13721     }
13722   }
13723 
13724   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13725   CurBlock->FunctionType = T;
13726 
13727   const FunctionType *Fn = T->getAs<FunctionType>();
13728   QualType RetTy = Fn->getReturnType();
13729   bool isVariadic =
13730     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13731 
13732   CurBlock->TheDecl->setIsVariadic(isVariadic);
13733 
13734   // Context.DependentTy is used as a placeholder for a missing block
13735   // return type.  TODO:  what should we do with declarators like:
13736   //   ^ * { ... }
13737   // If the answer is "apply template argument deduction"....
13738   if (RetTy != Context.DependentTy) {
13739     CurBlock->ReturnType = RetTy;
13740     CurBlock->TheDecl->setBlockMissingReturnType(false);
13741     CurBlock->HasImplicitReturnType = false;
13742   }
13743 
13744   // Push block parameters from the declarator if we had them.
13745   SmallVector<ParmVarDecl*, 8> Params;
13746   if (ExplicitSignature) {
13747     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13748       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13749       if (Param->getIdentifier() == nullptr &&
13750           !Param->isImplicit() &&
13751           !Param->isInvalidDecl() &&
13752           !getLangOpts().CPlusPlus)
13753         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13754       Params.push_back(Param);
13755     }
13756 
13757   // Fake up parameter variables if we have a typedef, like
13758   //   ^ fntype { ... }
13759   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13760     for (const auto &I : Fn->param_types()) {
13761       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13762           CurBlock->TheDecl, ParamInfo.getBeginLoc(), I);
13763       Params.push_back(Param);
13764     }
13765   }
13766 
13767   // Set the parameters on the block decl.
13768   if (!Params.empty()) {
13769     CurBlock->TheDecl->setParams(Params);
13770     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13771                              /*CheckParameterNames=*/false);
13772   }
13773 
13774   // Finally we can process decl attributes.
13775   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13776 
13777   // Put the parameter variables in scope.
13778   for (auto AI : CurBlock->TheDecl->parameters()) {
13779     AI->setOwningFunction(CurBlock->TheDecl);
13780 
13781     // If this has an identifier, add it to the scope stack.
13782     if (AI->getIdentifier()) {
13783       CheckShadow(CurBlock->TheScope, AI);
13784 
13785       PushOnScopeChains(AI, CurBlock->TheScope);
13786     }
13787   }
13788 }
13789 
13790 /// ActOnBlockError - If there is an error parsing a block, this callback
13791 /// is invoked to pop the information about the block from the action impl.
13792 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13793   // Leave the expression-evaluation context.
13794   DiscardCleanupsInEvaluationContext();
13795   PopExpressionEvaluationContext();
13796 
13797   // Pop off CurBlock, handle nested blocks.
13798   PopDeclContext();
13799   PopFunctionScopeInfo();
13800 }
13801 
13802 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13803 /// literal was successfully completed.  ^(int x){...}
13804 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13805                                     Stmt *Body, Scope *CurScope) {
13806   // If blocks are disabled, emit an error.
13807   if (!LangOpts.Blocks)
13808     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13809 
13810   // Leave the expression-evaluation context.
13811   if (hasAnyUnrecoverableErrorsInThisFunction())
13812     DiscardCleanupsInEvaluationContext();
13813   assert(!Cleanup.exprNeedsCleanups() &&
13814          "cleanups within block not correctly bound!");
13815   PopExpressionEvaluationContext();
13816 
13817   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13818   BlockDecl *BD = BSI->TheDecl;
13819 
13820   if (BSI->HasImplicitReturnType)
13821     deduceClosureReturnType(*BSI);
13822 
13823   PopDeclContext();
13824 
13825   QualType RetTy = Context.VoidTy;
13826   if (!BSI->ReturnType.isNull())
13827     RetTy = BSI->ReturnType;
13828 
13829   bool NoReturn = BD->hasAttr<NoReturnAttr>();
13830   QualType BlockTy;
13831 
13832   // Set the captured variables on the block.
13833   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13834   SmallVector<BlockDecl::Capture, 4> Captures;
13835   for (Capture &Cap : BSI->Captures) {
13836     if (Cap.isThisCapture())
13837       continue;
13838     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13839                               Cap.isNested(), Cap.getInitExpr());
13840     Captures.push_back(NewCap);
13841   }
13842   BD->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13843 
13844   // If the user wrote a function type in some form, try to use that.
13845   if (!BSI->FunctionType.isNull()) {
13846     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13847 
13848     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13849     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13850 
13851     // Turn protoless block types into nullary block types.
13852     if (isa<FunctionNoProtoType>(FTy)) {
13853       FunctionProtoType::ExtProtoInfo EPI;
13854       EPI.ExtInfo = Ext;
13855       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13856 
13857     // Otherwise, if we don't need to change anything about the function type,
13858     // preserve its sugar structure.
13859     } else if (FTy->getReturnType() == RetTy &&
13860                (!NoReturn || FTy->getNoReturnAttr())) {
13861       BlockTy = BSI->FunctionType;
13862 
13863     // Otherwise, make the minimal modifications to the function type.
13864     } else {
13865       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13866       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13867       EPI.TypeQuals = Qualifiers();
13868       EPI.ExtInfo = Ext;
13869       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13870     }
13871 
13872   // If we don't have a function type, just build one from nothing.
13873   } else {
13874     FunctionProtoType::ExtProtoInfo EPI;
13875     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13876     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13877   }
13878 
13879   DiagnoseUnusedParameters(BD->parameters());
13880   BlockTy = Context.getBlockPointerType(BlockTy);
13881 
13882   // If needed, diagnose invalid gotos and switches in the block.
13883   if (getCurFunction()->NeedsScopeChecking() &&
13884       !PP.isCodeCompletionEnabled())
13885     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13886 
13887   BD->setBody(cast<CompoundStmt>(Body));
13888 
13889   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13890     DiagnoseUnguardedAvailabilityViolations(BD);
13891 
13892   // Try to apply the named return value optimization. We have to check again
13893   // if we can do this, though, because blocks keep return statements around
13894   // to deduce an implicit return type.
13895   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13896       !BD->isDependentContext())
13897     computeNRVO(Body, BSI);
13898 
13899   BlockExpr *Result = new (Context) BlockExpr(BD, BlockTy);
13900   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13901   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13902 
13903   // If the block isn't obviously global, i.e. it captures anything at
13904   // all, then we need to do a few things in the surrounding context:
13905   if (Result->getBlockDecl()->hasCaptures()) {
13906     // First, this expression has a new cleanup object.
13907     ExprCleanupObjects.push_back(Result->getBlockDecl());
13908     Cleanup.setExprNeedsCleanups(true);
13909 
13910     // It also gets a branch-protected scope if any of the captured
13911     // variables needs destruction.
13912     for (const auto &CI : Result->getBlockDecl()->captures()) {
13913       const VarDecl *var = CI.getVariable();
13914       if (var->getType().isDestructedType() != QualType::DK_none) {
13915         setFunctionHasBranchProtectedScope();
13916         break;
13917       }
13918     }
13919   }
13920 
13921   if (getCurFunction())
13922     getCurFunction()->addBlock(BD);
13923 
13924   return Result;
13925 }
13926 
13927 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13928                             SourceLocation RPLoc) {
13929   TypeSourceInfo *TInfo;
13930   GetTypeFromParser(Ty, &TInfo);
13931   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13932 }
13933 
13934 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13935                                 Expr *E, TypeSourceInfo *TInfo,
13936                                 SourceLocation RPLoc) {
13937   Expr *OrigExpr = E;
13938   bool IsMS = false;
13939 
13940   // CUDA device code does not support varargs.
13941   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13942     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13943       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13944       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13945         return ExprError(Diag(E->getBeginLoc(), diag::err_va_arg_in_device));
13946     }
13947   }
13948 
13949   // NVPTX does not support va_arg expression.
13950   if (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
13951       Context.getTargetInfo().getTriple().isNVPTX())
13952     targetDiag(E->getBeginLoc(), diag::err_va_arg_in_device);
13953 
13954   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13955   // as Microsoft ABI on an actual Microsoft platform, where
13956   // __builtin_ms_va_list and __builtin_va_list are the same.)
13957   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13958       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13959     QualType MSVaListType = Context.getBuiltinMSVaListType();
13960     if (Context.hasSameType(MSVaListType, E->getType())) {
13961       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13962         return ExprError();
13963       IsMS = true;
13964     }
13965   }
13966 
13967   // Get the va_list type
13968   QualType VaListType = Context.getBuiltinVaListType();
13969   if (!IsMS) {
13970     if (VaListType->isArrayType()) {
13971       // Deal with implicit array decay; for example, on x86-64,
13972       // va_list is an array, but it's supposed to decay to
13973       // a pointer for va_arg.
13974       VaListType = Context.getArrayDecayedType(VaListType);
13975       // Make sure the input expression also decays appropriately.
13976       ExprResult Result = UsualUnaryConversions(E);
13977       if (Result.isInvalid())
13978         return ExprError();
13979       E = Result.get();
13980     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13981       // If va_list is a record type and we are compiling in C++ mode,
13982       // check the argument using reference binding.
13983       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13984           Context, Context.getLValueReferenceType(VaListType), false);
13985       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13986       if (Init.isInvalid())
13987         return ExprError();
13988       E = Init.getAs<Expr>();
13989     } else {
13990       // Otherwise, the va_list argument must be an l-value because
13991       // it is modified by va_arg.
13992       if (!E->isTypeDependent() &&
13993           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13994         return ExprError();
13995     }
13996   }
13997 
13998   if (!IsMS && !E->isTypeDependent() &&
13999       !Context.hasSameType(VaListType, E->getType()))
14000     return ExprError(
14001         Diag(E->getBeginLoc(),
14002              diag::err_first_argument_to_va_arg_not_of_type_va_list)
14003         << OrigExpr->getType() << E->getSourceRange());
14004 
14005   if (!TInfo->getType()->isDependentType()) {
14006     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
14007                             diag::err_second_parameter_to_va_arg_incomplete,
14008                             TInfo->getTypeLoc()))
14009       return ExprError();
14010 
14011     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
14012                                TInfo->getType(),
14013                                diag::err_second_parameter_to_va_arg_abstract,
14014                                TInfo->getTypeLoc()))
14015       return ExprError();
14016 
14017     if (!TInfo->getType().isPODType(Context)) {
14018       Diag(TInfo->getTypeLoc().getBeginLoc(),
14019            TInfo->getType()->isObjCLifetimeType()
14020              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
14021              : diag::warn_second_parameter_to_va_arg_not_pod)
14022         << TInfo->getType()
14023         << TInfo->getTypeLoc().getSourceRange();
14024     }
14025 
14026     // Check for va_arg where arguments of the given type will be promoted
14027     // (i.e. this va_arg is guaranteed to have undefined behavior).
14028     QualType PromoteType;
14029     if (TInfo->getType()->isPromotableIntegerType()) {
14030       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
14031       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
14032         PromoteType = QualType();
14033     }
14034     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
14035       PromoteType = Context.DoubleTy;
14036     if (!PromoteType.isNull())
14037       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
14038                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
14039                           << TInfo->getType()
14040                           << PromoteType
14041                           << TInfo->getTypeLoc().getSourceRange());
14042   }
14043 
14044   QualType T = TInfo->getType().getNonLValueExprType(Context);
14045   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
14046 }
14047 
14048 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
14049   // The type of __null will be int or long, depending on the size of
14050   // pointers on the target.
14051   QualType Ty;
14052   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
14053   if (pw == Context.getTargetInfo().getIntWidth())
14054     Ty = Context.IntTy;
14055   else if (pw == Context.getTargetInfo().getLongWidth())
14056     Ty = Context.LongTy;
14057   else if (pw == Context.getTargetInfo().getLongLongWidth())
14058     Ty = Context.LongLongTy;
14059   else {
14060     llvm_unreachable("I don't know size of pointer!");
14061   }
14062 
14063   return new (Context) GNUNullExpr(Ty, TokenLoc);
14064 }
14065 
14066 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
14067                                               bool Diagnose) {
14068   if (!getLangOpts().ObjC)
14069     return false;
14070 
14071   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
14072   if (!PT)
14073     return false;
14074 
14075   if (!PT->isObjCIdType()) {
14076     // Check if the destination is the 'NSString' interface.
14077     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
14078     if (!ID || !ID->getIdentifier()->isStr("NSString"))
14079       return false;
14080   }
14081 
14082   // Ignore any parens, implicit casts (should only be
14083   // array-to-pointer decays), and not-so-opaque values.  The last is
14084   // important for making this trigger for property assignments.
14085   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
14086   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
14087     if (OV->getSourceExpr())
14088       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
14089 
14090   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
14091   if (!SL || !SL->isAscii())
14092     return false;
14093   if (Diagnose) {
14094     Diag(SL->getBeginLoc(), diag::err_missing_atsign_prefix)
14095         << FixItHint::CreateInsertion(SL->getBeginLoc(), "@");
14096     Exp = BuildObjCStringLiteral(SL->getBeginLoc(), SL).get();
14097   }
14098   return true;
14099 }
14100 
14101 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
14102                                               const Expr *SrcExpr) {
14103   if (!DstType->isFunctionPointerType() ||
14104       !SrcExpr->getType()->isFunctionType())
14105     return false;
14106 
14107   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
14108   if (!DRE)
14109     return false;
14110 
14111   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14112   if (!FD)
14113     return false;
14114 
14115   return !S.checkAddressOfFunctionIsAvailable(FD,
14116                                               /*Complain=*/true,
14117                                               SrcExpr->getBeginLoc());
14118 }
14119 
14120 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
14121                                     SourceLocation Loc,
14122                                     QualType DstType, QualType SrcType,
14123                                     Expr *SrcExpr, AssignmentAction Action,
14124                                     bool *Complained) {
14125   if (Complained)
14126     *Complained = false;
14127 
14128   // Decode the result (notice that AST's are still created for extensions).
14129   bool CheckInferredResultType = false;
14130   bool isInvalid = false;
14131   unsigned DiagKind = 0;
14132   FixItHint Hint;
14133   ConversionFixItGenerator ConvHints;
14134   bool MayHaveConvFixit = false;
14135   bool MayHaveFunctionDiff = false;
14136   const ObjCInterfaceDecl *IFace = nullptr;
14137   const ObjCProtocolDecl *PDecl = nullptr;
14138 
14139   switch (ConvTy) {
14140   case Compatible:
14141       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
14142       return false;
14143 
14144   case PointerToInt:
14145     DiagKind = diag::ext_typecheck_convert_pointer_int;
14146     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14147     MayHaveConvFixit = true;
14148     break;
14149   case IntToPointer:
14150     DiagKind = diag::ext_typecheck_convert_int_pointer;
14151     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14152     MayHaveConvFixit = true;
14153     break;
14154   case IncompatiblePointer:
14155     if (Action == AA_Passing_CFAudited)
14156       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
14157     else if (SrcType->isFunctionPointerType() &&
14158              DstType->isFunctionPointerType())
14159       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
14160     else
14161       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
14162 
14163     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
14164       SrcType->isObjCObjectPointerType();
14165     if (Hint.isNull() && !CheckInferredResultType) {
14166       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14167     }
14168     else if (CheckInferredResultType) {
14169       SrcType = SrcType.getUnqualifiedType();
14170       DstType = DstType.getUnqualifiedType();
14171     }
14172     MayHaveConvFixit = true;
14173     break;
14174   case IncompatiblePointerSign:
14175     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
14176     break;
14177   case FunctionVoidPointer:
14178     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
14179     break;
14180   case IncompatiblePointerDiscardsQualifiers: {
14181     // Perform array-to-pointer decay if necessary.
14182     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
14183 
14184     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
14185     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
14186     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
14187       DiagKind = diag::err_typecheck_incompatible_address_space;
14188       break;
14189 
14190     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
14191       DiagKind = diag::err_typecheck_incompatible_ownership;
14192       break;
14193     }
14194 
14195     llvm_unreachable("unknown error case for discarding qualifiers!");
14196     // fallthrough
14197   }
14198   case CompatiblePointerDiscardsQualifiers:
14199     // If the qualifiers lost were because we were applying the
14200     // (deprecated) C++ conversion from a string literal to a char*
14201     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
14202     // Ideally, this check would be performed in
14203     // checkPointerTypesForAssignment. However, that would require a
14204     // bit of refactoring (so that the second argument is an
14205     // expression, rather than a type), which should be done as part
14206     // of a larger effort to fix checkPointerTypesForAssignment for
14207     // C++ semantics.
14208     if (getLangOpts().CPlusPlus &&
14209         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
14210       return false;
14211     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
14212     break;
14213   case IncompatibleNestedPointerQualifiers:
14214     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
14215     break;
14216   case IntToBlockPointer:
14217     DiagKind = diag::err_int_to_block_pointer;
14218     break;
14219   case IncompatibleBlockPointer:
14220     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
14221     break;
14222   case IncompatibleObjCQualifiedId: {
14223     if (SrcType->isObjCQualifiedIdType()) {
14224       const ObjCObjectPointerType *srcOPT =
14225                 SrcType->getAs<ObjCObjectPointerType>();
14226       for (auto *srcProto : srcOPT->quals()) {
14227         PDecl = srcProto;
14228         break;
14229       }
14230       if (const ObjCInterfaceType *IFaceT =
14231             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14232         IFace = IFaceT->getDecl();
14233     }
14234     else if (DstType->isObjCQualifiedIdType()) {
14235       const ObjCObjectPointerType *dstOPT =
14236         DstType->getAs<ObjCObjectPointerType>();
14237       for (auto *dstProto : dstOPT->quals()) {
14238         PDecl = dstProto;
14239         break;
14240       }
14241       if (const ObjCInterfaceType *IFaceT =
14242             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
14243         IFace = IFaceT->getDecl();
14244     }
14245     DiagKind = diag::warn_incompatible_qualified_id;
14246     break;
14247   }
14248   case IncompatibleVectors:
14249     DiagKind = diag::warn_incompatible_vectors;
14250     break;
14251   case IncompatibleObjCWeakRef:
14252     DiagKind = diag::err_arc_weak_unavailable_assign;
14253     break;
14254   case Incompatible:
14255     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
14256       if (Complained)
14257         *Complained = true;
14258       return true;
14259     }
14260 
14261     DiagKind = diag::err_typecheck_convert_incompatible;
14262     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
14263     MayHaveConvFixit = true;
14264     isInvalid = true;
14265     MayHaveFunctionDiff = true;
14266     break;
14267   }
14268 
14269   QualType FirstType, SecondType;
14270   switch (Action) {
14271   case AA_Assigning:
14272   case AA_Initializing:
14273     // The destination type comes first.
14274     FirstType = DstType;
14275     SecondType = SrcType;
14276     break;
14277 
14278   case AA_Returning:
14279   case AA_Passing:
14280   case AA_Passing_CFAudited:
14281   case AA_Converting:
14282   case AA_Sending:
14283   case AA_Casting:
14284     // The source type comes first.
14285     FirstType = SrcType;
14286     SecondType = DstType;
14287     break;
14288   }
14289 
14290   PartialDiagnostic FDiag = PDiag(DiagKind);
14291   if (Action == AA_Passing_CFAudited)
14292     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
14293   else
14294     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
14295 
14296   // If we can fix the conversion, suggest the FixIts.
14297   assert(ConvHints.isNull() || Hint.isNull());
14298   if (!ConvHints.isNull()) {
14299     for (FixItHint &H : ConvHints.Hints)
14300       FDiag << H;
14301   } else {
14302     FDiag << Hint;
14303   }
14304   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
14305 
14306   if (MayHaveFunctionDiff)
14307     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
14308 
14309   Diag(Loc, FDiag);
14310   if (DiagKind == diag::warn_incompatible_qualified_id &&
14311       PDecl && IFace && !IFace->hasDefinition())
14312       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
14313         << IFace << PDecl;
14314 
14315   if (SecondType == Context.OverloadTy)
14316     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
14317                               FirstType, /*TakingAddress=*/true);
14318 
14319   if (CheckInferredResultType)
14320     EmitRelatedResultTypeNote(SrcExpr);
14321 
14322   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
14323     EmitRelatedResultTypeNoteForReturn(DstType);
14324 
14325   if (Complained)
14326     *Complained = true;
14327   return isInvalid;
14328 }
14329 
14330 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14331                                                  llvm::APSInt *Result) {
14332   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
14333   public:
14334     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14335       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
14336     }
14337   } Diagnoser;
14338 
14339   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
14340 }
14341 
14342 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
14343                                                  llvm::APSInt *Result,
14344                                                  unsigned DiagID,
14345                                                  bool AllowFold) {
14346   class IDDiagnoser : public VerifyICEDiagnoser {
14347     unsigned DiagID;
14348 
14349   public:
14350     IDDiagnoser(unsigned DiagID)
14351       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
14352 
14353     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
14354       S.Diag(Loc, DiagID) << SR;
14355     }
14356   } Diagnoser(DiagID);
14357 
14358   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
14359 }
14360 
14361 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
14362                                             SourceRange SR) {
14363   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
14364 }
14365 
14366 ExprResult
14367 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
14368                                       VerifyICEDiagnoser &Diagnoser,
14369                                       bool AllowFold) {
14370   SourceLocation DiagLoc = E->getBeginLoc();
14371 
14372   if (getLangOpts().CPlusPlus11) {
14373     // C++11 [expr.const]p5:
14374     //   If an expression of literal class type is used in a context where an
14375     //   integral constant expression is required, then that class type shall
14376     //   have a single non-explicit conversion function to an integral or
14377     //   unscoped enumeration type
14378     ExprResult Converted;
14379     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
14380     public:
14381       CXX11ConvertDiagnoser(bool Silent)
14382           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
14383                                 Silent, true) {}
14384 
14385       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
14386                                            QualType T) override {
14387         return S.Diag(Loc, diag::err_ice_not_integral) << T;
14388       }
14389 
14390       SemaDiagnosticBuilder diagnoseIncomplete(
14391           Sema &S, SourceLocation Loc, QualType T) override {
14392         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
14393       }
14394 
14395       SemaDiagnosticBuilder diagnoseExplicitConv(
14396           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14397         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
14398       }
14399 
14400       SemaDiagnosticBuilder noteExplicitConv(
14401           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14402         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14403                  << ConvTy->isEnumeralType() << ConvTy;
14404       }
14405 
14406       SemaDiagnosticBuilder diagnoseAmbiguous(
14407           Sema &S, SourceLocation Loc, QualType T) override {
14408         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
14409       }
14410 
14411       SemaDiagnosticBuilder noteAmbiguous(
14412           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
14413         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
14414                  << ConvTy->isEnumeralType() << ConvTy;
14415       }
14416 
14417       SemaDiagnosticBuilder diagnoseConversion(
14418           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
14419         llvm_unreachable("conversion functions are permitted");
14420       }
14421     } ConvertDiagnoser(Diagnoser.Suppress);
14422 
14423     Converted = PerformContextualImplicitConversion(DiagLoc, E,
14424                                                     ConvertDiagnoser);
14425     if (Converted.isInvalid())
14426       return Converted;
14427     E = Converted.get();
14428     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
14429       return ExprError();
14430   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14431     // An ICE must be of integral or unscoped enumeration type.
14432     if (!Diagnoser.Suppress)
14433       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14434     return ExprError();
14435   }
14436 
14437   if (!isa<ConstantExpr>(E))
14438     E = ConstantExpr::Create(Context, E);
14439 
14440   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
14441   // in the non-ICE case.
14442   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
14443     if (Result)
14444       *Result = E->EvaluateKnownConstIntCheckOverflow(Context);
14445     return E;
14446   }
14447 
14448   Expr::EvalResult EvalResult;
14449   SmallVector<PartialDiagnosticAt, 8> Notes;
14450   EvalResult.Diag = &Notes;
14451 
14452   // Try to evaluate the expression, and produce diagnostics explaining why it's
14453   // not a constant expression as a side-effect.
14454   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
14455                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
14456 
14457   // In C++11, we can rely on diagnostics being produced for any expression
14458   // which is not a constant expression. If no diagnostics were produced, then
14459   // this is a constant expression.
14460   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
14461     if (Result)
14462       *Result = EvalResult.Val.getInt();
14463     return E;
14464   }
14465 
14466   // If our only note is the usual "invalid subexpression" note, just point
14467   // the caret at its location rather than producing an essentially
14468   // redundant note.
14469   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
14470         diag::note_invalid_subexpr_in_const_expr) {
14471     DiagLoc = Notes[0].first;
14472     Notes.clear();
14473   }
14474 
14475   if (!Folded || !AllowFold) {
14476     if (!Diagnoser.Suppress) {
14477       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
14478       for (const PartialDiagnosticAt &Note : Notes)
14479         Diag(Note.first, Note.second);
14480     }
14481 
14482     return ExprError();
14483   }
14484 
14485   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
14486   for (const PartialDiagnosticAt &Note : Notes)
14487     Diag(Note.first, Note.second);
14488 
14489   if (Result)
14490     *Result = EvalResult.Val.getInt();
14491   return E;
14492 }
14493 
14494 namespace {
14495   // Handle the case where we conclude a expression which we speculatively
14496   // considered to be unevaluated is actually evaluated.
14497   class TransformToPE : public TreeTransform<TransformToPE> {
14498     typedef TreeTransform<TransformToPE> BaseTransform;
14499 
14500   public:
14501     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
14502 
14503     // Make sure we redo semantic analysis
14504     bool AlwaysRebuild() { return true; }
14505 
14506     // We need to special-case DeclRefExprs referring to FieldDecls which
14507     // are not part of a member pointer formation; normal TreeTransforming
14508     // doesn't catch this case because of the way we represent them in the AST.
14509     // FIXME: This is a bit ugly; is it really the best way to handle this
14510     // case?
14511     //
14512     // Error on DeclRefExprs referring to FieldDecls.
14513     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14514       if (isa<FieldDecl>(E->getDecl()) &&
14515           !SemaRef.isUnevaluatedContext())
14516         return SemaRef.Diag(E->getLocation(),
14517                             diag::err_invalid_non_static_member_use)
14518             << E->getDecl() << E->getSourceRange();
14519 
14520       return BaseTransform::TransformDeclRefExpr(E);
14521     }
14522 
14523     // Exception: filter out member pointer formation
14524     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14525       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14526         return E;
14527 
14528       return BaseTransform::TransformUnaryOperator(E);
14529     }
14530 
14531     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14532       // Lambdas never need to be transformed.
14533       return E;
14534     }
14535   };
14536 }
14537 
14538 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14539   assert(isUnevaluatedContext() &&
14540          "Should only transform unevaluated expressions");
14541   ExprEvalContexts.back().Context =
14542       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14543   if (isUnevaluatedContext())
14544     return E;
14545   return TransformToPE(*this).TransformExpr(E);
14546 }
14547 
14548 void
14549 Sema::PushExpressionEvaluationContext(
14550     ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl,
14551     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14552   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14553                                 LambdaContextDecl, ExprContext);
14554   Cleanup.reset();
14555   if (!MaybeODRUseExprs.empty())
14556     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14557 }
14558 
14559 void
14560 Sema::PushExpressionEvaluationContext(
14561     ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t,
14562     ExpressionEvaluationContextRecord::ExpressionKind ExprContext) {
14563   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14564   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, ExprContext);
14565 }
14566 
14567 namespace {
14568 
14569 const DeclRefExpr *CheckPossibleDeref(Sema &S, const Expr *PossibleDeref) {
14570   PossibleDeref = PossibleDeref->IgnoreParenImpCasts();
14571   if (const auto *E = dyn_cast<UnaryOperator>(PossibleDeref)) {
14572     if (E->getOpcode() == UO_Deref)
14573       return CheckPossibleDeref(S, E->getSubExpr());
14574   } else if (const auto *E = dyn_cast<ArraySubscriptExpr>(PossibleDeref)) {
14575     return CheckPossibleDeref(S, E->getBase());
14576   } else if (const auto *E = dyn_cast<MemberExpr>(PossibleDeref)) {
14577     return CheckPossibleDeref(S, E->getBase());
14578   } else if (const auto E = dyn_cast<DeclRefExpr>(PossibleDeref)) {
14579     QualType Inner;
14580     QualType Ty = E->getType();
14581     if (const auto *Ptr = Ty->getAs<PointerType>())
14582       Inner = Ptr->getPointeeType();
14583     else if (const auto *Arr = S.Context.getAsArrayType(Ty))
14584       Inner = Arr->getElementType();
14585     else
14586       return nullptr;
14587 
14588     if (Inner->hasAttr(attr::NoDeref))
14589       return E;
14590   }
14591   return nullptr;
14592 }
14593 
14594 } // namespace
14595 
14596 void Sema::WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec) {
14597   for (const Expr *E : Rec.PossibleDerefs) {
14598     const DeclRefExpr *DeclRef = CheckPossibleDeref(*this, E);
14599     if (DeclRef) {
14600       const ValueDecl *Decl = DeclRef->getDecl();
14601       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type)
14602           << Decl->getName() << E->getSourceRange();
14603       Diag(Decl->getLocation(), diag::note_previous_decl) << Decl->getName();
14604     } else {
14605       Diag(E->getExprLoc(), diag::warn_dereference_of_noderef_type_no_decl)
14606           << E->getSourceRange();
14607     }
14608   }
14609   Rec.PossibleDerefs.clear();
14610 }
14611 
14612 void Sema::PopExpressionEvaluationContext() {
14613   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14614   unsigned NumTypos = Rec.NumTypos;
14615 
14616   if (!Rec.Lambdas.empty()) {
14617     using ExpressionKind = ExpressionEvaluationContextRecord::ExpressionKind;
14618     if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument || Rec.isUnevaluated() ||
14619         (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17)) {
14620       unsigned D;
14621       if (Rec.isUnevaluated()) {
14622         // C++11 [expr.prim.lambda]p2:
14623         //   A lambda-expression shall not appear in an unevaluated operand
14624         //   (Clause 5).
14625         D = diag::err_lambda_unevaluated_operand;
14626       } else if (Rec.isConstantEvaluated() && !getLangOpts().CPlusPlus17) {
14627         // C++1y [expr.const]p2:
14628         //   A conditional-expression e is a core constant expression unless the
14629         //   evaluation of e, following the rules of the abstract machine, would
14630         //   evaluate [...] a lambda-expression.
14631         D = diag::err_lambda_in_constant_expression;
14632       } else if (Rec.ExprContext == ExpressionKind::EK_TemplateArgument) {
14633         // C++17 [expr.prim.lamda]p2:
14634         // A lambda-expression shall not appear [...] in a template-argument.
14635         D = diag::err_lambda_in_invalid_context;
14636       } else
14637         llvm_unreachable("Couldn't infer lambda error message.");
14638 
14639       for (const auto *L : Rec.Lambdas)
14640         Diag(L->getBeginLoc(), D);
14641     } else {
14642       // Mark the capture expressions odr-used. This was deferred
14643       // during lambda expression creation.
14644       for (auto *Lambda : Rec.Lambdas) {
14645         for (auto *C : Lambda->capture_inits())
14646           MarkDeclarationsReferencedInExpr(C);
14647       }
14648     }
14649   }
14650 
14651   WarnOnPendingNoDerefs(Rec);
14652 
14653   // When are coming out of an unevaluated context, clear out any
14654   // temporaries that we may have created as part of the evaluation of
14655   // the expression in that context: they aren't relevant because they
14656   // will never be constructed.
14657   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14658     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14659                              ExprCleanupObjects.end());
14660     Cleanup = Rec.ParentCleanup;
14661     CleanupVarDeclMarking();
14662     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14663   // Otherwise, merge the contexts together.
14664   } else {
14665     Cleanup.mergeFrom(Rec.ParentCleanup);
14666     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14667                             Rec.SavedMaybeODRUseExprs.end());
14668   }
14669 
14670   // Pop the current expression evaluation context off the stack.
14671   ExprEvalContexts.pop_back();
14672 
14673   // The global expression evaluation context record is never popped.
14674   ExprEvalContexts.back().NumTypos += NumTypos;
14675 }
14676 
14677 void Sema::DiscardCleanupsInEvaluationContext() {
14678   ExprCleanupObjects.erase(
14679          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14680          ExprCleanupObjects.end());
14681   Cleanup.reset();
14682   MaybeODRUseExprs.clear();
14683 }
14684 
14685 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14686   ExprResult Result = CheckPlaceholderExpr(E);
14687   if (Result.isInvalid())
14688     return ExprError();
14689   E = Result.get();
14690   if (!E->getType()->isVariablyModifiedType())
14691     return E;
14692   return TransformToPotentiallyEvaluated(E);
14693 }
14694 
14695 /// Are we within a context in which some evaluation could be performed (be it
14696 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14697 /// captured by C++'s idea of an "unevaluated context".
14698 static bool isEvaluatableContext(Sema &SemaRef) {
14699   switch (SemaRef.ExprEvalContexts.back().Context) {
14700     case Sema::ExpressionEvaluationContext::Unevaluated:
14701     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14702       // Expressions in this context are never evaluated.
14703       return false;
14704 
14705     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14706     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14707     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14708     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14709       // Expressions in this context could be evaluated.
14710       return true;
14711 
14712     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14713       // Referenced declarations will only be used if the construct in the
14714       // containing expression is used, at which point we'll be given another
14715       // turn to mark them.
14716       return false;
14717   }
14718   llvm_unreachable("Invalid context");
14719 }
14720 
14721 /// Are we within a context in which references to resolved functions or to
14722 /// variables result in odr-use?
14723 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14724   // An expression in a template is not really an expression until it's been
14725   // instantiated, so it doesn't trigger odr-use.
14726   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14727     return false;
14728 
14729   switch (SemaRef.ExprEvalContexts.back().Context) {
14730     case Sema::ExpressionEvaluationContext::Unevaluated:
14731     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14732     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14733     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14734       return false;
14735 
14736     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14737     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14738       return true;
14739 
14740     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14741       return false;
14742   }
14743   llvm_unreachable("Invalid context");
14744 }
14745 
14746 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14747   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14748   return Func->isConstexpr() &&
14749          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14750 }
14751 
14752 /// Mark a function referenced, and check whether it is odr-used
14753 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14754 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14755                                   bool MightBeOdrUse) {
14756   assert(Func && "No function?");
14757 
14758   Func->setReferenced();
14759 
14760   // C++11 [basic.def.odr]p3:
14761   //   A function whose name appears as a potentially-evaluated expression is
14762   //   odr-used if it is the unique lookup result or the selected member of a
14763   //   set of overloaded functions [...].
14764   //
14765   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14766   // can just check that here.
14767   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14768 
14769   // Determine whether we require a function definition to exist, per
14770   // C++11 [temp.inst]p3:
14771   //   Unless a function template specialization has been explicitly
14772   //   instantiated or explicitly specialized, the function template
14773   //   specialization is implicitly instantiated when the specialization is
14774   //   referenced in a context that requires a function definition to exist.
14775   //
14776   // That is either when this is an odr-use, or when a usage of a constexpr
14777   // function occurs within an evaluatable context.
14778   bool NeedDefinition =
14779       OdrUse || (isEvaluatableContext(*this) &&
14780                  isImplicitlyDefinableConstexprFunction(Func));
14781 
14782   // C++14 [temp.expl.spec]p6:
14783   //   If a template [...] is explicitly specialized then that specialization
14784   //   shall be declared before the first use of that specialization that would
14785   //   cause an implicit instantiation to take place, in every translation unit
14786   //   in which such a use occurs
14787   if (NeedDefinition &&
14788       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14789        Func->getMemberSpecializationInfo()))
14790     checkSpecializationVisibility(Loc, Func);
14791 
14792   // C++14 [except.spec]p17:
14793   //   An exception-specification is considered to be needed when:
14794   //   - the function is odr-used or, if it appears in an unevaluated operand,
14795   //     would be odr-used if the expression were potentially-evaluated;
14796   //
14797   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14798   // function is a pure virtual function we're calling, and in that case the
14799   // function was selected by overload resolution and we need to resolve its
14800   // exception specification for a different reason.
14801   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14802   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14803     ResolveExceptionSpec(Loc, FPT);
14804 
14805   if (getLangOpts().CUDA)
14806     CheckCUDACall(Loc, Func);
14807 
14808   // If we don't need to mark the function as used, and we don't need to
14809   // try to provide a definition, there's nothing more to do.
14810   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14811       (!NeedDefinition || Func->getBody()))
14812     return;
14813 
14814   // Note that this declaration has been used.
14815   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14816     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14817     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14818       if (Constructor->isDefaultConstructor()) {
14819         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14820           return;
14821         DefineImplicitDefaultConstructor(Loc, Constructor);
14822       } else if (Constructor->isCopyConstructor()) {
14823         DefineImplicitCopyConstructor(Loc, Constructor);
14824       } else if (Constructor->isMoveConstructor()) {
14825         DefineImplicitMoveConstructor(Loc, Constructor);
14826       }
14827     } else if (Constructor->getInheritedConstructor()) {
14828       DefineInheritingConstructor(Loc, Constructor);
14829     }
14830   } else if (CXXDestructorDecl *Destructor =
14831                  dyn_cast<CXXDestructorDecl>(Func)) {
14832     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14833     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14834       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14835         return;
14836       DefineImplicitDestructor(Loc, Destructor);
14837     }
14838     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14839       MarkVTableUsed(Loc, Destructor->getParent());
14840   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14841     if (MethodDecl->isOverloadedOperator() &&
14842         MethodDecl->getOverloadedOperator() == OO_Equal) {
14843       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14844       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14845         if (MethodDecl->isCopyAssignmentOperator())
14846           DefineImplicitCopyAssignment(Loc, MethodDecl);
14847         else if (MethodDecl->isMoveAssignmentOperator())
14848           DefineImplicitMoveAssignment(Loc, MethodDecl);
14849       }
14850     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14851                MethodDecl->getParent()->isLambda()) {
14852       CXXConversionDecl *Conversion =
14853           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14854       if (Conversion->isLambdaToBlockPointerConversion())
14855         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14856       else
14857         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14858     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14859       MarkVTableUsed(Loc, MethodDecl->getParent());
14860   }
14861 
14862   // Recursive functions should be marked when used from another function.
14863   // FIXME: Is this really right?
14864   if (CurContext == Func) return;
14865 
14866   // Implicit instantiation of function templates and member functions of
14867   // class templates.
14868   if (Func->isImplicitlyInstantiable()) {
14869     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14870     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14871     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14872     if (FirstInstantiation) {
14873       PointOfInstantiation = Loc;
14874       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14875     } else if (TSK != TSK_ImplicitInstantiation) {
14876       // Use the point of use as the point of instantiation, instead of the
14877       // point of explicit instantiation (which we track as the actual point of
14878       // instantiation). This gives better backtraces in diagnostics.
14879       PointOfInstantiation = Loc;
14880     }
14881 
14882     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14883         Func->isConstexpr()) {
14884       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14885           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14886           CodeSynthesisContexts.size())
14887         PendingLocalImplicitInstantiations.push_back(
14888             std::make_pair(Func, PointOfInstantiation));
14889       else if (Func->isConstexpr())
14890         // Do not defer instantiations of constexpr functions, to avoid the
14891         // expression evaluator needing to call back into Sema if it sees a
14892         // call to such a function.
14893         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14894       else {
14895         Func->setInstantiationIsPending(true);
14896         PendingInstantiations.push_back(std::make_pair(Func,
14897                                                        PointOfInstantiation));
14898         // Notify the consumer that a function was implicitly instantiated.
14899         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14900       }
14901     }
14902   } else {
14903     // Walk redefinitions, as some of them may be instantiable.
14904     for (auto i : Func->redecls()) {
14905       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14906         MarkFunctionReferenced(Loc, i, OdrUse);
14907     }
14908   }
14909 
14910   if (!OdrUse) return;
14911 
14912   // Keep track of used but undefined functions.
14913   if (!Func->isDefined()) {
14914     if (mightHaveNonExternalLinkage(Func))
14915       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14916     else if (Func->getMostRecentDecl()->isInlined() &&
14917              !LangOpts.GNUInline &&
14918              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14919       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14920     else if (isExternalWithNoLinkageType(Func))
14921       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14922   }
14923 
14924   Func->markUsed(Context);
14925 
14926   if (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)
14927     checkOpenMPDeviceFunction(Loc, Func);
14928 }
14929 
14930 static void
14931 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14932                                    ValueDecl *var, DeclContext *DC) {
14933   DeclContext *VarDC = var->getDeclContext();
14934 
14935   //  If the parameter still belongs to the translation unit, then
14936   //  we're actually just using one parameter in the declaration of
14937   //  the next.
14938   if (isa<ParmVarDecl>(var) &&
14939       isa<TranslationUnitDecl>(VarDC))
14940     return;
14941 
14942   // For C code, don't diagnose about capture if we're not actually in code
14943   // right now; it's impossible to write a non-constant expression outside of
14944   // function context, so we'll get other (more useful) diagnostics later.
14945   //
14946   // For C++, things get a bit more nasty... it would be nice to suppress this
14947   // diagnostic for certain cases like using a local variable in an array bound
14948   // for a member of a local class, but the correct predicate is not obvious.
14949   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14950     return;
14951 
14952   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14953   unsigned ContextKind = 3; // unknown
14954   if (isa<CXXMethodDecl>(VarDC) &&
14955       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14956     ContextKind = 2;
14957   } else if (isa<FunctionDecl>(VarDC)) {
14958     ContextKind = 0;
14959   } else if (isa<BlockDecl>(VarDC)) {
14960     ContextKind = 1;
14961   }
14962 
14963   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14964     << var << ValueKind << ContextKind << VarDC;
14965   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14966       << var;
14967 
14968   // FIXME: Add additional diagnostic info about class etc. which prevents
14969   // capture.
14970 }
14971 
14972 
14973 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14974                                       bool &SubCapturesAreNested,
14975                                       QualType &CaptureType,
14976                                       QualType &DeclRefType) {
14977    // Check whether we've already captured it.
14978   if (CSI->CaptureMap.count(Var)) {
14979     // If we found a capture, any subcaptures are nested.
14980     SubCapturesAreNested = true;
14981 
14982     // Retrieve the capture type for this variable.
14983     CaptureType = CSI->getCapture(Var).getCaptureType();
14984 
14985     // Compute the type of an expression that refers to this variable.
14986     DeclRefType = CaptureType.getNonReferenceType();
14987 
14988     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14989     // are mutable in the sense that user can change their value - they are
14990     // private instances of the captured declarations.
14991     const Capture &Cap = CSI->getCapture(Var);
14992     if (Cap.isCopyCapture() &&
14993         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14994         !(isa<CapturedRegionScopeInfo>(CSI) &&
14995           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14996       DeclRefType.addConst();
14997     return true;
14998   }
14999   return false;
15000 }
15001 
15002 // Only block literals, captured statements, and lambda expressions can
15003 // capture; other scopes don't work.
15004 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
15005                                  SourceLocation Loc,
15006                                  const bool Diagnose, Sema &S) {
15007   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
15008     return getLambdaAwareParentOfDeclContext(DC);
15009   else if (Var->hasLocalStorage()) {
15010     if (Diagnose)
15011        diagnoseUncapturableValueReference(S, Loc, Var, DC);
15012   }
15013   return nullptr;
15014 }
15015 
15016 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15017 // certain types of variables (unnamed, variably modified types etc.)
15018 // so check for eligibility.
15019 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
15020                                  SourceLocation Loc,
15021                                  const bool Diagnose, Sema &S) {
15022 
15023   bool IsBlock = isa<BlockScopeInfo>(CSI);
15024   bool IsLambda = isa<LambdaScopeInfo>(CSI);
15025 
15026   // Lambdas are not allowed to capture unnamed variables
15027   // (e.g. anonymous unions).
15028   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
15029   // assuming that's the intent.
15030   if (IsLambda && !Var->getDeclName()) {
15031     if (Diagnose) {
15032       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
15033       S.Diag(Var->getLocation(), diag::note_declared_at);
15034     }
15035     return false;
15036   }
15037 
15038   // Prohibit variably-modified types in blocks; they're difficult to deal with.
15039   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
15040     if (Diagnose) {
15041       S.Diag(Loc, diag::err_ref_vm_type);
15042       S.Diag(Var->getLocation(), diag::note_previous_decl)
15043         << Var->getDeclName();
15044     }
15045     return false;
15046   }
15047   // Prohibit structs with flexible array members too.
15048   // We cannot capture what is in the tail end of the struct.
15049   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
15050     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
15051       if (Diagnose) {
15052         if (IsBlock)
15053           S.Diag(Loc, diag::err_ref_flexarray_type);
15054         else
15055           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
15056             << Var->getDeclName();
15057         S.Diag(Var->getLocation(), diag::note_previous_decl)
15058           << Var->getDeclName();
15059       }
15060       return false;
15061     }
15062   }
15063   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15064   // Lambdas and captured statements are not allowed to capture __block
15065   // variables; they don't support the expected semantics.
15066   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
15067     if (Diagnose) {
15068       S.Diag(Loc, diag::err_capture_block_variable)
15069         << Var->getDeclName() << !IsLambda;
15070       S.Diag(Var->getLocation(), diag::note_previous_decl)
15071         << Var->getDeclName();
15072     }
15073     return false;
15074   }
15075   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
15076   if (S.getLangOpts().OpenCL && IsBlock &&
15077       Var->getType()->isBlockPointerType()) {
15078     if (Diagnose)
15079       S.Diag(Loc, diag::err_opencl_block_ref_block);
15080     return false;
15081   }
15082 
15083   return true;
15084 }
15085 
15086 // Returns true if the capture by block was successful.
15087 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
15088                                  SourceLocation Loc,
15089                                  const bool BuildAndDiagnose,
15090                                  QualType &CaptureType,
15091                                  QualType &DeclRefType,
15092                                  const bool Nested,
15093                                  Sema &S) {
15094   Expr *CopyExpr = nullptr;
15095   bool ByRef = false;
15096 
15097   // Blocks are not allowed to capture arrays, excepting OpenCL.
15098   // OpenCL v2.0 s1.12.5 (revision 40): arrays are captured by reference
15099   // (decayed to pointers).
15100   if (!S.getLangOpts().OpenCL && CaptureType->isArrayType()) {
15101     if (BuildAndDiagnose) {
15102       S.Diag(Loc, diag::err_ref_array_type);
15103       S.Diag(Var->getLocation(), diag::note_previous_decl)
15104       << Var->getDeclName();
15105     }
15106     return false;
15107   }
15108 
15109   // Forbid the block-capture of autoreleasing variables.
15110   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15111     if (BuildAndDiagnose) {
15112       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
15113         << /*block*/ 0;
15114       S.Diag(Var->getLocation(), diag::note_previous_decl)
15115         << Var->getDeclName();
15116     }
15117     return false;
15118   }
15119 
15120   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
15121   if (const auto *PT = CaptureType->getAs<PointerType>()) {
15122     // This function finds out whether there is an AttributedType of kind
15123     // attr::ObjCOwnership in Ty. The existence of AttributedType of kind
15124     // attr::ObjCOwnership implies __autoreleasing was explicitly specified
15125     // rather than being added implicitly by the compiler.
15126     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
15127       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
15128         if (AttrTy->getAttrKind() == attr::ObjCOwnership)
15129           return true;
15130 
15131         // Peel off AttributedTypes that are not of kind ObjCOwnership.
15132         Ty = AttrTy->getModifiedType();
15133       }
15134 
15135       return false;
15136     };
15137 
15138     QualType PointeeTy = PT->getPointeeType();
15139 
15140     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
15141         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
15142         !IsObjCOwnershipAttributedType(PointeeTy)) {
15143       if (BuildAndDiagnose) {
15144         SourceLocation VarLoc = Var->getLocation();
15145         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
15146         S.Diag(VarLoc, diag::note_declare_parameter_strong);
15147       }
15148     }
15149   }
15150 
15151   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
15152   if (HasBlocksAttr || CaptureType->isReferenceType() ||
15153       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
15154     // Block capture by reference does not change the capture or
15155     // declaration reference types.
15156     ByRef = true;
15157   } else {
15158     // Block capture by copy introduces 'const'.
15159     CaptureType = CaptureType.getNonReferenceType().withConst();
15160     DeclRefType = CaptureType;
15161 
15162     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
15163       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
15164         // The capture logic needs the destructor, so make sure we mark it.
15165         // Usually this is unnecessary because most local variables have
15166         // their destructors marked at declaration time, but parameters are
15167         // an exception because it's technically only the call site that
15168         // actually requires the destructor.
15169         if (isa<ParmVarDecl>(Var))
15170           S.FinalizeVarWithDestructor(Var, Record);
15171 
15172         // Enter a new evaluation context to insulate the copy
15173         // full-expression.
15174         EnterExpressionEvaluationContext scope(
15175             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
15176 
15177         // According to the blocks spec, the capture of a variable from
15178         // the stack requires a const copy constructor.  This is not true
15179         // of the copy/move done to move a __block variable to the heap.
15180         Expr *DeclRef = new (S.Context) DeclRefExpr(
15181             S.Context, Var, Nested, DeclRefType.withConst(), VK_LValue, Loc);
15182 
15183         ExprResult Result
15184           = S.PerformCopyInitialization(
15185               InitializedEntity::InitializeBlock(Var->getLocation(),
15186                                                   CaptureType, false),
15187               Loc, DeclRef);
15188 
15189         // Build a full-expression copy expression if initialization
15190         // succeeded and used a non-trivial constructor.  Recover from
15191         // errors by pretending that the copy isn't necessary.
15192         if (!Result.isInvalid() &&
15193             !cast<CXXConstructExpr>(Result.get())->getConstructor()
15194                 ->isTrivial()) {
15195           Result = S.MaybeCreateExprWithCleanups(Result);
15196           CopyExpr = Result.get();
15197         }
15198       }
15199     }
15200   }
15201 
15202   // Actually capture the variable.
15203   if (BuildAndDiagnose)
15204     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
15205                     SourceLocation(), CaptureType, CopyExpr);
15206 
15207   return true;
15208 
15209 }
15210 
15211 
15212 /// Capture the given variable in the captured region.
15213 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
15214                                     VarDecl *Var,
15215                                     SourceLocation Loc,
15216                                     const bool BuildAndDiagnose,
15217                                     QualType &CaptureType,
15218                                     QualType &DeclRefType,
15219                                     const bool RefersToCapturedVariable,
15220                                     Sema &S) {
15221   // By default, capture variables by reference.
15222   bool ByRef = true;
15223   // Using an LValue reference type is consistent with Lambdas (see below).
15224   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
15225     if (S.isOpenMPCapturedDecl(Var)) {
15226       bool HasConst = DeclRefType.isConstQualified();
15227       DeclRefType = DeclRefType.getUnqualifiedType();
15228       // Don't lose diagnostics about assignments to const.
15229       if (HasConst)
15230         DeclRefType.addConst();
15231     }
15232     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
15233   }
15234 
15235   if (ByRef)
15236     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15237   else
15238     CaptureType = DeclRefType;
15239 
15240   Expr *CopyExpr = nullptr;
15241   if (BuildAndDiagnose) {
15242     // The current implementation assumes that all variables are captured
15243     // by references. Since there is no capture by copy, no expression
15244     // evaluation will be needed.
15245     RecordDecl *RD = RSI->TheRecordDecl;
15246 
15247     FieldDecl *Field
15248       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
15249                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
15250                           nullptr, false, ICIS_NoInit);
15251     Field->setImplicit(true);
15252     Field->setAccess(AS_private);
15253     RD->addDecl(Field);
15254     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
15255       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
15256 
15257     CopyExpr = new (S.Context) DeclRefExpr(
15258         S.Context, Var, RefersToCapturedVariable, DeclRefType, VK_LValue, Loc);
15259     Var->setReferenced(true);
15260     Var->markUsed(S.Context);
15261   }
15262 
15263   // Actually capture the variable.
15264   if (BuildAndDiagnose)
15265     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
15266                     SourceLocation(), CaptureType, CopyExpr);
15267 
15268 
15269   return true;
15270 }
15271 
15272 /// Create a field within the lambda class for the variable
15273 /// being captured.
15274 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
15275                                     QualType FieldType, QualType DeclRefType,
15276                                     SourceLocation Loc,
15277                                     bool RefersToCapturedVariable) {
15278   CXXRecordDecl *Lambda = LSI->Lambda;
15279 
15280   // Build the non-static data member.
15281   FieldDecl *Field
15282     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
15283                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
15284                         nullptr, false, ICIS_NoInit);
15285   // If the variable being captured has an invalid type, mark the lambda class
15286   // as invalid as well.
15287   if (!FieldType->isDependentType()) {
15288     if (S.RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
15289       Lambda->setInvalidDecl();
15290       Field->setInvalidDecl();
15291     } else {
15292       NamedDecl *Def;
15293       FieldType->isIncompleteType(&Def);
15294       if (Def && Def->isInvalidDecl()) {
15295         Lambda->setInvalidDecl();
15296         Field->setInvalidDecl();
15297       }
15298     }
15299   }
15300   Field->setImplicit(true);
15301   Field->setAccess(AS_private);
15302   Lambda->addDecl(Field);
15303 }
15304 
15305 /// Capture the given variable in the lambda.
15306 static bool captureInLambda(LambdaScopeInfo *LSI,
15307                             VarDecl *Var,
15308                             SourceLocation Loc,
15309                             const bool BuildAndDiagnose,
15310                             QualType &CaptureType,
15311                             QualType &DeclRefType,
15312                             const bool RefersToCapturedVariable,
15313                             const Sema::TryCaptureKind Kind,
15314                             SourceLocation EllipsisLoc,
15315                             const bool IsTopScope,
15316                             Sema &S) {
15317 
15318   // Determine whether we are capturing by reference or by value.
15319   bool ByRef = false;
15320   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
15321     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
15322   } else {
15323     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
15324   }
15325 
15326   // Compute the type of the field that will capture this variable.
15327   if (ByRef) {
15328     // C++11 [expr.prim.lambda]p15:
15329     //   An entity is captured by reference if it is implicitly or
15330     //   explicitly captured but not captured by copy. It is
15331     //   unspecified whether additional unnamed non-static data
15332     //   members are declared in the closure type for entities
15333     //   captured by reference.
15334     //
15335     // FIXME: It is not clear whether we want to build an lvalue reference
15336     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
15337     // to do the former, while EDG does the latter. Core issue 1249 will
15338     // clarify, but for now we follow GCC because it's a more permissive and
15339     // easily defensible position.
15340     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
15341   } else {
15342     // C++11 [expr.prim.lambda]p14:
15343     //   For each entity captured by copy, an unnamed non-static
15344     //   data member is declared in the closure type. The
15345     //   declaration order of these members is unspecified. The type
15346     //   of such a data member is the type of the corresponding
15347     //   captured entity if the entity is not a reference to an
15348     //   object, or the referenced type otherwise. [Note: If the
15349     //   captured entity is a reference to a function, the
15350     //   corresponding data member is also a reference to a
15351     //   function. - end note ]
15352     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
15353       if (!RefType->getPointeeType()->isFunctionType())
15354         CaptureType = RefType->getPointeeType();
15355     }
15356 
15357     // Forbid the lambda copy-capture of autoreleasing variables.
15358     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
15359       if (BuildAndDiagnose) {
15360         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
15361         S.Diag(Var->getLocation(), diag::note_previous_decl)
15362           << Var->getDeclName();
15363       }
15364       return false;
15365     }
15366 
15367     // Make sure that by-copy captures are of a complete and non-abstract type.
15368     if (BuildAndDiagnose) {
15369       if (!CaptureType->isDependentType() &&
15370           S.RequireCompleteType(Loc, CaptureType,
15371                                 diag::err_capture_of_incomplete_type,
15372                                 Var->getDeclName()))
15373         return false;
15374 
15375       if (S.RequireNonAbstractType(Loc, CaptureType,
15376                                    diag::err_capture_of_abstract_type))
15377         return false;
15378     }
15379   }
15380 
15381   // Capture this variable in the lambda.
15382   if (BuildAndDiagnose)
15383     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
15384                             RefersToCapturedVariable);
15385 
15386   // Compute the type of a reference to this captured variable.
15387   if (ByRef)
15388     DeclRefType = CaptureType.getNonReferenceType();
15389   else {
15390     // C++ [expr.prim.lambda]p5:
15391     //   The closure type for a lambda-expression has a public inline
15392     //   function call operator [...]. This function call operator is
15393     //   declared const (9.3.1) if and only if the lambda-expression's
15394     //   parameter-declaration-clause is not followed by mutable.
15395     DeclRefType = CaptureType.getNonReferenceType();
15396     if (!LSI->Mutable && !CaptureType->isReferenceType())
15397       DeclRefType.addConst();
15398   }
15399 
15400   // Add the capture.
15401   if (BuildAndDiagnose)
15402     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
15403                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
15404 
15405   return true;
15406 }
15407 
15408 bool Sema::tryCaptureVariable(
15409     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
15410     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
15411     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
15412   // An init-capture is notionally from the context surrounding its
15413   // declaration, but its parent DC is the lambda class.
15414   DeclContext *VarDC = Var->getDeclContext();
15415   if (Var->isInitCapture())
15416     VarDC = VarDC->getParent();
15417 
15418   DeclContext *DC = CurContext;
15419   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
15420       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
15421   // We need to sync up the Declaration Context with the
15422   // FunctionScopeIndexToStopAt
15423   if (FunctionScopeIndexToStopAt) {
15424     unsigned FSIndex = FunctionScopes.size() - 1;
15425     while (FSIndex != MaxFunctionScopesIndex) {
15426       DC = getLambdaAwareParentOfDeclContext(DC);
15427       --FSIndex;
15428     }
15429   }
15430 
15431 
15432   // If the variable is declared in the current context, there is no need to
15433   // capture it.
15434   if (VarDC == DC) return true;
15435 
15436   // Capture global variables if it is required to use private copy of this
15437   // variable.
15438   bool IsGlobal = !Var->hasLocalStorage();
15439   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
15440     return true;
15441   Var = Var->getCanonicalDecl();
15442 
15443   // Walk up the stack to determine whether we can capture the variable,
15444   // performing the "simple" checks that don't depend on type. We stop when
15445   // we've either hit the declared scope of the variable or find an existing
15446   // capture of that variable.  We start from the innermost capturing-entity
15447   // (the DC) and ensure that all intervening capturing-entities
15448   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
15449   // declcontext can either capture the variable or have already captured
15450   // the variable.
15451   CaptureType = Var->getType();
15452   DeclRefType = CaptureType.getNonReferenceType();
15453   bool Nested = false;
15454   bool Explicit = (Kind != TryCapture_Implicit);
15455   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
15456   do {
15457     // Only block literals, captured statements, and lambda expressions can
15458     // capture; other scopes don't work.
15459     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
15460                                                               ExprLoc,
15461                                                               BuildAndDiagnose,
15462                                                               *this);
15463     // We need to check for the parent *first* because, if we *have*
15464     // private-captured a global variable, we need to recursively capture it in
15465     // intermediate blocks, lambdas, etc.
15466     if (!ParentDC) {
15467       if (IsGlobal) {
15468         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
15469         break;
15470       }
15471       return true;
15472     }
15473 
15474     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
15475     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
15476 
15477 
15478     // Check whether we've already captured it.
15479     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
15480                                              DeclRefType)) {
15481       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
15482       break;
15483     }
15484     // If we are instantiating a generic lambda call operator body,
15485     // we do not want to capture new variables.  What was captured
15486     // during either a lambdas transformation or initial parsing
15487     // should be used.
15488     if (isGenericLambdaCallOperatorSpecialization(DC)) {
15489       if (BuildAndDiagnose) {
15490         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15491         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
15492           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15493           Diag(Var->getLocation(), diag::note_previous_decl)
15494              << Var->getDeclName();
15495           Diag(LSI->Lambda->getBeginLoc(), diag::note_lambda_decl);
15496         } else
15497           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
15498       }
15499       return true;
15500     }
15501     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
15502     // certain types of variables (unnamed, variably modified types etc.)
15503     // so check for eligibility.
15504     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
15505        return true;
15506 
15507     // Try to capture variable-length arrays types.
15508     if (Var->getType()->isVariablyModifiedType()) {
15509       // We're going to walk down into the type and look for VLA
15510       // expressions.
15511       QualType QTy = Var->getType();
15512       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
15513         QTy = PVD->getOriginalType();
15514       captureVariablyModifiedType(Context, QTy, CSI);
15515     }
15516 
15517     if (getLangOpts().OpenMP) {
15518       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15519         // OpenMP private variables should not be captured in outer scope, so
15520         // just break here. Similarly, global variables that are captured in a
15521         // target region should not be captured outside the scope of the region.
15522         if (RSI->CapRegionKind == CR_OpenMP) {
15523           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
15524           auto IsTargetCap = !IsOpenMPPrivateDecl &&
15525                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
15526           // When we detect target captures we are looking from inside the
15527           // target region, therefore we need to propagate the capture from the
15528           // enclosing region. Therefore, the capture is not initially nested.
15529           if (IsTargetCap)
15530             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
15531 
15532           if (IsTargetCap || IsOpenMPPrivateDecl) {
15533             Nested = !IsTargetCap;
15534             DeclRefType = DeclRefType.getUnqualifiedType();
15535             CaptureType = Context.getLValueReferenceType(DeclRefType);
15536             break;
15537           }
15538         }
15539       }
15540     }
15541     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
15542       // No capture-default, and this is not an explicit capture
15543       // so cannot capture this variable.
15544       if (BuildAndDiagnose) {
15545         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
15546         Diag(Var->getLocation(), diag::note_previous_decl)
15547           << Var->getDeclName();
15548         if (cast<LambdaScopeInfo>(CSI)->Lambda)
15549           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getBeginLoc(),
15550                diag::note_lambda_decl);
15551         // FIXME: If we error out because an outer lambda can not implicitly
15552         // capture a variable that an inner lambda explicitly captures, we
15553         // should have the inner lambda do the explicit capture - because
15554         // it makes for cleaner diagnostics later.  This would purely be done
15555         // so that the diagnostic does not misleadingly claim that a variable
15556         // can not be captured by a lambda implicitly even though it is captured
15557         // explicitly.  Suggestion:
15558         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
15559         //    at the function head
15560         //  - cache the StartingDeclContext - this must be a lambda
15561         //  - captureInLambda in the innermost lambda the variable.
15562       }
15563       return true;
15564     }
15565 
15566     FunctionScopesIndex--;
15567     DC = ParentDC;
15568     Explicit = false;
15569   } while (!VarDC->Equals(DC));
15570 
15571   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
15572   // computing the type of the capture at each step, checking type-specific
15573   // requirements, and adding captures if requested.
15574   // If the variable had already been captured previously, we start capturing
15575   // at the lambda nested within that one.
15576   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
15577        ++I) {
15578     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15579 
15580     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15581       if (!captureInBlock(BSI, Var, ExprLoc,
15582                           BuildAndDiagnose, CaptureType,
15583                           DeclRefType, Nested, *this))
15584         return true;
15585       Nested = true;
15586     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15587       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15588                                    BuildAndDiagnose, CaptureType,
15589                                    DeclRefType, Nested, *this))
15590         return true;
15591       Nested = true;
15592     } else {
15593       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15594       if (!captureInLambda(LSI, Var, ExprLoc,
15595                            BuildAndDiagnose, CaptureType,
15596                            DeclRefType, Nested, Kind, EllipsisLoc,
15597                             /*IsTopScope*/I == N - 1, *this))
15598         return true;
15599       Nested = true;
15600     }
15601   }
15602   return false;
15603 }
15604 
15605 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15606                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15607   QualType CaptureType;
15608   QualType DeclRefType;
15609   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15610                             /*BuildAndDiagnose=*/true, CaptureType,
15611                             DeclRefType, nullptr);
15612 }
15613 
15614 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15615   QualType CaptureType;
15616   QualType DeclRefType;
15617   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15618                              /*BuildAndDiagnose=*/false, CaptureType,
15619                              DeclRefType, nullptr);
15620 }
15621 
15622 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15623   QualType CaptureType;
15624   QualType DeclRefType;
15625 
15626   // Determine whether we can capture this variable.
15627   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15628                          /*BuildAndDiagnose=*/false, CaptureType,
15629                          DeclRefType, nullptr))
15630     return QualType();
15631 
15632   return DeclRefType;
15633 }
15634 
15635 
15636 
15637 // If either the type of the variable or the initializer is dependent,
15638 // return false. Otherwise, determine whether the variable is a constant
15639 // expression. Use this if you need to know if a variable that might or
15640 // might not be dependent is truly a constant expression.
15641 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15642     ASTContext &Context) {
15643 
15644   if (Var->getType()->isDependentType())
15645     return false;
15646   const VarDecl *DefVD = nullptr;
15647   Var->getAnyInitializer(DefVD);
15648   if (!DefVD)
15649     return false;
15650   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15651   Expr *Init = cast<Expr>(Eval->Value);
15652   if (Init->isValueDependent())
15653     return false;
15654   return IsVariableAConstantExpression(Var, Context);
15655 }
15656 
15657 
15658 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15659   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15660   // an object that satisfies the requirements for appearing in a
15661   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15662   // is immediately applied."  This function handles the lvalue-to-rvalue
15663   // conversion part.
15664   MaybeODRUseExprs.erase(E->IgnoreParens());
15665 
15666   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15667   // to a variable that is a constant expression, and if so, identify it as
15668   // a reference to a variable that does not involve an odr-use of that
15669   // variable.
15670   if (LambdaScopeInfo *LSI = getCurLambda()) {
15671     Expr *SansParensExpr = E->IgnoreParens();
15672     VarDecl *Var = nullptr;
15673     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15674       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15675     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15676       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15677 
15678     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15679       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15680   }
15681 }
15682 
15683 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15684   Res = CorrectDelayedTyposInExpr(Res);
15685 
15686   if (!Res.isUsable())
15687     return Res;
15688 
15689   // If a constant-expression is a reference to a variable where we delay
15690   // deciding whether it is an odr-use, just assume we will apply the
15691   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15692   // (a non-type template argument), we have special handling anyway.
15693   UpdateMarkingForLValueToRValue(Res.get());
15694   return Res;
15695 }
15696 
15697 void Sema::CleanupVarDeclMarking() {
15698   for (Expr *E : MaybeODRUseExprs) {
15699     VarDecl *Var;
15700     SourceLocation Loc;
15701     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15702       Var = cast<VarDecl>(DRE->getDecl());
15703       Loc = DRE->getLocation();
15704     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15705       Var = cast<VarDecl>(ME->getMemberDecl());
15706       Loc = ME->getMemberLoc();
15707     } else {
15708       llvm_unreachable("Unexpected expression");
15709     }
15710 
15711     MarkVarDeclODRUsed(Var, Loc, *this,
15712                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15713   }
15714 
15715   MaybeODRUseExprs.clear();
15716 }
15717 
15718 
15719 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15720                                     VarDecl *Var, Expr *E) {
15721   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15722          "Invalid Expr argument to DoMarkVarDeclReferenced");
15723   Var->setReferenced();
15724 
15725   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15726 
15727   bool OdrUseContext = isOdrUseContext(SemaRef);
15728   bool UsableInConstantExpr =
15729       Var->isUsableInConstantExpressions(SemaRef.Context);
15730   bool NeedDefinition =
15731       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15732 
15733   VarTemplateSpecializationDecl *VarSpec =
15734       dyn_cast<VarTemplateSpecializationDecl>(Var);
15735   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15736          "Can't instantiate a partial template specialization.");
15737 
15738   // If this might be a member specialization of a static data member, check
15739   // the specialization is visible. We already did the checks for variable
15740   // template specializations when we created them.
15741   if (NeedDefinition && TSK != TSK_Undeclared &&
15742       !isa<VarTemplateSpecializationDecl>(Var))
15743     SemaRef.checkSpecializationVisibility(Loc, Var);
15744 
15745   // Perform implicit instantiation of static data members, static data member
15746   // templates of class templates, and variable template specializations. Delay
15747   // instantiations of variable templates, except for those that could be used
15748   // in a constant expression.
15749   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15750     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15751     // instantiation declaration if a variable is usable in a constant
15752     // expression (among other cases).
15753     bool TryInstantiating =
15754         TSK == TSK_ImplicitInstantiation ||
15755         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15756 
15757     if (TryInstantiating) {
15758       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15759       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15760       if (FirstInstantiation) {
15761         PointOfInstantiation = Loc;
15762         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15763       }
15764 
15765       bool InstantiationDependent = false;
15766       bool IsNonDependent =
15767           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15768                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15769                   : true;
15770 
15771       // Do not instantiate specializations that are still type-dependent.
15772       if (IsNonDependent) {
15773         if (UsableInConstantExpr) {
15774           // Do not defer instantiations of variables that could be used in a
15775           // constant expression.
15776           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15777         } else if (FirstInstantiation ||
15778                    isa<VarTemplateSpecializationDecl>(Var)) {
15779           // FIXME: For a specialization of a variable template, we don't
15780           // distinguish between "declaration and type implicitly instantiated"
15781           // and "implicit instantiation of definition requested", so we have
15782           // no direct way to avoid enqueueing the pending instantiation
15783           // multiple times.
15784           SemaRef.PendingInstantiations
15785               .push_back(std::make_pair(Var, PointOfInstantiation));
15786         }
15787       }
15788     }
15789   }
15790 
15791   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15792   // the requirements for appearing in a constant expression (5.19) and, if
15793   // it is an object, the lvalue-to-rvalue conversion (4.1)
15794   // is immediately applied."  We check the first part here, and
15795   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15796   // Note that we use the C++11 definition everywhere because nothing in
15797   // C++03 depends on whether we get the C++03 version correct. The second
15798   // part does not apply to references, since they are not objects.
15799   if (OdrUseContext && E &&
15800       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15801     // A reference initialized by a constant expression can never be
15802     // odr-used, so simply ignore it.
15803     if (!Var->getType()->isReferenceType() ||
15804         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15805       SemaRef.MaybeODRUseExprs.insert(E);
15806   } else if (OdrUseContext) {
15807     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15808                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15809   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15810     // If this is a dependent context, we don't need to mark variables as
15811     // odr-used, but we may still need to track them for lambda capture.
15812     // FIXME: Do we also need to do this inside dependent typeid expressions
15813     // (which are modeled as unevaluated at this point)?
15814     const bool RefersToEnclosingScope =
15815         (SemaRef.CurContext != Var->getDeclContext() &&
15816          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15817     if (RefersToEnclosingScope) {
15818       LambdaScopeInfo *const LSI =
15819           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15820       if (LSI && (!LSI->CallOperator ||
15821                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15822         // If a variable could potentially be odr-used, defer marking it so
15823         // until we finish analyzing the full expression for any
15824         // lvalue-to-rvalue
15825         // or discarded value conversions that would obviate odr-use.
15826         // Add it to the list of potential captures that will be analyzed
15827         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15828         // unless the variable is a reference that was initialized by a constant
15829         // expression (this will never need to be captured or odr-used).
15830         assert(E && "Capture variable should be used in an expression.");
15831         if (!Var->getType()->isReferenceType() ||
15832             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15833           LSI->addPotentialCapture(E->IgnoreParens());
15834       }
15835     }
15836   }
15837 }
15838 
15839 /// Mark a variable referenced, and check whether it is odr-used
15840 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15841 /// used directly for normal expressions referring to VarDecl.
15842 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15843   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15844 }
15845 
15846 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15847                                Decl *D, Expr *E, bool MightBeOdrUse) {
15848   if (SemaRef.isInOpenMPDeclareTargetContext())
15849     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15850 
15851   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15852     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15853     return;
15854   }
15855 
15856   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15857 
15858   // If this is a call to a method via a cast, also mark the method in the
15859   // derived class used in case codegen can devirtualize the call.
15860   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15861   if (!ME)
15862     return;
15863   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15864   if (!MD)
15865     return;
15866   // Only attempt to devirtualize if this is truly a virtual call.
15867   bool IsVirtualCall = MD->isVirtual() &&
15868                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15869   if (!IsVirtualCall)
15870     return;
15871 
15872   // If it's possible to devirtualize the call, mark the called function
15873   // referenced.
15874   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15875       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15876   if (DM)
15877     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15878 }
15879 
15880 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15881 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15882   // TODO: update this with DR# once a defect report is filed.
15883   // C++11 defect. The address of a pure member should not be an ODR use, even
15884   // if it's a qualified reference.
15885   bool OdrUse = true;
15886   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15887     if (Method->isVirtual() &&
15888         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15889       OdrUse = false;
15890   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15891 }
15892 
15893 /// Perform reference-marking and odr-use handling for a MemberExpr.
15894 void Sema::MarkMemberReferenced(MemberExpr *E) {
15895   // C++11 [basic.def.odr]p2:
15896   //   A non-overloaded function whose name appears as a potentially-evaluated
15897   //   expression or a member of a set of candidate functions, if selected by
15898   //   overload resolution when referred to from a potentially-evaluated
15899   //   expression, is odr-used, unless it is a pure virtual function and its
15900   //   name is not explicitly qualified.
15901   bool MightBeOdrUse = true;
15902   if (E->performsVirtualDispatch(getLangOpts())) {
15903     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15904       if (Method->isPure())
15905         MightBeOdrUse = false;
15906   }
15907   SourceLocation Loc =
15908       E->getMemberLoc().isValid() ? E->getMemberLoc() : E->getBeginLoc();
15909   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15910 }
15911 
15912 /// Perform marking for a reference to an arbitrary declaration.  It
15913 /// marks the declaration referenced, and performs odr-use checking for
15914 /// functions and variables. This method should not be used when building a
15915 /// normal expression which refers to a variable.
15916 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15917                                  bool MightBeOdrUse) {
15918   if (MightBeOdrUse) {
15919     if (auto *VD = dyn_cast<VarDecl>(D)) {
15920       MarkVariableReferenced(Loc, VD);
15921       return;
15922     }
15923   }
15924   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15925     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15926     return;
15927   }
15928   D->setReferenced();
15929 }
15930 
15931 namespace {
15932   // Mark all of the declarations used by a type as referenced.
15933   // FIXME: Not fully implemented yet! We need to have a better understanding
15934   // of when we're entering a context we should not recurse into.
15935   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15936   // TreeTransforms rebuilding the type in a new context. Rather than
15937   // duplicating the TreeTransform logic, we should consider reusing it here.
15938   // Currently that causes problems when rebuilding LambdaExprs.
15939   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15940     Sema &S;
15941     SourceLocation Loc;
15942 
15943   public:
15944     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15945 
15946     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15947 
15948     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15949   };
15950 }
15951 
15952 bool MarkReferencedDecls::TraverseTemplateArgument(
15953     const TemplateArgument &Arg) {
15954   {
15955     // A non-type template argument is a constant-evaluated context.
15956     EnterExpressionEvaluationContext Evaluated(
15957         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15958     if (Arg.getKind() == TemplateArgument::Declaration) {
15959       if (Decl *D = Arg.getAsDecl())
15960         S.MarkAnyDeclReferenced(Loc, D, true);
15961     } else if (Arg.getKind() == TemplateArgument::Expression) {
15962       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15963     }
15964   }
15965 
15966   return Inherited::TraverseTemplateArgument(Arg);
15967 }
15968 
15969 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15970   MarkReferencedDecls Marker(*this, Loc);
15971   Marker.TraverseType(T);
15972 }
15973 
15974 namespace {
15975   /// Helper class that marks all of the declarations referenced by
15976   /// potentially-evaluated subexpressions as "referenced".
15977   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15978     Sema &S;
15979     bool SkipLocalVariables;
15980 
15981   public:
15982     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15983 
15984     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15985       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15986 
15987     void VisitDeclRefExpr(DeclRefExpr *E) {
15988       // If we were asked not to visit local variables, don't.
15989       if (SkipLocalVariables) {
15990         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15991           if (VD->hasLocalStorage())
15992             return;
15993       }
15994 
15995       S.MarkDeclRefReferenced(E);
15996     }
15997 
15998     void VisitMemberExpr(MemberExpr *E) {
15999       S.MarkMemberReferenced(E);
16000       Inherited::VisitMemberExpr(E);
16001     }
16002 
16003     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
16004       S.MarkFunctionReferenced(
16005           E->getBeginLoc(),
16006           const_cast<CXXDestructorDecl *>(E->getTemporary()->getDestructor()));
16007       Visit(E->getSubExpr());
16008     }
16009 
16010     void VisitCXXNewExpr(CXXNewExpr *E) {
16011       if (E->getOperatorNew())
16012         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorNew());
16013       if (E->getOperatorDelete())
16014         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16015       Inherited::VisitCXXNewExpr(E);
16016     }
16017 
16018     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
16019       if (E->getOperatorDelete())
16020         S.MarkFunctionReferenced(E->getBeginLoc(), E->getOperatorDelete());
16021       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
16022       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
16023         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
16024         S.MarkFunctionReferenced(E->getBeginLoc(), S.LookupDestructor(Record));
16025       }
16026 
16027       Inherited::VisitCXXDeleteExpr(E);
16028     }
16029 
16030     void VisitCXXConstructExpr(CXXConstructExpr *E) {
16031       S.MarkFunctionReferenced(E->getBeginLoc(), E->getConstructor());
16032       Inherited::VisitCXXConstructExpr(E);
16033     }
16034 
16035     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
16036       Visit(E->getExpr());
16037     }
16038 
16039     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
16040       Inherited::VisitImplicitCastExpr(E);
16041 
16042       if (E->getCastKind() == CK_LValueToRValue)
16043         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
16044     }
16045   };
16046 }
16047 
16048 /// Mark any declarations that appear within this expression or any
16049 /// potentially-evaluated subexpressions as "referenced".
16050 ///
16051 /// \param SkipLocalVariables If true, don't mark local variables as
16052 /// 'referenced'.
16053 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
16054                                             bool SkipLocalVariables) {
16055   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
16056 }
16057 
16058 /// Emit a diagnostic that describes an effect on the run-time behavior
16059 /// of the program being compiled.
16060 ///
16061 /// This routine emits the given diagnostic when the code currently being
16062 /// type-checked is "potentially evaluated", meaning that there is a
16063 /// possibility that the code will actually be executable. Code in sizeof()
16064 /// expressions, code used only during overload resolution, etc., are not
16065 /// potentially evaluated. This routine will suppress such diagnostics or,
16066 /// in the absolutely nutty case of potentially potentially evaluated
16067 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
16068 /// later.
16069 ///
16070 /// This routine should be used for all diagnostics that describe the run-time
16071 /// behavior of a program, such as passing a non-POD value through an ellipsis.
16072 /// Failure to do so will likely result in spurious diagnostics or failures
16073 /// during overload resolution or within sizeof/alignof/typeof/typeid.
16074 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
16075                                const PartialDiagnostic &PD) {
16076   switch (ExprEvalContexts.back().Context) {
16077   case ExpressionEvaluationContext::Unevaluated:
16078   case ExpressionEvaluationContext::UnevaluatedList:
16079   case ExpressionEvaluationContext::UnevaluatedAbstract:
16080   case ExpressionEvaluationContext::DiscardedStatement:
16081     // The argument will never be evaluated, so don't complain.
16082     break;
16083 
16084   case ExpressionEvaluationContext::ConstantEvaluated:
16085     // Relevant diagnostics should be produced by constant evaluation.
16086     break;
16087 
16088   case ExpressionEvaluationContext::PotentiallyEvaluated:
16089   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
16090     if (Statement && getCurFunctionOrMethodDecl()) {
16091       FunctionScopes.back()->PossiblyUnreachableDiags.
16092         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
16093       return true;
16094     }
16095 
16096     // The initializer of a constexpr variable or of the first declaration of a
16097     // static data member is not syntactically a constant evaluated constant,
16098     // but nonetheless is always required to be a constant expression, so we
16099     // can skip diagnosing.
16100     // FIXME: Using the mangling context here is a hack.
16101     if (auto *VD = dyn_cast_or_null<VarDecl>(
16102             ExprEvalContexts.back().ManglingContextDecl)) {
16103       if (VD->isConstexpr() ||
16104           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
16105         break;
16106       // FIXME: For any other kind of variable, we should build a CFG for its
16107       // initializer and check whether the context in question is reachable.
16108     }
16109 
16110     Diag(Loc, PD);
16111     return true;
16112   }
16113 
16114   return false;
16115 }
16116 
16117 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
16118                                CallExpr *CE, FunctionDecl *FD) {
16119   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
16120     return false;
16121 
16122   // If we're inside a decltype's expression, don't check for a valid return
16123   // type or construct temporaries until we know whether this is the last call.
16124   if (ExprEvalContexts.back().ExprContext ==
16125       ExpressionEvaluationContextRecord::EK_Decltype) {
16126     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
16127     return false;
16128   }
16129 
16130   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
16131     FunctionDecl *FD;
16132     CallExpr *CE;
16133 
16134   public:
16135     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
16136       : FD(FD), CE(CE) { }
16137 
16138     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
16139       if (!FD) {
16140         S.Diag(Loc, diag::err_call_incomplete_return)
16141           << T << CE->getSourceRange();
16142         return;
16143       }
16144 
16145       S.Diag(Loc, diag::err_call_function_incomplete_return)
16146         << CE->getSourceRange() << FD->getDeclName() << T;
16147       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
16148           << FD->getDeclName();
16149     }
16150   } Diagnoser(FD, CE);
16151 
16152   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
16153     return true;
16154 
16155   return false;
16156 }
16157 
16158 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
16159 // will prevent this condition from triggering, which is what we want.
16160 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
16161   SourceLocation Loc;
16162 
16163   unsigned diagnostic = diag::warn_condition_is_assignment;
16164   bool IsOrAssign = false;
16165 
16166   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
16167     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
16168       return;
16169 
16170     IsOrAssign = Op->getOpcode() == BO_OrAssign;
16171 
16172     // Greylist some idioms by putting them into a warning subcategory.
16173     if (ObjCMessageExpr *ME
16174           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
16175       Selector Sel = ME->getSelector();
16176 
16177       // self = [<foo> init...]
16178       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
16179         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16180 
16181       // <foo> = [<bar> nextObject]
16182       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
16183         diagnostic = diag::warn_condition_is_idiomatic_assignment;
16184     }
16185 
16186     Loc = Op->getOperatorLoc();
16187   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
16188     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
16189       return;
16190 
16191     IsOrAssign = Op->getOperator() == OO_PipeEqual;
16192     Loc = Op->getOperatorLoc();
16193   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
16194     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
16195   else {
16196     // Not an assignment.
16197     return;
16198   }
16199 
16200   Diag(Loc, diagnostic) << E->getSourceRange();
16201 
16202   SourceLocation Open = E->getBeginLoc();
16203   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
16204   Diag(Loc, diag::note_condition_assign_silence)
16205         << FixItHint::CreateInsertion(Open, "(")
16206         << FixItHint::CreateInsertion(Close, ")");
16207 
16208   if (IsOrAssign)
16209     Diag(Loc, diag::note_condition_or_assign_to_comparison)
16210       << FixItHint::CreateReplacement(Loc, "!=");
16211   else
16212     Diag(Loc, diag::note_condition_assign_to_comparison)
16213       << FixItHint::CreateReplacement(Loc, "==");
16214 }
16215 
16216 /// Redundant parentheses over an equality comparison can indicate
16217 /// that the user intended an assignment used as condition.
16218 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
16219   // Don't warn if the parens came from a macro.
16220   SourceLocation parenLoc = ParenE->getBeginLoc();
16221   if (parenLoc.isInvalid() || parenLoc.isMacroID())
16222     return;
16223   // Don't warn for dependent expressions.
16224   if (ParenE->isTypeDependent())
16225     return;
16226 
16227   Expr *E = ParenE->IgnoreParens();
16228 
16229   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
16230     if (opE->getOpcode() == BO_EQ &&
16231         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
16232                                                            == Expr::MLV_Valid) {
16233       SourceLocation Loc = opE->getOperatorLoc();
16234 
16235       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
16236       SourceRange ParenERange = ParenE->getSourceRange();
16237       Diag(Loc, diag::note_equality_comparison_silence)
16238         << FixItHint::CreateRemoval(ParenERange.getBegin())
16239         << FixItHint::CreateRemoval(ParenERange.getEnd());
16240       Diag(Loc, diag::note_equality_comparison_to_assign)
16241         << FixItHint::CreateReplacement(Loc, "=");
16242     }
16243 }
16244 
16245 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
16246                                        bool IsConstexpr) {
16247   DiagnoseAssignmentAsCondition(E);
16248   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
16249     DiagnoseEqualityWithExtraParens(parenE);
16250 
16251   ExprResult result = CheckPlaceholderExpr(E);
16252   if (result.isInvalid()) return ExprError();
16253   E = result.get();
16254 
16255   if (!E->isTypeDependent()) {
16256     if (getLangOpts().CPlusPlus)
16257       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
16258 
16259     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
16260     if (ERes.isInvalid())
16261       return ExprError();
16262     E = ERes.get();
16263 
16264     QualType T = E->getType();
16265     if (!T->isScalarType()) { // C99 6.8.4.1p1
16266       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
16267         << T << E->getSourceRange();
16268       return ExprError();
16269     }
16270     CheckBoolLikeConversion(E, Loc);
16271   }
16272 
16273   return E;
16274 }
16275 
16276 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
16277                                            Expr *SubExpr, ConditionKind CK) {
16278   // Empty conditions are valid in for-statements.
16279   if (!SubExpr)
16280     return ConditionResult();
16281 
16282   ExprResult Cond;
16283   switch (CK) {
16284   case ConditionKind::Boolean:
16285     Cond = CheckBooleanCondition(Loc, SubExpr);
16286     break;
16287 
16288   case ConditionKind::ConstexprIf:
16289     Cond = CheckBooleanCondition(Loc, SubExpr, true);
16290     break;
16291 
16292   case ConditionKind::Switch:
16293     Cond = CheckSwitchCondition(Loc, SubExpr);
16294     break;
16295   }
16296   if (Cond.isInvalid())
16297     return ConditionError();
16298 
16299   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
16300   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
16301   if (!FullExpr.get())
16302     return ConditionError();
16303 
16304   return ConditionResult(*this, nullptr, FullExpr,
16305                          CK == ConditionKind::ConstexprIf);
16306 }
16307 
16308 namespace {
16309   /// A visitor for rebuilding a call to an __unknown_any expression
16310   /// to have an appropriate type.
16311   struct RebuildUnknownAnyFunction
16312     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
16313 
16314     Sema &S;
16315 
16316     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
16317 
16318     ExprResult VisitStmt(Stmt *S) {
16319       llvm_unreachable("unexpected statement!");
16320     }
16321 
16322     ExprResult VisitExpr(Expr *E) {
16323       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
16324         << E->getSourceRange();
16325       return ExprError();
16326     }
16327 
16328     /// Rebuild an expression which simply semantically wraps another
16329     /// expression which it shares the type and value kind of.
16330     template <class T> ExprResult rebuildSugarExpr(T *E) {
16331       ExprResult SubResult = Visit(E->getSubExpr());
16332       if (SubResult.isInvalid()) return ExprError();
16333 
16334       Expr *SubExpr = SubResult.get();
16335       E->setSubExpr(SubExpr);
16336       E->setType(SubExpr->getType());
16337       E->setValueKind(SubExpr->getValueKind());
16338       assert(E->getObjectKind() == OK_Ordinary);
16339       return E;
16340     }
16341 
16342     ExprResult VisitParenExpr(ParenExpr *E) {
16343       return rebuildSugarExpr(E);
16344     }
16345 
16346     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16347       return rebuildSugarExpr(E);
16348     }
16349 
16350     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16351       ExprResult SubResult = Visit(E->getSubExpr());
16352       if (SubResult.isInvalid()) return ExprError();
16353 
16354       Expr *SubExpr = SubResult.get();
16355       E->setSubExpr(SubExpr);
16356       E->setType(S.Context.getPointerType(SubExpr->getType()));
16357       assert(E->getValueKind() == VK_RValue);
16358       assert(E->getObjectKind() == OK_Ordinary);
16359       return E;
16360     }
16361 
16362     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
16363       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
16364 
16365       E->setType(VD->getType());
16366 
16367       assert(E->getValueKind() == VK_RValue);
16368       if (S.getLangOpts().CPlusPlus &&
16369           !(isa<CXXMethodDecl>(VD) &&
16370             cast<CXXMethodDecl>(VD)->isInstance()))
16371         E->setValueKind(VK_LValue);
16372 
16373       return E;
16374     }
16375 
16376     ExprResult VisitMemberExpr(MemberExpr *E) {
16377       return resolveDecl(E, E->getMemberDecl());
16378     }
16379 
16380     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16381       return resolveDecl(E, E->getDecl());
16382     }
16383   };
16384 }
16385 
16386 /// Given a function expression of unknown-any type, try to rebuild it
16387 /// to have a function type.
16388 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
16389   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
16390   if (Result.isInvalid()) return ExprError();
16391   return S.DefaultFunctionArrayConversion(Result.get());
16392 }
16393 
16394 namespace {
16395   /// A visitor for rebuilding an expression of type __unknown_anytype
16396   /// into one which resolves the type directly on the referring
16397   /// expression.  Strict preservation of the original source
16398   /// structure is not a goal.
16399   struct RebuildUnknownAnyExpr
16400     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
16401 
16402     Sema &S;
16403 
16404     /// The current destination type.
16405     QualType DestType;
16406 
16407     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
16408       : S(S), DestType(CastType) {}
16409 
16410     ExprResult VisitStmt(Stmt *S) {
16411       llvm_unreachable("unexpected statement!");
16412     }
16413 
16414     ExprResult VisitExpr(Expr *E) {
16415       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16416         << E->getSourceRange();
16417       return ExprError();
16418     }
16419 
16420     ExprResult VisitCallExpr(CallExpr *E);
16421     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
16422 
16423     /// Rebuild an expression which simply semantically wraps another
16424     /// expression which it shares the type and value kind of.
16425     template <class T> ExprResult rebuildSugarExpr(T *E) {
16426       ExprResult SubResult = Visit(E->getSubExpr());
16427       if (SubResult.isInvalid()) return ExprError();
16428       Expr *SubExpr = SubResult.get();
16429       E->setSubExpr(SubExpr);
16430       E->setType(SubExpr->getType());
16431       E->setValueKind(SubExpr->getValueKind());
16432       assert(E->getObjectKind() == OK_Ordinary);
16433       return E;
16434     }
16435 
16436     ExprResult VisitParenExpr(ParenExpr *E) {
16437       return rebuildSugarExpr(E);
16438     }
16439 
16440     ExprResult VisitUnaryExtension(UnaryOperator *E) {
16441       return rebuildSugarExpr(E);
16442     }
16443 
16444     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
16445       const PointerType *Ptr = DestType->getAs<PointerType>();
16446       if (!Ptr) {
16447         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
16448           << E->getSourceRange();
16449         return ExprError();
16450       }
16451 
16452       if (isa<CallExpr>(E->getSubExpr())) {
16453         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
16454           << E->getSourceRange();
16455         return ExprError();
16456       }
16457 
16458       assert(E->getValueKind() == VK_RValue);
16459       assert(E->getObjectKind() == OK_Ordinary);
16460       E->setType(DestType);
16461 
16462       // Build the sub-expression as if it were an object of the pointee type.
16463       DestType = Ptr->getPointeeType();
16464       ExprResult SubResult = Visit(E->getSubExpr());
16465       if (SubResult.isInvalid()) return ExprError();
16466       E->setSubExpr(SubResult.get());
16467       return E;
16468     }
16469 
16470     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
16471 
16472     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
16473 
16474     ExprResult VisitMemberExpr(MemberExpr *E) {
16475       return resolveDecl(E, E->getMemberDecl());
16476     }
16477 
16478     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
16479       return resolveDecl(E, E->getDecl());
16480     }
16481   };
16482 }
16483 
16484 /// Rebuilds a call expression which yielded __unknown_anytype.
16485 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
16486   Expr *CalleeExpr = E->getCallee();
16487 
16488   enum FnKind {
16489     FK_MemberFunction,
16490     FK_FunctionPointer,
16491     FK_BlockPointer
16492   };
16493 
16494   FnKind Kind;
16495   QualType CalleeType = CalleeExpr->getType();
16496   if (CalleeType == S.Context.BoundMemberTy) {
16497     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
16498     Kind = FK_MemberFunction;
16499     CalleeType = Expr::findBoundMemberType(CalleeExpr);
16500   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
16501     CalleeType = Ptr->getPointeeType();
16502     Kind = FK_FunctionPointer;
16503   } else {
16504     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
16505     Kind = FK_BlockPointer;
16506   }
16507   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
16508 
16509   // Verify that this is a legal result type of a function.
16510   if (DestType->isArrayType() || DestType->isFunctionType()) {
16511     unsigned diagID = diag::err_func_returning_array_function;
16512     if (Kind == FK_BlockPointer)
16513       diagID = diag::err_block_returning_array_function;
16514 
16515     S.Diag(E->getExprLoc(), diagID)
16516       << DestType->isFunctionType() << DestType;
16517     return ExprError();
16518   }
16519 
16520   // Otherwise, go ahead and set DestType as the call's result.
16521   E->setType(DestType.getNonLValueExprType(S.Context));
16522   E->setValueKind(Expr::getValueKindForType(DestType));
16523   assert(E->getObjectKind() == OK_Ordinary);
16524 
16525   // Rebuild the function type, replacing the result type with DestType.
16526   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
16527   if (Proto) {
16528     // __unknown_anytype(...) is a special case used by the debugger when
16529     // it has no idea what a function's signature is.
16530     //
16531     // We want to build this call essentially under the K&R
16532     // unprototyped rules, but making a FunctionNoProtoType in C++
16533     // would foul up all sorts of assumptions.  However, we cannot
16534     // simply pass all arguments as variadic arguments, nor can we
16535     // portably just call the function under a non-variadic type; see
16536     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
16537     // However, it turns out that in practice it is generally safe to
16538     // call a function declared as "A foo(B,C,D);" under the prototype
16539     // "A foo(B,C,D,...);".  The only known exception is with the
16540     // Windows ABI, where any variadic function is implicitly cdecl
16541     // regardless of its normal CC.  Therefore we change the parameter
16542     // types to match the types of the arguments.
16543     //
16544     // This is a hack, but it is far superior to moving the
16545     // corresponding target-specific code from IR-gen to Sema/AST.
16546 
16547     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
16548     SmallVector<QualType, 8> ArgTypes;
16549     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
16550       ArgTypes.reserve(E->getNumArgs());
16551       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
16552         Expr *Arg = E->getArg(i);
16553         QualType ArgType = Arg->getType();
16554         if (E->isLValue()) {
16555           ArgType = S.Context.getLValueReferenceType(ArgType);
16556         } else if (E->isXValue()) {
16557           ArgType = S.Context.getRValueReferenceType(ArgType);
16558         }
16559         ArgTypes.push_back(ArgType);
16560       }
16561       ParamTypes = ArgTypes;
16562     }
16563     DestType = S.Context.getFunctionType(DestType, ParamTypes,
16564                                          Proto->getExtProtoInfo());
16565   } else {
16566     DestType = S.Context.getFunctionNoProtoType(DestType,
16567                                                 FnType->getExtInfo());
16568   }
16569 
16570   // Rebuild the appropriate pointer-to-function type.
16571   switch (Kind) {
16572   case FK_MemberFunction:
16573     // Nothing to do.
16574     break;
16575 
16576   case FK_FunctionPointer:
16577     DestType = S.Context.getPointerType(DestType);
16578     break;
16579 
16580   case FK_BlockPointer:
16581     DestType = S.Context.getBlockPointerType(DestType);
16582     break;
16583   }
16584 
16585   // Finally, we can recurse.
16586   ExprResult CalleeResult = Visit(CalleeExpr);
16587   if (!CalleeResult.isUsable()) return ExprError();
16588   E->setCallee(CalleeResult.get());
16589 
16590   // Bind a temporary if necessary.
16591   return S.MaybeBindToTemporary(E);
16592 }
16593 
16594 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16595   // Verify that this is a legal result type of a call.
16596   if (DestType->isArrayType() || DestType->isFunctionType()) {
16597     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16598       << DestType->isFunctionType() << DestType;
16599     return ExprError();
16600   }
16601 
16602   // Rewrite the method result type if available.
16603   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16604     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16605     Method->setReturnType(DestType);
16606   }
16607 
16608   // Change the type of the message.
16609   E->setType(DestType.getNonReferenceType());
16610   E->setValueKind(Expr::getValueKindForType(DestType));
16611 
16612   return S.MaybeBindToTemporary(E);
16613 }
16614 
16615 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16616   // The only case we should ever see here is a function-to-pointer decay.
16617   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16618     assert(E->getValueKind() == VK_RValue);
16619     assert(E->getObjectKind() == OK_Ordinary);
16620 
16621     E->setType(DestType);
16622 
16623     // Rebuild the sub-expression as the pointee (function) type.
16624     DestType = DestType->castAs<PointerType>()->getPointeeType();
16625 
16626     ExprResult Result = Visit(E->getSubExpr());
16627     if (!Result.isUsable()) return ExprError();
16628 
16629     E->setSubExpr(Result.get());
16630     return E;
16631   } else if (E->getCastKind() == CK_LValueToRValue) {
16632     assert(E->getValueKind() == VK_RValue);
16633     assert(E->getObjectKind() == OK_Ordinary);
16634 
16635     assert(isa<BlockPointerType>(E->getType()));
16636 
16637     E->setType(DestType);
16638 
16639     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16640     DestType = S.Context.getLValueReferenceType(DestType);
16641 
16642     ExprResult Result = Visit(E->getSubExpr());
16643     if (!Result.isUsable()) return ExprError();
16644 
16645     E->setSubExpr(Result.get());
16646     return E;
16647   } else {
16648     llvm_unreachable("Unhandled cast type!");
16649   }
16650 }
16651 
16652 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16653   ExprValueKind ValueKind = VK_LValue;
16654   QualType Type = DestType;
16655 
16656   // We know how to make this work for certain kinds of decls:
16657 
16658   //  - functions
16659   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16660     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16661       DestType = Ptr->getPointeeType();
16662       ExprResult Result = resolveDecl(E, VD);
16663       if (Result.isInvalid()) return ExprError();
16664       return S.ImpCastExprToType(Result.get(), Type,
16665                                  CK_FunctionToPointerDecay, VK_RValue);
16666     }
16667 
16668     if (!Type->isFunctionType()) {
16669       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16670         << VD << E->getSourceRange();
16671       return ExprError();
16672     }
16673     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16674       // We must match the FunctionDecl's type to the hack introduced in
16675       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16676       // type. See the lengthy commentary in that routine.
16677       QualType FDT = FD->getType();
16678       const FunctionType *FnType = FDT->castAs<FunctionType>();
16679       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16680       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16681       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16682         SourceLocation Loc = FD->getLocation();
16683         FunctionDecl *NewFD = FunctionDecl::Create(S.Context,
16684                                       FD->getDeclContext(),
16685                                       Loc, Loc, FD->getNameInfo().getName(),
16686                                       DestType, FD->getTypeSourceInfo(),
16687                                       SC_None, false/*isInlineSpecified*/,
16688                                       FD->hasPrototype(),
16689                                       false/*isConstexprSpecified*/);
16690 
16691         if (FD->getQualifier())
16692           NewFD->setQualifierInfo(FD->getQualifierLoc());
16693 
16694         SmallVector<ParmVarDecl*, 16> Params;
16695         for (const auto &AI : FT->param_types()) {
16696           ParmVarDecl *Param =
16697             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16698           Param->setScopeInfo(0, Params.size());
16699           Params.push_back(Param);
16700         }
16701         NewFD->setParams(Params);
16702         DRE->setDecl(NewFD);
16703         VD = DRE->getDecl();
16704       }
16705     }
16706 
16707     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16708       if (MD->isInstance()) {
16709         ValueKind = VK_RValue;
16710         Type = S.Context.BoundMemberTy;
16711       }
16712 
16713     // Function references aren't l-values in C.
16714     if (!S.getLangOpts().CPlusPlus)
16715       ValueKind = VK_RValue;
16716 
16717   //  - variables
16718   } else if (isa<VarDecl>(VD)) {
16719     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16720       Type = RefTy->getPointeeType();
16721     } else if (Type->isFunctionType()) {
16722       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16723         << VD << E->getSourceRange();
16724       return ExprError();
16725     }
16726 
16727   //  - nothing else
16728   } else {
16729     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16730       << VD << E->getSourceRange();
16731     return ExprError();
16732   }
16733 
16734   // Modifying the declaration like this is friendly to IR-gen but
16735   // also really dangerous.
16736   VD->setType(DestType);
16737   E->setType(Type);
16738   E->setValueKind(ValueKind);
16739   return E;
16740 }
16741 
16742 /// Check a cast of an unknown-any type.  We intentionally only
16743 /// trigger this for C-style casts.
16744 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16745                                      Expr *CastExpr, CastKind &CastKind,
16746                                      ExprValueKind &VK, CXXCastPath &Path) {
16747   // The type we're casting to must be either void or complete.
16748   if (!CastType->isVoidType() &&
16749       RequireCompleteType(TypeRange.getBegin(), CastType,
16750                           diag::err_typecheck_cast_to_incomplete))
16751     return ExprError();
16752 
16753   // Rewrite the casted expression from scratch.
16754   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16755   if (!result.isUsable()) return ExprError();
16756 
16757   CastExpr = result.get();
16758   VK = CastExpr->getValueKind();
16759   CastKind = CK_NoOp;
16760 
16761   return CastExpr;
16762 }
16763 
16764 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16765   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16766 }
16767 
16768 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16769                                     Expr *arg, QualType &paramType) {
16770   // If the syntactic form of the argument is not an explicit cast of
16771   // any sort, just do default argument promotion.
16772   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16773   if (!castArg) {
16774     ExprResult result = DefaultArgumentPromotion(arg);
16775     if (result.isInvalid()) return ExprError();
16776     paramType = result.get()->getType();
16777     return result;
16778   }
16779 
16780   // Otherwise, use the type that was written in the explicit cast.
16781   assert(!arg->hasPlaceholderType());
16782   paramType = castArg->getTypeAsWritten();
16783 
16784   // Copy-initialize a parameter of that type.
16785   InitializedEntity entity =
16786     InitializedEntity::InitializeParameter(Context, paramType,
16787                                            /*consumed*/ false);
16788   return PerformCopyInitialization(entity, callLoc, arg);
16789 }
16790 
16791 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16792   Expr *orig = E;
16793   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16794   while (true) {
16795     E = E->IgnoreParenImpCasts();
16796     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16797       E = call->getCallee();
16798       diagID = diag::err_uncasted_call_of_unknown_any;
16799     } else {
16800       break;
16801     }
16802   }
16803 
16804   SourceLocation loc;
16805   NamedDecl *d;
16806   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16807     loc = ref->getLocation();
16808     d = ref->getDecl();
16809   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16810     loc = mem->getMemberLoc();
16811     d = mem->getMemberDecl();
16812   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16813     diagID = diag::err_uncasted_call_of_unknown_any;
16814     loc = msg->getSelectorStartLoc();
16815     d = msg->getMethodDecl();
16816     if (!d) {
16817       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16818         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16819         << orig->getSourceRange();
16820       return ExprError();
16821     }
16822   } else {
16823     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16824       << E->getSourceRange();
16825     return ExprError();
16826   }
16827 
16828   S.Diag(loc, diagID) << d << orig->getSourceRange();
16829 
16830   // Never recoverable.
16831   return ExprError();
16832 }
16833 
16834 /// Check for operands with placeholder types and complain if found.
16835 /// Returns ExprError() if there was an error and no recovery was possible.
16836 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16837   if (!getLangOpts().CPlusPlus) {
16838     // C cannot handle TypoExpr nodes on either side of a binop because it
16839     // doesn't handle dependent types properly, so make sure any TypoExprs have
16840     // been dealt with before checking the operands.
16841     ExprResult Result = CorrectDelayedTyposInExpr(E);
16842     if (!Result.isUsable()) return ExprError();
16843     E = Result.get();
16844   }
16845 
16846   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16847   if (!placeholderType) return E;
16848 
16849   switch (placeholderType->getKind()) {
16850 
16851   // Overloaded expressions.
16852   case BuiltinType::Overload: {
16853     // Try to resolve a single function template specialization.
16854     // This is obligatory.
16855     ExprResult Result = E;
16856     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16857       return Result;
16858 
16859     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16860     // leaves Result unchanged on failure.
16861     Result = E;
16862     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16863       return Result;
16864 
16865     // If that failed, try to recover with a call.
16866     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16867                          /*complain*/ true);
16868     return Result;
16869   }
16870 
16871   // Bound member functions.
16872   case BuiltinType::BoundMember: {
16873     ExprResult result = E;
16874     const Expr *BME = E->IgnoreParens();
16875     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16876     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16877     if (isa<CXXPseudoDestructorExpr>(BME)) {
16878       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16879     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16880       if (ME->getMemberNameInfo().getName().getNameKind() ==
16881           DeclarationName::CXXDestructorName)
16882         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16883     }
16884     tryToRecoverWithCall(result, PD,
16885                          /*complain*/ true);
16886     return result;
16887   }
16888 
16889   // ARC unbridged casts.
16890   case BuiltinType::ARCUnbridgedCast: {
16891     Expr *realCast = stripARCUnbridgedCast(E);
16892     diagnoseARCUnbridgedCast(realCast);
16893     return realCast;
16894   }
16895 
16896   // Expressions of unknown type.
16897   case BuiltinType::UnknownAny:
16898     return diagnoseUnknownAnyExpr(*this, E);
16899 
16900   // Pseudo-objects.
16901   case BuiltinType::PseudoObject:
16902     return checkPseudoObjectRValue(E);
16903 
16904   case BuiltinType::BuiltinFn: {
16905     // Accept __noop without parens by implicitly converting it to a call expr.
16906     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16907     if (DRE) {
16908       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16909       if (FD->getBuiltinID() == Builtin::BI__noop) {
16910         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16911                               CK_BuiltinFnToFnPtr)
16912                 .get();
16913         return CallExpr::Create(Context, E, /*Args=*/{}, Context.IntTy,
16914                                 VK_RValue, SourceLocation());
16915       }
16916     }
16917 
16918     Diag(E->getBeginLoc(), diag::err_builtin_fn_use);
16919     return ExprError();
16920   }
16921 
16922   // Expressions of unknown type.
16923   case BuiltinType::OMPArraySection:
16924     Diag(E->getBeginLoc(), diag::err_omp_array_section_use);
16925     return ExprError();
16926 
16927   // Everything else should be impossible.
16928 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16929   case BuiltinType::Id:
16930 #include "clang/Basic/OpenCLImageTypes.def"
16931 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
16932   case BuiltinType::Id:
16933 #include "clang/Basic/OpenCLExtensionTypes.def"
16934 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16935 #define PLACEHOLDER_TYPE(Id, SingletonId)
16936 #include "clang/AST/BuiltinTypes.def"
16937     break;
16938   }
16939 
16940   llvm_unreachable("invalid placeholder type!");
16941 }
16942 
16943 bool Sema::CheckCaseExpression(Expr *E) {
16944   if (E->isTypeDependent())
16945     return true;
16946   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16947     return E->getType()->isIntegralOrEnumerationType();
16948   return false;
16949 }
16950 
16951 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16952 ExprResult
16953 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16954   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16955          "Unknown Objective-C Boolean value!");
16956   QualType BoolT = Context.ObjCBuiltinBoolTy;
16957   if (!Context.getBOOLDecl()) {
16958     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16959                         Sema::LookupOrdinaryName);
16960     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16961       NamedDecl *ND = Result.getFoundDecl();
16962       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16963         Context.setBOOLDecl(TD);
16964     }
16965   }
16966   if (Context.getBOOLDecl())
16967     BoolT = Context.getBOOLType();
16968   return new (Context)
16969       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16970 }
16971 
16972 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16973     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16974     SourceLocation RParen) {
16975 
16976   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16977 
16978   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16979                            [&](const AvailabilitySpec &Spec) {
16980                              return Spec.getPlatform() == Platform;
16981                            });
16982 
16983   VersionTuple Version;
16984   if (Spec != AvailSpecs.end())
16985     Version = Spec->getVersion();
16986 
16987   // The use of `@available` in the enclosing function should be analyzed to
16988   // warn when it's used inappropriately (i.e. not if(@available)).
16989   if (getCurFunctionOrMethodDecl())
16990     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16991   else if (getCurBlock() || getCurLambda())
16992     getCurFunction()->HasPotentialAvailabilityViolations = true;
16993 
16994   return new (Context)
16995       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16996 }
16997