1 //===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for expressions.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TreeTransform.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/ExprOpenMP.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/Overload.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/SemaInternal.h"
46 #include "clang/Sema/Template.h"
47 #include "llvm/Support/ConvertUTF.h"
48 using namespace clang;
49 using namespace sema;
50 
51 /// Determine whether the use of this declaration is valid, without
52 /// emitting diagnostics.
53 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
54   // See if this is an auto-typed variable whose initializer we are parsing.
55   if (ParsingInitForAutoVars.count(D))
56     return false;
57 
58   // See if this is a deleted function.
59   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
60     if (FD->isDeleted())
61       return false;
62 
63     // If the function has a deduced return type, and we can't deduce it,
64     // then we can't use it either.
65     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
66         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
67       return false;
68   }
69 
70   // See if this function is unavailable.
71   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
72       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
73     return false;
74 
75   return true;
76 }
77 
78 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
79   // Warn if this is used but marked unused.
80   if (const auto *A = D->getAttr<UnusedAttr>()) {
81     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
82     // should diagnose them.
83     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
84         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
85       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
86       if (DC && !DC->hasAttr<UnusedAttr>())
87         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
88     }
89   }
90 }
91 
92 /// Emit a note explaining that this function is deleted.
93 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
94   assert(Decl->isDeleted());
95 
96   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
97 
98   if (Method && Method->isDeleted() && Method->isDefaulted()) {
99     // If the method was explicitly defaulted, point at that declaration.
100     if (!Method->isImplicit())
101       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
102 
103     // Try to diagnose why this special member function was implicitly
104     // deleted. This might fail, if that reason no longer applies.
105     CXXSpecialMember CSM = getSpecialMember(Method);
106     if (CSM != CXXInvalid)
107       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
108 
109     return;
110   }
111 
112   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
113   if (Ctor && Ctor->isInheritingConstructor())
114     return NoteDeletedInheritingConstructor(Ctor);
115 
116   Diag(Decl->getLocation(), diag::note_availability_specified_here)
117     << Decl << true;
118 }
119 
120 /// Determine whether a FunctionDecl was ever declared with an
121 /// explicit storage class.
122 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
123   for (auto I : D->redecls()) {
124     if (I->getStorageClass() != SC_None)
125       return true;
126   }
127   return false;
128 }
129 
130 /// Check whether we're in an extern inline function and referring to a
131 /// variable or function with internal linkage (C11 6.7.4p3).
132 ///
133 /// This is only a warning because we used to silently accept this code, but
134 /// in many cases it will not behave correctly. This is not enabled in C++ mode
135 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
136 /// and so while there may still be user mistakes, most of the time we can't
137 /// prove that there are errors.
138 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
139                                                       const NamedDecl *D,
140                                                       SourceLocation Loc) {
141   // This is disabled under C++; there are too many ways for this to fire in
142   // contexts where the warning is a false positive, or where it is technically
143   // correct but benign.
144   if (S.getLangOpts().CPlusPlus)
145     return;
146 
147   // Check if this is an inlined function or method.
148   FunctionDecl *Current = S.getCurFunctionDecl();
149   if (!Current)
150     return;
151   if (!Current->isInlined())
152     return;
153   if (!Current->isExternallyVisible())
154     return;
155 
156   // Check if the decl has internal linkage.
157   if (D->getFormalLinkage() != InternalLinkage)
158     return;
159 
160   // Downgrade from ExtWarn to Extension if
161   //  (1) the supposedly external inline function is in the main file,
162   //      and probably won't be included anywhere else.
163   //  (2) the thing we're referencing is a pure function.
164   //  (3) the thing we're referencing is another inline function.
165   // This last can give us false negatives, but it's better than warning on
166   // wrappers for simple C library functions.
167   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
168   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
169   if (!DowngradeWarning && UsedFn)
170     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
171 
172   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
173                                : diag::ext_internal_in_extern_inline)
174     << /*IsVar=*/!UsedFn << D;
175 
176   S.MaybeSuggestAddingStaticToDecl(Current);
177 
178   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
179       << D;
180 }
181 
182 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
183   const FunctionDecl *First = Cur->getFirstDecl();
184 
185   // Suggest "static" on the function, if possible.
186   if (!hasAnyExplicitStorageClass(First)) {
187     SourceLocation DeclBegin = First->getSourceRange().getBegin();
188     Diag(DeclBegin, diag::note_convert_inline_to_static)
189       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
190   }
191 }
192 
193 /// Determine whether the use of this declaration is valid, and
194 /// emit any corresponding diagnostics.
195 ///
196 /// This routine diagnoses various problems with referencing
197 /// declarations that can occur when using a declaration. For example,
198 /// it might warn if a deprecated or unavailable declaration is being
199 /// used, or produce an error (and return true) if a C++0x deleted
200 /// function is being used.
201 ///
202 /// \returns true if there was an error (this declaration cannot be
203 /// referenced), false otherwise.
204 ///
205 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
206                              const ObjCInterfaceDecl *UnknownObjCClass,
207                              bool ObjCPropertyAccess,
208                              bool AvoidPartialAvailabilityChecks) {
209   SourceLocation Loc = Locs.front();
210   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
211     // If there were any diagnostics suppressed by template argument deduction,
212     // emit them now.
213     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
214     if (Pos != SuppressedDiagnostics.end()) {
215       for (const PartialDiagnosticAt &Suppressed : Pos->second)
216         Diag(Suppressed.first, Suppressed.second);
217 
218       // Clear out the list of suppressed diagnostics, so that we don't emit
219       // them again for this specialization. However, we don't obsolete this
220       // entry from the table, because we want to avoid ever emitting these
221       // diagnostics again.
222       Pos->second.clear();
223     }
224 
225     // C++ [basic.start.main]p3:
226     //   The function 'main' shall not be used within a program.
227     if (cast<FunctionDecl>(D)->isMain())
228       Diag(Loc, diag::ext_main_used);
229   }
230 
231   // See if this is an auto-typed variable whose initializer we are parsing.
232   if (ParsingInitForAutoVars.count(D)) {
233     if (isa<BindingDecl>(D)) {
234       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
235         << D->getDeclName();
236     } else {
237       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
238         << D->getDeclName() << cast<VarDecl>(D)->getType();
239     }
240     return true;
241   }
242 
243   // See if this is a deleted function.
244   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
245     if (FD->isDeleted()) {
246       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
247       if (Ctor && Ctor->isInheritingConstructor())
248         Diag(Loc, diag::err_deleted_inherited_ctor_use)
249             << Ctor->getParent()
250             << Ctor->getInheritedConstructor().getConstructor()->getParent();
251       else
252         Diag(Loc, diag::err_deleted_function_use);
253       NoteDeletedFunction(FD);
254       return true;
255     }
256 
257     // If the function has a deduced return type, and we can't deduce it,
258     // then we can't use it either.
259     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
260         DeduceReturnType(FD, Loc))
261       return true;
262 
263     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
264       return true;
265   }
266 
267   auto getReferencedObjCProp = [](const NamedDecl *D) ->
268                                       const ObjCPropertyDecl * {
269     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
270       return MD->findPropertyDecl();
271     return nullptr;
272   };
273   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
274     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
275       return true;
276   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
277       return true;
278   }
279 
280   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
281   // Only the variables omp_in and omp_out are allowed in the combiner.
282   // Only the variables omp_priv and omp_orig are allowed in the
283   // initializer-clause.
284   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
285   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
286       isa<VarDecl>(D)) {
287     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
288         << getCurFunction()->HasOMPDeclareReductionCombiner;
289     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
290     return true;
291   }
292 
293   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
294                              AvoidPartialAvailabilityChecks);
295 
296   DiagnoseUnusedOfDecl(*this, D, Loc);
297 
298   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
299 
300   return false;
301 }
302 
303 /// Retrieve the message suffix that should be added to a
304 /// diagnostic complaining about the given function being deleted or
305 /// unavailable.
306 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
307   std::string Message;
308   if (FD->getAvailability(&Message))
309     return ": " + Message;
310 
311   return std::string();
312 }
313 
314 /// DiagnoseSentinelCalls - This routine checks whether a call or
315 /// message-send is to a declaration with the sentinel attribute, and
316 /// if so, it checks that the requirements of the sentinel are
317 /// satisfied.
318 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
319                                  ArrayRef<Expr *> Args) {
320   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
321   if (!attr)
322     return;
323 
324   // The number of formal parameters of the declaration.
325   unsigned numFormalParams;
326 
327   // The kind of declaration.  This is also an index into a %select in
328   // the diagnostic.
329   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
330 
331   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
332     numFormalParams = MD->param_size();
333     calleeType = CT_Method;
334   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
335     numFormalParams = FD->param_size();
336     calleeType = CT_Function;
337   } else if (isa<VarDecl>(D)) {
338     QualType type = cast<ValueDecl>(D)->getType();
339     const FunctionType *fn = nullptr;
340     if (const PointerType *ptr = type->getAs<PointerType>()) {
341       fn = ptr->getPointeeType()->getAs<FunctionType>();
342       if (!fn) return;
343       calleeType = CT_Function;
344     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
345       fn = ptr->getPointeeType()->castAs<FunctionType>();
346       calleeType = CT_Block;
347     } else {
348       return;
349     }
350 
351     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
352       numFormalParams = proto->getNumParams();
353     } else {
354       numFormalParams = 0;
355     }
356   } else {
357     return;
358   }
359 
360   // "nullPos" is the number of formal parameters at the end which
361   // effectively count as part of the variadic arguments.  This is
362   // useful if you would prefer to not have *any* formal parameters,
363   // but the language forces you to have at least one.
364   unsigned nullPos = attr->getNullPos();
365   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
366   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
367 
368   // The number of arguments which should follow the sentinel.
369   unsigned numArgsAfterSentinel = attr->getSentinel();
370 
371   // If there aren't enough arguments for all the formal parameters,
372   // the sentinel, and the args after the sentinel, complain.
373   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
374     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
375     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
376     return;
377   }
378 
379   // Otherwise, find the sentinel expression.
380   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
381   if (!sentinelExpr) return;
382   if (sentinelExpr->isValueDependent()) return;
383   if (Context.isSentinelNullExpr(sentinelExpr)) return;
384 
385   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
386   // or 'NULL' if those are actually defined in the context.  Only use
387   // 'nil' for ObjC methods, where it's much more likely that the
388   // variadic arguments form a list of object pointers.
389   SourceLocation MissingNilLoc
390     = getLocForEndOfToken(sentinelExpr->getLocEnd());
391   std::string NullValue;
392   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
393     NullValue = "nil";
394   else if (getLangOpts().CPlusPlus11)
395     NullValue = "nullptr";
396   else if (PP.isMacroDefined("NULL"))
397     NullValue = "NULL";
398   else
399     NullValue = "(void*) 0";
400 
401   if (MissingNilLoc.isInvalid())
402     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
403   else
404     Diag(MissingNilLoc, diag::warn_missing_sentinel)
405       << int(calleeType)
406       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
407   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
408 }
409 
410 SourceRange Sema::getExprRange(Expr *E) const {
411   return E ? E->getSourceRange() : SourceRange();
412 }
413 
414 //===----------------------------------------------------------------------===//
415 //  Standard Promotions and Conversions
416 //===----------------------------------------------------------------------===//
417 
418 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
419 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
420   // Handle any placeholder expressions which made it here.
421   if (E->getType()->isPlaceholderType()) {
422     ExprResult result = CheckPlaceholderExpr(E);
423     if (result.isInvalid()) return ExprError();
424     E = result.get();
425   }
426 
427   QualType Ty = E->getType();
428   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
429 
430   if (Ty->isFunctionType()) {
431     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
432       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
433         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
434           return ExprError();
435 
436     E = ImpCastExprToType(E, Context.getPointerType(Ty),
437                           CK_FunctionToPointerDecay).get();
438   } else if (Ty->isArrayType()) {
439     // In C90 mode, arrays only promote to pointers if the array expression is
440     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
441     // type 'array of type' is converted to an expression that has type 'pointer
442     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
443     // that has type 'array of type' ...".  The relevant change is "an lvalue"
444     // (C90) to "an expression" (C99).
445     //
446     // C++ 4.2p1:
447     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
448     // T" can be converted to an rvalue of type "pointer to T".
449     //
450     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
451       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
452                             CK_ArrayToPointerDecay).get();
453   }
454   return E;
455 }
456 
457 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
458   // Check to see if we are dereferencing a null pointer.  If so,
459   // and if not volatile-qualified, this is undefined behavior that the
460   // optimizer will delete, so warn about it.  People sometimes try to use this
461   // to get a deterministic trap and are surprised by clang's behavior.  This
462   // only handles the pattern "*null", which is a very syntactic check.
463   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
464     if (UO->getOpcode() == UO_Deref &&
465         UO->getSubExpr()->IgnoreParenCasts()->
466           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
467         !UO->getType().isVolatileQualified()) {
468     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
469                           S.PDiag(diag::warn_indirection_through_null)
470                             << UO->getSubExpr()->getSourceRange());
471     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
472                         S.PDiag(diag::note_indirection_through_null));
473   }
474 }
475 
476 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
477                                     SourceLocation AssignLoc,
478                                     const Expr* RHS) {
479   const ObjCIvarDecl *IV = OIRE->getDecl();
480   if (!IV)
481     return;
482 
483   DeclarationName MemberName = IV->getDeclName();
484   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
485   if (!Member || !Member->isStr("isa"))
486     return;
487 
488   const Expr *Base = OIRE->getBase();
489   QualType BaseType = Base->getType();
490   if (OIRE->isArrow())
491     BaseType = BaseType->getPointeeType();
492   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
493     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
494       ObjCInterfaceDecl *ClassDeclared = nullptr;
495       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
496       if (!ClassDeclared->getSuperClass()
497           && (*ClassDeclared->ivar_begin()) == IV) {
498         if (RHS) {
499           NamedDecl *ObjectSetClass =
500             S.LookupSingleName(S.TUScope,
501                                &S.Context.Idents.get("object_setClass"),
502                                SourceLocation(), S.LookupOrdinaryName);
503           if (ObjectSetClass) {
504             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
505             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
506             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
507             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
508                                                      AssignLoc), ",") <<
509             FixItHint::CreateInsertion(RHSLocEnd, ")");
510           }
511           else
512             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
513         } else {
514           NamedDecl *ObjectGetClass =
515             S.LookupSingleName(S.TUScope,
516                                &S.Context.Idents.get("object_getClass"),
517                                SourceLocation(), S.LookupOrdinaryName);
518           if (ObjectGetClass)
519             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
520             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
521             FixItHint::CreateReplacement(
522                                          SourceRange(OIRE->getOpLoc(),
523                                                      OIRE->getLocEnd()), ")");
524           else
525             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
526         }
527         S.Diag(IV->getLocation(), diag::note_ivar_decl);
528       }
529     }
530 }
531 
532 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
533   // Handle any placeholder expressions which made it here.
534   if (E->getType()->isPlaceholderType()) {
535     ExprResult result = CheckPlaceholderExpr(E);
536     if (result.isInvalid()) return ExprError();
537     E = result.get();
538   }
539 
540   // C++ [conv.lval]p1:
541   //   A glvalue of a non-function, non-array type T can be
542   //   converted to a prvalue.
543   if (!E->isGLValue()) return E;
544 
545   QualType T = E->getType();
546   assert(!T.isNull() && "r-value conversion on typeless expression?");
547 
548   // We don't want to throw lvalue-to-rvalue casts on top of
549   // expressions of certain types in C++.
550   if (getLangOpts().CPlusPlus &&
551       (E->getType() == Context.OverloadTy ||
552        T->isDependentType() ||
553        T->isRecordType()))
554     return E;
555 
556   // The C standard is actually really unclear on this point, and
557   // DR106 tells us what the result should be but not why.  It's
558   // generally best to say that void types just doesn't undergo
559   // lvalue-to-rvalue at all.  Note that expressions of unqualified
560   // 'void' type are never l-values, but qualified void can be.
561   if (T->isVoidType())
562     return E;
563 
564   // OpenCL usually rejects direct accesses to values of 'half' type.
565   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
566       T->isHalfType()) {
567     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
568       << 0 << T;
569     return ExprError();
570   }
571 
572   CheckForNullPointerDereference(*this, E);
573   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
574     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
575                                      &Context.Idents.get("object_getClass"),
576                                      SourceLocation(), LookupOrdinaryName);
577     if (ObjectGetClass)
578       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
579         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
580         FixItHint::CreateReplacement(
581                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
582     else
583       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
584   }
585   else if (const ObjCIvarRefExpr *OIRE =
586             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
587     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
588 
589   // C++ [conv.lval]p1:
590   //   [...] If T is a non-class type, the type of the prvalue is the
591   //   cv-unqualified version of T. Otherwise, the type of the
592   //   rvalue is T.
593   //
594   // C99 6.3.2.1p2:
595   //   If the lvalue has qualified type, the value has the unqualified
596   //   version of the type of the lvalue; otherwise, the value has the
597   //   type of the lvalue.
598   if (T.hasQualifiers())
599     T = T.getUnqualifiedType();
600 
601   // Under the MS ABI, lock down the inheritance model now.
602   if (T->isMemberPointerType() &&
603       Context.getTargetInfo().getCXXABI().isMicrosoft())
604     (void)isCompleteType(E->getExprLoc(), T);
605 
606   UpdateMarkingForLValueToRValue(E);
607 
608   // Loading a __weak object implicitly retains the value, so we need a cleanup to
609   // balance that.
610   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
611     Cleanup.setExprNeedsCleanups(true);
612 
613   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
614                                             nullptr, VK_RValue);
615 
616   // C11 6.3.2.1p2:
617   //   ... if the lvalue has atomic type, the value has the non-atomic version
618   //   of the type of the lvalue ...
619   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
620     T = Atomic->getValueType().getUnqualifiedType();
621     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
622                                    nullptr, VK_RValue);
623   }
624 
625   return Res;
626 }
627 
628 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
629   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
630   if (Res.isInvalid())
631     return ExprError();
632   Res = DefaultLvalueConversion(Res.get());
633   if (Res.isInvalid())
634     return ExprError();
635   return Res;
636 }
637 
638 /// CallExprUnaryConversions - a special case of an unary conversion
639 /// performed on a function designator of a call expression.
640 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
641   QualType Ty = E->getType();
642   ExprResult Res = E;
643   // Only do implicit cast for a function type, but not for a pointer
644   // to function type.
645   if (Ty->isFunctionType()) {
646     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
647                             CK_FunctionToPointerDecay).get();
648     if (Res.isInvalid())
649       return ExprError();
650   }
651   Res = DefaultLvalueConversion(Res.get());
652   if (Res.isInvalid())
653     return ExprError();
654   return Res.get();
655 }
656 
657 /// UsualUnaryConversions - Performs various conversions that are common to most
658 /// operators (C99 6.3). The conversions of array and function types are
659 /// sometimes suppressed. For example, the array->pointer conversion doesn't
660 /// apply if the array is an argument to the sizeof or address (&) operators.
661 /// In these instances, this routine should *not* be called.
662 ExprResult Sema::UsualUnaryConversions(Expr *E) {
663   // First, convert to an r-value.
664   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
665   if (Res.isInvalid())
666     return ExprError();
667   E = Res.get();
668 
669   QualType Ty = E->getType();
670   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
671 
672   // Half FP have to be promoted to float unless it is natively supported
673   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
674     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
675 
676   // Try to perform integral promotions if the object has a theoretically
677   // promotable type.
678   if (Ty->isIntegralOrUnscopedEnumerationType()) {
679     // C99 6.3.1.1p2:
680     //
681     //   The following may be used in an expression wherever an int or
682     //   unsigned int may be used:
683     //     - an object or expression with an integer type whose integer
684     //       conversion rank is less than or equal to the rank of int
685     //       and unsigned int.
686     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
687     //
688     //   If an int can represent all values of the original type, the
689     //   value is converted to an int; otherwise, it is converted to an
690     //   unsigned int. These are called the integer promotions. All
691     //   other types are unchanged by the integer promotions.
692 
693     QualType PTy = Context.isPromotableBitField(E);
694     if (!PTy.isNull()) {
695       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
696       return E;
697     }
698     if (Ty->isPromotableIntegerType()) {
699       QualType PT = Context.getPromotedIntegerType(Ty);
700       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
701       return E;
702     }
703   }
704   return E;
705 }
706 
707 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
708 /// do not have a prototype. Arguments that have type float or __fp16
709 /// are promoted to double. All other argument types are converted by
710 /// UsualUnaryConversions().
711 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
712   QualType Ty = E->getType();
713   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
714 
715   ExprResult Res = UsualUnaryConversions(E);
716   if (Res.isInvalid())
717     return ExprError();
718   E = Res.get();
719 
720   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
721   // promote to double.
722   // Note that default argument promotion applies only to float (and
723   // half/fp16); it does not apply to _Float16.
724   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
725   if (BTy && (BTy->getKind() == BuiltinType::Half ||
726               BTy->getKind() == BuiltinType::Float)) {
727     if (getLangOpts().OpenCL &&
728         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
729         if (BTy->getKind() == BuiltinType::Half) {
730             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
731         }
732     } else {
733       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
734     }
735   }
736 
737   // C++ performs lvalue-to-rvalue conversion as a default argument
738   // promotion, even on class types, but note:
739   //   C++11 [conv.lval]p2:
740   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
741   //     operand or a subexpression thereof the value contained in the
742   //     referenced object is not accessed. Otherwise, if the glvalue
743   //     has a class type, the conversion copy-initializes a temporary
744   //     of type T from the glvalue and the result of the conversion
745   //     is a prvalue for the temporary.
746   // FIXME: add some way to gate this entire thing for correctness in
747   // potentially potentially evaluated contexts.
748   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
749     ExprResult Temp = PerformCopyInitialization(
750                        InitializedEntity::InitializeTemporary(E->getType()),
751                                                 E->getExprLoc(), E);
752     if (Temp.isInvalid())
753       return ExprError();
754     E = Temp.get();
755   }
756 
757   return E;
758 }
759 
760 /// Determine the degree of POD-ness for an expression.
761 /// Incomplete types are considered POD, since this check can be performed
762 /// when we're in an unevaluated context.
763 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
764   if (Ty->isIncompleteType()) {
765     // C++11 [expr.call]p7:
766     //   After these conversions, if the argument does not have arithmetic,
767     //   enumeration, pointer, pointer to member, or class type, the program
768     //   is ill-formed.
769     //
770     // Since we've already performed array-to-pointer and function-to-pointer
771     // decay, the only such type in C++ is cv void. This also handles
772     // initializer lists as variadic arguments.
773     if (Ty->isVoidType())
774       return VAK_Invalid;
775 
776     if (Ty->isObjCObjectType())
777       return VAK_Invalid;
778     return VAK_Valid;
779   }
780 
781   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
782     return VAK_Invalid;
783 
784   if (Ty.isCXX98PODType(Context))
785     return VAK_Valid;
786 
787   // C++11 [expr.call]p7:
788   //   Passing a potentially-evaluated argument of class type (Clause 9)
789   //   having a non-trivial copy constructor, a non-trivial move constructor,
790   //   or a non-trivial destructor, with no corresponding parameter,
791   //   is conditionally-supported with implementation-defined semantics.
792   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
793     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
794       if (!Record->hasNonTrivialCopyConstructor() &&
795           !Record->hasNonTrivialMoveConstructor() &&
796           !Record->hasNonTrivialDestructor())
797         return VAK_ValidInCXX11;
798 
799   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
800     return VAK_Valid;
801 
802   if (Ty->isObjCObjectType())
803     return VAK_Invalid;
804 
805   if (getLangOpts().MSVCCompat)
806     return VAK_MSVCUndefined;
807 
808   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
809   // permitted to reject them. We should consider doing so.
810   return VAK_Undefined;
811 }
812 
813 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
814   // Don't allow one to pass an Objective-C interface to a vararg.
815   const QualType &Ty = E->getType();
816   VarArgKind VAK = isValidVarArgType(Ty);
817 
818   // Complain about passing non-POD types through varargs.
819   switch (VAK) {
820   case VAK_ValidInCXX11:
821     DiagRuntimeBehavior(
822         E->getLocStart(), nullptr,
823         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
824           << Ty << CT);
825     LLVM_FALLTHROUGH;
826   case VAK_Valid:
827     if (Ty->isRecordType()) {
828       // This is unlikely to be what the user intended. If the class has a
829       // 'c_str' member function, the user probably meant to call that.
830       DiagRuntimeBehavior(E->getLocStart(), nullptr,
831                           PDiag(diag::warn_pass_class_arg_to_vararg)
832                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
833     }
834     break;
835 
836   case VAK_Undefined:
837   case VAK_MSVCUndefined:
838     DiagRuntimeBehavior(
839         E->getLocStart(), nullptr,
840         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
841           << getLangOpts().CPlusPlus11 << Ty << CT);
842     break;
843 
844   case VAK_Invalid:
845     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
846       Diag(E->getLocStart(),
847            diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
848     else if (Ty->isObjCObjectType())
849       DiagRuntimeBehavior(
850           E->getLocStart(), nullptr,
851           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
852             << Ty << CT);
853     else
854       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
855         << isa<InitListExpr>(E) << Ty << CT;
856     break;
857   }
858 }
859 
860 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
861 /// will create a trap if the resulting type is not a POD type.
862 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
863                                                   FunctionDecl *FDecl) {
864   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
865     // Strip the unbridged-cast placeholder expression off, if applicable.
866     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
867         (CT == VariadicMethod ||
868          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
869       E = stripARCUnbridgedCast(E);
870 
871     // Otherwise, do normal placeholder checking.
872     } else {
873       ExprResult ExprRes = CheckPlaceholderExpr(E);
874       if (ExprRes.isInvalid())
875         return ExprError();
876       E = ExprRes.get();
877     }
878   }
879 
880   ExprResult ExprRes = DefaultArgumentPromotion(E);
881   if (ExprRes.isInvalid())
882     return ExprError();
883   E = ExprRes.get();
884 
885   // Diagnostics regarding non-POD argument types are
886   // emitted along with format string checking in Sema::CheckFunctionCall().
887   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
888     // Turn this into a trap.
889     CXXScopeSpec SS;
890     SourceLocation TemplateKWLoc;
891     UnqualifiedId Name;
892     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
893                        E->getLocStart());
894     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
895                                           Name, true, false);
896     if (TrapFn.isInvalid())
897       return ExprError();
898 
899     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
900                                     E->getLocStart(), None,
901                                     E->getLocEnd());
902     if (Call.isInvalid())
903       return ExprError();
904 
905     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
906                                   Call.get(), E);
907     if (Comma.isInvalid())
908       return ExprError();
909     return Comma.get();
910   }
911 
912   if (!getLangOpts().CPlusPlus &&
913       RequireCompleteType(E->getExprLoc(), E->getType(),
914                           diag::err_call_incomplete_argument))
915     return ExprError();
916 
917   return E;
918 }
919 
920 /// Converts an integer to complex float type.  Helper function of
921 /// UsualArithmeticConversions()
922 ///
923 /// \return false if the integer expression is an integer type and is
924 /// successfully converted to the complex type.
925 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
926                                                   ExprResult &ComplexExpr,
927                                                   QualType IntTy,
928                                                   QualType ComplexTy,
929                                                   bool SkipCast) {
930   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
931   if (SkipCast) return false;
932   if (IntTy->isIntegerType()) {
933     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
934     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
935     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
936                                   CK_FloatingRealToComplex);
937   } else {
938     assert(IntTy->isComplexIntegerType());
939     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
940                                   CK_IntegralComplexToFloatingComplex);
941   }
942   return false;
943 }
944 
945 /// Handle arithmetic conversion with complex types.  Helper function of
946 /// UsualArithmeticConversions()
947 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
948                                              ExprResult &RHS, QualType LHSType,
949                                              QualType RHSType,
950                                              bool IsCompAssign) {
951   // if we have an integer operand, the result is the complex type.
952   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
953                                              /*skipCast*/false))
954     return LHSType;
955   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
956                                              /*skipCast*/IsCompAssign))
957     return RHSType;
958 
959   // This handles complex/complex, complex/float, or float/complex.
960   // When both operands are complex, the shorter operand is converted to the
961   // type of the longer, and that is the type of the result. This corresponds
962   // to what is done when combining two real floating-point operands.
963   // The fun begins when size promotion occur across type domains.
964   // From H&S 6.3.4: When one operand is complex and the other is a real
965   // floating-point type, the less precise type is converted, within it's
966   // real or complex domain, to the precision of the other type. For example,
967   // when combining a "long double" with a "double _Complex", the
968   // "double _Complex" is promoted to "long double _Complex".
969 
970   // Compute the rank of the two types, regardless of whether they are complex.
971   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
972 
973   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
974   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
975   QualType LHSElementType =
976       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
977   QualType RHSElementType =
978       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
979 
980   QualType ResultType = S.Context.getComplexType(LHSElementType);
981   if (Order < 0) {
982     // Promote the precision of the LHS if not an assignment.
983     ResultType = S.Context.getComplexType(RHSElementType);
984     if (!IsCompAssign) {
985       if (LHSComplexType)
986         LHS =
987             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
988       else
989         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
990     }
991   } else if (Order > 0) {
992     // Promote the precision of the RHS.
993     if (RHSComplexType)
994       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
995     else
996       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
997   }
998   return ResultType;
999 }
1000 
1001 /// Handle arithmetic conversion from integer to float.  Helper function
1002 /// of UsualArithmeticConversions()
1003 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1004                                            ExprResult &IntExpr,
1005                                            QualType FloatTy, QualType IntTy,
1006                                            bool ConvertFloat, bool ConvertInt) {
1007   if (IntTy->isIntegerType()) {
1008     if (ConvertInt)
1009       // Convert intExpr to the lhs floating point type.
1010       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1011                                     CK_IntegralToFloating);
1012     return FloatTy;
1013   }
1014 
1015   // Convert both sides to the appropriate complex float.
1016   assert(IntTy->isComplexIntegerType());
1017   QualType result = S.Context.getComplexType(FloatTy);
1018 
1019   // _Complex int -> _Complex float
1020   if (ConvertInt)
1021     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1022                                   CK_IntegralComplexToFloatingComplex);
1023 
1024   // float -> _Complex float
1025   if (ConvertFloat)
1026     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1027                                     CK_FloatingRealToComplex);
1028 
1029   return result;
1030 }
1031 
1032 /// Handle arithmethic conversion with floating point types.  Helper
1033 /// function of UsualArithmeticConversions()
1034 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1035                                       ExprResult &RHS, QualType LHSType,
1036                                       QualType RHSType, bool IsCompAssign) {
1037   bool LHSFloat = LHSType->isRealFloatingType();
1038   bool RHSFloat = RHSType->isRealFloatingType();
1039 
1040   // If we have two real floating types, convert the smaller operand
1041   // to the bigger result.
1042   if (LHSFloat && RHSFloat) {
1043     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1044     if (order > 0) {
1045       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1046       return LHSType;
1047     }
1048 
1049     assert(order < 0 && "illegal float comparison");
1050     if (!IsCompAssign)
1051       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1052     return RHSType;
1053   }
1054 
1055   if (LHSFloat) {
1056     // Half FP has to be promoted to float unless it is natively supported
1057     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1058       LHSType = S.Context.FloatTy;
1059 
1060     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1061                                       /*convertFloat=*/!IsCompAssign,
1062                                       /*convertInt=*/ true);
1063   }
1064   assert(RHSFloat);
1065   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1066                                     /*convertInt=*/ true,
1067                                     /*convertFloat=*/!IsCompAssign);
1068 }
1069 
1070 /// Diagnose attempts to convert between __float128 and long double if
1071 /// there is no support for such conversion. Helper function of
1072 /// UsualArithmeticConversions().
1073 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1074                                       QualType RHSType) {
1075   /*  No issue converting if at least one of the types is not a floating point
1076       type or the two types have the same rank.
1077   */
1078   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1079       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1080     return false;
1081 
1082   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1083          "The remaining types must be floating point types.");
1084 
1085   auto *LHSComplex = LHSType->getAs<ComplexType>();
1086   auto *RHSComplex = RHSType->getAs<ComplexType>();
1087 
1088   QualType LHSElemType = LHSComplex ?
1089     LHSComplex->getElementType() : LHSType;
1090   QualType RHSElemType = RHSComplex ?
1091     RHSComplex->getElementType() : RHSType;
1092 
1093   // No issue if the two types have the same representation
1094   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1095       &S.Context.getFloatTypeSemantics(RHSElemType))
1096     return false;
1097 
1098   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1099                                 RHSElemType == S.Context.LongDoubleTy);
1100   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1101                             RHSElemType == S.Context.Float128Ty);
1102 
1103   // We've handled the situation where __float128 and long double have the same
1104   // representation. We allow all conversions for all possible long double types
1105   // except PPC's double double.
1106   return Float128AndLongDouble &&
1107     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1108      &llvm::APFloat::PPCDoubleDouble());
1109 }
1110 
1111 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1112 
1113 namespace {
1114 /// These helper callbacks are placed in an anonymous namespace to
1115 /// permit their use as function template parameters.
1116 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1117   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1118 }
1119 
1120 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1121   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1122                              CK_IntegralComplexCast);
1123 }
1124 }
1125 
1126 /// Handle integer arithmetic conversions.  Helper function of
1127 /// UsualArithmeticConversions()
1128 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1129 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1130                                         ExprResult &RHS, QualType LHSType,
1131                                         QualType RHSType, bool IsCompAssign) {
1132   // The rules for this case are in C99 6.3.1.8
1133   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1134   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1135   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1136   if (LHSSigned == RHSSigned) {
1137     // Same signedness; use the higher-ranked type
1138     if (order >= 0) {
1139       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1140       return LHSType;
1141     } else if (!IsCompAssign)
1142       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1143     return RHSType;
1144   } else if (order != (LHSSigned ? 1 : -1)) {
1145     // The unsigned type has greater than or equal rank to the
1146     // signed type, so use the unsigned type
1147     if (RHSSigned) {
1148       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1149       return LHSType;
1150     } else if (!IsCompAssign)
1151       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1152     return RHSType;
1153   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1154     // The two types are different widths; if we are here, that
1155     // means the signed type is larger than the unsigned type, so
1156     // use the signed type.
1157     if (LHSSigned) {
1158       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1159       return LHSType;
1160     } else if (!IsCompAssign)
1161       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1162     return RHSType;
1163   } else {
1164     // The signed type is higher-ranked than the unsigned type,
1165     // but isn't actually any bigger (like unsigned int and long
1166     // on most 32-bit systems).  Use the unsigned type corresponding
1167     // to the signed type.
1168     QualType result =
1169       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1170     RHS = (*doRHSCast)(S, RHS.get(), result);
1171     if (!IsCompAssign)
1172       LHS = (*doLHSCast)(S, LHS.get(), result);
1173     return result;
1174   }
1175 }
1176 
1177 /// Handle conversions with GCC complex int extension.  Helper function
1178 /// of UsualArithmeticConversions()
1179 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1180                                            ExprResult &RHS, QualType LHSType,
1181                                            QualType RHSType,
1182                                            bool IsCompAssign) {
1183   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1184   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1185 
1186   if (LHSComplexInt && RHSComplexInt) {
1187     QualType LHSEltType = LHSComplexInt->getElementType();
1188     QualType RHSEltType = RHSComplexInt->getElementType();
1189     QualType ScalarType =
1190       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1191         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1192 
1193     return S.Context.getComplexType(ScalarType);
1194   }
1195 
1196   if (LHSComplexInt) {
1197     QualType LHSEltType = LHSComplexInt->getElementType();
1198     QualType ScalarType =
1199       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1200         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1201     QualType ComplexType = S.Context.getComplexType(ScalarType);
1202     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1203                               CK_IntegralRealToComplex);
1204 
1205     return ComplexType;
1206   }
1207 
1208   assert(RHSComplexInt);
1209 
1210   QualType RHSEltType = RHSComplexInt->getElementType();
1211   QualType ScalarType =
1212     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1213       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1214   QualType ComplexType = S.Context.getComplexType(ScalarType);
1215 
1216   if (!IsCompAssign)
1217     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1218                               CK_IntegralRealToComplex);
1219   return ComplexType;
1220 }
1221 
1222 /// UsualArithmeticConversions - Performs various conversions that are common to
1223 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1224 /// routine returns the first non-arithmetic type found. The client is
1225 /// responsible for emitting appropriate error diagnostics.
1226 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1227                                           bool IsCompAssign) {
1228   if (!IsCompAssign) {
1229     LHS = UsualUnaryConversions(LHS.get());
1230     if (LHS.isInvalid())
1231       return QualType();
1232   }
1233 
1234   RHS = UsualUnaryConversions(RHS.get());
1235   if (RHS.isInvalid())
1236     return QualType();
1237 
1238   // For conversion purposes, we ignore any qualifiers.
1239   // For example, "const float" and "float" are equivalent.
1240   QualType LHSType =
1241     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1242   QualType RHSType =
1243     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1244 
1245   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1246   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1247     LHSType = AtomicLHS->getValueType();
1248 
1249   // If both types are identical, no conversion is needed.
1250   if (LHSType == RHSType)
1251     return LHSType;
1252 
1253   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1254   // The caller can deal with this (e.g. pointer + int).
1255   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1256     return QualType();
1257 
1258   // Apply unary and bitfield promotions to the LHS's type.
1259   QualType LHSUnpromotedType = LHSType;
1260   if (LHSType->isPromotableIntegerType())
1261     LHSType = Context.getPromotedIntegerType(LHSType);
1262   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1263   if (!LHSBitfieldPromoteTy.isNull())
1264     LHSType = LHSBitfieldPromoteTy;
1265   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1266     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1267 
1268   // If both types are identical, no conversion is needed.
1269   if (LHSType == RHSType)
1270     return LHSType;
1271 
1272   // At this point, we have two different arithmetic types.
1273 
1274   // Diagnose attempts to convert between __float128 and long double where
1275   // such conversions currently can't be handled.
1276   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1277     return QualType();
1278 
1279   // Handle complex types first (C99 6.3.1.8p1).
1280   if (LHSType->isComplexType() || RHSType->isComplexType())
1281     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1282                                         IsCompAssign);
1283 
1284   // Now handle "real" floating types (i.e. float, double, long double).
1285   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1286     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1287                                  IsCompAssign);
1288 
1289   // Handle GCC complex int extension.
1290   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1291     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1292                                       IsCompAssign);
1293 
1294   // Finally, we have two differing integer types.
1295   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1296            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1297 }
1298 
1299 
1300 //===----------------------------------------------------------------------===//
1301 //  Semantic Analysis for various Expression Types
1302 //===----------------------------------------------------------------------===//
1303 
1304 
1305 ExprResult
1306 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1307                                 SourceLocation DefaultLoc,
1308                                 SourceLocation RParenLoc,
1309                                 Expr *ControllingExpr,
1310                                 ArrayRef<ParsedType> ArgTypes,
1311                                 ArrayRef<Expr *> ArgExprs) {
1312   unsigned NumAssocs = ArgTypes.size();
1313   assert(NumAssocs == ArgExprs.size());
1314 
1315   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1316   for (unsigned i = 0; i < NumAssocs; ++i) {
1317     if (ArgTypes[i])
1318       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1319     else
1320       Types[i] = nullptr;
1321   }
1322 
1323   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1324                                              ControllingExpr,
1325                                              llvm::makeArrayRef(Types, NumAssocs),
1326                                              ArgExprs);
1327   delete [] Types;
1328   return ER;
1329 }
1330 
1331 ExprResult
1332 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1333                                  SourceLocation DefaultLoc,
1334                                  SourceLocation RParenLoc,
1335                                  Expr *ControllingExpr,
1336                                  ArrayRef<TypeSourceInfo *> Types,
1337                                  ArrayRef<Expr *> Exprs) {
1338   unsigned NumAssocs = Types.size();
1339   assert(NumAssocs == Exprs.size());
1340 
1341   // Decay and strip qualifiers for the controlling expression type, and handle
1342   // placeholder type replacement. See committee discussion from WG14 DR423.
1343   {
1344     EnterExpressionEvaluationContext Unevaluated(
1345         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1346     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1347     if (R.isInvalid())
1348       return ExprError();
1349     ControllingExpr = R.get();
1350   }
1351 
1352   // The controlling expression is an unevaluated operand, so side effects are
1353   // likely unintended.
1354   if (!inTemplateInstantiation() &&
1355       ControllingExpr->HasSideEffects(Context, false))
1356     Diag(ControllingExpr->getExprLoc(),
1357          diag::warn_side_effects_unevaluated_context);
1358 
1359   bool TypeErrorFound = false,
1360        IsResultDependent = ControllingExpr->isTypeDependent(),
1361        ContainsUnexpandedParameterPack
1362          = ControllingExpr->containsUnexpandedParameterPack();
1363 
1364   for (unsigned i = 0; i < NumAssocs; ++i) {
1365     if (Exprs[i]->containsUnexpandedParameterPack())
1366       ContainsUnexpandedParameterPack = true;
1367 
1368     if (Types[i]) {
1369       if (Types[i]->getType()->containsUnexpandedParameterPack())
1370         ContainsUnexpandedParameterPack = true;
1371 
1372       if (Types[i]->getType()->isDependentType()) {
1373         IsResultDependent = true;
1374       } else {
1375         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1376         // complete object type other than a variably modified type."
1377         unsigned D = 0;
1378         if (Types[i]->getType()->isIncompleteType())
1379           D = diag::err_assoc_type_incomplete;
1380         else if (!Types[i]->getType()->isObjectType())
1381           D = diag::err_assoc_type_nonobject;
1382         else if (Types[i]->getType()->isVariablyModifiedType())
1383           D = diag::err_assoc_type_variably_modified;
1384 
1385         if (D != 0) {
1386           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1387             << Types[i]->getTypeLoc().getSourceRange()
1388             << Types[i]->getType();
1389           TypeErrorFound = true;
1390         }
1391 
1392         // C11 6.5.1.1p2 "No two generic associations in the same generic
1393         // selection shall specify compatible types."
1394         for (unsigned j = i+1; j < NumAssocs; ++j)
1395           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1396               Context.typesAreCompatible(Types[i]->getType(),
1397                                          Types[j]->getType())) {
1398             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1399                  diag::err_assoc_compatible_types)
1400               << Types[j]->getTypeLoc().getSourceRange()
1401               << Types[j]->getType()
1402               << Types[i]->getType();
1403             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1404                  diag::note_compat_assoc)
1405               << Types[i]->getTypeLoc().getSourceRange()
1406               << Types[i]->getType();
1407             TypeErrorFound = true;
1408           }
1409       }
1410     }
1411   }
1412   if (TypeErrorFound)
1413     return ExprError();
1414 
1415   // If we determined that the generic selection is result-dependent, don't
1416   // try to compute the result expression.
1417   if (IsResultDependent)
1418     return new (Context) GenericSelectionExpr(
1419         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1420         ContainsUnexpandedParameterPack);
1421 
1422   SmallVector<unsigned, 1> CompatIndices;
1423   unsigned DefaultIndex = -1U;
1424   for (unsigned i = 0; i < NumAssocs; ++i) {
1425     if (!Types[i])
1426       DefaultIndex = i;
1427     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1428                                         Types[i]->getType()))
1429       CompatIndices.push_back(i);
1430   }
1431 
1432   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1433   // type compatible with at most one of the types named in its generic
1434   // association list."
1435   if (CompatIndices.size() > 1) {
1436     // We strip parens here because the controlling expression is typically
1437     // parenthesized in macro definitions.
1438     ControllingExpr = ControllingExpr->IgnoreParens();
1439     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1440       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1441       << (unsigned) CompatIndices.size();
1442     for (unsigned I : CompatIndices) {
1443       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1444            diag::note_compat_assoc)
1445         << Types[I]->getTypeLoc().getSourceRange()
1446         << Types[I]->getType();
1447     }
1448     return ExprError();
1449   }
1450 
1451   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1452   // its controlling expression shall have type compatible with exactly one of
1453   // the types named in its generic association list."
1454   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1455     // We strip parens here because the controlling expression is typically
1456     // parenthesized in macro definitions.
1457     ControllingExpr = ControllingExpr->IgnoreParens();
1458     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1459       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1460     return ExprError();
1461   }
1462 
1463   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1464   // type name that is compatible with the type of the controlling expression,
1465   // then the result expression of the generic selection is the expression
1466   // in that generic association. Otherwise, the result expression of the
1467   // generic selection is the expression in the default generic association."
1468   unsigned ResultIndex =
1469     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1470 
1471   return new (Context) GenericSelectionExpr(
1472       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1473       ContainsUnexpandedParameterPack, ResultIndex);
1474 }
1475 
1476 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1477 /// location of the token and the offset of the ud-suffix within it.
1478 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1479                                      unsigned Offset) {
1480   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1481                                         S.getLangOpts());
1482 }
1483 
1484 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1485 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1486 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1487                                                  IdentifierInfo *UDSuffix,
1488                                                  SourceLocation UDSuffixLoc,
1489                                                  ArrayRef<Expr*> Args,
1490                                                  SourceLocation LitEndLoc) {
1491   assert(Args.size() <= 2 && "too many arguments for literal operator");
1492 
1493   QualType ArgTy[2];
1494   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1495     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1496     if (ArgTy[ArgIdx]->isArrayType())
1497       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1498   }
1499 
1500   DeclarationName OpName =
1501     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1502   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1503   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1504 
1505   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1506   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1507                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1508                               /*AllowStringTemplate*/ false,
1509                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1510     return ExprError();
1511 
1512   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1513 }
1514 
1515 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1516 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1517 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1518 /// multiple tokens.  However, the common case is that StringToks points to one
1519 /// string.
1520 ///
1521 ExprResult
1522 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1523   assert(!StringToks.empty() && "Must have at least one string!");
1524 
1525   StringLiteralParser Literal(StringToks, PP);
1526   if (Literal.hadError)
1527     return ExprError();
1528 
1529   SmallVector<SourceLocation, 4> StringTokLocs;
1530   for (const Token &Tok : StringToks)
1531     StringTokLocs.push_back(Tok.getLocation());
1532 
1533   QualType CharTy = Context.CharTy;
1534   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1535   if (Literal.isWide()) {
1536     CharTy = Context.getWideCharType();
1537     Kind = StringLiteral::Wide;
1538   } else if (Literal.isUTF8()) {
1539     if (getLangOpts().Char8)
1540       CharTy = Context.Char8Ty;
1541     Kind = StringLiteral::UTF8;
1542   } else if (Literal.isUTF16()) {
1543     CharTy = Context.Char16Ty;
1544     Kind = StringLiteral::UTF16;
1545   } else if (Literal.isUTF32()) {
1546     CharTy = Context.Char32Ty;
1547     Kind = StringLiteral::UTF32;
1548   } else if (Literal.isPascal()) {
1549     CharTy = Context.UnsignedCharTy;
1550   }
1551 
1552   QualType CharTyConst = CharTy;
1553   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1554   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1555     CharTyConst.addConst();
1556 
1557   CharTyConst = Context.adjustStringLiteralBaseType(CharTyConst);
1558 
1559   // Get an array type for the string, according to C99 6.4.5.  This includes
1560   // the nul terminator character as well as the string length for pascal
1561   // strings.
1562   QualType StrTy = Context.getConstantArrayType(
1563       CharTyConst, llvm::APInt(32, Literal.GetNumStringChars() + 1),
1564       ArrayType::Normal, 0);
1565 
1566   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1567   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1568                                              Kind, Literal.Pascal, StrTy,
1569                                              &StringTokLocs[0],
1570                                              StringTokLocs.size());
1571   if (Literal.getUDSuffix().empty())
1572     return Lit;
1573 
1574   // We're building a user-defined literal.
1575   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1576   SourceLocation UDSuffixLoc =
1577     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1578                    Literal.getUDSuffixOffset());
1579 
1580   // Make sure we're allowed user-defined literals here.
1581   if (!UDLScope)
1582     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1583 
1584   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1585   //   operator "" X (str, len)
1586   QualType SizeType = Context.getSizeType();
1587 
1588   DeclarationName OpName =
1589     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1590   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1591   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1592 
1593   QualType ArgTy[] = {
1594     Context.getArrayDecayedType(StrTy), SizeType
1595   };
1596 
1597   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1598   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1599                                 /*AllowRaw*/ false, /*AllowTemplate*/ false,
1600                                 /*AllowStringTemplate*/ true,
1601                                 /*DiagnoseMissing*/ true)) {
1602 
1603   case LOLR_Cooked: {
1604     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1605     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1606                                                     StringTokLocs[0]);
1607     Expr *Args[] = { Lit, LenArg };
1608 
1609     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1610   }
1611 
1612   case LOLR_StringTemplate: {
1613     TemplateArgumentListInfo ExplicitArgs;
1614 
1615     unsigned CharBits = Context.getIntWidth(CharTy);
1616     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1617     llvm::APSInt Value(CharBits, CharIsUnsigned);
1618 
1619     TemplateArgument TypeArg(CharTy);
1620     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1621     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1622 
1623     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1624       Value = Lit->getCodeUnit(I);
1625       TemplateArgument Arg(Context, Value, CharTy);
1626       TemplateArgumentLocInfo ArgInfo;
1627       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1628     }
1629     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1630                                     &ExplicitArgs);
1631   }
1632   case LOLR_Raw:
1633   case LOLR_Template:
1634   case LOLR_ErrorNoDiagnostic:
1635     llvm_unreachable("unexpected literal operator lookup result");
1636   case LOLR_Error:
1637     return ExprError();
1638   }
1639   llvm_unreachable("unexpected literal operator lookup result");
1640 }
1641 
1642 ExprResult
1643 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1644                        SourceLocation Loc,
1645                        const CXXScopeSpec *SS) {
1646   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1647   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1648 }
1649 
1650 /// BuildDeclRefExpr - Build an expression that references a
1651 /// declaration that does not require a closure capture.
1652 ExprResult
1653 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1654                        const DeclarationNameInfo &NameInfo,
1655                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1656                        const TemplateArgumentListInfo *TemplateArgs) {
1657   bool RefersToCapturedVariable =
1658       isa<VarDecl>(D) &&
1659       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1660 
1661   DeclRefExpr *E;
1662   if (isa<VarTemplateSpecializationDecl>(D)) {
1663     VarTemplateSpecializationDecl *VarSpec =
1664         cast<VarTemplateSpecializationDecl>(D);
1665 
1666     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1667                                         : NestedNameSpecifierLoc(),
1668                             VarSpec->getTemplateKeywordLoc(), D,
1669                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1670                             FoundD, TemplateArgs);
1671   } else {
1672     assert(!TemplateArgs && "No template arguments for non-variable"
1673                             " template specialization references");
1674     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1675                                         : NestedNameSpecifierLoc(),
1676                             SourceLocation(), D, RefersToCapturedVariable,
1677                             NameInfo, Ty, VK, FoundD);
1678   }
1679 
1680   MarkDeclRefReferenced(E);
1681 
1682   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1683       Ty.getObjCLifetime() == Qualifiers::OCL_Weak && !isUnevaluatedContext() &&
1684       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1685     getCurFunction()->recordUseOfWeak(E);
1686 
1687   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1688   if (IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
1689     FD = IFD->getAnonField();
1690   if (FD) {
1691     UnusedPrivateFields.remove(FD);
1692     // Just in case we're building an illegal pointer-to-member.
1693     if (FD->isBitField())
1694       E->setObjectKind(OK_BitField);
1695   }
1696 
1697   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1698   // designates a bit-field.
1699   if (auto *BD = dyn_cast<BindingDecl>(D))
1700     if (auto *BE = BD->getBinding())
1701       E->setObjectKind(BE->getObjectKind());
1702 
1703   return E;
1704 }
1705 
1706 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1707 /// possibly a list of template arguments.
1708 ///
1709 /// If this produces template arguments, it is permitted to call
1710 /// DecomposeTemplateName.
1711 ///
1712 /// This actually loses a lot of source location information for
1713 /// non-standard name kinds; we should consider preserving that in
1714 /// some way.
1715 void
1716 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1717                              TemplateArgumentListInfo &Buffer,
1718                              DeclarationNameInfo &NameInfo,
1719                              const TemplateArgumentListInfo *&TemplateArgs) {
1720   if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId) {
1721     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1722     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1723 
1724     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1725                                        Id.TemplateId->NumArgs);
1726     translateTemplateArguments(TemplateArgsPtr, Buffer);
1727 
1728     TemplateName TName = Id.TemplateId->Template.get();
1729     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1730     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1731     TemplateArgs = &Buffer;
1732   } else {
1733     NameInfo = GetNameFromUnqualifiedId(Id);
1734     TemplateArgs = nullptr;
1735   }
1736 }
1737 
1738 static void emitEmptyLookupTypoDiagnostic(
1739     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1740     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1741     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1742   DeclContext *Ctx =
1743       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1744   if (!TC) {
1745     // Emit a special diagnostic for failed member lookups.
1746     // FIXME: computing the declaration context might fail here (?)
1747     if (Ctx)
1748       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1749                                                  << SS.getRange();
1750     else
1751       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1752     return;
1753   }
1754 
1755   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1756   bool DroppedSpecifier =
1757       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1758   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1759                         ? diag::note_implicit_param_decl
1760                         : diag::note_previous_decl;
1761   if (!Ctx)
1762     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1763                          SemaRef.PDiag(NoteID));
1764   else
1765     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1766                                  << Typo << Ctx << DroppedSpecifier
1767                                  << SS.getRange(),
1768                          SemaRef.PDiag(NoteID));
1769 }
1770 
1771 /// Diagnose an empty lookup.
1772 ///
1773 /// \return false if new lookup candidates were found
1774 bool
1775 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1776                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1777                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1778                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1779   DeclarationName Name = R.getLookupName();
1780 
1781   unsigned diagnostic = diag::err_undeclared_var_use;
1782   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1783   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1784       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1785       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1786     diagnostic = diag::err_undeclared_use;
1787     diagnostic_suggest = diag::err_undeclared_use_suggest;
1788   }
1789 
1790   // If the original lookup was an unqualified lookup, fake an
1791   // unqualified lookup.  This is useful when (for example) the
1792   // original lookup would not have found something because it was a
1793   // dependent name.
1794   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1795   while (DC) {
1796     if (isa<CXXRecordDecl>(DC)) {
1797       LookupQualifiedName(R, DC);
1798 
1799       if (!R.empty()) {
1800         // Don't give errors about ambiguities in this lookup.
1801         R.suppressDiagnostics();
1802 
1803         // During a default argument instantiation the CurContext points
1804         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1805         // function parameter list, hence add an explicit check.
1806         bool isDefaultArgument =
1807             !CodeSynthesisContexts.empty() &&
1808             CodeSynthesisContexts.back().Kind ==
1809                 CodeSynthesisContext::DefaultFunctionArgumentInstantiation;
1810         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1811         bool isInstance = CurMethod &&
1812                           CurMethod->isInstance() &&
1813                           DC == CurMethod->getParent() && !isDefaultArgument;
1814 
1815         // Give a code modification hint to insert 'this->'.
1816         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1817         // Actually quite difficult!
1818         if (getLangOpts().MSVCCompat)
1819           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1820         if (isInstance) {
1821           Diag(R.getNameLoc(), diagnostic) << Name
1822             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1823           CheckCXXThisCapture(R.getNameLoc());
1824         } else {
1825           Diag(R.getNameLoc(), diagnostic) << Name;
1826         }
1827 
1828         // Do we really want to note all of these?
1829         for (NamedDecl *D : R)
1830           Diag(D->getLocation(), diag::note_dependent_var_use);
1831 
1832         // Return true if we are inside a default argument instantiation
1833         // and the found name refers to an instance member function, otherwise
1834         // the function calling DiagnoseEmptyLookup will try to create an
1835         // implicit member call and this is wrong for default argument.
1836         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1837           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1838           return true;
1839         }
1840 
1841         // Tell the callee to try to recover.
1842         return false;
1843       }
1844 
1845       R.clear();
1846     }
1847 
1848     // In Microsoft mode, if we are performing lookup from within a friend
1849     // function definition declared at class scope then we must set
1850     // DC to the lexical parent to be able to search into the parent
1851     // class.
1852     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1853         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1854         DC->getLexicalParent()->isRecord())
1855       DC = DC->getLexicalParent();
1856     else
1857       DC = DC->getParent();
1858   }
1859 
1860   // We didn't find anything, so try to correct for a typo.
1861   TypoCorrection Corrected;
1862   if (S && Out) {
1863     SourceLocation TypoLoc = R.getNameLoc();
1864     assert(!ExplicitTemplateArgs &&
1865            "Diagnosing an empty lookup with explicit template args!");
1866     *Out = CorrectTypoDelayed(
1867         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1868         [=](const TypoCorrection &TC) {
1869           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1870                                         diagnostic, diagnostic_suggest);
1871         },
1872         nullptr, CTK_ErrorRecovery);
1873     if (*Out)
1874       return true;
1875   } else if (S && (Corrected =
1876                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1877                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1878     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1879     bool DroppedSpecifier =
1880         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1881     R.setLookupName(Corrected.getCorrection());
1882 
1883     bool AcceptableWithRecovery = false;
1884     bool AcceptableWithoutRecovery = false;
1885     NamedDecl *ND = Corrected.getFoundDecl();
1886     if (ND) {
1887       if (Corrected.isOverloaded()) {
1888         OverloadCandidateSet OCS(R.getNameLoc(),
1889                                  OverloadCandidateSet::CSK_Normal);
1890         OverloadCandidateSet::iterator Best;
1891         for (NamedDecl *CD : Corrected) {
1892           if (FunctionTemplateDecl *FTD =
1893                    dyn_cast<FunctionTemplateDecl>(CD))
1894             AddTemplateOverloadCandidate(
1895                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1896                 Args, OCS);
1897           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1898             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1899               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1900                                    Args, OCS);
1901         }
1902         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1903         case OR_Success:
1904           ND = Best->FoundDecl;
1905           Corrected.setCorrectionDecl(ND);
1906           break;
1907         default:
1908           // FIXME: Arbitrarily pick the first declaration for the note.
1909           Corrected.setCorrectionDecl(ND);
1910           break;
1911         }
1912       }
1913       R.addDecl(ND);
1914       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1915         CXXRecordDecl *Record = nullptr;
1916         if (Corrected.getCorrectionSpecifier()) {
1917           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1918           Record = Ty->getAsCXXRecordDecl();
1919         }
1920         if (!Record)
1921           Record = cast<CXXRecordDecl>(
1922               ND->getDeclContext()->getRedeclContext());
1923         R.setNamingClass(Record);
1924       }
1925 
1926       auto *UnderlyingND = ND->getUnderlyingDecl();
1927       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
1928                                isa<FunctionTemplateDecl>(UnderlyingND);
1929       // FIXME: If we ended up with a typo for a type name or
1930       // Objective-C class name, we're in trouble because the parser
1931       // is in the wrong place to recover. Suggest the typo
1932       // correction, but don't make it a fix-it since we're not going
1933       // to recover well anyway.
1934       AcceptableWithoutRecovery =
1935           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
1936     } else {
1937       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1938       // because we aren't able to recover.
1939       AcceptableWithoutRecovery = true;
1940     }
1941 
1942     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1943       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
1944                             ? diag::note_implicit_param_decl
1945                             : diag::note_previous_decl;
1946       if (SS.isEmpty())
1947         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1948                      PDiag(NoteID), AcceptableWithRecovery);
1949       else
1950         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1951                                   << Name << computeDeclContext(SS, false)
1952                                   << DroppedSpecifier << SS.getRange(),
1953                      PDiag(NoteID), AcceptableWithRecovery);
1954 
1955       // Tell the callee whether to try to recover.
1956       return !AcceptableWithRecovery;
1957     }
1958   }
1959   R.clear();
1960 
1961   // Emit a special diagnostic for failed member lookups.
1962   // FIXME: computing the declaration context might fail here (?)
1963   if (!SS.isEmpty()) {
1964     Diag(R.getNameLoc(), diag::err_no_member)
1965       << Name << computeDeclContext(SS, false)
1966       << SS.getRange();
1967     return true;
1968   }
1969 
1970   // Give up, we can't recover.
1971   Diag(R.getNameLoc(), diagnostic) << Name;
1972   return true;
1973 }
1974 
1975 /// In Microsoft mode, if we are inside a template class whose parent class has
1976 /// dependent base classes, and we can't resolve an unqualified identifier, then
1977 /// assume the identifier is a member of a dependent base class.  We can only
1978 /// recover successfully in static methods, instance methods, and other contexts
1979 /// where 'this' is available.  This doesn't precisely match MSVC's
1980 /// instantiation model, but it's close enough.
1981 static Expr *
1982 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
1983                                DeclarationNameInfo &NameInfo,
1984                                SourceLocation TemplateKWLoc,
1985                                const TemplateArgumentListInfo *TemplateArgs) {
1986   // Only try to recover from lookup into dependent bases in static methods or
1987   // contexts where 'this' is available.
1988   QualType ThisType = S.getCurrentThisType();
1989   const CXXRecordDecl *RD = nullptr;
1990   if (!ThisType.isNull())
1991     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
1992   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
1993     RD = MD->getParent();
1994   if (!RD || !RD->hasAnyDependentBases())
1995     return nullptr;
1996 
1997   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
1998   // is available, suggest inserting 'this->' as a fixit.
1999   SourceLocation Loc = NameInfo.getLoc();
2000   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2001   DB << NameInfo.getName() << RD;
2002 
2003   if (!ThisType.isNull()) {
2004     DB << FixItHint::CreateInsertion(Loc, "this->");
2005     return CXXDependentScopeMemberExpr::Create(
2006         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2007         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2008         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2009   }
2010 
2011   // Synthesize a fake NNS that points to the derived class.  This will
2012   // perform name lookup during template instantiation.
2013   CXXScopeSpec SS;
2014   auto *NNS =
2015       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2016   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2017   return DependentScopeDeclRefExpr::Create(
2018       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2019       TemplateArgs);
2020 }
2021 
2022 ExprResult
2023 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2024                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2025                         bool HasTrailingLParen, bool IsAddressOfOperand,
2026                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2027                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2028   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2029          "cannot be direct & operand and have a trailing lparen");
2030   if (SS.isInvalid())
2031     return ExprError();
2032 
2033   TemplateArgumentListInfo TemplateArgsBuffer;
2034 
2035   // Decompose the UnqualifiedId into the following data.
2036   DeclarationNameInfo NameInfo;
2037   const TemplateArgumentListInfo *TemplateArgs;
2038   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2039 
2040   DeclarationName Name = NameInfo.getName();
2041   IdentifierInfo *II = Name.getAsIdentifierInfo();
2042   SourceLocation NameLoc = NameInfo.getLoc();
2043 
2044   if (II && II->isEditorPlaceholder()) {
2045     // FIXME: When typed placeholders are supported we can create a typed
2046     // placeholder expression node.
2047     return ExprError();
2048   }
2049 
2050   // C++ [temp.dep.expr]p3:
2051   //   An id-expression is type-dependent if it contains:
2052   //     -- an identifier that was declared with a dependent type,
2053   //        (note: handled after lookup)
2054   //     -- a template-id that is dependent,
2055   //        (note: handled in BuildTemplateIdExpr)
2056   //     -- a conversion-function-id that specifies a dependent type,
2057   //     -- a nested-name-specifier that contains a class-name that
2058   //        names a dependent type.
2059   // Determine whether this is a member of an unknown specialization;
2060   // we need to handle these differently.
2061   bool DependentID = false;
2062   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2063       Name.getCXXNameType()->isDependentType()) {
2064     DependentID = true;
2065   } else if (SS.isSet()) {
2066     if (DeclContext *DC = computeDeclContext(SS, false)) {
2067       if (RequireCompleteDeclContext(SS, DC))
2068         return ExprError();
2069     } else {
2070       DependentID = true;
2071     }
2072   }
2073 
2074   if (DependentID)
2075     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2076                                       IsAddressOfOperand, TemplateArgs);
2077 
2078   // Perform the required lookup.
2079   LookupResult R(*this, NameInfo,
2080                  (Id.getKind() == UnqualifiedIdKind::IK_ImplicitSelfParam)
2081                      ? LookupObjCImplicitSelfParam
2082                      : LookupOrdinaryName);
2083   if (TemplateKWLoc.isValid() || TemplateArgs) {
2084     // Lookup the template name again to correctly establish the context in
2085     // which it was found. This is really unfortunate as we already did the
2086     // lookup to determine that it was a template name in the first place. If
2087     // this becomes a performance hit, we can work harder to preserve those
2088     // results until we get here but it's likely not worth it.
2089     bool MemberOfUnknownSpecialization;
2090     if (LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2091                            MemberOfUnknownSpecialization, TemplateKWLoc))
2092       return ExprError();
2093 
2094     if (MemberOfUnknownSpecialization ||
2095         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2096       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2097                                         IsAddressOfOperand, TemplateArgs);
2098   } else {
2099     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2100     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2101 
2102     // If the result might be in a dependent base class, this is a dependent
2103     // id-expression.
2104     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2105       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2106                                         IsAddressOfOperand, TemplateArgs);
2107 
2108     // If this reference is in an Objective-C method, then we need to do
2109     // some special Objective-C lookup, too.
2110     if (IvarLookupFollowUp) {
2111       ExprResult E(LookupInObjCMethod(R, S, II, true));
2112       if (E.isInvalid())
2113         return ExprError();
2114 
2115       if (Expr *Ex = E.getAs<Expr>())
2116         return Ex;
2117     }
2118   }
2119 
2120   if (R.isAmbiguous())
2121     return ExprError();
2122 
2123   // This could be an implicitly declared function reference (legal in C90,
2124   // extension in C99, forbidden in C++).
2125   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2126     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2127     if (D) R.addDecl(D);
2128   }
2129 
2130   // Determine whether this name might be a candidate for
2131   // argument-dependent lookup.
2132   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2133 
2134   if (R.empty() && !ADL) {
2135     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2136       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2137                                                    TemplateKWLoc, TemplateArgs))
2138         return E;
2139     }
2140 
2141     // Don't diagnose an empty lookup for inline assembly.
2142     if (IsInlineAsmIdentifier)
2143       return ExprError();
2144 
2145     // If this name wasn't predeclared and if this is not a function
2146     // call, diagnose the problem.
2147     TypoExpr *TE = nullptr;
2148     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2149         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2150     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2151     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2152            "Typo correction callback misconfigured");
2153     if (CCC) {
2154       // Make sure the callback knows what the typo being diagnosed is.
2155       CCC->setTypoName(II);
2156       if (SS.isValid())
2157         CCC->setTypoNNS(SS.getScopeRep());
2158     }
2159     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2160     // a template name, but we happen to have always already looked up the name
2161     // before we get here if it must be a template name.
2162     if (DiagnoseEmptyLookup(S, SS, R,
2163                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2164                             nullptr, None, &TE)) {
2165       if (TE && KeywordReplacement) {
2166         auto &State = getTypoExprState(TE);
2167         auto BestTC = State.Consumer->getNextCorrection();
2168         if (BestTC.isKeyword()) {
2169           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2170           if (State.DiagHandler)
2171             State.DiagHandler(BestTC);
2172           KeywordReplacement->startToken();
2173           KeywordReplacement->setKind(II->getTokenID());
2174           KeywordReplacement->setIdentifierInfo(II);
2175           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2176           // Clean up the state associated with the TypoExpr, since it has
2177           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2178           clearDelayedTypo(TE);
2179           // Signal that a correction to a keyword was performed by returning a
2180           // valid-but-null ExprResult.
2181           return (Expr*)nullptr;
2182         }
2183         State.Consumer->resetCorrectionStream();
2184       }
2185       return TE ? TE : ExprError();
2186     }
2187 
2188     assert(!R.empty() &&
2189            "DiagnoseEmptyLookup returned false but added no results");
2190 
2191     // If we found an Objective-C instance variable, let
2192     // LookupInObjCMethod build the appropriate expression to
2193     // reference the ivar.
2194     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2195       R.clear();
2196       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2197       // In a hopelessly buggy code, Objective-C instance variable
2198       // lookup fails and no expression will be built to reference it.
2199       if (!E.isInvalid() && !E.get())
2200         return ExprError();
2201       return E;
2202     }
2203   }
2204 
2205   // This is guaranteed from this point on.
2206   assert(!R.empty() || ADL);
2207 
2208   // Check whether this might be a C++ implicit instance member access.
2209   // C++ [class.mfct.non-static]p3:
2210   //   When an id-expression that is not part of a class member access
2211   //   syntax and not used to form a pointer to member is used in the
2212   //   body of a non-static member function of class X, if name lookup
2213   //   resolves the name in the id-expression to a non-static non-type
2214   //   member of some class C, the id-expression is transformed into a
2215   //   class member access expression using (*this) as the
2216   //   postfix-expression to the left of the . operator.
2217   //
2218   // But we don't actually need to do this for '&' operands if R
2219   // resolved to a function or overloaded function set, because the
2220   // expression is ill-formed if it actually works out to be a
2221   // non-static member function:
2222   //
2223   // C++ [expr.ref]p4:
2224   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2225   //   [t]he expression can be used only as the left-hand operand of a
2226   //   member function call.
2227   //
2228   // There are other safeguards against such uses, but it's important
2229   // to get this right here so that we don't end up making a
2230   // spuriously dependent expression if we're inside a dependent
2231   // instance method.
2232   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2233     bool MightBeImplicitMember;
2234     if (!IsAddressOfOperand)
2235       MightBeImplicitMember = true;
2236     else if (!SS.isEmpty())
2237       MightBeImplicitMember = false;
2238     else if (R.isOverloadedResult())
2239       MightBeImplicitMember = false;
2240     else if (R.isUnresolvableResult())
2241       MightBeImplicitMember = true;
2242     else
2243       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2244                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2245                               isa<MSPropertyDecl>(R.getFoundDecl());
2246 
2247     if (MightBeImplicitMember)
2248       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2249                                              R, TemplateArgs, S);
2250   }
2251 
2252   if (TemplateArgs || TemplateKWLoc.isValid()) {
2253 
2254     // In C++1y, if this is a variable template id, then check it
2255     // in BuildTemplateIdExpr().
2256     // The single lookup result must be a variable template declaration.
2257     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2258         Id.TemplateId->Kind == TNK_Var_template) {
2259       assert(R.getAsSingle<VarTemplateDecl>() &&
2260              "There should only be one declaration found.");
2261     }
2262 
2263     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2264   }
2265 
2266   return BuildDeclarationNameExpr(SS, R, ADL);
2267 }
2268 
2269 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2270 /// declaration name, generally during template instantiation.
2271 /// There's a large number of things which don't need to be done along
2272 /// this path.
2273 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2274     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2275     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2276   DeclContext *DC = computeDeclContext(SS, false);
2277   if (!DC)
2278     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2279                                      NameInfo, /*TemplateArgs=*/nullptr);
2280 
2281   if (RequireCompleteDeclContext(SS, DC))
2282     return ExprError();
2283 
2284   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2285   LookupQualifiedName(R, DC);
2286 
2287   if (R.isAmbiguous())
2288     return ExprError();
2289 
2290   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2291     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2292                                      NameInfo, /*TemplateArgs=*/nullptr);
2293 
2294   if (R.empty()) {
2295     Diag(NameInfo.getLoc(), diag::err_no_member)
2296       << NameInfo.getName() << DC << SS.getRange();
2297     return ExprError();
2298   }
2299 
2300   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2301     // Diagnose a missing typename if this resolved unambiguously to a type in
2302     // a dependent context.  If we can recover with a type, downgrade this to
2303     // a warning in Microsoft compatibility mode.
2304     unsigned DiagID = diag::err_typename_missing;
2305     if (RecoveryTSI && getLangOpts().MSVCCompat)
2306       DiagID = diag::ext_typename_missing;
2307     SourceLocation Loc = SS.getBeginLoc();
2308     auto D = Diag(Loc, DiagID);
2309     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2310       << SourceRange(Loc, NameInfo.getEndLoc());
2311 
2312     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2313     // context.
2314     if (!RecoveryTSI)
2315       return ExprError();
2316 
2317     // Only issue the fixit if we're prepared to recover.
2318     D << FixItHint::CreateInsertion(Loc, "typename ");
2319 
2320     // Recover by pretending this was an elaborated type.
2321     QualType Ty = Context.getTypeDeclType(TD);
2322     TypeLocBuilder TLB;
2323     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2324 
2325     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2326     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2327     QTL.setElaboratedKeywordLoc(SourceLocation());
2328     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2329 
2330     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2331 
2332     return ExprEmpty();
2333   }
2334 
2335   // Defend against this resolving to an implicit member access. We usually
2336   // won't get here if this might be a legitimate a class member (we end up in
2337   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2338   // a pointer-to-member or in an unevaluated context in C++11.
2339   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2340     return BuildPossibleImplicitMemberExpr(SS,
2341                                            /*TemplateKWLoc=*/SourceLocation(),
2342                                            R, /*TemplateArgs=*/nullptr, S);
2343 
2344   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2345 }
2346 
2347 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2348 /// detected that we're currently inside an ObjC method.  Perform some
2349 /// additional lookup.
2350 ///
2351 /// Ideally, most of this would be done by lookup, but there's
2352 /// actually quite a lot of extra work involved.
2353 ///
2354 /// Returns a null sentinel to indicate trivial success.
2355 ExprResult
2356 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2357                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2358   SourceLocation Loc = Lookup.getNameLoc();
2359   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2360 
2361   // Check for error condition which is already reported.
2362   if (!CurMethod)
2363     return ExprError();
2364 
2365   // There are two cases to handle here.  1) scoped lookup could have failed,
2366   // in which case we should look for an ivar.  2) scoped lookup could have
2367   // found a decl, but that decl is outside the current instance method (i.e.
2368   // a global variable).  In these two cases, we do a lookup for an ivar with
2369   // this name, if the lookup sucedes, we replace it our current decl.
2370 
2371   // If we're in a class method, we don't normally want to look for
2372   // ivars.  But if we don't find anything else, and there's an
2373   // ivar, that's an error.
2374   bool IsClassMethod = CurMethod->isClassMethod();
2375 
2376   bool LookForIvars;
2377   if (Lookup.empty())
2378     LookForIvars = true;
2379   else if (IsClassMethod)
2380     LookForIvars = false;
2381   else
2382     LookForIvars = (Lookup.isSingleResult() &&
2383                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2384   ObjCInterfaceDecl *IFace = nullptr;
2385   if (LookForIvars) {
2386     IFace = CurMethod->getClassInterface();
2387     ObjCInterfaceDecl *ClassDeclared;
2388     ObjCIvarDecl *IV = nullptr;
2389     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2390       // Diagnose using an ivar in a class method.
2391       if (IsClassMethod)
2392         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2393                          << IV->getDeclName());
2394 
2395       // If we're referencing an invalid decl, just return this as a silent
2396       // error node.  The error diagnostic was already emitted on the decl.
2397       if (IV->isInvalidDecl())
2398         return ExprError();
2399 
2400       // Check if referencing a field with __attribute__((deprecated)).
2401       if (DiagnoseUseOfDecl(IV, Loc))
2402         return ExprError();
2403 
2404       // Diagnose the use of an ivar outside of the declaring class.
2405       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2406           !declaresSameEntity(ClassDeclared, IFace) &&
2407           !getLangOpts().DebuggerSupport)
2408         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2409 
2410       // FIXME: This should use a new expr for a direct reference, don't
2411       // turn this into Self->ivar, just return a BareIVarExpr or something.
2412       IdentifierInfo &II = Context.Idents.get("self");
2413       UnqualifiedId SelfName;
2414       SelfName.setIdentifier(&II, SourceLocation());
2415       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2416       CXXScopeSpec SelfScopeSpec;
2417       SourceLocation TemplateKWLoc;
2418       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2419                                               SelfName, false, false);
2420       if (SelfExpr.isInvalid())
2421         return ExprError();
2422 
2423       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2424       if (SelfExpr.isInvalid())
2425         return ExprError();
2426 
2427       MarkAnyDeclReferenced(Loc, IV, true);
2428 
2429       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2430       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2431           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2432         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2433 
2434       ObjCIvarRefExpr *Result = new (Context)
2435           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2436                           IV->getLocation(), SelfExpr.get(), true, true);
2437 
2438       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2439         if (!isUnevaluatedContext() &&
2440             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2441           getCurFunction()->recordUseOfWeak(Result);
2442       }
2443       if (getLangOpts().ObjCAutoRefCount) {
2444         if (CurContext->isClosure())
2445           Diag(Loc, diag::warn_implicitly_retains_self)
2446             << FixItHint::CreateInsertion(Loc, "self->");
2447       }
2448 
2449       return Result;
2450     }
2451   } else if (CurMethod->isInstanceMethod()) {
2452     // We should warn if a local variable hides an ivar.
2453     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2454       ObjCInterfaceDecl *ClassDeclared;
2455       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2456         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2457             declaresSameEntity(IFace, ClassDeclared))
2458           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2459       }
2460     }
2461   } else if (Lookup.isSingleResult() &&
2462              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2463     // If accessing a stand-alone ivar in a class method, this is an error.
2464     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2465       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2466                        << IV->getDeclName());
2467   }
2468 
2469   if (Lookup.empty() && II && AllowBuiltinCreation) {
2470     // FIXME. Consolidate this with similar code in LookupName.
2471     if (unsigned BuiltinID = II->getBuiltinID()) {
2472       if (!(getLangOpts().CPlusPlus &&
2473             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2474         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2475                                            S, Lookup.isForRedeclaration(),
2476                                            Lookup.getNameLoc());
2477         if (D) Lookup.addDecl(D);
2478       }
2479     }
2480   }
2481   // Sentinel value saying that we didn't do anything special.
2482   return ExprResult((Expr *)nullptr);
2483 }
2484 
2485 /// Cast a base object to a member's actual type.
2486 ///
2487 /// Logically this happens in three phases:
2488 ///
2489 /// * First we cast from the base type to the naming class.
2490 ///   The naming class is the class into which we were looking
2491 ///   when we found the member;  it's the qualifier type if a
2492 ///   qualifier was provided, and otherwise it's the base type.
2493 ///
2494 /// * Next we cast from the naming class to the declaring class.
2495 ///   If the member we found was brought into a class's scope by
2496 ///   a using declaration, this is that class;  otherwise it's
2497 ///   the class declaring the member.
2498 ///
2499 /// * Finally we cast from the declaring class to the "true"
2500 ///   declaring class of the member.  This conversion does not
2501 ///   obey access control.
2502 ExprResult
2503 Sema::PerformObjectMemberConversion(Expr *From,
2504                                     NestedNameSpecifier *Qualifier,
2505                                     NamedDecl *FoundDecl,
2506                                     NamedDecl *Member) {
2507   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2508   if (!RD)
2509     return From;
2510 
2511   QualType DestRecordType;
2512   QualType DestType;
2513   QualType FromRecordType;
2514   QualType FromType = From->getType();
2515   bool PointerConversions = false;
2516   if (isa<FieldDecl>(Member)) {
2517     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2518 
2519     if (FromType->getAs<PointerType>()) {
2520       DestType = Context.getPointerType(DestRecordType);
2521       FromRecordType = FromType->getPointeeType();
2522       PointerConversions = true;
2523     } else {
2524       DestType = DestRecordType;
2525       FromRecordType = FromType;
2526     }
2527   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2528     if (Method->isStatic())
2529       return From;
2530 
2531     DestType = Method->getThisType(Context);
2532     DestRecordType = DestType->getPointeeType();
2533 
2534     if (FromType->getAs<PointerType>()) {
2535       FromRecordType = FromType->getPointeeType();
2536       PointerConversions = true;
2537     } else {
2538       FromRecordType = FromType;
2539       DestType = DestRecordType;
2540     }
2541   } else {
2542     // No conversion necessary.
2543     return From;
2544   }
2545 
2546   if (DestType->isDependentType() || FromType->isDependentType())
2547     return From;
2548 
2549   // If the unqualified types are the same, no conversion is necessary.
2550   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2551     return From;
2552 
2553   SourceRange FromRange = From->getSourceRange();
2554   SourceLocation FromLoc = FromRange.getBegin();
2555 
2556   ExprValueKind VK = From->getValueKind();
2557 
2558   // C++ [class.member.lookup]p8:
2559   //   [...] Ambiguities can often be resolved by qualifying a name with its
2560   //   class name.
2561   //
2562   // If the member was a qualified name and the qualified referred to a
2563   // specific base subobject type, we'll cast to that intermediate type
2564   // first and then to the object in which the member is declared. That allows
2565   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2566   //
2567   //   class Base { public: int x; };
2568   //   class Derived1 : public Base { };
2569   //   class Derived2 : public Base { };
2570   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2571   //
2572   //   void VeryDerived::f() {
2573   //     x = 17; // error: ambiguous base subobjects
2574   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2575   //   }
2576   if (Qualifier && Qualifier->getAsType()) {
2577     QualType QType = QualType(Qualifier->getAsType(), 0);
2578     assert(QType->isRecordType() && "lookup done with non-record type");
2579 
2580     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2581 
2582     // In C++98, the qualifier type doesn't actually have to be a base
2583     // type of the object type, in which case we just ignore it.
2584     // Otherwise build the appropriate casts.
2585     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2586       CXXCastPath BasePath;
2587       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2588                                        FromLoc, FromRange, &BasePath))
2589         return ExprError();
2590 
2591       if (PointerConversions)
2592         QType = Context.getPointerType(QType);
2593       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2594                                VK, &BasePath).get();
2595 
2596       FromType = QType;
2597       FromRecordType = QRecordType;
2598 
2599       // If the qualifier type was the same as the destination type,
2600       // we're done.
2601       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2602         return From;
2603     }
2604   }
2605 
2606   bool IgnoreAccess = false;
2607 
2608   // If we actually found the member through a using declaration, cast
2609   // down to the using declaration's type.
2610   //
2611   // Pointer equality is fine here because only one declaration of a
2612   // class ever has member declarations.
2613   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2614     assert(isa<UsingShadowDecl>(FoundDecl));
2615     QualType URecordType = Context.getTypeDeclType(
2616                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2617 
2618     // We only need to do this if the naming-class to declaring-class
2619     // conversion is non-trivial.
2620     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2621       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2622       CXXCastPath BasePath;
2623       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2624                                        FromLoc, FromRange, &BasePath))
2625         return ExprError();
2626 
2627       QualType UType = URecordType;
2628       if (PointerConversions)
2629         UType = Context.getPointerType(UType);
2630       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2631                                VK, &BasePath).get();
2632       FromType = UType;
2633       FromRecordType = URecordType;
2634     }
2635 
2636     // We don't do access control for the conversion from the
2637     // declaring class to the true declaring class.
2638     IgnoreAccess = true;
2639   }
2640 
2641   CXXCastPath BasePath;
2642   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2643                                    FromLoc, FromRange, &BasePath,
2644                                    IgnoreAccess))
2645     return ExprError();
2646 
2647   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2648                            VK, &BasePath);
2649 }
2650 
2651 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2652                                       const LookupResult &R,
2653                                       bool HasTrailingLParen) {
2654   // Only when used directly as the postfix-expression of a call.
2655   if (!HasTrailingLParen)
2656     return false;
2657 
2658   // Never if a scope specifier was provided.
2659   if (SS.isSet())
2660     return false;
2661 
2662   // Only in C++ or ObjC++.
2663   if (!getLangOpts().CPlusPlus)
2664     return false;
2665 
2666   // Turn off ADL when we find certain kinds of declarations during
2667   // normal lookup:
2668   for (NamedDecl *D : R) {
2669     // C++0x [basic.lookup.argdep]p3:
2670     //     -- a declaration of a class member
2671     // Since using decls preserve this property, we check this on the
2672     // original decl.
2673     if (D->isCXXClassMember())
2674       return false;
2675 
2676     // C++0x [basic.lookup.argdep]p3:
2677     //     -- a block-scope function declaration that is not a
2678     //        using-declaration
2679     // NOTE: we also trigger this for function templates (in fact, we
2680     // don't check the decl type at all, since all other decl types
2681     // turn off ADL anyway).
2682     if (isa<UsingShadowDecl>(D))
2683       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2684     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2685       return false;
2686 
2687     // C++0x [basic.lookup.argdep]p3:
2688     //     -- a declaration that is neither a function or a function
2689     //        template
2690     // And also for builtin functions.
2691     if (isa<FunctionDecl>(D)) {
2692       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2693 
2694       // But also builtin functions.
2695       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2696         return false;
2697     } else if (!isa<FunctionTemplateDecl>(D))
2698       return false;
2699   }
2700 
2701   return true;
2702 }
2703 
2704 
2705 /// Diagnoses obvious problems with the use of the given declaration
2706 /// as an expression.  This is only actually called for lookups that
2707 /// were not overloaded, and it doesn't promise that the declaration
2708 /// will in fact be used.
2709 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2710   if (D->isInvalidDecl())
2711     return true;
2712 
2713   if (isa<TypedefNameDecl>(D)) {
2714     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2715     return true;
2716   }
2717 
2718   if (isa<ObjCInterfaceDecl>(D)) {
2719     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2720     return true;
2721   }
2722 
2723   if (isa<NamespaceDecl>(D)) {
2724     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2725     return true;
2726   }
2727 
2728   return false;
2729 }
2730 
2731 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2732                                           LookupResult &R, bool NeedsADL,
2733                                           bool AcceptInvalidDecl) {
2734   // If this is a single, fully-resolved result and we don't need ADL,
2735   // just build an ordinary singleton decl ref.
2736   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2737     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2738                                     R.getRepresentativeDecl(), nullptr,
2739                                     AcceptInvalidDecl);
2740 
2741   // We only need to check the declaration if there's exactly one
2742   // result, because in the overloaded case the results can only be
2743   // functions and function templates.
2744   if (R.isSingleResult() &&
2745       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2746     return ExprError();
2747 
2748   // Otherwise, just build an unresolved lookup expression.  Suppress
2749   // any lookup-related diagnostics; we'll hash these out later, when
2750   // we've picked a target.
2751   R.suppressDiagnostics();
2752 
2753   UnresolvedLookupExpr *ULE
2754     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2755                                    SS.getWithLocInContext(Context),
2756                                    R.getLookupNameInfo(),
2757                                    NeedsADL, R.isOverloadedResult(),
2758                                    R.begin(), R.end());
2759 
2760   return ULE;
2761 }
2762 
2763 static void
2764 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2765                                    ValueDecl *var, DeclContext *DC);
2766 
2767 /// Complete semantic analysis for a reference to the given declaration.
2768 ExprResult Sema::BuildDeclarationNameExpr(
2769     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2770     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2771     bool AcceptInvalidDecl) {
2772   assert(D && "Cannot refer to a NULL declaration");
2773   assert(!isa<FunctionTemplateDecl>(D) &&
2774          "Cannot refer unambiguously to a function template");
2775 
2776   SourceLocation Loc = NameInfo.getLoc();
2777   if (CheckDeclInExpr(*this, Loc, D))
2778     return ExprError();
2779 
2780   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2781     // Specifically diagnose references to class templates that are missing
2782     // a template argument list.
2783     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2784     return ExprError();
2785   }
2786 
2787   // Make sure that we're referring to a value.
2788   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2789   if (!VD) {
2790     Diag(Loc, diag::err_ref_non_value)
2791       << D << SS.getRange();
2792     Diag(D->getLocation(), diag::note_declared_at);
2793     return ExprError();
2794   }
2795 
2796   // Check whether this declaration can be used. Note that we suppress
2797   // this check when we're going to perform argument-dependent lookup
2798   // on this function name, because this might not be the function
2799   // that overload resolution actually selects.
2800   if (DiagnoseUseOfDecl(VD, Loc))
2801     return ExprError();
2802 
2803   // Only create DeclRefExpr's for valid Decl's.
2804   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2805     return ExprError();
2806 
2807   // Handle members of anonymous structs and unions.  If we got here,
2808   // and the reference is to a class member indirect field, then this
2809   // must be the subject of a pointer-to-member expression.
2810   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2811     if (!indirectField->isCXXClassMember())
2812       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2813                                                       indirectField);
2814 
2815   {
2816     QualType type = VD->getType();
2817     if (type.isNull())
2818       return ExprError();
2819     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2820       // C++ [except.spec]p17:
2821       //   An exception-specification is considered to be needed when:
2822       //   - in an expression, the function is the unique lookup result or
2823       //     the selected member of a set of overloaded functions.
2824       ResolveExceptionSpec(Loc, FPT);
2825       type = VD->getType();
2826     }
2827     ExprValueKind valueKind = VK_RValue;
2828 
2829     switch (D->getKind()) {
2830     // Ignore all the non-ValueDecl kinds.
2831 #define ABSTRACT_DECL(kind)
2832 #define VALUE(type, base)
2833 #define DECL(type, base) \
2834     case Decl::type:
2835 #include "clang/AST/DeclNodes.inc"
2836       llvm_unreachable("invalid value decl kind");
2837 
2838     // These shouldn't make it here.
2839     case Decl::ObjCAtDefsField:
2840     case Decl::ObjCIvar:
2841       llvm_unreachable("forming non-member reference to ivar?");
2842 
2843     // Enum constants are always r-values and never references.
2844     // Unresolved using declarations are dependent.
2845     case Decl::EnumConstant:
2846     case Decl::UnresolvedUsingValue:
2847     case Decl::OMPDeclareReduction:
2848       valueKind = VK_RValue;
2849       break;
2850 
2851     // Fields and indirect fields that got here must be for
2852     // pointer-to-member expressions; we just call them l-values for
2853     // internal consistency, because this subexpression doesn't really
2854     // exist in the high-level semantics.
2855     case Decl::Field:
2856     case Decl::IndirectField:
2857       assert(getLangOpts().CPlusPlus &&
2858              "building reference to field in C?");
2859 
2860       // These can't have reference type in well-formed programs, but
2861       // for internal consistency we do this anyway.
2862       type = type.getNonReferenceType();
2863       valueKind = VK_LValue;
2864       break;
2865 
2866     // Non-type template parameters are either l-values or r-values
2867     // depending on the type.
2868     case Decl::NonTypeTemplateParm: {
2869       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2870         type = reftype->getPointeeType();
2871         valueKind = VK_LValue; // even if the parameter is an r-value reference
2872         break;
2873       }
2874 
2875       // For non-references, we need to strip qualifiers just in case
2876       // the template parameter was declared as 'const int' or whatever.
2877       valueKind = VK_RValue;
2878       type = type.getUnqualifiedType();
2879       break;
2880     }
2881 
2882     case Decl::Var:
2883     case Decl::VarTemplateSpecialization:
2884     case Decl::VarTemplatePartialSpecialization:
2885     case Decl::Decomposition:
2886     case Decl::OMPCapturedExpr:
2887       // In C, "extern void blah;" is valid and is an r-value.
2888       if (!getLangOpts().CPlusPlus &&
2889           !type.hasQualifiers() &&
2890           type->isVoidType()) {
2891         valueKind = VK_RValue;
2892         break;
2893       }
2894       LLVM_FALLTHROUGH;
2895 
2896     case Decl::ImplicitParam:
2897     case Decl::ParmVar: {
2898       // These are always l-values.
2899       valueKind = VK_LValue;
2900       type = type.getNonReferenceType();
2901 
2902       // FIXME: Does the addition of const really only apply in
2903       // potentially-evaluated contexts? Since the variable isn't actually
2904       // captured in an unevaluated context, it seems that the answer is no.
2905       if (!isUnevaluatedContext()) {
2906         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2907         if (!CapturedType.isNull())
2908           type = CapturedType;
2909       }
2910 
2911       break;
2912     }
2913 
2914     case Decl::Binding: {
2915       // These are always lvalues.
2916       valueKind = VK_LValue;
2917       type = type.getNonReferenceType();
2918       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2919       // decides how that's supposed to work.
2920       auto *BD = cast<BindingDecl>(VD);
2921       if (BD->getDeclContext()->isFunctionOrMethod() &&
2922           BD->getDeclContext() != CurContext)
2923         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2924       break;
2925     }
2926 
2927     case Decl::Function: {
2928       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2929         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2930           type = Context.BuiltinFnTy;
2931           valueKind = VK_RValue;
2932           break;
2933         }
2934       }
2935 
2936       const FunctionType *fty = type->castAs<FunctionType>();
2937 
2938       // If we're referring to a function with an __unknown_anytype
2939       // result type, make the entire expression __unknown_anytype.
2940       if (fty->getReturnType() == Context.UnknownAnyTy) {
2941         type = Context.UnknownAnyTy;
2942         valueKind = VK_RValue;
2943         break;
2944       }
2945 
2946       // Functions are l-values in C++.
2947       if (getLangOpts().CPlusPlus) {
2948         valueKind = VK_LValue;
2949         break;
2950       }
2951 
2952       // C99 DR 316 says that, if a function type comes from a
2953       // function definition (without a prototype), that type is only
2954       // used for checking compatibility. Therefore, when referencing
2955       // the function, we pretend that we don't have the full function
2956       // type.
2957       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2958           isa<FunctionProtoType>(fty))
2959         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2960                                               fty->getExtInfo());
2961 
2962       // Functions are r-values in C.
2963       valueKind = VK_RValue;
2964       break;
2965     }
2966 
2967     case Decl::CXXDeductionGuide:
2968       llvm_unreachable("building reference to deduction guide");
2969 
2970     case Decl::MSProperty:
2971       valueKind = VK_LValue;
2972       break;
2973 
2974     case Decl::CXXMethod:
2975       // If we're referring to a method with an __unknown_anytype
2976       // result type, make the entire expression __unknown_anytype.
2977       // This should only be possible with a type written directly.
2978       if (const FunctionProtoType *proto
2979             = dyn_cast<FunctionProtoType>(VD->getType()))
2980         if (proto->getReturnType() == Context.UnknownAnyTy) {
2981           type = Context.UnknownAnyTy;
2982           valueKind = VK_RValue;
2983           break;
2984         }
2985 
2986       // C++ methods are l-values if static, r-values if non-static.
2987       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2988         valueKind = VK_LValue;
2989         break;
2990       }
2991       LLVM_FALLTHROUGH;
2992 
2993     case Decl::CXXConversion:
2994     case Decl::CXXDestructor:
2995     case Decl::CXXConstructor:
2996       valueKind = VK_RValue;
2997       break;
2998     }
2999 
3000     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3001                             TemplateArgs);
3002   }
3003 }
3004 
3005 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3006                                     SmallString<32> &Target) {
3007   Target.resize(CharByteWidth * (Source.size() + 1));
3008   char *ResultPtr = &Target[0];
3009   const llvm::UTF8 *ErrorPtr;
3010   bool success =
3011       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3012   (void)success;
3013   assert(success);
3014   Target.resize(ResultPtr - &Target[0]);
3015 }
3016 
3017 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3018                                      PredefinedExpr::IdentType IT) {
3019   // Pick the current block, lambda, captured statement or function.
3020   Decl *currentDecl = nullptr;
3021   if (const BlockScopeInfo *BSI = getCurBlock())
3022     currentDecl = BSI->TheDecl;
3023   else if (const LambdaScopeInfo *LSI = getCurLambda())
3024     currentDecl = LSI->CallOperator;
3025   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3026     currentDecl = CSI->TheCapturedDecl;
3027   else
3028     currentDecl = getCurFunctionOrMethodDecl();
3029 
3030   if (!currentDecl) {
3031     Diag(Loc, diag::ext_predef_outside_function);
3032     currentDecl = Context.getTranslationUnitDecl();
3033   }
3034 
3035   QualType ResTy;
3036   StringLiteral *SL = nullptr;
3037   if (cast<DeclContext>(currentDecl)->isDependentContext())
3038     ResTy = Context.DependentTy;
3039   else {
3040     // Pre-defined identifiers are of type char[x], where x is the length of
3041     // the string.
3042     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3043     unsigned Length = Str.length();
3044 
3045     llvm::APInt LengthI(32, Length + 1);
3046     if (IT == PredefinedExpr::LFunction) {
3047       ResTy =
3048           Context.adjustStringLiteralBaseType(Context.WideCharTy.withConst());
3049       SmallString<32> RawChars;
3050       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3051                               Str, RawChars);
3052       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3053                                            /*IndexTypeQuals*/ 0);
3054       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3055                                  /*Pascal*/ false, ResTy, Loc);
3056     } else {
3057       ResTy = Context.adjustStringLiteralBaseType(Context.CharTy.withConst());
3058       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3059                                            /*IndexTypeQuals*/ 0);
3060       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3061                                  /*Pascal*/ false, ResTy, Loc);
3062     }
3063   }
3064 
3065   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3066 }
3067 
3068 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3069   PredefinedExpr::IdentType IT;
3070 
3071   switch (Kind) {
3072   default: llvm_unreachable("Unknown simple primary expr!");
3073   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3074   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3075   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3076   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3077   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3078   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3079   }
3080 
3081   return BuildPredefinedExpr(Loc, IT);
3082 }
3083 
3084 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3085   SmallString<16> CharBuffer;
3086   bool Invalid = false;
3087   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3088   if (Invalid)
3089     return ExprError();
3090 
3091   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3092                             PP, Tok.getKind());
3093   if (Literal.hadError())
3094     return ExprError();
3095 
3096   QualType Ty;
3097   if (Literal.isWide())
3098     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3099   else if (Literal.isUTF8() && getLangOpts().Char8)
3100     Ty = Context.Char8Ty; // u8'x' -> char8_t when it exists.
3101   else if (Literal.isUTF16())
3102     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3103   else if (Literal.isUTF32())
3104     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3105   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3106     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3107   else
3108     Ty = Context.CharTy;  // 'x' -> char in C++
3109 
3110   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3111   if (Literal.isWide())
3112     Kind = CharacterLiteral::Wide;
3113   else if (Literal.isUTF16())
3114     Kind = CharacterLiteral::UTF16;
3115   else if (Literal.isUTF32())
3116     Kind = CharacterLiteral::UTF32;
3117   else if (Literal.isUTF8())
3118     Kind = CharacterLiteral::UTF8;
3119 
3120   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3121                                              Tok.getLocation());
3122 
3123   if (Literal.getUDSuffix().empty())
3124     return Lit;
3125 
3126   // We're building a user-defined literal.
3127   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3128   SourceLocation UDSuffixLoc =
3129     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3130 
3131   // Make sure we're allowed user-defined literals here.
3132   if (!UDLScope)
3133     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3134 
3135   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3136   //   operator "" X (ch)
3137   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3138                                         Lit, Tok.getLocation());
3139 }
3140 
3141 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3142   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3143   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3144                                 Context.IntTy, Loc);
3145 }
3146 
3147 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3148                                   QualType Ty, SourceLocation Loc) {
3149   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3150 
3151   using llvm::APFloat;
3152   APFloat Val(Format);
3153 
3154   APFloat::opStatus result = Literal.GetFloatValue(Val);
3155 
3156   // Overflow is always an error, but underflow is only an error if
3157   // we underflowed to zero (APFloat reports denormals as underflow).
3158   if ((result & APFloat::opOverflow) ||
3159       ((result & APFloat::opUnderflow) && Val.isZero())) {
3160     unsigned diagnostic;
3161     SmallString<20> buffer;
3162     if (result & APFloat::opOverflow) {
3163       diagnostic = diag::warn_float_overflow;
3164       APFloat::getLargest(Format).toString(buffer);
3165     } else {
3166       diagnostic = diag::warn_float_underflow;
3167       APFloat::getSmallest(Format).toString(buffer);
3168     }
3169 
3170     S.Diag(Loc, diagnostic)
3171       << Ty
3172       << StringRef(buffer.data(), buffer.size());
3173   }
3174 
3175   bool isExact = (result == APFloat::opOK);
3176   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3177 }
3178 
3179 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3180   assert(E && "Invalid expression");
3181 
3182   if (E->isValueDependent())
3183     return false;
3184 
3185   QualType QT = E->getType();
3186   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3187     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3188     return true;
3189   }
3190 
3191   llvm::APSInt ValueAPS;
3192   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3193 
3194   if (R.isInvalid())
3195     return true;
3196 
3197   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3198   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3199     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3200         << ValueAPS.toString(10) << ValueIsPositive;
3201     return true;
3202   }
3203 
3204   return false;
3205 }
3206 
3207 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3208   // Fast path for a single digit (which is quite common).  A single digit
3209   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3210   if (Tok.getLength() == 1) {
3211     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3212     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3213   }
3214 
3215   SmallString<128> SpellingBuffer;
3216   // NumericLiteralParser wants to overread by one character.  Add padding to
3217   // the buffer in case the token is copied to the buffer.  If getSpelling()
3218   // returns a StringRef to the memory buffer, it should have a null char at
3219   // the EOF, so it is also safe.
3220   SpellingBuffer.resize(Tok.getLength() + 1);
3221 
3222   // Get the spelling of the token, which eliminates trigraphs, etc.
3223   bool Invalid = false;
3224   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3225   if (Invalid)
3226     return ExprError();
3227 
3228   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3229   if (Literal.hadError)
3230     return ExprError();
3231 
3232   if (Literal.hasUDSuffix()) {
3233     // We're building a user-defined literal.
3234     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3235     SourceLocation UDSuffixLoc =
3236       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3237 
3238     // Make sure we're allowed user-defined literals here.
3239     if (!UDLScope)
3240       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3241 
3242     QualType CookedTy;
3243     if (Literal.isFloatingLiteral()) {
3244       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3245       // long double, the literal is treated as a call of the form
3246       //   operator "" X (f L)
3247       CookedTy = Context.LongDoubleTy;
3248     } else {
3249       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3250       // unsigned long long, the literal is treated as a call of the form
3251       //   operator "" X (n ULL)
3252       CookedTy = Context.UnsignedLongLongTy;
3253     }
3254 
3255     DeclarationName OpName =
3256       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3257     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3258     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3259 
3260     SourceLocation TokLoc = Tok.getLocation();
3261 
3262     // Perform literal operator lookup to determine if we're building a raw
3263     // literal or a cooked one.
3264     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3265     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3266                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3267                                   /*AllowStringTemplate*/ false,
3268                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3269     case LOLR_ErrorNoDiagnostic:
3270       // Lookup failure for imaginary constants isn't fatal, there's still the
3271       // GNU extension producing _Complex types.
3272       break;
3273     case LOLR_Error:
3274       return ExprError();
3275     case LOLR_Cooked: {
3276       Expr *Lit;
3277       if (Literal.isFloatingLiteral()) {
3278         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3279       } else {
3280         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3281         if (Literal.GetIntegerValue(ResultVal))
3282           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3283               << /* Unsigned */ 1;
3284         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3285                                      Tok.getLocation());
3286       }
3287       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3288     }
3289 
3290     case LOLR_Raw: {
3291       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3292       // literal is treated as a call of the form
3293       //   operator "" X ("n")
3294       unsigned Length = Literal.getUDSuffixOffset();
3295       QualType StrTy = Context.getConstantArrayType(
3296           Context.adjustStringLiteralBaseType(Context.CharTy.withConst()),
3297           llvm::APInt(32, Length + 1), ArrayType::Normal, 0);
3298       Expr *Lit = StringLiteral::Create(
3299           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3300           /*Pascal*/false, StrTy, &TokLoc, 1);
3301       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3302     }
3303 
3304     case LOLR_Template: {
3305       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3306       // template), L is treated as a call fo the form
3307       //   operator "" X <'c1', 'c2', ... 'ck'>()
3308       // where n is the source character sequence c1 c2 ... ck.
3309       TemplateArgumentListInfo ExplicitArgs;
3310       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3311       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3312       llvm::APSInt Value(CharBits, CharIsUnsigned);
3313       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3314         Value = TokSpelling[I];
3315         TemplateArgument Arg(Context, Value, Context.CharTy);
3316         TemplateArgumentLocInfo ArgInfo;
3317         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3318       }
3319       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3320                                       &ExplicitArgs);
3321     }
3322     case LOLR_StringTemplate:
3323       llvm_unreachable("unexpected literal operator lookup result");
3324     }
3325   }
3326 
3327   Expr *Res;
3328 
3329   if (Literal.isFloatingLiteral()) {
3330     QualType Ty;
3331     if (Literal.isHalf){
3332       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3333         Ty = Context.HalfTy;
3334       else {
3335         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3336         return ExprError();
3337       }
3338     } else if (Literal.isFloat)
3339       Ty = Context.FloatTy;
3340     else if (Literal.isLong)
3341       Ty = Context.LongDoubleTy;
3342     else if (Literal.isFloat16)
3343       Ty = Context.Float16Ty;
3344     else if (Literal.isFloat128)
3345       Ty = Context.Float128Ty;
3346     else
3347       Ty = Context.DoubleTy;
3348 
3349     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3350 
3351     if (Ty == Context.DoubleTy) {
3352       if (getLangOpts().SinglePrecisionConstants) {
3353         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3354         if (BTy->getKind() != BuiltinType::Float) {
3355           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3356         }
3357       } else if (getLangOpts().OpenCL &&
3358                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3359         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3360         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3361         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3362       }
3363     }
3364   } else if (!Literal.isIntegerLiteral()) {
3365     return ExprError();
3366   } else {
3367     QualType Ty;
3368 
3369     // 'long long' is a C99 or C++11 feature.
3370     if (!getLangOpts().C99 && Literal.isLongLong) {
3371       if (getLangOpts().CPlusPlus)
3372         Diag(Tok.getLocation(),
3373              getLangOpts().CPlusPlus11 ?
3374              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3375       else
3376         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3377     }
3378 
3379     // Get the value in the widest-possible width.
3380     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3381     llvm::APInt ResultVal(MaxWidth, 0);
3382 
3383     if (Literal.GetIntegerValue(ResultVal)) {
3384       // If this value didn't fit into uintmax_t, error and force to ull.
3385       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3386           << /* Unsigned */ 1;
3387       Ty = Context.UnsignedLongLongTy;
3388       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3389              "long long is not intmax_t?");
3390     } else {
3391       // If this value fits into a ULL, try to figure out what else it fits into
3392       // according to the rules of C99 6.4.4.1p5.
3393 
3394       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3395       // be an unsigned int.
3396       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3397 
3398       // Check from smallest to largest, picking the smallest type we can.
3399       unsigned Width = 0;
3400 
3401       // Microsoft specific integer suffixes are explicitly sized.
3402       if (Literal.MicrosoftInteger) {
3403         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3404           Width = 8;
3405           Ty = Context.CharTy;
3406         } else {
3407           Width = Literal.MicrosoftInteger;
3408           Ty = Context.getIntTypeForBitwidth(Width,
3409                                              /*Signed=*/!Literal.isUnsigned);
3410         }
3411       }
3412 
3413       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3414         // Are int/unsigned possibilities?
3415         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3416 
3417         // Does it fit in a unsigned int?
3418         if (ResultVal.isIntN(IntSize)) {
3419           // Does it fit in a signed int?
3420           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3421             Ty = Context.IntTy;
3422           else if (AllowUnsigned)
3423             Ty = Context.UnsignedIntTy;
3424           Width = IntSize;
3425         }
3426       }
3427 
3428       // Are long/unsigned long possibilities?
3429       if (Ty.isNull() && !Literal.isLongLong) {
3430         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3431 
3432         // Does it fit in a unsigned long?
3433         if (ResultVal.isIntN(LongSize)) {
3434           // Does it fit in a signed long?
3435           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3436             Ty = Context.LongTy;
3437           else if (AllowUnsigned)
3438             Ty = Context.UnsignedLongTy;
3439           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3440           // is compatible.
3441           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3442             const unsigned LongLongSize =
3443                 Context.getTargetInfo().getLongLongWidth();
3444             Diag(Tok.getLocation(),
3445                  getLangOpts().CPlusPlus
3446                      ? Literal.isLong
3447                            ? diag::warn_old_implicitly_unsigned_long_cxx
3448                            : /*C++98 UB*/ diag::
3449                                  ext_old_implicitly_unsigned_long_cxx
3450                      : diag::warn_old_implicitly_unsigned_long)
3451                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3452                                             : /*will be ill-formed*/ 1);
3453             Ty = Context.UnsignedLongTy;
3454           }
3455           Width = LongSize;
3456         }
3457       }
3458 
3459       // Check long long if needed.
3460       if (Ty.isNull()) {
3461         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3462 
3463         // Does it fit in a unsigned long long?
3464         if (ResultVal.isIntN(LongLongSize)) {
3465           // Does it fit in a signed long long?
3466           // To be compatible with MSVC, hex integer literals ending with the
3467           // LL or i64 suffix are always signed in Microsoft mode.
3468           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3469               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3470             Ty = Context.LongLongTy;
3471           else if (AllowUnsigned)
3472             Ty = Context.UnsignedLongLongTy;
3473           Width = LongLongSize;
3474         }
3475       }
3476 
3477       // If we still couldn't decide a type, we probably have something that
3478       // does not fit in a signed long long, but has no U suffix.
3479       if (Ty.isNull()) {
3480         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3481         Ty = Context.UnsignedLongLongTy;
3482         Width = Context.getTargetInfo().getLongLongWidth();
3483       }
3484 
3485       if (ResultVal.getBitWidth() != Width)
3486         ResultVal = ResultVal.trunc(Width);
3487     }
3488     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3489   }
3490 
3491   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3492   if (Literal.isImaginary) {
3493     Res = new (Context) ImaginaryLiteral(Res,
3494                                         Context.getComplexType(Res->getType()));
3495 
3496     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3497   }
3498   return Res;
3499 }
3500 
3501 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3502   assert(E && "ActOnParenExpr() missing expr");
3503   return new (Context) ParenExpr(L, R, E);
3504 }
3505 
3506 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3507                                          SourceLocation Loc,
3508                                          SourceRange ArgRange) {
3509   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3510   // scalar or vector data type argument..."
3511   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3512   // type (C99 6.2.5p18) or void.
3513   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3514     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3515       << T << ArgRange;
3516     return true;
3517   }
3518 
3519   assert((T->isVoidType() || !T->isIncompleteType()) &&
3520          "Scalar types should always be complete");
3521   return false;
3522 }
3523 
3524 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3525                                            SourceLocation Loc,
3526                                            SourceRange ArgRange,
3527                                            UnaryExprOrTypeTrait TraitKind) {
3528   // Invalid types must be hard errors for SFINAE in C++.
3529   if (S.LangOpts.CPlusPlus)
3530     return true;
3531 
3532   // C99 6.5.3.4p1:
3533   if (T->isFunctionType() &&
3534       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3535     // sizeof(function)/alignof(function) is allowed as an extension.
3536     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3537       << TraitKind << ArgRange;
3538     return false;
3539   }
3540 
3541   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3542   // this is an error (OpenCL v1.1 s6.3.k)
3543   if (T->isVoidType()) {
3544     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3545                                         : diag::ext_sizeof_alignof_void_type;
3546     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3547     return false;
3548   }
3549 
3550   return true;
3551 }
3552 
3553 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3554                                              SourceLocation Loc,
3555                                              SourceRange ArgRange,
3556                                              UnaryExprOrTypeTrait TraitKind) {
3557   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3558   // runtime doesn't allow it.
3559   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3560     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3561       << T << (TraitKind == UETT_SizeOf)
3562       << ArgRange;
3563     return true;
3564   }
3565 
3566   return false;
3567 }
3568 
3569 /// Check whether E is a pointer from a decayed array type (the decayed
3570 /// pointer type is equal to T) and emit a warning if it is.
3571 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3572                                      Expr *E) {
3573   // Don't warn if the operation changed the type.
3574   if (T != E->getType())
3575     return;
3576 
3577   // Now look for array decays.
3578   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3579   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3580     return;
3581 
3582   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3583                                              << ICE->getType()
3584                                              << ICE->getSubExpr()->getType();
3585 }
3586 
3587 /// Check the constraints on expression operands to unary type expression
3588 /// and type traits.
3589 ///
3590 /// Completes any types necessary and validates the constraints on the operand
3591 /// expression. The logic mostly mirrors the type-based overload, but may modify
3592 /// the expression as it completes the type for that expression through template
3593 /// instantiation, etc.
3594 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3595                                             UnaryExprOrTypeTrait ExprKind) {
3596   QualType ExprTy = E->getType();
3597   assert(!ExprTy->isReferenceType());
3598 
3599   if (ExprKind == UETT_VecStep)
3600     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3601                                         E->getSourceRange());
3602 
3603   // Whitelist some types as extensions
3604   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3605                                       E->getSourceRange(), ExprKind))
3606     return false;
3607 
3608   // 'alignof' applied to an expression only requires the base element type of
3609   // the expression to be complete. 'sizeof' requires the expression's type to
3610   // be complete (and will attempt to complete it if it's an array of unknown
3611   // bound).
3612   if (ExprKind == UETT_AlignOf) {
3613     if (RequireCompleteType(E->getExprLoc(),
3614                             Context.getBaseElementType(E->getType()),
3615                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3616                             E->getSourceRange()))
3617       return true;
3618   } else {
3619     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3620                                 ExprKind, E->getSourceRange()))
3621       return true;
3622   }
3623 
3624   // Completing the expression's type may have changed it.
3625   ExprTy = E->getType();
3626   assert(!ExprTy->isReferenceType());
3627 
3628   if (ExprTy->isFunctionType()) {
3629     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3630       << ExprKind << E->getSourceRange();
3631     return true;
3632   }
3633 
3634   // The operand for sizeof and alignof is in an unevaluated expression context,
3635   // so side effects could result in unintended consequences.
3636   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3637       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3638     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3639 
3640   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3641                                        E->getSourceRange(), ExprKind))
3642     return true;
3643 
3644   if (ExprKind == UETT_SizeOf) {
3645     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3646       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3647         QualType OType = PVD->getOriginalType();
3648         QualType Type = PVD->getType();
3649         if (Type->isPointerType() && OType->isArrayType()) {
3650           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3651             << Type << OType;
3652           Diag(PVD->getLocation(), diag::note_declared_at);
3653         }
3654       }
3655     }
3656 
3657     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3658     // decays into a pointer and returns an unintended result. This is most
3659     // likely a typo for "sizeof(array) op x".
3660     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3661       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3662                                BO->getLHS());
3663       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3664                                BO->getRHS());
3665     }
3666   }
3667 
3668   return false;
3669 }
3670 
3671 /// Check the constraints on operands to unary expression and type
3672 /// traits.
3673 ///
3674 /// This will complete any types necessary, and validate the various constraints
3675 /// on those operands.
3676 ///
3677 /// The UsualUnaryConversions() function is *not* called by this routine.
3678 /// C99 6.3.2.1p[2-4] all state:
3679 ///   Except when it is the operand of the sizeof operator ...
3680 ///
3681 /// C++ [expr.sizeof]p4
3682 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3683 ///   standard conversions are not applied to the operand of sizeof.
3684 ///
3685 /// This policy is followed for all of the unary trait expressions.
3686 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3687                                             SourceLocation OpLoc,
3688                                             SourceRange ExprRange,
3689                                             UnaryExprOrTypeTrait ExprKind) {
3690   if (ExprType->isDependentType())
3691     return false;
3692 
3693   // C++ [expr.sizeof]p2:
3694   //     When applied to a reference or a reference type, the result
3695   //     is the size of the referenced type.
3696   // C++11 [expr.alignof]p3:
3697   //     When alignof is applied to a reference type, the result
3698   //     shall be the alignment of the referenced type.
3699   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3700     ExprType = Ref->getPointeeType();
3701 
3702   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3703   //   When alignof or _Alignof is applied to an array type, the result
3704   //   is the alignment of the element type.
3705   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3706     ExprType = Context.getBaseElementType(ExprType);
3707 
3708   if (ExprKind == UETT_VecStep)
3709     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3710 
3711   // Whitelist some types as extensions
3712   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3713                                       ExprKind))
3714     return false;
3715 
3716   if (RequireCompleteType(OpLoc, ExprType,
3717                           diag::err_sizeof_alignof_incomplete_type,
3718                           ExprKind, ExprRange))
3719     return true;
3720 
3721   if (ExprType->isFunctionType()) {
3722     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3723       << ExprKind << ExprRange;
3724     return true;
3725   }
3726 
3727   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3728                                        ExprKind))
3729     return true;
3730 
3731   return false;
3732 }
3733 
3734 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3735   E = E->IgnoreParens();
3736 
3737   // Cannot know anything else if the expression is dependent.
3738   if (E->isTypeDependent())
3739     return false;
3740 
3741   if (E->getObjectKind() == OK_BitField) {
3742     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3743        << 1 << E->getSourceRange();
3744     return true;
3745   }
3746 
3747   ValueDecl *D = nullptr;
3748   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3749     D = DRE->getDecl();
3750   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3751     D = ME->getMemberDecl();
3752   }
3753 
3754   // If it's a field, require the containing struct to have a
3755   // complete definition so that we can compute the layout.
3756   //
3757   // This can happen in C++11 onwards, either by naming the member
3758   // in a way that is not transformed into a member access expression
3759   // (in an unevaluated operand, for instance), or by naming the member
3760   // in a trailing-return-type.
3761   //
3762   // For the record, since __alignof__ on expressions is a GCC
3763   // extension, GCC seems to permit this but always gives the
3764   // nonsensical answer 0.
3765   //
3766   // We don't really need the layout here --- we could instead just
3767   // directly check for all the appropriate alignment-lowing
3768   // attributes --- but that would require duplicating a lot of
3769   // logic that just isn't worth duplicating for such a marginal
3770   // use-case.
3771   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3772     // Fast path this check, since we at least know the record has a
3773     // definition if we can find a member of it.
3774     if (!FD->getParent()->isCompleteDefinition()) {
3775       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3776         << E->getSourceRange();
3777       return true;
3778     }
3779 
3780     // Otherwise, if it's a field, and the field doesn't have
3781     // reference type, then it must have a complete type (or be a
3782     // flexible array member, which we explicitly want to
3783     // white-list anyway), which makes the following checks trivial.
3784     if (!FD->getType()->isReferenceType())
3785       return false;
3786   }
3787 
3788   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3789 }
3790 
3791 bool Sema::CheckVecStepExpr(Expr *E) {
3792   E = E->IgnoreParens();
3793 
3794   // Cannot know anything else if the expression is dependent.
3795   if (E->isTypeDependent())
3796     return false;
3797 
3798   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3799 }
3800 
3801 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3802                                         CapturingScopeInfo *CSI) {
3803   assert(T->isVariablyModifiedType());
3804   assert(CSI != nullptr);
3805 
3806   // We're going to walk down into the type and look for VLA expressions.
3807   do {
3808     const Type *Ty = T.getTypePtr();
3809     switch (Ty->getTypeClass()) {
3810 #define TYPE(Class, Base)
3811 #define ABSTRACT_TYPE(Class, Base)
3812 #define NON_CANONICAL_TYPE(Class, Base)
3813 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3814 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3815 #include "clang/AST/TypeNodes.def"
3816       T = QualType();
3817       break;
3818     // These types are never variably-modified.
3819     case Type::Builtin:
3820     case Type::Complex:
3821     case Type::Vector:
3822     case Type::ExtVector:
3823     case Type::Record:
3824     case Type::Enum:
3825     case Type::Elaborated:
3826     case Type::TemplateSpecialization:
3827     case Type::ObjCObject:
3828     case Type::ObjCInterface:
3829     case Type::ObjCObjectPointer:
3830     case Type::ObjCTypeParam:
3831     case Type::Pipe:
3832       llvm_unreachable("type class is never variably-modified!");
3833     case Type::Adjusted:
3834       T = cast<AdjustedType>(Ty)->getOriginalType();
3835       break;
3836     case Type::Decayed:
3837       T = cast<DecayedType>(Ty)->getPointeeType();
3838       break;
3839     case Type::Pointer:
3840       T = cast<PointerType>(Ty)->getPointeeType();
3841       break;
3842     case Type::BlockPointer:
3843       T = cast<BlockPointerType>(Ty)->getPointeeType();
3844       break;
3845     case Type::LValueReference:
3846     case Type::RValueReference:
3847       T = cast<ReferenceType>(Ty)->getPointeeType();
3848       break;
3849     case Type::MemberPointer:
3850       T = cast<MemberPointerType>(Ty)->getPointeeType();
3851       break;
3852     case Type::ConstantArray:
3853     case Type::IncompleteArray:
3854       // Losing element qualification here is fine.
3855       T = cast<ArrayType>(Ty)->getElementType();
3856       break;
3857     case Type::VariableArray: {
3858       // Losing element qualification here is fine.
3859       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3860 
3861       // Unknown size indication requires no size computation.
3862       // Otherwise, evaluate and record it.
3863       if (auto Size = VAT->getSizeExpr()) {
3864         if (!CSI->isVLATypeCaptured(VAT)) {
3865           RecordDecl *CapRecord = nullptr;
3866           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3867             CapRecord = LSI->Lambda;
3868           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3869             CapRecord = CRSI->TheRecordDecl;
3870           }
3871           if (CapRecord) {
3872             auto ExprLoc = Size->getExprLoc();
3873             auto SizeType = Context.getSizeType();
3874             // Build the non-static data member.
3875             auto Field =
3876                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3877                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3878                                   /*BW*/ nullptr, /*Mutable*/ false,
3879                                   /*InitStyle*/ ICIS_NoInit);
3880             Field->setImplicit(true);
3881             Field->setAccess(AS_private);
3882             Field->setCapturedVLAType(VAT);
3883             CapRecord->addDecl(Field);
3884 
3885             CSI->addVLATypeCapture(ExprLoc, SizeType);
3886           }
3887         }
3888       }
3889       T = VAT->getElementType();
3890       break;
3891     }
3892     case Type::FunctionProto:
3893     case Type::FunctionNoProto:
3894       T = cast<FunctionType>(Ty)->getReturnType();
3895       break;
3896     case Type::Paren:
3897     case Type::TypeOf:
3898     case Type::UnaryTransform:
3899     case Type::Attributed:
3900     case Type::SubstTemplateTypeParm:
3901     case Type::PackExpansion:
3902       // Keep walking after single level desugaring.
3903       T = T.getSingleStepDesugaredType(Context);
3904       break;
3905     case Type::Typedef:
3906       T = cast<TypedefType>(Ty)->desugar();
3907       break;
3908     case Type::Decltype:
3909       T = cast<DecltypeType>(Ty)->desugar();
3910       break;
3911     case Type::Auto:
3912     case Type::DeducedTemplateSpecialization:
3913       T = cast<DeducedType>(Ty)->getDeducedType();
3914       break;
3915     case Type::TypeOfExpr:
3916       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3917       break;
3918     case Type::Atomic:
3919       T = cast<AtomicType>(Ty)->getValueType();
3920       break;
3921     }
3922   } while (!T.isNull() && T->isVariablyModifiedType());
3923 }
3924 
3925 /// Build a sizeof or alignof expression given a type operand.
3926 ExprResult
3927 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3928                                      SourceLocation OpLoc,
3929                                      UnaryExprOrTypeTrait ExprKind,
3930                                      SourceRange R) {
3931   if (!TInfo)
3932     return ExprError();
3933 
3934   QualType T = TInfo->getType();
3935 
3936   if (!T->isDependentType() &&
3937       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3938     return ExprError();
3939 
3940   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3941     if (auto *TT = T->getAs<TypedefType>()) {
3942       for (auto I = FunctionScopes.rbegin(),
3943                 E = std::prev(FunctionScopes.rend());
3944            I != E; ++I) {
3945         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3946         if (CSI == nullptr)
3947           break;
3948         DeclContext *DC = nullptr;
3949         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3950           DC = LSI->CallOperator;
3951         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3952           DC = CRSI->TheCapturedDecl;
3953         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3954           DC = BSI->TheDecl;
3955         if (DC) {
3956           if (DC->containsDecl(TT->getDecl()))
3957             break;
3958           captureVariablyModifiedType(Context, T, CSI);
3959         }
3960       }
3961     }
3962   }
3963 
3964   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3965   return new (Context) UnaryExprOrTypeTraitExpr(
3966       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3967 }
3968 
3969 /// Build a sizeof or alignof expression given an expression
3970 /// operand.
3971 ExprResult
3972 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3973                                      UnaryExprOrTypeTrait ExprKind) {
3974   ExprResult PE = CheckPlaceholderExpr(E);
3975   if (PE.isInvalid())
3976     return ExprError();
3977 
3978   E = PE.get();
3979 
3980   // Verify that the operand is valid.
3981   bool isInvalid = false;
3982   if (E->isTypeDependent()) {
3983     // Delay type-checking for type-dependent expressions.
3984   } else if (ExprKind == UETT_AlignOf) {
3985     isInvalid = CheckAlignOfExpr(*this, E);
3986   } else if (ExprKind == UETT_VecStep) {
3987     isInvalid = CheckVecStepExpr(E);
3988   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3989       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3990       isInvalid = true;
3991   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3992     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3993     isInvalid = true;
3994   } else {
3995     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3996   }
3997 
3998   if (isInvalid)
3999     return ExprError();
4000 
4001   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4002     PE = TransformToPotentiallyEvaluated(E);
4003     if (PE.isInvalid()) return ExprError();
4004     E = PE.get();
4005   }
4006 
4007   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4008   return new (Context) UnaryExprOrTypeTraitExpr(
4009       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4010 }
4011 
4012 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4013 /// expr and the same for @c alignof and @c __alignof
4014 /// Note that the ArgRange is invalid if isType is false.
4015 ExprResult
4016 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4017                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4018                                     void *TyOrEx, SourceRange ArgRange) {
4019   // If error parsing type, ignore.
4020   if (!TyOrEx) return ExprError();
4021 
4022   if (IsType) {
4023     TypeSourceInfo *TInfo;
4024     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4025     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4026   }
4027 
4028   Expr *ArgEx = (Expr *)TyOrEx;
4029   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4030   return Result;
4031 }
4032 
4033 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4034                                      bool IsReal) {
4035   if (V.get()->isTypeDependent())
4036     return S.Context.DependentTy;
4037 
4038   // _Real and _Imag are only l-values for normal l-values.
4039   if (V.get()->getObjectKind() != OK_Ordinary) {
4040     V = S.DefaultLvalueConversion(V.get());
4041     if (V.isInvalid())
4042       return QualType();
4043   }
4044 
4045   // These operators return the element type of a complex type.
4046   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4047     return CT->getElementType();
4048 
4049   // Otherwise they pass through real integer and floating point types here.
4050   if (V.get()->getType()->isArithmeticType())
4051     return V.get()->getType();
4052 
4053   // Test for placeholders.
4054   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4055   if (PR.isInvalid()) return QualType();
4056   if (PR.get() != V.get()) {
4057     V = PR;
4058     return CheckRealImagOperand(S, V, Loc, IsReal);
4059   }
4060 
4061   // Reject anything else.
4062   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4063     << (IsReal ? "__real" : "__imag");
4064   return QualType();
4065 }
4066 
4067 
4068 
4069 ExprResult
4070 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4071                           tok::TokenKind Kind, Expr *Input) {
4072   UnaryOperatorKind Opc;
4073   switch (Kind) {
4074   default: llvm_unreachable("Unknown unary op!");
4075   case tok::plusplus:   Opc = UO_PostInc; break;
4076   case tok::minusminus: Opc = UO_PostDec; break;
4077   }
4078 
4079   // Since this might is a postfix expression, get rid of ParenListExprs.
4080   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4081   if (Result.isInvalid()) return ExprError();
4082   Input = Result.get();
4083 
4084   return BuildUnaryOp(S, OpLoc, Opc, Input);
4085 }
4086 
4087 /// Diagnose if arithmetic on the given ObjC pointer is illegal.
4088 ///
4089 /// \return true on error
4090 static bool checkArithmeticOnObjCPointer(Sema &S,
4091                                          SourceLocation opLoc,
4092                                          Expr *op) {
4093   assert(op->getType()->isObjCObjectPointerType());
4094   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4095       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4096     return false;
4097 
4098   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4099     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4100     << op->getSourceRange();
4101   return true;
4102 }
4103 
4104 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4105   auto *BaseNoParens = Base->IgnoreParens();
4106   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4107     return MSProp->getPropertyDecl()->getType()->isArrayType();
4108   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4109 }
4110 
4111 ExprResult
4112 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4113                               Expr *idx, SourceLocation rbLoc) {
4114   if (base && !base->getType().isNull() &&
4115       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4116     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4117                                     /*Length=*/nullptr, rbLoc);
4118 
4119   // Since this might be a postfix expression, get rid of ParenListExprs.
4120   if (isa<ParenListExpr>(base)) {
4121     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4122     if (result.isInvalid()) return ExprError();
4123     base = result.get();
4124   }
4125 
4126   // Handle any non-overload placeholder types in the base and index
4127   // expressions.  We can't handle overloads here because the other
4128   // operand might be an overloadable type, in which case the overload
4129   // resolution for the operator overload should get the first crack
4130   // at the overload.
4131   bool IsMSPropertySubscript = false;
4132   if (base->getType()->isNonOverloadPlaceholderType()) {
4133     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4134     if (!IsMSPropertySubscript) {
4135       ExprResult result = CheckPlaceholderExpr(base);
4136       if (result.isInvalid())
4137         return ExprError();
4138       base = result.get();
4139     }
4140   }
4141   if (idx->getType()->isNonOverloadPlaceholderType()) {
4142     ExprResult result = CheckPlaceholderExpr(idx);
4143     if (result.isInvalid()) return ExprError();
4144     idx = result.get();
4145   }
4146 
4147   // Build an unanalyzed expression if either operand is type-dependent.
4148   if (getLangOpts().CPlusPlus &&
4149       (base->isTypeDependent() || idx->isTypeDependent())) {
4150     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4151                                             VK_LValue, OK_Ordinary, rbLoc);
4152   }
4153 
4154   // MSDN, property (C++)
4155   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4156   // This attribute can also be used in the declaration of an empty array in a
4157   // class or structure definition. For example:
4158   // __declspec(property(get=GetX, put=PutX)) int x[];
4159   // The above statement indicates that x[] can be used with one or more array
4160   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4161   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4162   if (IsMSPropertySubscript) {
4163     // Build MS property subscript expression if base is MS property reference
4164     // or MS property subscript.
4165     return new (Context) MSPropertySubscriptExpr(
4166         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4167   }
4168 
4169   // Use C++ overloaded-operator rules if either operand has record
4170   // type.  The spec says to do this if either type is *overloadable*,
4171   // but enum types can't declare subscript operators or conversion
4172   // operators, so there's nothing interesting for overload resolution
4173   // to do if there aren't any record types involved.
4174   //
4175   // ObjC pointers have their own subscripting logic that is not tied
4176   // to overload resolution and so should not take this path.
4177   if (getLangOpts().CPlusPlus &&
4178       (base->getType()->isRecordType() ||
4179        (!base->getType()->isObjCObjectPointerType() &&
4180         idx->getType()->isRecordType()))) {
4181     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4182   }
4183 
4184   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4185 }
4186 
4187 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4188                                           Expr *LowerBound,
4189                                           SourceLocation ColonLoc, Expr *Length,
4190                                           SourceLocation RBLoc) {
4191   if (Base->getType()->isPlaceholderType() &&
4192       !Base->getType()->isSpecificPlaceholderType(
4193           BuiltinType::OMPArraySection)) {
4194     ExprResult Result = CheckPlaceholderExpr(Base);
4195     if (Result.isInvalid())
4196       return ExprError();
4197     Base = Result.get();
4198   }
4199   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4200     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4201     if (Result.isInvalid())
4202       return ExprError();
4203     Result = DefaultLvalueConversion(Result.get());
4204     if (Result.isInvalid())
4205       return ExprError();
4206     LowerBound = Result.get();
4207   }
4208   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4209     ExprResult Result = CheckPlaceholderExpr(Length);
4210     if (Result.isInvalid())
4211       return ExprError();
4212     Result = DefaultLvalueConversion(Result.get());
4213     if (Result.isInvalid())
4214       return ExprError();
4215     Length = Result.get();
4216   }
4217 
4218   // Build an unanalyzed expression if either operand is type-dependent.
4219   if (Base->isTypeDependent() ||
4220       (LowerBound &&
4221        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4222       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4223     return new (Context)
4224         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4225                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4226   }
4227 
4228   // Perform default conversions.
4229   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4230   QualType ResultTy;
4231   if (OriginalTy->isAnyPointerType()) {
4232     ResultTy = OriginalTy->getPointeeType();
4233   } else if (OriginalTy->isArrayType()) {
4234     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4235   } else {
4236     return ExprError(
4237         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4238         << Base->getSourceRange());
4239   }
4240   // C99 6.5.2.1p1
4241   if (LowerBound) {
4242     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4243                                                       LowerBound);
4244     if (Res.isInvalid())
4245       return ExprError(Diag(LowerBound->getExprLoc(),
4246                             diag::err_omp_typecheck_section_not_integer)
4247                        << 0 << LowerBound->getSourceRange());
4248     LowerBound = Res.get();
4249 
4250     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4251         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4252       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4253           << 0 << LowerBound->getSourceRange();
4254   }
4255   if (Length) {
4256     auto Res =
4257         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4258     if (Res.isInvalid())
4259       return ExprError(Diag(Length->getExprLoc(),
4260                             diag::err_omp_typecheck_section_not_integer)
4261                        << 1 << Length->getSourceRange());
4262     Length = Res.get();
4263 
4264     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4265         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4266       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4267           << 1 << Length->getSourceRange();
4268   }
4269 
4270   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4271   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4272   // type. Note that functions are not objects, and that (in C99 parlance)
4273   // incomplete types are not object types.
4274   if (ResultTy->isFunctionType()) {
4275     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4276         << ResultTy << Base->getSourceRange();
4277     return ExprError();
4278   }
4279 
4280   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4281                           diag::err_omp_section_incomplete_type, Base))
4282     return ExprError();
4283 
4284   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4285     llvm::APSInt LowerBoundValue;
4286     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4287       // OpenMP 4.5, [2.4 Array Sections]
4288       // The array section must be a subset of the original array.
4289       if (LowerBoundValue.isNegative()) {
4290         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4291             << LowerBound->getSourceRange();
4292         return ExprError();
4293       }
4294     }
4295   }
4296 
4297   if (Length) {
4298     llvm::APSInt LengthValue;
4299     if (Length->EvaluateAsInt(LengthValue, Context)) {
4300       // OpenMP 4.5, [2.4 Array Sections]
4301       // The length must evaluate to non-negative integers.
4302       if (LengthValue.isNegative()) {
4303         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4304             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4305             << Length->getSourceRange();
4306         return ExprError();
4307       }
4308     }
4309   } else if (ColonLoc.isValid() &&
4310              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4311                                       !OriginalTy->isVariableArrayType()))) {
4312     // OpenMP 4.5, [2.4 Array Sections]
4313     // When the size of the array dimension is not known, the length must be
4314     // specified explicitly.
4315     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4316         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4317     return ExprError();
4318   }
4319 
4320   if (!Base->getType()->isSpecificPlaceholderType(
4321           BuiltinType::OMPArraySection)) {
4322     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4323     if (Result.isInvalid())
4324       return ExprError();
4325     Base = Result.get();
4326   }
4327   return new (Context)
4328       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4329                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4330 }
4331 
4332 ExprResult
4333 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4334                                       Expr *Idx, SourceLocation RLoc) {
4335   Expr *LHSExp = Base;
4336   Expr *RHSExp = Idx;
4337 
4338   ExprValueKind VK = VK_LValue;
4339   ExprObjectKind OK = OK_Ordinary;
4340 
4341   // Per C++ core issue 1213, the result is an xvalue if either operand is
4342   // a non-lvalue array, and an lvalue otherwise.
4343   if (getLangOpts().CPlusPlus11 &&
4344       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4345        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4346     VK = VK_XValue;
4347 
4348   // Perform default conversions.
4349   if (!LHSExp->getType()->getAs<VectorType>()) {
4350     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4351     if (Result.isInvalid())
4352       return ExprError();
4353     LHSExp = Result.get();
4354   }
4355   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4356   if (Result.isInvalid())
4357     return ExprError();
4358   RHSExp = Result.get();
4359 
4360   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4361 
4362   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4363   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4364   // in the subscript position. As a result, we need to derive the array base
4365   // and index from the expression types.
4366   Expr *BaseExpr, *IndexExpr;
4367   QualType ResultType;
4368   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4369     BaseExpr = LHSExp;
4370     IndexExpr = RHSExp;
4371     ResultType = Context.DependentTy;
4372   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4373     BaseExpr = LHSExp;
4374     IndexExpr = RHSExp;
4375     ResultType = PTy->getPointeeType();
4376   } else if (const ObjCObjectPointerType *PTy =
4377                LHSTy->getAs<ObjCObjectPointerType>()) {
4378     BaseExpr = LHSExp;
4379     IndexExpr = RHSExp;
4380 
4381     // Use custom logic if this should be the pseudo-object subscript
4382     // expression.
4383     if (!LangOpts.isSubscriptPointerArithmetic())
4384       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4385                                           nullptr);
4386 
4387     ResultType = PTy->getPointeeType();
4388   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4389      // Handle the uncommon case of "123[Ptr]".
4390     BaseExpr = RHSExp;
4391     IndexExpr = LHSExp;
4392     ResultType = PTy->getPointeeType();
4393   } else if (const ObjCObjectPointerType *PTy =
4394                RHSTy->getAs<ObjCObjectPointerType>()) {
4395      // Handle the uncommon case of "123[Ptr]".
4396     BaseExpr = RHSExp;
4397     IndexExpr = LHSExp;
4398     ResultType = PTy->getPointeeType();
4399     if (!LangOpts.isSubscriptPointerArithmetic()) {
4400       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4401         << ResultType << BaseExpr->getSourceRange();
4402       return ExprError();
4403     }
4404   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4405     BaseExpr = LHSExp;    // vectors: V[123]
4406     IndexExpr = RHSExp;
4407     VK = LHSExp->getValueKind();
4408     if (VK != VK_RValue)
4409       OK = OK_VectorComponent;
4410 
4411     ResultType = VTy->getElementType();
4412     QualType BaseType = BaseExpr->getType();
4413     Qualifiers BaseQuals = BaseType.getQualifiers();
4414     Qualifiers MemberQuals = ResultType.getQualifiers();
4415     Qualifiers Combined = BaseQuals + MemberQuals;
4416     if (Combined != MemberQuals)
4417       ResultType = Context.getQualifiedType(ResultType, Combined);
4418   } else if (LHSTy->isArrayType()) {
4419     // If we see an array that wasn't promoted by
4420     // DefaultFunctionArrayLvalueConversion, it must be an array that
4421     // wasn't promoted because of the C90 rule that doesn't
4422     // allow promoting non-lvalue arrays.  Warn, then
4423     // force the promotion here.
4424     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4425         LHSExp->getSourceRange();
4426     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4427                                CK_ArrayToPointerDecay).get();
4428     LHSTy = LHSExp->getType();
4429 
4430     BaseExpr = LHSExp;
4431     IndexExpr = RHSExp;
4432     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4433   } else if (RHSTy->isArrayType()) {
4434     // Same as previous, except for 123[f().a] case
4435     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4436         RHSExp->getSourceRange();
4437     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4438                                CK_ArrayToPointerDecay).get();
4439     RHSTy = RHSExp->getType();
4440 
4441     BaseExpr = RHSExp;
4442     IndexExpr = LHSExp;
4443     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4444   } else {
4445     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4446        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4447   }
4448   // C99 6.5.2.1p1
4449   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4450     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4451                      << IndexExpr->getSourceRange());
4452 
4453   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4454        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4455          && !IndexExpr->isTypeDependent())
4456     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4457 
4458   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4459   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4460   // type. Note that Functions are not objects, and that (in C99 parlance)
4461   // incomplete types are not object types.
4462   if (ResultType->isFunctionType()) {
4463     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4464       << ResultType << BaseExpr->getSourceRange();
4465     return ExprError();
4466   }
4467 
4468   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4469     // GNU extension: subscripting on pointer to void
4470     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4471       << BaseExpr->getSourceRange();
4472 
4473     // C forbids expressions of unqualified void type from being l-values.
4474     // See IsCForbiddenLValueType.
4475     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4476   } else if (!ResultType->isDependentType() &&
4477       RequireCompleteType(LLoc, ResultType,
4478                           diag::err_subscript_incomplete_type, BaseExpr))
4479     return ExprError();
4480 
4481   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4482          !ResultType.isCForbiddenLValueType());
4483 
4484   return new (Context)
4485       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4486 }
4487 
4488 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4489                                   ParmVarDecl *Param) {
4490   if (Param->hasUnparsedDefaultArg()) {
4491     Diag(CallLoc,
4492          diag::err_use_of_default_argument_to_function_declared_later) <<
4493       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4494     Diag(UnparsedDefaultArgLocs[Param],
4495          diag::note_default_argument_declared_here);
4496     return true;
4497   }
4498 
4499   if (Param->hasUninstantiatedDefaultArg()) {
4500     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4501 
4502     EnterExpressionEvaluationContext EvalContext(
4503         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4504 
4505     // Instantiate the expression.
4506     //
4507     // FIXME: Pass in a correct Pattern argument, otherwise
4508     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4509     //
4510     // template<typename T>
4511     // struct A {
4512     //   static int FooImpl();
4513     //
4514     //   template<typename Tp>
4515     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4516     //   // template argument list [[T], [Tp]], should be [[Tp]].
4517     //   friend A<Tp> Foo(int a);
4518     // };
4519     //
4520     // template<typename T>
4521     // A<T> Foo(int a = A<T>::FooImpl());
4522     MultiLevelTemplateArgumentList MutiLevelArgList
4523       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4524 
4525     InstantiatingTemplate Inst(*this, CallLoc, Param,
4526                                MutiLevelArgList.getInnermost());
4527     if (Inst.isInvalid())
4528       return true;
4529     if (Inst.isAlreadyInstantiating()) {
4530       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4531       Param->setInvalidDecl();
4532       return true;
4533     }
4534 
4535     ExprResult Result;
4536     {
4537       // C++ [dcl.fct.default]p5:
4538       //   The names in the [default argument] expression are bound, and
4539       //   the semantic constraints are checked, at the point where the
4540       //   default argument expression appears.
4541       ContextRAII SavedContext(*this, FD);
4542       LocalInstantiationScope Local(*this);
4543       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4544                                 /*DirectInit*/false);
4545     }
4546     if (Result.isInvalid())
4547       return true;
4548 
4549     // Check the expression as an initializer for the parameter.
4550     InitializedEntity Entity
4551       = InitializedEntity::InitializeParameter(Context, Param);
4552     InitializationKind Kind
4553       = InitializationKind::CreateCopy(Param->getLocation(),
4554              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4555     Expr *ResultE = Result.getAs<Expr>();
4556 
4557     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4558     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4559     if (Result.isInvalid())
4560       return true;
4561 
4562     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4563                                  Param->getOuterLocStart());
4564     if (Result.isInvalid())
4565       return true;
4566 
4567     // Remember the instantiated default argument.
4568     Param->setDefaultArg(Result.getAs<Expr>());
4569     if (ASTMutationListener *L = getASTMutationListener()) {
4570       L->DefaultArgumentInstantiated(Param);
4571     }
4572   }
4573 
4574   // If the default argument expression is not set yet, we are building it now.
4575   if (!Param->hasInit()) {
4576     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4577     Param->setInvalidDecl();
4578     return true;
4579   }
4580 
4581   // If the default expression creates temporaries, we need to
4582   // push them to the current stack of expression temporaries so they'll
4583   // be properly destroyed.
4584   // FIXME: We should really be rebuilding the default argument with new
4585   // bound temporaries; see the comment in PR5810.
4586   // We don't need to do that with block decls, though, because
4587   // blocks in default argument expression can never capture anything.
4588   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4589     // Set the "needs cleanups" bit regardless of whether there are
4590     // any explicit objects.
4591     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4592 
4593     // Append all the objects to the cleanup list.  Right now, this
4594     // should always be a no-op, because blocks in default argument
4595     // expressions should never be able to capture anything.
4596     assert(!Init->getNumObjects() &&
4597            "default argument expression has capturing blocks?");
4598   }
4599 
4600   // We already type-checked the argument, so we know it works.
4601   // Just mark all of the declarations in this potentially-evaluated expression
4602   // as being "referenced".
4603   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4604                                    /*SkipLocalVariables=*/true);
4605   return false;
4606 }
4607 
4608 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4609                                         FunctionDecl *FD, ParmVarDecl *Param) {
4610   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4611     return ExprError();
4612   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4613 }
4614 
4615 Sema::VariadicCallType
4616 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4617                           Expr *Fn) {
4618   if (Proto && Proto->isVariadic()) {
4619     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4620       return VariadicConstructor;
4621     else if (Fn && Fn->getType()->isBlockPointerType())
4622       return VariadicBlock;
4623     else if (FDecl) {
4624       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4625         if (Method->isInstance())
4626           return VariadicMethod;
4627     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4628       return VariadicMethod;
4629     return VariadicFunction;
4630   }
4631   return VariadicDoesNotApply;
4632 }
4633 
4634 namespace {
4635 class FunctionCallCCC : public FunctionCallFilterCCC {
4636 public:
4637   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4638                   unsigned NumArgs, MemberExpr *ME)
4639       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4640         FunctionName(FuncName) {}
4641 
4642   bool ValidateCandidate(const TypoCorrection &candidate) override {
4643     if (!candidate.getCorrectionSpecifier() ||
4644         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4645       return false;
4646     }
4647 
4648     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4649   }
4650 
4651 private:
4652   const IdentifierInfo *const FunctionName;
4653 };
4654 }
4655 
4656 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4657                                                FunctionDecl *FDecl,
4658                                                ArrayRef<Expr *> Args) {
4659   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4660   DeclarationName FuncName = FDecl->getDeclName();
4661   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4662 
4663   if (TypoCorrection Corrected = S.CorrectTypo(
4664           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4665           S.getScopeForContext(S.CurContext), nullptr,
4666           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4667                                              Args.size(), ME),
4668           Sema::CTK_ErrorRecovery)) {
4669     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4670       if (Corrected.isOverloaded()) {
4671         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4672         OverloadCandidateSet::iterator Best;
4673         for (NamedDecl *CD : Corrected) {
4674           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4675             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4676                                    OCS);
4677         }
4678         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4679         case OR_Success:
4680           ND = Best->FoundDecl;
4681           Corrected.setCorrectionDecl(ND);
4682           break;
4683         default:
4684           break;
4685         }
4686       }
4687       ND = ND->getUnderlyingDecl();
4688       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4689         return Corrected;
4690     }
4691   }
4692   return TypoCorrection();
4693 }
4694 
4695 /// ConvertArgumentsForCall - Converts the arguments specified in
4696 /// Args/NumArgs to the parameter types of the function FDecl with
4697 /// function prototype Proto. Call is the call expression itself, and
4698 /// Fn is the function expression. For a C++ member function, this
4699 /// routine does not attempt to convert the object argument. Returns
4700 /// true if the call is ill-formed.
4701 bool
4702 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4703                               FunctionDecl *FDecl,
4704                               const FunctionProtoType *Proto,
4705                               ArrayRef<Expr *> Args,
4706                               SourceLocation RParenLoc,
4707                               bool IsExecConfig) {
4708   // Bail out early if calling a builtin with custom typechecking.
4709   if (FDecl)
4710     if (unsigned ID = FDecl->getBuiltinID())
4711       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4712         return false;
4713 
4714   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4715   // assignment, to the types of the corresponding parameter, ...
4716   unsigned NumParams = Proto->getNumParams();
4717   bool Invalid = false;
4718   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4719   unsigned FnKind = Fn->getType()->isBlockPointerType()
4720                        ? 1 /* block */
4721                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4722                                        : 0 /* function */);
4723 
4724   // If too few arguments are available (and we don't have default
4725   // arguments for the remaining parameters), don't make the call.
4726   if (Args.size() < NumParams) {
4727     if (Args.size() < MinArgs) {
4728       TypoCorrection TC;
4729       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4730         unsigned diag_id =
4731             MinArgs == NumParams && !Proto->isVariadic()
4732                 ? diag::err_typecheck_call_too_few_args_suggest
4733                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4734         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4735                                         << static_cast<unsigned>(Args.size())
4736                                         << TC.getCorrectionRange());
4737       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4738         Diag(RParenLoc,
4739              MinArgs == NumParams && !Proto->isVariadic()
4740                  ? diag::err_typecheck_call_too_few_args_one
4741                  : diag::err_typecheck_call_too_few_args_at_least_one)
4742             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4743       else
4744         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4745                             ? diag::err_typecheck_call_too_few_args
4746                             : diag::err_typecheck_call_too_few_args_at_least)
4747             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4748             << Fn->getSourceRange();
4749 
4750       // Emit the location of the prototype.
4751       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4752         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4753           << FDecl;
4754 
4755       return true;
4756     }
4757     Call->setNumArgs(Context, NumParams);
4758   }
4759 
4760   // If too many are passed and not variadic, error on the extras and drop
4761   // them.
4762   if (Args.size() > NumParams) {
4763     if (!Proto->isVariadic()) {
4764       TypoCorrection TC;
4765       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4766         unsigned diag_id =
4767             MinArgs == NumParams && !Proto->isVariadic()
4768                 ? diag::err_typecheck_call_too_many_args_suggest
4769                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4770         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4771                                         << static_cast<unsigned>(Args.size())
4772                                         << TC.getCorrectionRange());
4773       } else if (NumParams == 1 && FDecl &&
4774                  FDecl->getParamDecl(0)->getDeclName())
4775         Diag(Args[NumParams]->getLocStart(),
4776              MinArgs == NumParams
4777                  ? diag::err_typecheck_call_too_many_args_one
4778                  : diag::err_typecheck_call_too_many_args_at_most_one)
4779             << FnKind << FDecl->getParamDecl(0)
4780             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4781             << SourceRange(Args[NumParams]->getLocStart(),
4782                            Args.back()->getLocEnd());
4783       else
4784         Diag(Args[NumParams]->getLocStart(),
4785              MinArgs == NumParams
4786                  ? diag::err_typecheck_call_too_many_args
4787                  : diag::err_typecheck_call_too_many_args_at_most)
4788             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4789             << Fn->getSourceRange()
4790             << SourceRange(Args[NumParams]->getLocStart(),
4791                            Args.back()->getLocEnd());
4792 
4793       // Emit the location of the prototype.
4794       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4795         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4796           << FDecl;
4797 
4798       // This deletes the extra arguments.
4799       Call->setNumArgs(Context, NumParams);
4800       return true;
4801     }
4802   }
4803   SmallVector<Expr *, 8> AllArgs;
4804   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4805 
4806   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4807                                    Proto, 0, Args, AllArgs, CallType);
4808   if (Invalid)
4809     return true;
4810   unsigned TotalNumArgs = AllArgs.size();
4811   for (unsigned i = 0; i < TotalNumArgs; ++i)
4812     Call->setArg(i, AllArgs[i]);
4813 
4814   return false;
4815 }
4816 
4817 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4818                                   const FunctionProtoType *Proto,
4819                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4820                                   SmallVectorImpl<Expr *> &AllArgs,
4821                                   VariadicCallType CallType, bool AllowExplicit,
4822                                   bool IsListInitialization) {
4823   unsigned NumParams = Proto->getNumParams();
4824   bool Invalid = false;
4825   size_t ArgIx = 0;
4826   // Continue to check argument types (even if we have too few/many args).
4827   for (unsigned i = FirstParam; i < NumParams; i++) {
4828     QualType ProtoArgType = Proto->getParamType(i);
4829 
4830     Expr *Arg;
4831     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4832     if (ArgIx < Args.size()) {
4833       Arg = Args[ArgIx++];
4834 
4835       if (RequireCompleteType(Arg->getLocStart(),
4836                               ProtoArgType,
4837                               diag::err_call_incomplete_argument, Arg))
4838         return true;
4839 
4840       // Strip the unbridged-cast placeholder expression off, if applicable.
4841       bool CFAudited = false;
4842       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4843           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4844           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4845         Arg = stripARCUnbridgedCast(Arg);
4846       else if (getLangOpts().ObjCAutoRefCount &&
4847                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4848                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4849         CFAudited = true;
4850 
4851       if (Proto->getExtParameterInfo(i).isNoEscape())
4852         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4853           BE->getBlockDecl()->setDoesNotEscape();
4854 
4855       InitializedEntity Entity =
4856           Param ? InitializedEntity::InitializeParameter(Context, Param,
4857                                                          ProtoArgType)
4858                 : InitializedEntity::InitializeParameter(
4859                       Context, ProtoArgType, Proto->isParamConsumed(i));
4860 
4861       // Remember that parameter belongs to a CF audited API.
4862       if (CFAudited)
4863         Entity.setParameterCFAudited();
4864 
4865       ExprResult ArgE = PerformCopyInitialization(
4866           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4867       if (ArgE.isInvalid())
4868         return true;
4869 
4870       Arg = ArgE.getAs<Expr>();
4871     } else {
4872       assert(Param && "can't use default arguments without a known callee");
4873 
4874       ExprResult ArgExpr =
4875         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4876       if (ArgExpr.isInvalid())
4877         return true;
4878 
4879       Arg = ArgExpr.getAs<Expr>();
4880     }
4881 
4882     // Check for array bounds violations for each argument to the call. This
4883     // check only triggers warnings when the argument isn't a more complex Expr
4884     // with its own checking, such as a BinaryOperator.
4885     CheckArrayAccess(Arg);
4886 
4887     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4888     CheckStaticArrayArgument(CallLoc, Param, Arg);
4889 
4890     AllArgs.push_back(Arg);
4891   }
4892 
4893   // If this is a variadic call, handle args passed through "...".
4894   if (CallType != VariadicDoesNotApply) {
4895     // Assume that extern "C" functions with variadic arguments that
4896     // return __unknown_anytype aren't *really* variadic.
4897     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4898         FDecl->isExternC()) {
4899       for (Expr *A : Args.slice(ArgIx)) {
4900         QualType paramType; // ignored
4901         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4902         Invalid |= arg.isInvalid();
4903         AllArgs.push_back(arg.get());
4904       }
4905 
4906     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4907     } else {
4908       for (Expr *A : Args.slice(ArgIx)) {
4909         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4910         Invalid |= Arg.isInvalid();
4911         AllArgs.push_back(Arg.get());
4912       }
4913     }
4914 
4915     // Check for array bounds violations.
4916     for (Expr *A : Args.slice(ArgIx))
4917       CheckArrayAccess(A);
4918   }
4919   return Invalid;
4920 }
4921 
4922 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4923   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4924   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4925     TL = DTL.getOriginalLoc();
4926   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4927     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4928       << ATL.getLocalSourceRange();
4929 }
4930 
4931 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4932 /// array parameter, check that it is non-null, and that if it is formed by
4933 /// array-to-pointer decay, the underlying array is sufficiently large.
4934 ///
4935 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4936 /// array type derivation, then for each call to the function, the value of the
4937 /// corresponding actual argument shall provide access to the first element of
4938 /// an array with at least as many elements as specified by the size expression.
4939 void
4940 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4941                                ParmVarDecl *Param,
4942                                const Expr *ArgExpr) {
4943   // Static array parameters are not supported in C++.
4944   if (!Param || getLangOpts().CPlusPlus)
4945     return;
4946 
4947   QualType OrigTy = Param->getOriginalType();
4948 
4949   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4950   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4951     return;
4952 
4953   if (ArgExpr->isNullPointerConstant(Context,
4954                                      Expr::NPC_NeverValueDependent)) {
4955     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4956     DiagnoseCalleeStaticArrayParam(*this, Param);
4957     return;
4958   }
4959 
4960   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4961   if (!CAT)
4962     return;
4963 
4964   const ConstantArrayType *ArgCAT =
4965     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4966   if (!ArgCAT)
4967     return;
4968 
4969   if (ArgCAT->getSize().ult(CAT->getSize())) {
4970     Diag(CallLoc, diag::warn_static_array_too_small)
4971       << ArgExpr->getSourceRange()
4972       << (unsigned) ArgCAT->getSize().getZExtValue()
4973       << (unsigned) CAT->getSize().getZExtValue();
4974     DiagnoseCalleeStaticArrayParam(*this, Param);
4975   }
4976 }
4977 
4978 /// Given a function expression of unknown-any type, try to rebuild it
4979 /// to have a function type.
4980 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4981 
4982 /// Is the given type a placeholder that we need to lower out
4983 /// immediately during argument processing?
4984 static bool isPlaceholderToRemoveAsArg(QualType type) {
4985   // Placeholders are never sugared.
4986   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4987   if (!placeholder) return false;
4988 
4989   switch (placeholder->getKind()) {
4990   // Ignore all the non-placeholder types.
4991 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4992   case BuiltinType::Id:
4993 #include "clang/Basic/OpenCLImageTypes.def"
4994 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4995 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4996 #include "clang/AST/BuiltinTypes.def"
4997     return false;
4998 
4999   // We cannot lower out overload sets; they might validly be resolved
5000   // by the call machinery.
5001   case BuiltinType::Overload:
5002     return false;
5003 
5004   // Unbridged casts in ARC can be handled in some call positions and
5005   // should be left in place.
5006   case BuiltinType::ARCUnbridgedCast:
5007     return false;
5008 
5009   // Pseudo-objects should be converted as soon as possible.
5010   case BuiltinType::PseudoObject:
5011     return true;
5012 
5013   // The debugger mode could theoretically but currently does not try
5014   // to resolve unknown-typed arguments based on known parameter types.
5015   case BuiltinType::UnknownAny:
5016     return true;
5017 
5018   // These are always invalid as call arguments and should be reported.
5019   case BuiltinType::BoundMember:
5020   case BuiltinType::BuiltinFn:
5021   case BuiltinType::OMPArraySection:
5022     return true;
5023 
5024   }
5025   llvm_unreachable("bad builtin type kind");
5026 }
5027 
5028 /// Check an argument list for placeholders that we won't try to
5029 /// handle later.
5030 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5031   // Apply this processing to all the arguments at once instead of
5032   // dying at the first failure.
5033   bool hasInvalid = false;
5034   for (size_t i = 0, e = args.size(); i != e; i++) {
5035     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5036       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5037       if (result.isInvalid()) hasInvalid = true;
5038       else args[i] = result.get();
5039     } else if (hasInvalid) {
5040       (void)S.CorrectDelayedTyposInExpr(args[i]);
5041     }
5042   }
5043   return hasInvalid;
5044 }
5045 
5046 /// If a builtin function has a pointer argument with no explicit address
5047 /// space, then it should be able to accept a pointer to any address
5048 /// space as input.  In order to do this, we need to replace the
5049 /// standard builtin declaration with one that uses the same address space
5050 /// as the call.
5051 ///
5052 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5053 ///                  it does not contain any pointer arguments without
5054 ///                  an address space qualifer.  Otherwise the rewritten
5055 ///                  FunctionDecl is returned.
5056 /// TODO: Handle pointer return types.
5057 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5058                                                 const FunctionDecl *FDecl,
5059                                                 MultiExprArg ArgExprs) {
5060 
5061   QualType DeclType = FDecl->getType();
5062   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5063 
5064   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5065       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5066     return nullptr;
5067 
5068   bool NeedsNewDecl = false;
5069   unsigned i = 0;
5070   SmallVector<QualType, 8> OverloadParams;
5071 
5072   for (QualType ParamType : FT->param_types()) {
5073 
5074     // Convert array arguments to pointer to simplify type lookup.
5075     ExprResult ArgRes =
5076         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5077     if (ArgRes.isInvalid())
5078       return nullptr;
5079     Expr *Arg = ArgRes.get();
5080     QualType ArgType = Arg->getType();
5081     if (!ParamType->isPointerType() ||
5082         ParamType.getQualifiers().hasAddressSpace() ||
5083         !ArgType->isPointerType() ||
5084         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5085       OverloadParams.push_back(ParamType);
5086       continue;
5087     }
5088 
5089     NeedsNewDecl = true;
5090     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5091 
5092     QualType PointeeType = ParamType->getPointeeType();
5093     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5094     OverloadParams.push_back(Context.getPointerType(PointeeType));
5095   }
5096 
5097   if (!NeedsNewDecl)
5098     return nullptr;
5099 
5100   FunctionProtoType::ExtProtoInfo EPI;
5101   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5102                                                 OverloadParams, EPI);
5103   DeclContext *Parent = Context.getTranslationUnitDecl();
5104   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5105                                                     FDecl->getLocation(),
5106                                                     FDecl->getLocation(),
5107                                                     FDecl->getIdentifier(),
5108                                                     OverloadTy,
5109                                                     /*TInfo=*/nullptr,
5110                                                     SC_Extern, false,
5111                                                     /*hasPrototype=*/true);
5112   SmallVector<ParmVarDecl*, 16> Params;
5113   FT = cast<FunctionProtoType>(OverloadTy);
5114   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5115     QualType ParamType = FT->getParamType(i);
5116     ParmVarDecl *Parm =
5117         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5118                                 SourceLocation(), nullptr, ParamType,
5119                                 /*TInfo=*/nullptr, SC_None, nullptr);
5120     Parm->setScopeInfo(0, i);
5121     Params.push_back(Parm);
5122   }
5123   OverloadDecl->setParams(Params);
5124   return OverloadDecl;
5125 }
5126 
5127 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5128                                     FunctionDecl *Callee,
5129                                     MultiExprArg ArgExprs) {
5130   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5131   // similar attributes) really don't like it when functions are called with an
5132   // invalid number of args.
5133   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5134                          /*PartialOverloading=*/false) &&
5135       !Callee->isVariadic())
5136     return;
5137   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5138     return;
5139 
5140   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5141     S.Diag(Fn->getLocStart(),
5142            isa<CXXMethodDecl>(Callee)
5143                ? diag::err_ovl_no_viable_member_function_in_call
5144                : diag::err_ovl_no_viable_function_in_call)
5145         << Callee << Callee->getSourceRange();
5146     S.Diag(Callee->getLocation(),
5147            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5148         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5149     return;
5150   }
5151 }
5152 
5153 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5154     const UnresolvedMemberExpr *const UME, Sema &S) {
5155 
5156   const auto GetFunctionLevelDCIfCXXClass =
5157       [](Sema &S) -> const CXXRecordDecl * {
5158     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5159     if (!DC || !DC->getParent())
5160       return nullptr;
5161 
5162     // If the call to some member function was made from within a member
5163     // function body 'M' return return 'M's parent.
5164     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5165       return MD->getParent()->getCanonicalDecl();
5166     // else the call was made from within a default member initializer of a
5167     // class, so return the class.
5168     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5169       return RD->getCanonicalDecl();
5170     return nullptr;
5171   };
5172   // If our DeclContext is neither a member function nor a class (in the
5173   // case of a lambda in a default member initializer), we can't have an
5174   // enclosing 'this'.
5175 
5176   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5177   if (!CurParentClass)
5178     return false;
5179 
5180   // The naming class for implicit member functions call is the class in which
5181   // name lookup starts.
5182   const CXXRecordDecl *const NamingClass =
5183       UME->getNamingClass()->getCanonicalDecl();
5184   assert(NamingClass && "Must have naming class even for implicit access");
5185 
5186   // If the unresolved member functions were found in a 'naming class' that is
5187   // related (either the same or derived from) to the class that contains the
5188   // member function that itself contained the implicit member access.
5189 
5190   return CurParentClass == NamingClass ||
5191          CurParentClass->isDerivedFrom(NamingClass);
5192 }
5193 
5194 static void
5195 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5196     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5197 
5198   if (!UME)
5199     return;
5200 
5201   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5202   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5203   // already been captured, or if this is an implicit member function call (if
5204   // it isn't, an attempt to capture 'this' should already have been made).
5205   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5206       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5207     return;
5208 
5209   // Check if the naming class in which the unresolved members were found is
5210   // related (same as or is a base of) to the enclosing class.
5211 
5212   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5213     return;
5214 
5215 
5216   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5217   // If the enclosing function is not dependent, then this lambda is
5218   // capture ready, so if we can capture this, do so.
5219   if (!EnclosingFunctionCtx->isDependentContext()) {
5220     // If the current lambda and all enclosing lambdas can capture 'this' -
5221     // then go ahead and capture 'this' (since our unresolved overload set
5222     // contains at least one non-static member function).
5223     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5224       S.CheckCXXThisCapture(CallLoc);
5225   } else if (S.CurContext->isDependentContext()) {
5226     // ... since this is an implicit member reference, that might potentially
5227     // involve a 'this' capture, mark 'this' for potential capture in
5228     // enclosing lambdas.
5229     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5230       CurLSI->addPotentialThisCapture(CallLoc);
5231   }
5232 }
5233 
5234 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5235 /// This provides the location of the left/right parens and a list of comma
5236 /// locations.
5237 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5238                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5239                                Expr *ExecConfig, bool IsExecConfig) {
5240   // Since this might be a postfix expression, get rid of ParenListExprs.
5241   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5242   if (Result.isInvalid()) return ExprError();
5243   Fn = Result.get();
5244 
5245   if (checkArgsForPlaceholders(*this, ArgExprs))
5246     return ExprError();
5247 
5248   if (getLangOpts().CPlusPlus) {
5249     // If this is a pseudo-destructor expression, build the call immediately.
5250     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5251       if (!ArgExprs.empty()) {
5252         // Pseudo-destructor calls should not have any arguments.
5253         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5254             << FixItHint::CreateRemoval(
5255                    SourceRange(ArgExprs.front()->getLocStart(),
5256                                ArgExprs.back()->getLocEnd()));
5257       }
5258 
5259       return new (Context)
5260           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5261     }
5262     if (Fn->getType() == Context.PseudoObjectTy) {
5263       ExprResult result = CheckPlaceholderExpr(Fn);
5264       if (result.isInvalid()) return ExprError();
5265       Fn = result.get();
5266     }
5267 
5268     // Determine whether this is a dependent call inside a C++ template,
5269     // in which case we won't do any semantic analysis now.
5270     bool Dependent = false;
5271     if (Fn->isTypeDependent())
5272       Dependent = true;
5273     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5274       Dependent = true;
5275 
5276     if (Dependent) {
5277       if (ExecConfig) {
5278         return new (Context) CUDAKernelCallExpr(
5279             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5280             Context.DependentTy, VK_RValue, RParenLoc);
5281       } else {
5282 
5283        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5284             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5285             Fn->getLocStart());
5286 
5287         return new (Context) CallExpr(
5288             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5289       }
5290     }
5291 
5292     // Determine whether this is a call to an object (C++ [over.call.object]).
5293     if (Fn->getType()->isRecordType())
5294       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5295                                           RParenLoc);
5296 
5297     if (Fn->getType() == Context.UnknownAnyTy) {
5298       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5299       if (result.isInvalid()) return ExprError();
5300       Fn = result.get();
5301     }
5302 
5303     if (Fn->getType() == Context.BoundMemberTy) {
5304       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5305                                        RParenLoc);
5306     }
5307   }
5308 
5309   // Check for overloaded calls.  This can happen even in C due to extensions.
5310   if (Fn->getType() == Context.OverloadTy) {
5311     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5312 
5313     // We aren't supposed to apply this logic if there's an '&' involved.
5314     if (!find.HasFormOfMemberPointer) {
5315       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5316         return new (Context) CallExpr(
5317             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5318       OverloadExpr *ovl = find.Expression;
5319       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5320         return BuildOverloadedCallExpr(
5321             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5322             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5323       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5324                                        RParenLoc);
5325     }
5326   }
5327 
5328   // If we're directly calling a function, get the appropriate declaration.
5329   if (Fn->getType() == Context.UnknownAnyTy) {
5330     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5331     if (result.isInvalid()) return ExprError();
5332     Fn = result.get();
5333   }
5334 
5335   Expr *NakedFn = Fn->IgnoreParens();
5336 
5337   bool CallingNDeclIndirectly = false;
5338   NamedDecl *NDecl = nullptr;
5339   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5340     if (UnOp->getOpcode() == UO_AddrOf) {
5341       CallingNDeclIndirectly = true;
5342       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5343     }
5344   }
5345 
5346   if (isa<DeclRefExpr>(NakedFn)) {
5347     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5348 
5349     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5350     if (FDecl && FDecl->getBuiltinID()) {
5351       // Rewrite the function decl for this builtin by replacing parameters
5352       // with no explicit address space with the address space of the arguments
5353       // in ArgExprs.
5354       if ((FDecl =
5355                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5356         NDecl = FDecl;
5357         Fn = DeclRefExpr::Create(
5358             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5359             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5360       }
5361     }
5362   } else if (isa<MemberExpr>(NakedFn))
5363     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5364 
5365   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5366     if (CallingNDeclIndirectly &&
5367         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5368                                            Fn->getLocStart()))
5369       return ExprError();
5370 
5371     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5372       return ExprError();
5373 
5374     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5375   }
5376 
5377   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5378                                ExecConfig, IsExecConfig);
5379 }
5380 
5381 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5382 ///
5383 /// __builtin_astype( value, dst type )
5384 ///
5385 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5386                                  SourceLocation BuiltinLoc,
5387                                  SourceLocation RParenLoc) {
5388   ExprValueKind VK = VK_RValue;
5389   ExprObjectKind OK = OK_Ordinary;
5390   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5391   QualType SrcTy = E->getType();
5392   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5393     return ExprError(Diag(BuiltinLoc,
5394                           diag::err_invalid_astype_of_different_size)
5395                      << DstTy
5396                      << SrcTy
5397                      << E->getSourceRange());
5398   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5399 }
5400 
5401 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5402 /// provided arguments.
5403 ///
5404 /// __builtin_convertvector( value, dst type )
5405 ///
5406 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5407                                         SourceLocation BuiltinLoc,
5408                                         SourceLocation RParenLoc) {
5409   TypeSourceInfo *TInfo;
5410   GetTypeFromParser(ParsedDestTy, &TInfo);
5411   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5412 }
5413 
5414 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5415 /// i.e. an expression not of \p OverloadTy.  The expression should
5416 /// unary-convert to an expression of function-pointer or
5417 /// block-pointer type.
5418 ///
5419 /// \param NDecl the declaration being called, if available
5420 ExprResult
5421 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5422                             SourceLocation LParenLoc,
5423                             ArrayRef<Expr *> Args,
5424                             SourceLocation RParenLoc,
5425                             Expr *Config, bool IsExecConfig) {
5426   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5427   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5428 
5429   // Functions with 'interrupt' attribute cannot be called directly.
5430   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5431     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5432     return ExprError();
5433   }
5434 
5435   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5436   // so there's some risk when calling out to non-interrupt handler functions
5437   // that the callee might not preserve them. This is easy to diagnose here,
5438   // but can be very challenging to debug.
5439   if (auto *Caller = getCurFunctionDecl())
5440     if (Caller->hasAttr<ARMInterruptAttr>()) {
5441       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5442       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5443         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5444     }
5445 
5446   // Promote the function operand.
5447   // We special-case function promotion here because we only allow promoting
5448   // builtin functions to function pointers in the callee of a call.
5449   ExprResult Result;
5450   if (BuiltinID &&
5451       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5452     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5453                                CK_BuiltinFnToFnPtr).get();
5454   } else {
5455     Result = CallExprUnaryConversions(Fn);
5456   }
5457   if (Result.isInvalid())
5458     return ExprError();
5459   Fn = Result.get();
5460 
5461   // Make the call expr early, before semantic checks.  This guarantees cleanup
5462   // of arguments and function on error.
5463   CallExpr *TheCall;
5464   if (Config)
5465     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5466                                                cast<CallExpr>(Config), Args,
5467                                                Context.BoolTy, VK_RValue,
5468                                                RParenLoc);
5469   else
5470     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5471                                      VK_RValue, RParenLoc);
5472 
5473   if (!getLangOpts().CPlusPlus) {
5474     // C cannot always handle TypoExpr nodes in builtin calls and direct
5475     // function calls as their argument checking don't necessarily handle
5476     // dependent types properly, so make sure any TypoExprs have been
5477     // dealt with.
5478     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5479     if (!Result.isUsable()) return ExprError();
5480     TheCall = dyn_cast<CallExpr>(Result.get());
5481     if (!TheCall) return Result;
5482     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5483   }
5484 
5485   // Bail out early if calling a builtin with custom typechecking.
5486   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5487     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5488 
5489  retry:
5490   const FunctionType *FuncT;
5491   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5492     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5493     // have type pointer to function".
5494     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5495     if (!FuncT)
5496       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5497                          << Fn->getType() << Fn->getSourceRange());
5498   } else if (const BlockPointerType *BPT =
5499                Fn->getType()->getAs<BlockPointerType>()) {
5500     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5501   } else {
5502     // Handle calls to expressions of unknown-any type.
5503     if (Fn->getType() == Context.UnknownAnyTy) {
5504       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5505       if (rewrite.isInvalid()) return ExprError();
5506       Fn = rewrite.get();
5507       TheCall->setCallee(Fn);
5508       goto retry;
5509     }
5510 
5511     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5512       << Fn->getType() << Fn->getSourceRange());
5513   }
5514 
5515   if (getLangOpts().CUDA) {
5516     if (Config) {
5517       // CUDA: Kernel calls must be to global functions
5518       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5519         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5520             << FDecl << Fn->getSourceRange());
5521 
5522       // CUDA: Kernel function must have 'void' return type
5523       if (!FuncT->getReturnType()->isVoidType())
5524         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5525             << Fn->getType() << Fn->getSourceRange());
5526     } else {
5527       // CUDA: Calls to global functions must be configured
5528       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5529         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5530             << FDecl << Fn->getSourceRange());
5531     }
5532   }
5533 
5534   // Check for a valid return type
5535   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5536                           FDecl))
5537     return ExprError();
5538 
5539   // We know the result type of the call, set it.
5540   TheCall->setType(FuncT->getCallResultType(Context));
5541   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5542 
5543   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5544   if (Proto) {
5545     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5546                                 IsExecConfig))
5547       return ExprError();
5548   } else {
5549     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5550 
5551     if (FDecl) {
5552       // Check if we have too few/too many template arguments, based
5553       // on our knowledge of the function definition.
5554       const FunctionDecl *Def = nullptr;
5555       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5556         Proto = Def->getType()->getAs<FunctionProtoType>();
5557        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5558           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5559           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5560       }
5561 
5562       // If the function we're calling isn't a function prototype, but we have
5563       // a function prototype from a prior declaratiom, use that prototype.
5564       if (!FDecl->hasPrototype())
5565         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5566     }
5567 
5568     // Promote the arguments (C99 6.5.2.2p6).
5569     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5570       Expr *Arg = Args[i];
5571 
5572       if (Proto && i < Proto->getNumParams()) {
5573         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5574             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5575         ExprResult ArgE =
5576             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5577         if (ArgE.isInvalid())
5578           return true;
5579 
5580         Arg = ArgE.getAs<Expr>();
5581 
5582       } else {
5583         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5584 
5585         if (ArgE.isInvalid())
5586           return true;
5587 
5588         Arg = ArgE.getAs<Expr>();
5589       }
5590 
5591       if (RequireCompleteType(Arg->getLocStart(),
5592                               Arg->getType(),
5593                               diag::err_call_incomplete_argument, Arg))
5594         return ExprError();
5595 
5596       TheCall->setArg(i, Arg);
5597     }
5598   }
5599 
5600   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5601     if (!Method->isStatic())
5602       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5603         << Fn->getSourceRange());
5604 
5605   // Check for sentinels
5606   if (NDecl)
5607     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5608 
5609   // Do special checking on direct calls to functions.
5610   if (FDecl) {
5611     if (CheckFunctionCall(FDecl, TheCall, Proto))
5612       return ExprError();
5613 
5614     if (BuiltinID)
5615       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5616   } else if (NDecl) {
5617     if (CheckPointerCall(NDecl, TheCall, Proto))
5618       return ExprError();
5619   } else {
5620     if (CheckOtherCall(TheCall, Proto))
5621       return ExprError();
5622   }
5623 
5624   return MaybeBindToTemporary(TheCall);
5625 }
5626 
5627 ExprResult
5628 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5629                            SourceLocation RParenLoc, Expr *InitExpr) {
5630   assert(Ty && "ActOnCompoundLiteral(): missing type");
5631   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5632 
5633   TypeSourceInfo *TInfo;
5634   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5635   if (!TInfo)
5636     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5637 
5638   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5639 }
5640 
5641 ExprResult
5642 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5643                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5644   QualType literalType = TInfo->getType();
5645 
5646   if (literalType->isArrayType()) {
5647     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5648           diag::err_illegal_decl_array_incomplete_type,
5649           SourceRange(LParenLoc,
5650                       LiteralExpr->getSourceRange().getEnd())))
5651       return ExprError();
5652     if (literalType->isVariableArrayType())
5653       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5654         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5655   } else if (!literalType->isDependentType() &&
5656              RequireCompleteType(LParenLoc, literalType,
5657                diag::err_typecheck_decl_incomplete_type,
5658                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5659     return ExprError();
5660 
5661   InitializedEntity Entity
5662     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5663   InitializationKind Kind
5664     = InitializationKind::CreateCStyleCast(LParenLoc,
5665                                            SourceRange(LParenLoc, RParenLoc),
5666                                            /*InitList=*/true);
5667   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5668   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5669                                       &literalType);
5670   if (Result.isInvalid())
5671     return ExprError();
5672   LiteralExpr = Result.get();
5673 
5674   bool isFileScope = !CurContext->isFunctionOrMethod();
5675   if (isFileScope &&
5676       !LiteralExpr->isTypeDependent() &&
5677       !LiteralExpr->isValueDependent() &&
5678       !literalType->isDependentType()) { // 6.5.2.5p3
5679     if (CheckForConstantInitializer(LiteralExpr, literalType))
5680       return ExprError();
5681   }
5682 
5683   // In C, compound literals are l-values for some reason.
5684   // For GCC compatibility, in C++, file-scope array compound literals with
5685   // constant initializers are also l-values, and compound literals are
5686   // otherwise prvalues.
5687   //
5688   // (GCC also treats C++ list-initialized file-scope array prvalues with
5689   // constant initializers as l-values, but that's non-conforming, so we don't
5690   // follow it there.)
5691   //
5692   // FIXME: It would be better to handle the lvalue cases as materializing and
5693   // lifetime-extending a temporary object, but our materialized temporaries
5694   // representation only supports lifetime extension from a variable, not "out
5695   // of thin air".
5696   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5697   // is bound to the result of applying array-to-pointer decay to the compound
5698   // literal.
5699   // FIXME: GCC supports compound literals of reference type, which should
5700   // obviously have a value kind derived from the kind of reference involved.
5701   ExprValueKind VK =
5702       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5703           ? VK_RValue
5704           : VK_LValue;
5705 
5706   return MaybeBindToTemporary(
5707       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5708                                         VK, LiteralExpr, isFileScope));
5709 }
5710 
5711 ExprResult
5712 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5713                     SourceLocation RBraceLoc) {
5714   // Immediately handle non-overload placeholders.  Overloads can be
5715   // resolved contextually, but everything else here can't.
5716   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5717     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5718       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5719 
5720       // Ignore failures; dropping the entire initializer list because
5721       // of one failure would be terrible for indexing/etc.
5722       if (result.isInvalid()) continue;
5723 
5724       InitArgList[I] = result.get();
5725     }
5726   }
5727 
5728   // Semantic analysis for initializers is done by ActOnDeclarator() and
5729   // CheckInitializer() - it requires knowledge of the object being initialized.
5730 
5731   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5732                                                RBraceLoc);
5733   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5734   return E;
5735 }
5736 
5737 /// Do an explicit extend of the given block pointer if we're in ARC.
5738 void Sema::maybeExtendBlockObject(ExprResult &E) {
5739   assert(E.get()->getType()->isBlockPointerType());
5740   assert(E.get()->isRValue());
5741 
5742   // Only do this in an r-value context.
5743   if (!getLangOpts().ObjCAutoRefCount) return;
5744 
5745   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5746                                CK_ARCExtendBlockObject, E.get(),
5747                                /*base path*/ nullptr, VK_RValue);
5748   Cleanup.setExprNeedsCleanups(true);
5749 }
5750 
5751 /// Prepare a conversion of the given expression to an ObjC object
5752 /// pointer type.
5753 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5754   QualType type = E.get()->getType();
5755   if (type->isObjCObjectPointerType()) {
5756     return CK_BitCast;
5757   } else if (type->isBlockPointerType()) {
5758     maybeExtendBlockObject(E);
5759     return CK_BlockPointerToObjCPointerCast;
5760   } else {
5761     assert(type->isPointerType());
5762     return CK_CPointerToObjCPointerCast;
5763   }
5764 }
5765 
5766 /// Prepares for a scalar cast, performing all the necessary stages
5767 /// except the final cast and returning the kind required.
5768 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5769   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5770   // Also, callers should have filtered out the invalid cases with
5771   // pointers.  Everything else should be possible.
5772 
5773   QualType SrcTy = Src.get()->getType();
5774   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5775     return CK_NoOp;
5776 
5777   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5778   case Type::STK_MemberPointer:
5779     llvm_unreachable("member pointer type in C");
5780 
5781   case Type::STK_CPointer:
5782   case Type::STK_BlockPointer:
5783   case Type::STK_ObjCObjectPointer:
5784     switch (DestTy->getScalarTypeKind()) {
5785     case Type::STK_CPointer: {
5786       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5787       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5788       if (SrcAS != DestAS)
5789         return CK_AddressSpaceConversion;
5790       return CK_BitCast;
5791     }
5792     case Type::STK_BlockPointer:
5793       return (SrcKind == Type::STK_BlockPointer
5794                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5795     case Type::STK_ObjCObjectPointer:
5796       if (SrcKind == Type::STK_ObjCObjectPointer)
5797         return CK_BitCast;
5798       if (SrcKind == Type::STK_CPointer)
5799         return CK_CPointerToObjCPointerCast;
5800       maybeExtendBlockObject(Src);
5801       return CK_BlockPointerToObjCPointerCast;
5802     case Type::STK_Bool:
5803       return CK_PointerToBoolean;
5804     case Type::STK_Integral:
5805       return CK_PointerToIntegral;
5806     case Type::STK_Floating:
5807     case Type::STK_FloatingComplex:
5808     case Type::STK_IntegralComplex:
5809     case Type::STK_MemberPointer:
5810       llvm_unreachable("illegal cast from pointer");
5811     }
5812     llvm_unreachable("Should have returned before this");
5813 
5814   case Type::STK_Bool: // casting from bool is like casting from an integer
5815   case Type::STK_Integral:
5816     switch (DestTy->getScalarTypeKind()) {
5817     case Type::STK_CPointer:
5818     case Type::STK_ObjCObjectPointer:
5819     case Type::STK_BlockPointer:
5820       if (Src.get()->isNullPointerConstant(Context,
5821                                            Expr::NPC_ValueDependentIsNull))
5822         return CK_NullToPointer;
5823       return CK_IntegralToPointer;
5824     case Type::STK_Bool:
5825       return CK_IntegralToBoolean;
5826     case Type::STK_Integral:
5827       return CK_IntegralCast;
5828     case Type::STK_Floating:
5829       return CK_IntegralToFloating;
5830     case Type::STK_IntegralComplex:
5831       Src = ImpCastExprToType(Src.get(),
5832                       DestTy->castAs<ComplexType>()->getElementType(),
5833                       CK_IntegralCast);
5834       return CK_IntegralRealToComplex;
5835     case Type::STK_FloatingComplex:
5836       Src = ImpCastExprToType(Src.get(),
5837                       DestTy->castAs<ComplexType>()->getElementType(),
5838                       CK_IntegralToFloating);
5839       return CK_FloatingRealToComplex;
5840     case Type::STK_MemberPointer:
5841       llvm_unreachable("member pointer type in C");
5842     }
5843     llvm_unreachable("Should have returned before this");
5844 
5845   case Type::STK_Floating:
5846     switch (DestTy->getScalarTypeKind()) {
5847     case Type::STK_Floating:
5848       return CK_FloatingCast;
5849     case Type::STK_Bool:
5850       return CK_FloatingToBoolean;
5851     case Type::STK_Integral:
5852       return CK_FloatingToIntegral;
5853     case Type::STK_FloatingComplex:
5854       Src = ImpCastExprToType(Src.get(),
5855                               DestTy->castAs<ComplexType>()->getElementType(),
5856                               CK_FloatingCast);
5857       return CK_FloatingRealToComplex;
5858     case Type::STK_IntegralComplex:
5859       Src = ImpCastExprToType(Src.get(),
5860                               DestTy->castAs<ComplexType>()->getElementType(),
5861                               CK_FloatingToIntegral);
5862       return CK_IntegralRealToComplex;
5863     case Type::STK_CPointer:
5864     case Type::STK_ObjCObjectPointer:
5865     case Type::STK_BlockPointer:
5866       llvm_unreachable("valid float->pointer cast?");
5867     case Type::STK_MemberPointer:
5868       llvm_unreachable("member pointer type in C");
5869     }
5870     llvm_unreachable("Should have returned before this");
5871 
5872   case Type::STK_FloatingComplex:
5873     switch (DestTy->getScalarTypeKind()) {
5874     case Type::STK_FloatingComplex:
5875       return CK_FloatingComplexCast;
5876     case Type::STK_IntegralComplex:
5877       return CK_FloatingComplexToIntegralComplex;
5878     case Type::STK_Floating: {
5879       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5880       if (Context.hasSameType(ET, DestTy))
5881         return CK_FloatingComplexToReal;
5882       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5883       return CK_FloatingCast;
5884     }
5885     case Type::STK_Bool:
5886       return CK_FloatingComplexToBoolean;
5887     case Type::STK_Integral:
5888       Src = ImpCastExprToType(Src.get(),
5889                               SrcTy->castAs<ComplexType>()->getElementType(),
5890                               CK_FloatingComplexToReal);
5891       return CK_FloatingToIntegral;
5892     case Type::STK_CPointer:
5893     case Type::STK_ObjCObjectPointer:
5894     case Type::STK_BlockPointer:
5895       llvm_unreachable("valid complex float->pointer cast?");
5896     case Type::STK_MemberPointer:
5897       llvm_unreachable("member pointer type in C");
5898     }
5899     llvm_unreachable("Should have returned before this");
5900 
5901   case Type::STK_IntegralComplex:
5902     switch (DestTy->getScalarTypeKind()) {
5903     case Type::STK_FloatingComplex:
5904       return CK_IntegralComplexToFloatingComplex;
5905     case Type::STK_IntegralComplex:
5906       return CK_IntegralComplexCast;
5907     case Type::STK_Integral: {
5908       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5909       if (Context.hasSameType(ET, DestTy))
5910         return CK_IntegralComplexToReal;
5911       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5912       return CK_IntegralCast;
5913     }
5914     case Type::STK_Bool:
5915       return CK_IntegralComplexToBoolean;
5916     case Type::STK_Floating:
5917       Src = ImpCastExprToType(Src.get(),
5918                               SrcTy->castAs<ComplexType>()->getElementType(),
5919                               CK_IntegralComplexToReal);
5920       return CK_IntegralToFloating;
5921     case Type::STK_CPointer:
5922     case Type::STK_ObjCObjectPointer:
5923     case Type::STK_BlockPointer:
5924       llvm_unreachable("valid complex int->pointer cast?");
5925     case Type::STK_MemberPointer:
5926       llvm_unreachable("member pointer type in C");
5927     }
5928     llvm_unreachable("Should have returned before this");
5929   }
5930 
5931   llvm_unreachable("Unhandled scalar cast");
5932 }
5933 
5934 static bool breakDownVectorType(QualType type, uint64_t &len,
5935                                 QualType &eltType) {
5936   // Vectors are simple.
5937   if (const VectorType *vecType = type->getAs<VectorType>()) {
5938     len = vecType->getNumElements();
5939     eltType = vecType->getElementType();
5940     assert(eltType->isScalarType());
5941     return true;
5942   }
5943 
5944   // We allow lax conversion to and from non-vector types, but only if
5945   // they're real types (i.e. non-complex, non-pointer scalar types).
5946   if (!type->isRealType()) return false;
5947 
5948   len = 1;
5949   eltType = type;
5950   return true;
5951 }
5952 
5953 /// Are the two types lax-compatible vector types?  That is, given
5954 /// that one of them is a vector, do they have equal storage sizes,
5955 /// where the storage size is the number of elements times the element
5956 /// size?
5957 ///
5958 /// This will also return false if either of the types is neither a
5959 /// vector nor a real type.
5960 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5961   assert(destTy->isVectorType() || srcTy->isVectorType());
5962 
5963   // Disallow lax conversions between scalars and ExtVectors (these
5964   // conversions are allowed for other vector types because common headers
5965   // depend on them).  Most scalar OP ExtVector cases are handled by the
5966   // splat path anyway, which does what we want (convert, not bitcast).
5967   // What this rules out for ExtVectors is crazy things like char4*float.
5968   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5969   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5970 
5971   uint64_t srcLen, destLen;
5972   QualType srcEltTy, destEltTy;
5973   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5974   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5975 
5976   // ASTContext::getTypeSize will return the size rounded up to a
5977   // power of 2, so instead of using that, we need to use the raw
5978   // element size multiplied by the element count.
5979   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5980   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5981 
5982   return (srcLen * srcEltSize == destLen * destEltSize);
5983 }
5984 
5985 /// Is this a legal conversion between two types, one of which is
5986 /// known to be a vector type?
5987 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5988   assert(destTy->isVectorType() || srcTy->isVectorType());
5989 
5990   if (!Context.getLangOpts().LaxVectorConversions)
5991     return false;
5992   return areLaxCompatibleVectorTypes(srcTy, destTy);
5993 }
5994 
5995 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5996                            CastKind &Kind) {
5997   assert(VectorTy->isVectorType() && "Not a vector type!");
5998 
5999   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
6000     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
6001       return Diag(R.getBegin(),
6002                   Ty->isVectorType() ?
6003                   diag::err_invalid_conversion_between_vectors :
6004                   diag::err_invalid_conversion_between_vector_and_integer)
6005         << VectorTy << Ty << R;
6006   } else
6007     return Diag(R.getBegin(),
6008                 diag::err_invalid_conversion_between_vector_and_scalar)
6009       << VectorTy << Ty << R;
6010 
6011   Kind = CK_BitCast;
6012   return false;
6013 }
6014 
6015 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6016   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6017 
6018   if (DestElemTy == SplattedExpr->getType())
6019     return SplattedExpr;
6020 
6021   assert(DestElemTy->isFloatingType() ||
6022          DestElemTy->isIntegralOrEnumerationType());
6023 
6024   CastKind CK;
6025   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6026     // OpenCL requires that we convert `true` boolean expressions to -1, but
6027     // only when splatting vectors.
6028     if (DestElemTy->isFloatingType()) {
6029       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6030       // in two steps: boolean to signed integral, then to floating.
6031       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6032                                                  CK_BooleanToSignedIntegral);
6033       SplattedExpr = CastExprRes.get();
6034       CK = CK_IntegralToFloating;
6035     } else {
6036       CK = CK_BooleanToSignedIntegral;
6037     }
6038   } else {
6039     ExprResult CastExprRes = SplattedExpr;
6040     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6041     if (CastExprRes.isInvalid())
6042       return ExprError();
6043     SplattedExpr = CastExprRes.get();
6044   }
6045   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6046 }
6047 
6048 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6049                                     Expr *CastExpr, CastKind &Kind) {
6050   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6051 
6052   QualType SrcTy = CastExpr->getType();
6053 
6054   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6055   // an ExtVectorType.
6056   // In OpenCL, casts between vectors of different types are not allowed.
6057   // (See OpenCL 6.2).
6058   if (SrcTy->isVectorType()) {
6059     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6060         (getLangOpts().OpenCL &&
6061          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6062       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6063         << DestTy << SrcTy << R;
6064       return ExprError();
6065     }
6066     Kind = CK_BitCast;
6067     return CastExpr;
6068   }
6069 
6070   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6071   // conversion will take place first from scalar to elt type, and then
6072   // splat from elt type to vector.
6073   if (SrcTy->isPointerType())
6074     return Diag(R.getBegin(),
6075                 diag::err_invalid_conversion_between_vector_and_scalar)
6076       << DestTy << SrcTy << R;
6077 
6078   Kind = CK_VectorSplat;
6079   return prepareVectorSplat(DestTy, CastExpr);
6080 }
6081 
6082 ExprResult
6083 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6084                     Declarator &D, ParsedType &Ty,
6085                     SourceLocation RParenLoc, Expr *CastExpr) {
6086   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6087          "ActOnCastExpr(): missing type or expr");
6088 
6089   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6090   if (D.isInvalidType())
6091     return ExprError();
6092 
6093   if (getLangOpts().CPlusPlus) {
6094     // Check that there are no default arguments (C++ only).
6095     CheckExtraCXXDefaultArguments(D);
6096   } else {
6097     // Make sure any TypoExprs have been dealt with.
6098     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6099     if (!Res.isUsable())
6100       return ExprError();
6101     CastExpr = Res.get();
6102   }
6103 
6104   checkUnusedDeclAttributes(D);
6105 
6106   QualType castType = castTInfo->getType();
6107   Ty = CreateParsedType(castType, castTInfo);
6108 
6109   bool isVectorLiteral = false;
6110 
6111   // Check for an altivec or OpenCL literal,
6112   // i.e. all the elements are integer constants.
6113   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6114   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6115   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6116        && castType->isVectorType() && (PE || PLE)) {
6117     if (PLE && PLE->getNumExprs() == 0) {
6118       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6119       return ExprError();
6120     }
6121     if (PE || PLE->getNumExprs() == 1) {
6122       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6123       if (!E->getType()->isVectorType())
6124         isVectorLiteral = true;
6125     }
6126     else
6127       isVectorLiteral = true;
6128   }
6129 
6130   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6131   // then handle it as such.
6132   if (isVectorLiteral)
6133     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6134 
6135   // If the Expr being casted is a ParenListExpr, handle it specially.
6136   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6137   // sequence of BinOp comma operators.
6138   if (isa<ParenListExpr>(CastExpr)) {
6139     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6140     if (Result.isInvalid()) return ExprError();
6141     CastExpr = Result.get();
6142   }
6143 
6144   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6145       !getSourceManager().isInSystemMacro(LParenLoc))
6146     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6147 
6148   CheckTollFreeBridgeCast(castType, CastExpr);
6149 
6150   CheckObjCBridgeRelatedCast(castType, CastExpr);
6151 
6152   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6153 
6154   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6155 }
6156 
6157 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6158                                     SourceLocation RParenLoc, Expr *E,
6159                                     TypeSourceInfo *TInfo) {
6160   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6161          "Expected paren or paren list expression");
6162 
6163   Expr **exprs;
6164   unsigned numExprs;
6165   Expr *subExpr;
6166   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6167   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6168     LiteralLParenLoc = PE->getLParenLoc();
6169     LiteralRParenLoc = PE->getRParenLoc();
6170     exprs = PE->getExprs();
6171     numExprs = PE->getNumExprs();
6172   } else { // isa<ParenExpr> by assertion at function entrance
6173     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6174     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6175     subExpr = cast<ParenExpr>(E)->getSubExpr();
6176     exprs = &subExpr;
6177     numExprs = 1;
6178   }
6179 
6180   QualType Ty = TInfo->getType();
6181   assert(Ty->isVectorType() && "Expected vector type");
6182 
6183   SmallVector<Expr *, 8> initExprs;
6184   const VectorType *VTy = Ty->getAs<VectorType>();
6185   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6186 
6187   // '(...)' form of vector initialization in AltiVec: the number of
6188   // initializers must be one or must match the size of the vector.
6189   // If a single value is specified in the initializer then it will be
6190   // replicated to all the components of the vector
6191   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6192     // The number of initializers must be one or must match the size of the
6193     // vector. If a single value is specified in the initializer then it will
6194     // be replicated to all the components of the vector
6195     if (numExprs == 1) {
6196       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6197       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6198       if (Literal.isInvalid())
6199         return ExprError();
6200       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6201                                   PrepareScalarCast(Literal, ElemTy));
6202       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6203     }
6204     else if (numExprs < numElems) {
6205       Diag(E->getExprLoc(),
6206            diag::err_incorrect_number_of_vector_initializers);
6207       return ExprError();
6208     }
6209     else
6210       initExprs.append(exprs, exprs + numExprs);
6211   }
6212   else {
6213     // For OpenCL, when the number of initializers is a single value,
6214     // it will be replicated to all components of the vector.
6215     if (getLangOpts().OpenCL &&
6216         VTy->getVectorKind() == VectorType::GenericVector &&
6217         numExprs == 1) {
6218         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6219         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6220         if (Literal.isInvalid())
6221           return ExprError();
6222         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6223                                     PrepareScalarCast(Literal, ElemTy));
6224         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6225     }
6226 
6227     initExprs.append(exprs, exprs + numExprs);
6228   }
6229   // FIXME: This means that pretty-printing the final AST will produce curly
6230   // braces instead of the original commas.
6231   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6232                                                    initExprs, LiteralRParenLoc);
6233   initE->setType(Ty);
6234   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6235 }
6236 
6237 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6238 /// the ParenListExpr into a sequence of comma binary operators.
6239 ExprResult
6240 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6241   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6242   if (!E)
6243     return OrigExpr;
6244 
6245   ExprResult Result(E->getExpr(0));
6246 
6247   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6248     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6249                         E->getExpr(i));
6250 
6251   if (Result.isInvalid()) return ExprError();
6252 
6253   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6254 }
6255 
6256 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6257                                     SourceLocation R,
6258                                     MultiExprArg Val) {
6259   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6260   return expr;
6261 }
6262 
6263 /// Emit a specialized diagnostic when one expression is a null pointer
6264 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6265 /// emitted.
6266 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6267                                       SourceLocation QuestionLoc) {
6268   Expr *NullExpr = LHSExpr;
6269   Expr *NonPointerExpr = RHSExpr;
6270   Expr::NullPointerConstantKind NullKind =
6271       NullExpr->isNullPointerConstant(Context,
6272                                       Expr::NPC_ValueDependentIsNotNull);
6273 
6274   if (NullKind == Expr::NPCK_NotNull) {
6275     NullExpr = RHSExpr;
6276     NonPointerExpr = LHSExpr;
6277     NullKind =
6278         NullExpr->isNullPointerConstant(Context,
6279                                         Expr::NPC_ValueDependentIsNotNull);
6280   }
6281 
6282   if (NullKind == Expr::NPCK_NotNull)
6283     return false;
6284 
6285   if (NullKind == Expr::NPCK_ZeroExpression)
6286     return false;
6287 
6288   if (NullKind == Expr::NPCK_ZeroLiteral) {
6289     // In this case, check to make sure that we got here from a "NULL"
6290     // string in the source code.
6291     NullExpr = NullExpr->IgnoreParenImpCasts();
6292     SourceLocation loc = NullExpr->getExprLoc();
6293     if (!findMacroSpelling(loc, "NULL"))
6294       return false;
6295   }
6296 
6297   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6298   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6299       << NonPointerExpr->getType() << DiagType
6300       << NonPointerExpr->getSourceRange();
6301   return true;
6302 }
6303 
6304 /// Return false if the condition expression is valid, true otherwise.
6305 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6306   QualType CondTy = Cond->getType();
6307 
6308   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6309   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6310     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6311       << CondTy << Cond->getSourceRange();
6312     return true;
6313   }
6314 
6315   // C99 6.5.15p2
6316   if (CondTy->isScalarType()) return false;
6317 
6318   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6319     << CondTy << Cond->getSourceRange();
6320   return true;
6321 }
6322 
6323 /// Handle when one or both operands are void type.
6324 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6325                                          ExprResult &RHS) {
6326     Expr *LHSExpr = LHS.get();
6327     Expr *RHSExpr = RHS.get();
6328 
6329     if (!LHSExpr->getType()->isVoidType())
6330       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6331         << RHSExpr->getSourceRange();
6332     if (!RHSExpr->getType()->isVoidType())
6333       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6334         << LHSExpr->getSourceRange();
6335     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6336     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6337     return S.Context.VoidTy;
6338 }
6339 
6340 /// Return false if the NullExpr can be promoted to PointerTy,
6341 /// true otherwise.
6342 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6343                                         QualType PointerTy) {
6344   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6345       !NullExpr.get()->isNullPointerConstant(S.Context,
6346                                             Expr::NPC_ValueDependentIsNull))
6347     return true;
6348 
6349   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6350   return false;
6351 }
6352 
6353 /// Checks compatibility between two pointers and return the resulting
6354 /// type.
6355 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6356                                                      ExprResult &RHS,
6357                                                      SourceLocation Loc) {
6358   QualType LHSTy = LHS.get()->getType();
6359   QualType RHSTy = RHS.get()->getType();
6360 
6361   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6362     // Two identical pointers types are always compatible.
6363     return LHSTy;
6364   }
6365 
6366   QualType lhptee, rhptee;
6367 
6368   // Get the pointee types.
6369   bool IsBlockPointer = false;
6370   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6371     lhptee = LHSBTy->getPointeeType();
6372     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6373     IsBlockPointer = true;
6374   } else {
6375     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6376     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6377   }
6378 
6379   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6380   // differently qualified versions of compatible types, the result type is
6381   // a pointer to an appropriately qualified version of the composite
6382   // type.
6383 
6384   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6385   // clause doesn't make sense for our extensions. E.g. address space 2 should
6386   // be incompatible with address space 3: they may live on different devices or
6387   // anything.
6388   Qualifiers lhQual = lhptee.getQualifiers();
6389   Qualifiers rhQual = rhptee.getQualifiers();
6390 
6391   LangAS ResultAddrSpace = LangAS::Default;
6392   LangAS LAddrSpace = lhQual.getAddressSpace();
6393   LangAS RAddrSpace = rhQual.getAddressSpace();
6394   if (S.getLangOpts().OpenCL) {
6395     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6396     // spaces is disallowed.
6397     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6398       ResultAddrSpace = LAddrSpace;
6399     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6400       ResultAddrSpace = RAddrSpace;
6401     else {
6402       S.Diag(Loc,
6403              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6404           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6405           << RHS.get()->getSourceRange();
6406       return QualType();
6407     }
6408   }
6409 
6410   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6411   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6412   lhQual.removeCVRQualifiers();
6413   rhQual.removeCVRQualifiers();
6414 
6415   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6416   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6417   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6418   // qual types are compatible iff
6419   //  * corresponded types are compatible
6420   //  * CVR qualifiers are equal
6421   //  * address spaces are equal
6422   // Thus for conditional operator we merge CVR and address space unqualified
6423   // pointees and if there is a composite type we return a pointer to it with
6424   // merged qualifiers.
6425   if (S.getLangOpts().OpenCL) {
6426     LHSCastKind = LAddrSpace == ResultAddrSpace
6427                       ? CK_BitCast
6428                       : CK_AddressSpaceConversion;
6429     RHSCastKind = RAddrSpace == ResultAddrSpace
6430                       ? CK_BitCast
6431                       : CK_AddressSpaceConversion;
6432     lhQual.removeAddressSpace();
6433     rhQual.removeAddressSpace();
6434   }
6435 
6436   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6437   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6438 
6439   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6440 
6441   if (CompositeTy.isNull()) {
6442     // In this situation, we assume void* type. No especially good
6443     // reason, but this is what gcc does, and we do have to pick
6444     // to get a consistent AST.
6445     QualType incompatTy;
6446     incompatTy = S.Context.getPointerType(
6447         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6448     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6449     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6450     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6451     // for casts between types with incompatible address space qualifiers.
6452     // For the following code the compiler produces casts between global and
6453     // local address spaces of the corresponded innermost pointees:
6454     // local int *global *a;
6455     // global int *global *b;
6456     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6457     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6458         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6459         << RHS.get()->getSourceRange();
6460     return incompatTy;
6461   }
6462 
6463   // The pointer types are compatible.
6464   // In case of OpenCL ResultTy should have the address space qualifier
6465   // which is a superset of address spaces of both the 2nd and the 3rd
6466   // operands of the conditional operator.
6467   QualType ResultTy = [&, ResultAddrSpace]() {
6468     if (S.getLangOpts().OpenCL) {
6469       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6470       CompositeQuals.setAddressSpace(ResultAddrSpace);
6471       return S.Context
6472           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6473           .withCVRQualifiers(MergedCVRQual);
6474     }
6475     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6476   }();
6477   if (IsBlockPointer)
6478     ResultTy = S.Context.getBlockPointerType(ResultTy);
6479   else
6480     ResultTy = S.Context.getPointerType(ResultTy);
6481 
6482   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6483   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6484   return ResultTy;
6485 }
6486 
6487 /// Return the resulting type when the operands are both block pointers.
6488 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6489                                                           ExprResult &LHS,
6490                                                           ExprResult &RHS,
6491                                                           SourceLocation Loc) {
6492   QualType LHSTy = LHS.get()->getType();
6493   QualType RHSTy = RHS.get()->getType();
6494 
6495   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6496     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6497       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6498       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6499       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6500       return destType;
6501     }
6502     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6503       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6504       << RHS.get()->getSourceRange();
6505     return QualType();
6506   }
6507 
6508   // We have 2 block pointer types.
6509   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6510 }
6511 
6512 /// Return the resulting type when the operands are both pointers.
6513 static QualType
6514 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6515                                             ExprResult &RHS,
6516                                             SourceLocation Loc) {
6517   // get the pointer types
6518   QualType LHSTy = LHS.get()->getType();
6519   QualType RHSTy = RHS.get()->getType();
6520 
6521   // get the "pointed to" types
6522   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6523   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6524 
6525   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6526   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6527     // Figure out necessary qualifiers (C99 6.5.15p6)
6528     QualType destPointee
6529       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6530     QualType destType = S.Context.getPointerType(destPointee);
6531     // Add qualifiers if necessary.
6532     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6533     // Promote to void*.
6534     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6535     return destType;
6536   }
6537   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6538     QualType destPointee
6539       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6540     QualType destType = S.Context.getPointerType(destPointee);
6541     // Add qualifiers if necessary.
6542     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6543     // Promote to void*.
6544     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6545     return destType;
6546   }
6547 
6548   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6549 }
6550 
6551 /// Return false if the first expression is not an integer and the second
6552 /// expression is not a pointer, true otherwise.
6553 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6554                                         Expr* PointerExpr, SourceLocation Loc,
6555                                         bool IsIntFirstExpr) {
6556   if (!PointerExpr->getType()->isPointerType() ||
6557       !Int.get()->getType()->isIntegerType())
6558     return false;
6559 
6560   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6561   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6562 
6563   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6564     << Expr1->getType() << Expr2->getType()
6565     << Expr1->getSourceRange() << Expr2->getSourceRange();
6566   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6567                             CK_IntegralToPointer);
6568   return true;
6569 }
6570 
6571 /// Simple conversion between integer and floating point types.
6572 ///
6573 /// Used when handling the OpenCL conditional operator where the
6574 /// condition is a vector while the other operands are scalar.
6575 ///
6576 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6577 /// types are either integer or floating type. Between the two
6578 /// operands, the type with the higher rank is defined as the "result
6579 /// type". The other operand needs to be promoted to the same type. No
6580 /// other type promotion is allowed. We cannot use
6581 /// UsualArithmeticConversions() for this purpose, since it always
6582 /// promotes promotable types.
6583 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6584                                             ExprResult &RHS,
6585                                             SourceLocation QuestionLoc) {
6586   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6587   if (LHS.isInvalid())
6588     return QualType();
6589   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6590   if (RHS.isInvalid())
6591     return QualType();
6592 
6593   // For conversion purposes, we ignore any qualifiers.
6594   // For example, "const float" and "float" are equivalent.
6595   QualType LHSType =
6596     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6597   QualType RHSType =
6598     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6599 
6600   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6601     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6602       << LHSType << LHS.get()->getSourceRange();
6603     return QualType();
6604   }
6605 
6606   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6607     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6608       << RHSType << RHS.get()->getSourceRange();
6609     return QualType();
6610   }
6611 
6612   // If both types are identical, no conversion is needed.
6613   if (LHSType == RHSType)
6614     return LHSType;
6615 
6616   // Now handle "real" floating types (i.e. float, double, long double).
6617   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6618     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6619                                  /*IsCompAssign = */ false);
6620 
6621   // Finally, we have two differing integer types.
6622   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6623   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6624 }
6625 
6626 /// Convert scalar operands to a vector that matches the
6627 ///        condition in length.
6628 ///
6629 /// Used when handling the OpenCL conditional operator where the
6630 /// condition is a vector while the other operands are scalar.
6631 ///
6632 /// We first compute the "result type" for the scalar operands
6633 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6634 /// into a vector of that type where the length matches the condition
6635 /// vector type. s6.11.6 requires that the element types of the result
6636 /// and the condition must have the same number of bits.
6637 static QualType
6638 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6639                               QualType CondTy, SourceLocation QuestionLoc) {
6640   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6641   if (ResTy.isNull()) return QualType();
6642 
6643   const VectorType *CV = CondTy->getAs<VectorType>();
6644   assert(CV);
6645 
6646   // Determine the vector result type
6647   unsigned NumElements = CV->getNumElements();
6648   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6649 
6650   // Ensure that all types have the same number of bits
6651   if (S.Context.getTypeSize(CV->getElementType())
6652       != S.Context.getTypeSize(ResTy)) {
6653     // Since VectorTy is created internally, it does not pretty print
6654     // with an OpenCL name. Instead, we just print a description.
6655     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6656     SmallString<64> Str;
6657     llvm::raw_svector_ostream OS(Str);
6658     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6659     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6660       << CondTy << OS.str();
6661     return QualType();
6662   }
6663 
6664   // Convert operands to the vector result type
6665   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6666   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6667 
6668   return VectorTy;
6669 }
6670 
6671 /// Return false if this is a valid OpenCL condition vector
6672 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6673                                        SourceLocation QuestionLoc) {
6674   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6675   // integral type.
6676   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6677   assert(CondTy);
6678   QualType EleTy = CondTy->getElementType();
6679   if (EleTy->isIntegerType()) return false;
6680 
6681   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6682     << Cond->getType() << Cond->getSourceRange();
6683   return true;
6684 }
6685 
6686 /// Return false if the vector condition type and the vector
6687 ///        result type are compatible.
6688 ///
6689 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6690 /// number of elements, and their element types have the same number
6691 /// of bits.
6692 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6693                               SourceLocation QuestionLoc) {
6694   const VectorType *CV = CondTy->getAs<VectorType>();
6695   const VectorType *RV = VecResTy->getAs<VectorType>();
6696   assert(CV && RV);
6697 
6698   if (CV->getNumElements() != RV->getNumElements()) {
6699     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6700       << CondTy << VecResTy;
6701     return true;
6702   }
6703 
6704   QualType CVE = CV->getElementType();
6705   QualType RVE = RV->getElementType();
6706 
6707   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6708     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6709       << CondTy << VecResTy;
6710     return true;
6711   }
6712 
6713   return false;
6714 }
6715 
6716 /// Return the resulting type for the conditional operator in
6717 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6718 ///        s6.3.i) when the condition is a vector type.
6719 static QualType
6720 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6721                              ExprResult &LHS, ExprResult &RHS,
6722                              SourceLocation QuestionLoc) {
6723   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6724   if (Cond.isInvalid())
6725     return QualType();
6726   QualType CondTy = Cond.get()->getType();
6727 
6728   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6729     return QualType();
6730 
6731   // If either operand is a vector then find the vector type of the
6732   // result as specified in OpenCL v1.1 s6.3.i.
6733   if (LHS.get()->getType()->isVectorType() ||
6734       RHS.get()->getType()->isVectorType()) {
6735     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6736                                               /*isCompAssign*/false,
6737                                               /*AllowBothBool*/true,
6738                                               /*AllowBoolConversions*/false);
6739     if (VecResTy.isNull()) return QualType();
6740     // The result type must match the condition type as specified in
6741     // OpenCL v1.1 s6.11.6.
6742     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6743       return QualType();
6744     return VecResTy;
6745   }
6746 
6747   // Both operands are scalar.
6748   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6749 }
6750 
6751 /// Return true if the Expr is block type
6752 static bool checkBlockType(Sema &S, const Expr *E) {
6753   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6754     QualType Ty = CE->getCallee()->getType();
6755     if (Ty->isBlockPointerType()) {
6756       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6757       return true;
6758     }
6759   }
6760   return false;
6761 }
6762 
6763 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6764 /// In that case, LHS = cond.
6765 /// C99 6.5.15
6766 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6767                                         ExprResult &RHS, ExprValueKind &VK,
6768                                         ExprObjectKind &OK,
6769                                         SourceLocation QuestionLoc) {
6770 
6771   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6772   if (!LHSResult.isUsable()) return QualType();
6773   LHS = LHSResult;
6774 
6775   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6776   if (!RHSResult.isUsable()) return QualType();
6777   RHS = RHSResult;
6778 
6779   // C++ is sufficiently different to merit its own checker.
6780   if (getLangOpts().CPlusPlus)
6781     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6782 
6783   VK = VK_RValue;
6784   OK = OK_Ordinary;
6785 
6786   // The OpenCL operator with a vector condition is sufficiently
6787   // different to merit its own checker.
6788   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6789     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6790 
6791   // First, check the condition.
6792   Cond = UsualUnaryConversions(Cond.get());
6793   if (Cond.isInvalid())
6794     return QualType();
6795   if (checkCondition(*this, Cond.get(), QuestionLoc))
6796     return QualType();
6797 
6798   // Now check the two expressions.
6799   if (LHS.get()->getType()->isVectorType() ||
6800       RHS.get()->getType()->isVectorType())
6801     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6802                                /*AllowBothBool*/true,
6803                                /*AllowBoolConversions*/false);
6804 
6805   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6806   if (LHS.isInvalid() || RHS.isInvalid())
6807     return QualType();
6808 
6809   QualType LHSTy = LHS.get()->getType();
6810   QualType RHSTy = RHS.get()->getType();
6811 
6812   // Diagnose attempts to convert between __float128 and long double where
6813   // such conversions currently can't be handled.
6814   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6815     Diag(QuestionLoc,
6816          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6817       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6818     return QualType();
6819   }
6820 
6821   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6822   // selection operator (?:).
6823   if (getLangOpts().OpenCL &&
6824       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6825     return QualType();
6826   }
6827 
6828   // If both operands have arithmetic type, do the usual arithmetic conversions
6829   // to find a common type: C99 6.5.15p3,5.
6830   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6831     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6832     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6833 
6834     return ResTy;
6835   }
6836 
6837   // If both operands are the same structure or union type, the result is that
6838   // type.
6839   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6840     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6841       if (LHSRT->getDecl() == RHSRT->getDecl())
6842         // "If both the operands have structure or union type, the result has
6843         // that type."  This implies that CV qualifiers are dropped.
6844         return LHSTy.getUnqualifiedType();
6845     // FIXME: Type of conditional expression must be complete in C mode.
6846   }
6847 
6848   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6849   // The following || allows only one side to be void (a GCC-ism).
6850   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6851     return checkConditionalVoidType(*this, LHS, RHS);
6852   }
6853 
6854   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6855   // the type of the other operand."
6856   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6857   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6858 
6859   // All objective-c pointer type analysis is done here.
6860   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6861                                                         QuestionLoc);
6862   if (LHS.isInvalid() || RHS.isInvalid())
6863     return QualType();
6864   if (!compositeType.isNull())
6865     return compositeType;
6866 
6867 
6868   // Handle block pointer types.
6869   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6870     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6871                                                      QuestionLoc);
6872 
6873   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6874   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6875     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6876                                                        QuestionLoc);
6877 
6878   // GCC compatibility: soften pointer/integer mismatch.  Note that
6879   // null pointers have been filtered out by this point.
6880   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6881       /*isIntFirstExpr=*/true))
6882     return RHSTy;
6883   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6884       /*isIntFirstExpr=*/false))
6885     return LHSTy;
6886 
6887   // Emit a better diagnostic if one of the expressions is a null pointer
6888   // constant and the other is not a pointer type. In this case, the user most
6889   // likely forgot to take the address of the other expression.
6890   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6891     return QualType();
6892 
6893   // Otherwise, the operands are not compatible.
6894   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6895     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6896     << RHS.get()->getSourceRange();
6897   return QualType();
6898 }
6899 
6900 /// FindCompositeObjCPointerType - Helper method to find composite type of
6901 /// two objective-c pointer types of the two input expressions.
6902 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6903                                             SourceLocation QuestionLoc) {
6904   QualType LHSTy = LHS.get()->getType();
6905   QualType RHSTy = RHS.get()->getType();
6906 
6907   // Handle things like Class and struct objc_class*.  Here we case the result
6908   // to the pseudo-builtin, because that will be implicitly cast back to the
6909   // redefinition type if an attempt is made to access its fields.
6910   if (LHSTy->isObjCClassType() &&
6911       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6912     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6913     return LHSTy;
6914   }
6915   if (RHSTy->isObjCClassType() &&
6916       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6917     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6918     return RHSTy;
6919   }
6920   // And the same for struct objc_object* / id
6921   if (LHSTy->isObjCIdType() &&
6922       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6923     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6924     return LHSTy;
6925   }
6926   if (RHSTy->isObjCIdType() &&
6927       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6928     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6929     return RHSTy;
6930   }
6931   // And the same for struct objc_selector* / SEL
6932   if (Context.isObjCSelType(LHSTy) &&
6933       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6934     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6935     return LHSTy;
6936   }
6937   if (Context.isObjCSelType(RHSTy) &&
6938       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6939     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6940     return RHSTy;
6941   }
6942   // Check constraints for Objective-C object pointers types.
6943   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6944 
6945     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6946       // Two identical object pointer types are always compatible.
6947       return LHSTy;
6948     }
6949     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6950     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6951     QualType compositeType = LHSTy;
6952 
6953     // If both operands are interfaces and either operand can be
6954     // assigned to the other, use that type as the composite
6955     // type. This allows
6956     //   xxx ? (A*) a : (B*) b
6957     // where B is a subclass of A.
6958     //
6959     // Additionally, as for assignment, if either type is 'id'
6960     // allow silent coercion. Finally, if the types are
6961     // incompatible then make sure to use 'id' as the composite
6962     // type so the result is acceptable for sending messages to.
6963 
6964     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6965     // It could return the composite type.
6966     if (!(compositeType =
6967           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6968       // Nothing more to do.
6969     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6970       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6971     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6972       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6973     } else if ((LHSTy->isObjCQualifiedIdType() ||
6974                 RHSTy->isObjCQualifiedIdType()) &&
6975                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6976       // Need to handle "id<xx>" explicitly.
6977       // GCC allows qualified id and any Objective-C type to devolve to
6978       // id. Currently localizing to here until clear this should be
6979       // part of ObjCQualifiedIdTypesAreCompatible.
6980       compositeType = Context.getObjCIdType();
6981     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6982       compositeType = Context.getObjCIdType();
6983     } else {
6984       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6985       << LHSTy << RHSTy
6986       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6987       QualType incompatTy = Context.getObjCIdType();
6988       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6989       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6990       return incompatTy;
6991     }
6992     // The object pointer types are compatible.
6993     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6994     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6995     return compositeType;
6996   }
6997   // Check Objective-C object pointer types and 'void *'
6998   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6999     if (getLangOpts().ObjCAutoRefCount) {
7000       // ARC forbids the implicit conversion of object pointers to 'void *',
7001       // so these types are not compatible.
7002       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7003           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7004       LHS = RHS = true;
7005       return QualType();
7006     }
7007     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7008     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7009     QualType destPointee
7010     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7011     QualType destType = Context.getPointerType(destPointee);
7012     // Add qualifiers if necessary.
7013     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7014     // Promote to void*.
7015     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7016     return destType;
7017   }
7018   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7019     if (getLangOpts().ObjCAutoRefCount) {
7020       // ARC forbids the implicit conversion of object pointers to 'void *',
7021       // so these types are not compatible.
7022       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7023           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7024       LHS = RHS = true;
7025       return QualType();
7026     }
7027     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7028     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7029     QualType destPointee
7030     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7031     QualType destType = Context.getPointerType(destPointee);
7032     // Add qualifiers if necessary.
7033     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7034     // Promote to void*.
7035     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7036     return destType;
7037   }
7038   return QualType();
7039 }
7040 
7041 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7042 /// ParenRange in parentheses.
7043 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7044                                const PartialDiagnostic &Note,
7045                                SourceRange ParenRange) {
7046   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7047   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7048       EndLoc.isValid()) {
7049     Self.Diag(Loc, Note)
7050       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7051       << FixItHint::CreateInsertion(EndLoc, ")");
7052   } else {
7053     // We can't display the parentheses, so just show the bare note.
7054     Self.Diag(Loc, Note) << ParenRange;
7055   }
7056 }
7057 
7058 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7059   return BinaryOperator::isAdditiveOp(Opc) ||
7060          BinaryOperator::isMultiplicativeOp(Opc) ||
7061          BinaryOperator::isShiftOp(Opc);
7062 }
7063 
7064 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7065 /// expression, either using a built-in or overloaded operator,
7066 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7067 /// expression.
7068 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7069                                    Expr **RHSExprs) {
7070   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7071   E = E->IgnoreImpCasts();
7072   E = E->IgnoreConversionOperator();
7073   E = E->IgnoreImpCasts();
7074 
7075   // Built-in binary operator.
7076   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7077     if (IsArithmeticOp(OP->getOpcode())) {
7078       *Opcode = OP->getOpcode();
7079       *RHSExprs = OP->getRHS();
7080       return true;
7081     }
7082   }
7083 
7084   // Overloaded operator.
7085   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7086     if (Call->getNumArgs() != 2)
7087       return false;
7088 
7089     // Make sure this is really a binary operator that is safe to pass into
7090     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7091     OverloadedOperatorKind OO = Call->getOperator();
7092     if (OO < OO_Plus || OO > OO_Arrow ||
7093         OO == OO_PlusPlus || OO == OO_MinusMinus)
7094       return false;
7095 
7096     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7097     if (IsArithmeticOp(OpKind)) {
7098       *Opcode = OpKind;
7099       *RHSExprs = Call->getArg(1);
7100       return true;
7101     }
7102   }
7103 
7104   return false;
7105 }
7106 
7107 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7108 /// or is a logical expression such as (x==y) which has int type, but is
7109 /// commonly interpreted as boolean.
7110 static bool ExprLooksBoolean(Expr *E) {
7111   E = E->IgnoreParenImpCasts();
7112 
7113   if (E->getType()->isBooleanType())
7114     return true;
7115   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7116     return OP->isComparisonOp() || OP->isLogicalOp();
7117   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7118     return OP->getOpcode() == UO_LNot;
7119   if (E->getType()->isPointerType())
7120     return true;
7121 
7122   return false;
7123 }
7124 
7125 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7126 /// and binary operator are mixed in a way that suggests the programmer assumed
7127 /// the conditional operator has higher precedence, for example:
7128 /// "int x = a + someBinaryCondition ? 1 : 2".
7129 static void DiagnoseConditionalPrecedence(Sema &Self,
7130                                           SourceLocation OpLoc,
7131                                           Expr *Condition,
7132                                           Expr *LHSExpr,
7133                                           Expr *RHSExpr) {
7134   BinaryOperatorKind CondOpcode;
7135   Expr *CondRHS;
7136 
7137   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7138     return;
7139   if (!ExprLooksBoolean(CondRHS))
7140     return;
7141 
7142   // The condition is an arithmetic binary expression, with a right-
7143   // hand side that looks boolean, so warn.
7144 
7145   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7146       << Condition->getSourceRange()
7147       << BinaryOperator::getOpcodeStr(CondOpcode);
7148 
7149   SuggestParentheses(Self, OpLoc,
7150     Self.PDiag(diag::note_precedence_silence)
7151       << BinaryOperator::getOpcodeStr(CondOpcode),
7152     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7153 
7154   SuggestParentheses(Self, OpLoc,
7155     Self.PDiag(diag::note_precedence_conditional_first),
7156     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7157 }
7158 
7159 /// Compute the nullability of a conditional expression.
7160 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7161                                               QualType LHSTy, QualType RHSTy,
7162                                               ASTContext &Ctx) {
7163   if (!ResTy->isAnyPointerType())
7164     return ResTy;
7165 
7166   auto GetNullability = [&Ctx](QualType Ty) {
7167     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7168     if (Kind)
7169       return *Kind;
7170     return NullabilityKind::Unspecified;
7171   };
7172 
7173   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7174   NullabilityKind MergedKind;
7175 
7176   // Compute nullability of a binary conditional expression.
7177   if (IsBin) {
7178     if (LHSKind == NullabilityKind::NonNull)
7179       MergedKind = NullabilityKind::NonNull;
7180     else
7181       MergedKind = RHSKind;
7182   // Compute nullability of a normal conditional expression.
7183   } else {
7184     if (LHSKind == NullabilityKind::Nullable ||
7185         RHSKind == NullabilityKind::Nullable)
7186       MergedKind = NullabilityKind::Nullable;
7187     else if (LHSKind == NullabilityKind::NonNull)
7188       MergedKind = RHSKind;
7189     else if (RHSKind == NullabilityKind::NonNull)
7190       MergedKind = LHSKind;
7191     else
7192       MergedKind = NullabilityKind::Unspecified;
7193   }
7194 
7195   // Return if ResTy already has the correct nullability.
7196   if (GetNullability(ResTy) == MergedKind)
7197     return ResTy;
7198 
7199   // Strip all nullability from ResTy.
7200   while (ResTy->getNullability(Ctx))
7201     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7202 
7203   // Create a new AttributedType with the new nullability kind.
7204   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7205   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7206 }
7207 
7208 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7209 /// in the case of a the GNU conditional expr extension.
7210 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7211                                     SourceLocation ColonLoc,
7212                                     Expr *CondExpr, Expr *LHSExpr,
7213                                     Expr *RHSExpr) {
7214   if (!getLangOpts().CPlusPlus) {
7215     // C cannot handle TypoExpr nodes in the condition because it
7216     // doesn't handle dependent types properly, so make sure any TypoExprs have
7217     // been dealt with before checking the operands.
7218     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7219     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7220     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7221 
7222     if (!CondResult.isUsable())
7223       return ExprError();
7224 
7225     if (LHSExpr) {
7226       if (!LHSResult.isUsable())
7227         return ExprError();
7228     }
7229 
7230     if (!RHSResult.isUsable())
7231       return ExprError();
7232 
7233     CondExpr = CondResult.get();
7234     LHSExpr = LHSResult.get();
7235     RHSExpr = RHSResult.get();
7236   }
7237 
7238   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7239   // was the condition.
7240   OpaqueValueExpr *opaqueValue = nullptr;
7241   Expr *commonExpr = nullptr;
7242   if (!LHSExpr) {
7243     commonExpr = CondExpr;
7244     // Lower out placeholder types first.  This is important so that we don't
7245     // try to capture a placeholder. This happens in few cases in C++; such
7246     // as Objective-C++'s dictionary subscripting syntax.
7247     if (commonExpr->hasPlaceholderType()) {
7248       ExprResult result = CheckPlaceholderExpr(commonExpr);
7249       if (!result.isUsable()) return ExprError();
7250       commonExpr = result.get();
7251     }
7252     // We usually want to apply unary conversions *before* saving, except
7253     // in the special case of a C++ l-value conditional.
7254     if (!(getLangOpts().CPlusPlus
7255           && !commonExpr->isTypeDependent()
7256           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7257           && commonExpr->isGLValue()
7258           && commonExpr->isOrdinaryOrBitFieldObject()
7259           && RHSExpr->isOrdinaryOrBitFieldObject()
7260           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7261       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7262       if (commonRes.isInvalid())
7263         return ExprError();
7264       commonExpr = commonRes.get();
7265     }
7266 
7267     // If the common expression is a class or array prvalue, materialize it
7268     // so that we can safely refer to it multiple times.
7269     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7270                                    commonExpr->getType()->isArrayType())) {
7271       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7272       if (MatExpr.isInvalid())
7273         return ExprError();
7274       commonExpr = MatExpr.get();
7275     }
7276 
7277     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7278                                                 commonExpr->getType(),
7279                                                 commonExpr->getValueKind(),
7280                                                 commonExpr->getObjectKind(),
7281                                                 commonExpr);
7282     LHSExpr = CondExpr = opaqueValue;
7283   }
7284 
7285   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7286   ExprValueKind VK = VK_RValue;
7287   ExprObjectKind OK = OK_Ordinary;
7288   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7289   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7290                                              VK, OK, QuestionLoc);
7291   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7292       RHS.isInvalid())
7293     return ExprError();
7294 
7295   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7296                                 RHS.get());
7297 
7298   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7299 
7300   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7301                                          Context);
7302 
7303   if (!commonExpr)
7304     return new (Context)
7305         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7306                             RHS.get(), result, VK, OK);
7307 
7308   return new (Context) BinaryConditionalOperator(
7309       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7310       ColonLoc, result, VK, OK);
7311 }
7312 
7313 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7314 // being closely modeled after the C99 spec:-). The odd characteristic of this
7315 // routine is it effectively iqnores the qualifiers on the top level pointee.
7316 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7317 // FIXME: add a couple examples in this comment.
7318 static Sema::AssignConvertType
7319 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7320   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7321   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7322 
7323   // get the "pointed to" type (ignoring qualifiers at the top level)
7324   const Type *lhptee, *rhptee;
7325   Qualifiers lhq, rhq;
7326   std::tie(lhptee, lhq) =
7327       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7328   std::tie(rhptee, rhq) =
7329       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7330 
7331   Sema::AssignConvertType ConvTy = Sema::Compatible;
7332 
7333   // C99 6.5.16.1p1: This following citation is common to constraints
7334   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7335   // qualifiers of the type *pointed to* by the right;
7336 
7337   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7338   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7339       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7340     // Ignore lifetime for further calculation.
7341     lhq.removeObjCLifetime();
7342     rhq.removeObjCLifetime();
7343   }
7344 
7345   if (!lhq.compatiblyIncludes(rhq)) {
7346     // Treat address-space mismatches as fatal.  TODO: address subspaces
7347     if (!lhq.isAddressSpaceSupersetOf(rhq))
7348       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7349 
7350     // It's okay to add or remove GC or lifetime qualifiers when converting to
7351     // and from void*.
7352     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7353                         .compatiblyIncludes(
7354                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7355              && (lhptee->isVoidType() || rhptee->isVoidType()))
7356       ; // keep old
7357 
7358     // Treat lifetime mismatches as fatal.
7359     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7360       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7361 
7362     // For GCC/MS compatibility, other qualifier mismatches are treated
7363     // as still compatible in C.
7364     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7365   }
7366 
7367   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7368   // incomplete type and the other is a pointer to a qualified or unqualified
7369   // version of void...
7370   if (lhptee->isVoidType()) {
7371     if (rhptee->isIncompleteOrObjectType())
7372       return ConvTy;
7373 
7374     // As an extension, we allow cast to/from void* to function pointer.
7375     assert(rhptee->isFunctionType());
7376     return Sema::FunctionVoidPointer;
7377   }
7378 
7379   if (rhptee->isVoidType()) {
7380     if (lhptee->isIncompleteOrObjectType())
7381       return ConvTy;
7382 
7383     // As an extension, we allow cast to/from void* to function pointer.
7384     assert(lhptee->isFunctionType());
7385     return Sema::FunctionVoidPointer;
7386   }
7387 
7388   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7389   // unqualified versions of compatible types, ...
7390   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7391   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7392     // Check if the pointee types are compatible ignoring the sign.
7393     // We explicitly check for char so that we catch "char" vs
7394     // "unsigned char" on systems where "char" is unsigned.
7395     if (lhptee->isCharType())
7396       ltrans = S.Context.UnsignedCharTy;
7397     else if (lhptee->hasSignedIntegerRepresentation())
7398       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7399 
7400     if (rhptee->isCharType())
7401       rtrans = S.Context.UnsignedCharTy;
7402     else if (rhptee->hasSignedIntegerRepresentation())
7403       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7404 
7405     if (ltrans == rtrans) {
7406       // Types are compatible ignoring the sign. Qualifier incompatibility
7407       // takes priority over sign incompatibility because the sign
7408       // warning can be disabled.
7409       if (ConvTy != Sema::Compatible)
7410         return ConvTy;
7411 
7412       return Sema::IncompatiblePointerSign;
7413     }
7414 
7415     // If we are a multi-level pointer, it's possible that our issue is simply
7416     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7417     // the eventual target type is the same and the pointers have the same
7418     // level of indirection, this must be the issue.
7419     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7420       do {
7421         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7422         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7423       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7424 
7425       if (lhptee == rhptee)
7426         return Sema::IncompatibleNestedPointerQualifiers;
7427     }
7428 
7429     // General pointer incompatibility takes priority over qualifiers.
7430     return Sema::IncompatiblePointer;
7431   }
7432   if (!S.getLangOpts().CPlusPlus &&
7433       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7434     return Sema::IncompatiblePointer;
7435   return ConvTy;
7436 }
7437 
7438 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7439 /// block pointer types are compatible or whether a block and normal pointer
7440 /// are compatible. It is more restrict than comparing two function pointer
7441 // types.
7442 static Sema::AssignConvertType
7443 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7444                                     QualType RHSType) {
7445   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7446   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7447 
7448   QualType lhptee, rhptee;
7449 
7450   // get the "pointed to" type (ignoring qualifiers at the top level)
7451   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7452   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7453 
7454   // In C++, the types have to match exactly.
7455   if (S.getLangOpts().CPlusPlus)
7456     return Sema::IncompatibleBlockPointer;
7457 
7458   Sema::AssignConvertType ConvTy = Sema::Compatible;
7459 
7460   // For blocks we enforce that qualifiers are identical.
7461   Qualifiers LQuals = lhptee.getLocalQualifiers();
7462   Qualifiers RQuals = rhptee.getLocalQualifiers();
7463   if (S.getLangOpts().OpenCL) {
7464     LQuals.removeAddressSpace();
7465     RQuals.removeAddressSpace();
7466   }
7467   if (LQuals != RQuals)
7468     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7469 
7470   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7471   // assignment.
7472   // The current behavior is similar to C++ lambdas. A block might be
7473   // assigned to a variable iff its return type and parameters are compatible
7474   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7475   // an assignment. Presumably it should behave in way that a function pointer
7476   // assignment does in C, so for each parameter and return type:
7477   //  * CVR and address space of LHS should be a superset of CVR and address
7478   //  space of RHS.
7479   //  * unqualified types should be compatible.
7480   if (S.getLangOpts().OpenCL) {
7481     if (!S.Context.typesAreBlockPointerCompatible(
7482             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7483             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7484       return Sema::IncompatibleBlockPointer;
7485   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7486     return Sema::IncompatibleBlockPointer;
7487 
7488   return ConvTy;
7489 }
7490 
7491 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7492 /// for assignment compatibility.
7493 static Sema::AssignConvertType
7494 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7495                                    QualType RHSType) {
7496   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7497   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7498 
7499   if (LHSType->isObjCBuiltinType()) {
7500     // Class is not compatible with ObjC object pointers.
7501     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7502         !RHSType->isObjCQualifiedClassType())
7503       return Sema::IncompatiblePointer;
7504     return Sema::Compatible;
7505   }
7506   if (RHSType->isObjCBuiltinType()) {
7507     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7508         !LHSType->isObjCQualifiedClassType())
7509       return Sema::IncompatiblePointer;
7510     return Sema::Compatible;
7511   }
7512   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7513   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7514 
7515   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7516       // make an exception for id<P>
7517       !LHSType->isObjCQualifiedIdType())
7518     return Sema::CompatiblePointerDiscardsQualifiers;
7519 
7520   if (S.Context.typesAreCompatible(LHSType, RHSType))
7521     return Sema::Compatible;
7522   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7523     return Sema::IncompatibleObjCQualifiedId;
7524   return Sema::IncompatiblePointer;
7525 }
7526 
7527 Sema::AssignConvertType
7528 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7529                                  QualType LHSType, QualType RHSType) {
7530   // Fake up an opaque expression.  We don't actually care about what
7531   // cast operations are required, so if CheckAssignmentConstraints
7532   // adds casts to this they'll be wasted, but fortunately that doesn't
7533   // usually happen on valid code.
7534   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7535   ExprResult RHSPtr = &RHSExpr;
7536   CastKind K;
7537 
7538   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7539 }
7540 
7541 /// This helper function returns true if QT is a vector type that has element
7542 /// type ElementType.
7543 static bool isVector(QualType QT, QualType ElementType) {
7544   if (const VectorType *VT = QT->getAs<VectorType>())
7545     return VT->getElementType() == ElementType;
7546   return false;
7547 }
7548 
7549 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7550 /// has code to accommodate several GCC extensions when type checking
7551 /// pointers. Here are some objectionable examples that GCC considers warnings:
7552 ///
7553 ///  int a, *pint;
7554 ///  short *pshort;
7555 ///  struct foo *pfoo;
7556 ///
7557 ///  pint = pshort; // warning: assignment from incompatible pointer type
7558 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7559 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7560 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7561 ///
7562 /// As a result, the code for dealing with pointers is more complex than the
7563 /// C99 spec dictates.
7564 ///
7565 /// Sets 'Kind' for any result kind except Incompatible.
7566 Sema::AssignConvertType
7567 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7568                                  CastKind &Kind, bool ConvertRHS) {
7569   QualType RHSType = RHS.get()->getType();
7570   QualType OrigLHSType = LHSType;
7571 
7572   // Get canonical types.  We're not formatting these types, just comparing
7573   // them.
7574   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7575   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7576 
7577   // Common case: no conversion required.
7578   if (LHSType == RHSType) {
7579     Kind = CK_NoOp;
7580     return Compatible;
7581   }
7582 
7583   // If we have an atomic type, try a non-atomic assignment, then just add an
7584   // atomic qualification step.
7585   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7586     Sema::AssignConvertType result =
7587       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7588     if (result != Compatible)
7589       return result;
7590     if (Kind != CK_NoOp && ConvertRHS)
7591       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7592     Kind = CK_NonAtomicToAtomic;
7593     return Compatible;
7594   }
7595 
7596   // If the left-hand side is a reference type, then we are in a
7597   // (rare!) case where we've allowed the use of references in C,
7598   // e.g., as a parameter type in a built-in function. In this case,
7599   // just make sure that the type referenced is compatible with the
7600   // right-hand side type. The caller is responsible for adjusting
7601   // LHSType so that the resulting expression does not have reference
7602   // type.
7603   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7604     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7605       Kind = CK_LValueBitCast;
7606       return Compatible;
7607     }
7608     return Incompatible;
7609   }
7610 
7611   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7612   // to the same ExtVector type.
7613   if (LHSType->isExtVectorType()) {
7614     if (RHSType->isExtVectorType())
7615       return Incompatible;
7616     if (RHSType->isArithmeticType()) {
7617       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7618       if (ConvertRHS)
7619         RHS = prepareVectorSplat(LHSType, RHS.get());
7620       Kind = CK_VectorSplat;
7621       return Compatible;
7622     }
7623   }
7624 
7625   // Conversions to or from vector type.
7626   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7627     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7628       // Allow assignments of an AltiVec vector type to an equivalent GCC
7629       // vector type and vice versa
7630       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7631         Kind = CK_BitCast;
7632         return Compatible;
7633       }
7634 
7635       // If we are allowing lax vector conversions, and LHS and RHS are both
7636       // vectors, the total size only needs to be the same. This is a bitcast;
7637       // no bits are changed but the result type is different.
7638       if (isLaxVectorConversion(RHSType, LHSType)) {
7639         Kind = CK_BitCast;
7640         return IncompatibleVectors;
7641       }
7642     }
7643 
7644     // When the RHS comes from another lax conversion (e.g. binops between
7645     // scalars and vectors) the result is canonicalized as a vector. When the
7646     // LHS is also a vector, the lax is allowed by the condition above. Handle
7647     // the case where LHS is a scalar.
7648     if (LHSType->isScalarType()) {
7649       const VectorType *VecType = RHSType->getAs<VectorType>();
7650       if (VecType && VecType->getNumElements() == 1 &&
7651           isLaxVectorConversion(RHSType, LHSType)) {
7652         ExprResult *VecExpr = &RHS;
7653         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7654         Kind = CK_BitCast;
7655         return Compatible;
7656       }
7657     }
7658 
7659     return Incompatible;
7660   }
7661 
7662   // Diagnose attempts to convert between __float128 and long double where
7663   // such conversions currently can't be handled.
7664   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7665     return Incompatible;
7666 
7667   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7668   // discards the imaginary part.
7669   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7670       !LHSType->getAs<ComplexType>())
7671     return Incompatible;
7672 
7673   // Arithmetic conversions.
7674   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7675       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7676     if (ConvertRHS)
7677       Kind = PrepareScalarCast(RHS, LHSType);
7678     return Compatible;
7679   }
7680 
7681   // Conversions to normal pointers.
7682   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7683     // U* -> T*
7684     if (isa<PointerType>(RHSType)) {
7685       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7686       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7687       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7688       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7689     }
7690 
7691     // int -> T*
7692     if (RHSType->isIntegerType()) {
7693       Kind = CK_IntegralToPointer; // FIXME: null?
7694       return IntToPointer;
7695     }
7696 
7697     // C pointers are not compatible with ObjC object pointers,
7698     // with two exceptions:
7699     if (isa<ObjCObjectPointerType>(RHSType)) {
7700       //  - conversions to void*
7701       if (LHSPointer->getPointeeType()->isVoidType()) {
7702         Kind = CK_BitCast;
7703         return Compatible;
7704       }
7705 
7706       //  - conversions from 'Class' to the redefinition type
7707       if (RHSType->isObjCClassType() &&
7708           Context.hasSameType(LHSType,
7709                               Context.getObjCClassRedefinitionType())) {
7710         Kind = CK_BitCast;
7711         return Compatible;
7712       }
7713 
7714       Kind = CK_BitCast;
7715       return IncompatiblePointer;
7716     }
7717 
7718     // U^ -> void*
7719     if (RHSType->getAs<BlockPointerType>()) {
7720       if (LHSPointer->getPointeeType()->isVoidType()) {
7721         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7722         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7723                                 ->getPointeeType()
7724                                 .getAddressSpace();
7725         Kind =
7726             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7727         return Compatible;
7728       }
7729     }
7730 
7731     return Incompatible;
7732   }
7733 
7734   // Conversions to block pointers.
7735   if (isa<BlockPointerType>(LHSType)) {
7736     // U^ -> T^
7737     if (RHSType->isBlockPointerType()) {
7738       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7739                               ->getPointeeType()
7740                               .getAddressSpace();
7741       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7742                               ->getPointeeType()
7743                               .getAddressSpace();
7744       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7745       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7746     }
7747 
7748     // int or null -> T^
7749     if (RHSType->isIntegerType()) {
7750       Kind = CK_IntegralToPointer; // FIXME: null
7751       return IntToBlockPointer;
7752     }
7753 
7754     // id -> T^
7755     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7756       Kind = CK_AnyPointerToBlockPointerCast;
7757       return Compatible;
7758     }
7759 
7760     // void* -> T^
7761     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7762       if (RHSPT->getPointeeType()->isVoidType()) {
7763         Kind = CK_AnyPointerToBlockPointerCast;
7764         return Compatible;
7765       }
7766 
7767     return Incompatible;
7768   }
7769 
7770   // Conversions to Objective-C pointers.
7771   if (isa<ObjCObjectPointerType>(LHSType)) {
7772     // A* -> B*
7773     if (RHSType->isObjCObjectPointerType()) {
7774       Kind = CK_BitCast;
7775       Sema::AssignConvertType result =
7776         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7777       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7778           result == Compatible &&
7779           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7780         result = IncompatibleObjCWeakRef;
7781       return result;
7782     }
7783 
7784     // int or null -> A*
7785     if (RHSType->isIntegerType()) {
7786       Kind = CK_IntegralToPointer; // FIXME: null
7787       return IntToPointer;
7788     }
7789 
7790     // In general, C pointers are not compatible with ObjC object pointers,
7791     // with two exceptions:
7792     if (isa<PointerType>(RHSType)) {
7793       Kind = CK_CPointerToObjCPointerCast;
7794 
7795       //  - conversions from 'void*'
7796       if (RHSType->isVoidPointerType()) {
7797         return Compatible;
7798       }
7799 
7800       //  - conversions to 'Class' from its redefinition type
7801       if (LHSType->isObjCClassType() &&
7802           Context.hasSameType(RHSType,
7803                               Context.getObjCClassRedefinitionType())) {
7804         return Compatible;
7805       }
7806 
7807       return IncompatiblePointer;
7808     }
7809 
7810     // Only under strict condition T^ is compatible with an Objective-C pointer.
7811     if (RHSType->isBlockPointerType() &&
7812         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7813       if (ConvertRHS)
7814         maybeExtendBlockObject(RHS);
7815       Kind = CK_BlockPointerToObjCPointerCast;
7816       return Compatible;
7817     }
7818 
7819     return Incompatible;
7820   }
7821 
7822   // Conversions from pointers that are not covered by the above.
7823   if (isa<PointerType>(RHSType)) {
7824     // T* -> _Bool
7825     if (LHSType == Context.BoolTy) {
7826       Kind = CK_PointerToBoolean;
7827       return Compatible;
7828     }
7829 
7830     // T* -> int
7831     if (LHSType->isIntegerType()) {
7832       Kind = CK_PointerToIntegral;
7833       return PointerToInt;
7834     }
7835 
7836     return Incompatible;
7837   }
7838 
7839   // Conversions from Objective-C pointers that are not covered by the above.
7840   if (isa<ObjCObjectPointerType>(RHSType)) {
7841     // T* -> _Bool
7842     if (LHSType == Context.BoolTy) {
7843       Kind = CK_PointerToBoolean;
7844       return Compatible;
7845     }
7846 
7847     // T* -> int
7848     if (LHSType->isIntegerType()) {
7849       Kind = CK_PointerToIntegral;
7850       return PointerToInt;
7851     }
7852 
7853     return Incompatible;
7854   }
7855 
7856   // struct A -> struct B
7857   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7858     if (Context.typesAreCompatible(LHSType, RHSType)) {
7859       Kind = CK_NoOp;
7860       return Compatible;
7861     }
7862   }
7863 
7864   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7865     Kind = CK_IntToOCLSampler;
7866     return Compatible;
7867   }
7868 
7869   return Incompatible;
7870 }
7871 
7872 /// Constructs a transparent union from an expression that is
7873 /// used to initialize the transparent union.
7874 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7875                                       ExprResult &EResult, QualType UnionType,
7876                                       FieldDecl *Field) {
7877   // Build an initializer list that designates the appropriate member
7878   // of the transparent union.
7879   Expr *E = EResult.get();
7880   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7881                                                    E, SourceLocation());
7882   Initializer->setType(UnionType);
7883   Initializer->setInitializedFieldInUnion(Field);
7884 
7885   // Build a compound literal constructing a value of the transparent
7886   // union type from this initializer list.
7887   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7888   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7889                                         VK_RValue, Initializer, false);
7890 }
7891 
7892 Sema::AssignConvertType
7893 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7894                                                ExprResult &RHS) {
7895   QualType RHSType = RHS.get()->getType();
7896 
7897   // If the ArgType is a Union type, we want to handle a potential
7898   // transparent_union GCC extension.
7899   const RecordType *UT = ArgType->getAsUnionType();
7900   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7901     return Incompatible;
7902 
7903   // The field to initialize within the transparent union.
7904   RecordDecl *UD = UT->getDecl();
7905   FieldDecl *InitField = nullptr;
7906   // It's compatible if the expression matches any of the fields.
7907   for (auto *it : UD->fields()) {
7908     if (it->getType()->isPointerType()) {
7909       // If the transparent union contains a pointer type, we allow:
7910       // 1) void pointer
7911       // 2) null pointer constant
7912       if (RHSType->isPointerType())
7913         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7914           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7915           InitField = it;
7916           break;
7917         }
7918 
7919       if (RHS.get()->isNullPointerConstant(Context,
7920                                            Expr::NPC_ValueDependentIsNull)) {
7921         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7922                                 CK_NullToPointer);
7923         InitField = it;
7924         break;
7925       }
7926     }
7927 
7928     CastKind Kind;
7929     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7930           == Compatible) {
7931       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7932       InitField = it;
7933       break;
7934     }
7935   }
7936 
7937   if (!InitField)
7938     return Incompatible;
7939 
7940   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7941   return Compatible;
7942 }
7943 
7944 Sema::AssignConvertType
7945 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7946                                        bool Diagnose,
7947                                        bool DiagnoseCFAudited,
7948                                        bool ConvertRHS) {
7949   // We need to be able to tell the caller whether we diagnosed a problem, if
7950   // they ask us to issue diagnostics.
7951   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7952 
7953   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7954   // we can't avoid *all* modifications at the moment, so we need some somewhere
7955   // to put the updated value.
7956   ExprResult LocalRHS = CallerRHS;
7957   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7958 
7959   if (getLangOpts().CPlusPlus) {
7960     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7961       // C++ 5.17p3: If the left operand is not of class type, the
7962       // expression is implicitly converted (C++ 4) to the
7963       // cv-unqualified type of the left operand.
7964       QualType RHSType = RHS.get()->getType();
7965       if (Diagnose) {
7966         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7967                                         AA_Assigning);
7968       } else {
7969         ImplicitConversionSequence ICS =
7970             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7971                                   /*SuppressUserConversions=*/false,
7972                                   /*AllowExplicit=*/false,
7973                                   /*InOverloadResolution=*/false,
7974                                   /*CStyle=*/false,
7975                                   /*AllowObjCWritebackConversion=*/false);
7976         if (ICS.isFailure())
7977           return Incompatible;
7978         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7979                                         ICS, AA_Assigning);
7980       }
7981       if (RHS.isInvalid())
7982         return Incompatible;
7983       Sema::AssignConvertType result = Compatible;
7984       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7985           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7986         result = IncompatibleObjCWeakRef;
7987       return result;
7988     }
7989 
7990     // FIXME: Currently, we fall through and treat C++ classes like C
7991     // structures.
7992     // FIXME: We also fall through for atomics; not sure what should
7993     // happen there, though.
7994   } else if (RHS.get()->getType() == Context.OverloadTy) {
7995     // As a set of extensions to C, we support overloading on functions. These
7996     // functions need to be resolved here.
7997     DeclAccessPair DAP;
7998     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7999             RHS.get(), LHSType, /*Complain=*/false, DAP))
8000       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
8001     else
8002       return Incompatible;
8003   }
8004 
8005   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8006   // a null pointer constant.
8007   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8008        LHSType->isBlockPointerType()) &&
8009       RHS.get()->isNullPointerConstant(Context,
8010                                        Expr::NPC_ValueDependentIsNull)) {
8011     if (Diagnose || ConvertRHS) {
8012       CastKind Kind;
8013       CXXCastPath Path;
8014       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8015                              /*IgnoreBaseAccess=*/false, Diagnose);
8016       if (ConvertRHS)
8017         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8018     }
8019     return Compatible;
8020   }
8021 
8022   // This check seems unnatural, however it is necessary to ensure the proper
8023   // conversion of functions/arrays. If the conversion were done for all
8024   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8025   // expressions that suppress this implicit conversion (&, sizeof).
8026   //
8027   // Suppress this for references: C++ 8.5.3p5.
8028   if (!LHSType->isReferenceType()) {
8029     // FIXME: We potentially allocate here even if ConvertRHS is false.
8030     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8031     if (RHS.isInvalid())
8032       return Incompatible;
8033   }
8034 
8035   Expr *PRE = RHS.get()->IgnoreParenCasts();
8036   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8037     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8038     if (PDecl && !PDecl->hasDefinition()) {
8039       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8040       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8041     }
8042   }
8043 
8044   CastKind Kind;
8045   Sema::AssignConvertType result =
8046     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8047 
8048   // C99 6.5.16.1p2: The value of the right operand is converted to the
8049   // type of the assignment expression.
8050   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8051   // so that we can use references in built-in functions even in C.
8052   // The getNonReferenceType() call makes sure that the resulting expression
8053   // does not have reference type.
8054   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8055     QualType Ty = LHSType.getNonLValueExprType(Context);
8056     Expr *E = RHS.get();
8057 
8058     // Check for various Objective-C errors. If we are not reporting
8059     // diagnostics and just checking for errors, e.g., during overload
8060     // resolution, return Incompatible to indicate the failure.
8061     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8062         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8063                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8064       if (!Diagnose)
8065         return Incompatible;
8066     }
8067     if (getLangOpts().ObjC1 &&
8068         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8069                                            E->getType(), E, Diagnose) ||
8070          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8071       if (!Diagnose)
8072         return Incompatible;
8073       // Replace the expression with a corrected version and continue so we
8074       // can find further errors.
8075       RHS = E;
8076       return Compatible;
8077     }
8078 
8079     if (ConvertRHS)
8080       RHS = ImpCastExprToType(E, Ty, Kind);
8081   }
8082   return result;
8083 }
8084 
8085 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8086                                ExprResult &RHS) {
8087   Diag(Loc, diag::err_typecheck_invalid_operands)
8088     << LHS.get()->getType() << RHS.get()->getType()
8089     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8090   return QualType();
8091 }
8092 
8093 // Diagnose cases where a scalar was implicitly converted to a vector and
8094 // diagnose the underlying types. Otherwise, diagnose the error
8095 // as invalid vector logical operands for non-C++ cases.
8096 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8097                                             ExprResult &RHS) {
8098   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8099   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8100 
8101   bool LHSNatVec = LHSType->isVectorType();
8102   bool RHSNatVec = RHSType->isVectorType();
8103 
8104   if (!(LHSNatVec && RHSNatVec)) {
8105     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8106     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8107     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8108         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8109         << Vector->getSourceRange();
8110     return QualType();
8111   }
8112 
8113   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8114       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8115       << RHS.get()->getSourceRange();
8116 
8117   return QualType();
8118 }
8119 
8120 /// Try to convert a value of non-vector type to a vector type by converting
8121 /// the type to the element type of the vector and then performing a splat.
8122 /// If the language is OpenCL, we only use conversions that promote scalar
8123 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8124 /// for float->int.
8125 ///
8126 /// OpenCL V2.0 6.2.6.p2:
8127 /// An error shall occur if any scalar operand type has greater rank
8128 /// than the type of the vector element.
8129 ///
8130 /// \param scalar - if non-null, actually perform the conversions
8131 /// \return true if the operation fails (but without diagnosing the failure)
8132 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8133                                      QualType scalarTy,
8134                                      QualType vectorEltTy,
8135                                      QualType vectorTy,
8136                                      unsigned &DiagID) {
8137   // The conversion to apply to the scalar before splatting it,
8138   // if necessary.
8139   CastKind scalarCast = CK_NoOp;
8140 
8141   if (vectorEltTy->isIntegralType(S.Context)) {
8142     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8143         (scalarTy->isIntegerType() &&
8144          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8145       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8146       return true;
8147     }
8148     if (!scalarTy->isIntegralType(S.Context))
8149       return true;
8150     scalarCast = CK_IntegralCast;
8151   } else if (vectorEltTy->isRealFloatingType()) {
8152     if (scalarTy->isRealFloatingType()) {
8153       if (S.getLangOpts().OpenCL &&
8154           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8155         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8156         return true;
8157       }
8158       scalarCast = CK_FloatingCast;
8159     }
8160     else if (scalarTy->isIntegralType(S.Context))
8161       scalarCast = CK_IntegralToFloating;
8162     else
8163       return true;
8164   } else {
8165     return true;
8166   }
8167 
8168   // Adjust scalar if desired.
8169   if (scalar) {
8170     if (scalarCast != CK_NoOp)
8171       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8172     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8173   }
8174   return false;
8175 }
8176 
8177 /// Convert vector E to a vector with the same number of elements but different
8178 /// element type.
8179 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8180   const auto *VecTy = E->getType()->getAs<VectorType>();
8181   assert(VecTy && "Expression E must be a vector");
8182   QualType NewVecTy = S.Context.getVectorType(ElementType,
8183                                               VecTy->getNumElements(),
8184                                               VecTy->getVectorKind());
8185 
8186   // Look through the implicit cast. Return the subexpression if its type is
8187   // NewVecTy.
8188   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8189     if (ICE->getSubExpr()->getType() == NewVecTy)
8190       return ICE->getSubExpr();
8191 
8192   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8193   return S.ImpCastExprToType(E, NewVecTy, Cast);
8194 }
8195 
8196 /// Test if a (constant) integer Int can be casted to another integer type
8197 /// IntTy without losing precision.
8198 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8199                                       QualType OtherIntTy) {
8200   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8201 
8202   // Reject cases where the value of the Int is unknown as that would
8203   // possibly cause truncation, but accept cases where the scalar can be
8204   // demoted without loss of precision.
8205   llvm::APSInt Result;
8206   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8207   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8208   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8209   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8210 
8211   if (CstInt) {
8212     // If the scalar is constant and is of a higher order and has more active
8213     // bits that the vector element type, reject it.
8214     unsigned NumBits = IntSigned
8215                            ? (Result.isNegative() ? Result.getMinSignedBits()
8216                                                   : Result.getActiveBits())
8217                            : Result.getActiveBits();
8218     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8219       return true;
8220 
8221     // If the signedness of the scalar type and the vector element type
8222     // differs and the number of bits is greater than that of the vector
8223     // element reject it.
8224     return (IntSigned != OtherIntSigned &&
8225             NumBits > S.Context.getIntWidth(OtherIntTy));
8226   }
8227 
8228   // Reject cases where the value of the scalar is not constant and it's
8229   // order is greater than that of the vector element type.
8230   return (Order < 0);
8231 }
8232 
8233 /// Test if a (constant) integer Int can be casted to floating point type
8234 /// FloatTy without losing precision.
8235 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8236                                      QualType FloatTy) {
8237   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8238 
8239   // Determine if the integer constant can be expressed as a floating point
8240   // number of the appropriate type.
8241   llvm::APSInt Result;
8242   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8243   uint64_t Bits = 0;
8244   if (CstInt) {
8245     // Reject constants that would be truncated if they were converted to
8246     // the floating point type. Test by simple to/from conversion.
8247     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8248     //        could be avoided if there was a convertFromAPInt method
8249     //        which could signal back if implicit truncation occurred.
8250     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8251     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8252                            llvm::APFloat::rmTowardZero);
8253     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8254                              !IntTy->hasSignedIntegerRepresentation());
8255     bool Ignored = false;
8256     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8257                            &Ignored);
8258     if (Result != ConvertBack)
8259       return true;
8260   } else {
8261     // Reject types that cannot be fully encoded into the mantissa of
8262     // the float.
8263     Bits = S.Context.getTypeSize(IntTy);
8264     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8265         S.Context.getFloatTypeSemantics(FloatTy));
8266     if (Bits > FloatPrec)
8267       return true;
8268   }
8269 
8270   return false;
8271 }
8272 
8273 /// Attempt to convert and splat Scalar into a vector whose types matches
8274 /// Vector following GCC conversion rules. The rule is that implicit
8275 /// conversion can occur when Scalar can be casted to match Vector's element
8276 /// type without causing truncation of Scalar.
8277 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8278                                         ExprResult *Vector) {
8279   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8280   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8281   const VectorType *VT = VectorTy->getAs<VectorType>();
8282 
8283   assert(!isa<ExtVectorType>(VT) &&
8284          "ExtVectorTypes should not be handled here!");
8285 
8286   QualType VectorEltTy = VT->getElementType();
8287 
8288   // Reject cases where the vector element type or the scalar element type are
8289   // not integral or floating point types.
8290   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8291     return true;
8292 
8293   // The conversion to apply to the scalar before splatting it,
8294   // if necessary.
8295   CastKind ScalarCast = CK_NoOp;
8296 
8297   // Accept cases where the vector elements are integers and the scalar is
8298   // an integer.
8299   // FIXME: Notionally if the scalar was a floating point value with a precise
8300   //        integral representation, we could cast it to an appropriate integer
8301   //        type and then perform the rest of the checks here. GCC will perform
8302   //        this conversion in some cases as determined by the input language.
8303   //        We should accept it on a language independent basis.
8304   if (VectorEltTy->isIntegralType(S.Context) &&
8305       ScalarTy->isIntegralType(S.Context) &&
8306       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8307 
8308     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8309       return true;
8310 
8311     ScalarCast = CK_IntegralCast;
8312   } else if (VectorEltTy->isRealFloatingType()) {
8313     if (ScalarTy->isRealFloatingType()) {
8314 
8315       // Reject cases where the scalar type is not a constant and has a higher
8316       // Order than the vector element type.
8317       llvm::APFloat Result(0.0);
8318       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8319       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8320       if (!CstScalar && Order < 0)
8321         return true;
8322 
8323       // If the scalar cannot be safely casted to the vector element type,
8324       // reject it.
8325       if (CstScalar) {
8326         bool Truncated = false;
8327         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8328                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8329         if (Truncated)
8330           return true;
8331       }
8332 
8333       ScalarCast = CK_FloatingCast;
8334     } else if (ScalarTy->isIntegralType(S.Context)) {
8335       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8336         return true;
8337 
8338       ScalarCast = CK_IntegralToFloating;
8339     } else
8340       return true;
8341   }
8342 
8343   // Adjust scalar if desired.
8344   if (Scalar) {
8345     if (ScalarCast != CK_NoOp)
8346       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8347     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8348   }
8349   return false;
8350 }
8351 
8352 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8353                                    SourceLocation Loc, bool IsCompAssign,
8354                                    bool AllowBothBool,
8355                                    bool AllowBoolConversions) {
8356   if (!IsCompAssign) {
8357     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8358     if (LHS.isInvalid())
8359       return QualType();
8360   }
8361   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8362   if (RHS.isInvalid())
8363     return QualType();
8364 
8365   // For conversion purposes, we ignore any qualifiers.
8366   // For example, "const float" and "float" are equivalent.
8367   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8368   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8369 
8370   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8371   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8372   assert(LHSVecType || RHSVecType);
8373 
8374   // AltiVec-style "vector bool op vector bool" combinations are allowed
8375   // for some operators but not others.
8376   if (!AllowBothBool &&
8377       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8378       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8379     return InvalidOperands(Loc, LHS, RHS);
8380 
8381   // If the vector types are identical, return.
8382   if (Context.hasSameType(LHSType, RHSType))
8383     return LHSType;
8384 
8385   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8386   if (LHSVecType && RHSVecType &&
8387       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8388     if (isa<ExtVectorType>(LHSVecType)) {
8389       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8390       return LHSType;
8391     }
8392 
8393     if (!IsCompAssign)
8394       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8395     return RHSType;
8396   }
8397 
8398   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8399   // can be mixed, with the result being the non-bool type.  The non-bool
8400   // operand must have integer element type.
8401   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8402       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8403       (Context.getTypeSize(LHSVecType->getElementType()) ==
8404        Context.getTypeSize(RHSVecType->getElementType()))) {
8405     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8406         LHSVecType->getElementType()->isIntegerType() &&
8407         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8408       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8409       return LHSType;
8410     }
8411     if (!IsCompAssign &&
8412         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8413         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8414         RHSVecType->getElementType()->isIntegerType()) {
8415       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8416       return RHSType;
8417     }
8418   }
8419 
8420   // If there's a vector type and a scalar, try to convert the scalar to
8421   // the vector element type and splat.
8422   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8423   if (!RHSVecType) {
8424     if (isa<ExtVectorType>(LHSVecType)) {
8425       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8426                                     LHSVecType->getElementType(), LHSType,
8427                                     DiagID))
8428         return LHSType;
8429     } else {
8430       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8431         return LHSType;
8432     }
8433   }
8434   if (!LHSVecType) {
8435     if (isa<ExtVectorType>(RHSVecType)) {
8436       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8437                                     LHSType, RHSVecType->getElementType(),
8438                                     RHSType, DiagID))
8439         return RHSType;
8440     } else {
8441       if (LHS.get()->getValueKind() == VK_LValue ||
8442           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8443         return RHSType;
8444     }
8445   }
8446 
8447   // FIXME: The code below also handles conversion between vectors and
8448   // non-scalars, we should break this down into fine grained specific checks
8449   // and emit proper diagnostics.
8450   QualType VecType = LHSVecType ? LHSType : RHSType;
8451   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8452   QualType OtherType = LHSVecType ? RHSType : LHSType;
8453   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8454   if (isLaxVectorConversion(OtherType, VecType)) {
8455     // If we're allowing lax vector conversions, only the total (data) size
8456     // needs to be the same. For non compound assignment, if one of the types is
8457     // scalar, the result is always the vector type.
8458     if (!IsCompAssign) {
8459       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8460       return VecType;
8461     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8462     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8463     // type. Note that this is already done by non-compound assignments in
8464     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8465     // <1 x T> -> T. The result is also a vector type.
8466     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8467                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8468       ExprResult *RHSExpr = &RHS;
8469       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8470       return VecType;
8471     }
8472   }
8473 
8474   // Okay, the expression is invalid.
8475 
8476   // If there's a non-vector, non-real operand, diagnose that.
8477   if ((!RHSVecType && !RHSType->isRealType()) ||
8478       (!LHSVecType && !LHSType->isRealType())) {
8479     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8480       << LHSType << RHSType
8481       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8482     return QualType();
8483   }
8484 
8485   // OpenCL V1.1 6.2.6.p1:
8486   // If the operands are of more than one vector type, then an error shall
8487   // occur. Implicit conversions between vector types are not permitted, per
8488   // section 6.2.1.
8489   if (getLangOpts().OpenCL &&
8490       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8491       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8492     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8493                                                            << RHSType;
8494     return QualType();
8495   }
8496 
8497 
8498   // If there is a vector type that is not a ExtVector and a scalar, we reach
8499   // this point if scalar could not be converted to the vector's element type
8500   // without truncation.
8501   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8502       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8503     QualType Scalar = LHSVecType ? RHSType : LHSType;
8504     QualType Vector = LHSVecType ? LHSType : RHSType;
8505     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8506     Diag(Loc,
8507          diag::err_typecheck_vector_not_convertable_implict_truncation)
8508         << ScalarOrVector << Scalar << Vector;
8509 
8510     return QualType();
8511   }
8512 
8513   // Otherwise, use the generic diagnostic.
8514   Diag(Loc, DiagID)
8515     << LHSType << RHSType
8516     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8517   return QualType();
8518 }
8519 
8520 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8521 // expression.  These are mainly cases where the null pointer is used as an
8522 // integer instead of a pointer.
8523 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8524                                 SourceLocation Loc, bool IsCompare) {
8525   // The canonical way to check for a GNU null is with isNullPointerConstant,
8526   // but we use a bit of a hack here for speed; this is a relatively
8527   // hot path, and isNullPointerConstant is slow.
8528   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8529   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8530 
8531   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8532 
8533   // Avoid analyzing cases where the result will either be invalid (and
8534   // diagnosed as such) or entirely valid and not something to warn about.
8535   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8536       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8537     return;
8538 
8539   // Comparison operations would not make sense with a null pointer no matter
8540   // what the other expression is.
8541   if (!IsCompare) {
8542     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8543         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8544         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8545     return;
8546   }
8547 
8548   // The rest of the operations only make sense with a null pointer
8549   // if the other expression is a pointer.
8550   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8551       NonNullType->canDecayToPointerType())
8552     return;
8553 
8554   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8555       << LHSNull /* LHS is NULL */ << NonNullType
8556       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8557 }
8558 
8559 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8560                                                ExprResult &RHS,
8561                                                SourceLocation Loc, bool IsDiv) {
8562   // Check for division/remainder by zero.
8563   llvm::APSInt RHSValue;
8564   if (!RHS.get()->isValueDependent() &&
8565       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8566     S.DiagRuntimeBehavior(Loc, RHS.get(),
8567                           S.PDiag(diag::warn_remainder_division_by_zero)
8568                             << IsDiv << RHS.get()->getSourceRange());
8569 }
8570 
8571 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8572                                            SourceLocation Loc,
8573                                            bool IsCompAssign, bool IsDiv) {
8574   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8575 
8576   if (LHS.get()->getType()->isVectorType() ||
8577       RHS.get()->getType()->isVectorType())
8578     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8579                                /*AllowBothBool*/getLangOpts().AltiVec,
8580                                /*AllowBoolConversions*/false);
8581 
8582   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8583   if (LHS.isInvalid() || RHS.isInvalid())
8584     return QualType();
8585 
8586 
8587   if (compType.isNull() || !compType->isArithmeticType())
8588     return InvalidOperands(Loc, LHS, RHS);
8589   if (IsDiv)
8590     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8591   return compType;
8592 }
8593 
8594 QualType Sema::CheckRemainderOperands(
8595   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8596   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8597 
8598   if (LHS.get()->getType()->isVectorType() ||
8599       RHS.get()->getType()->isVectorType()) {
8600     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8601         RHS.get()->getType()->hasIntegerRepresentation())
8602       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8603                                  /*AllowBothBool*/getLangOpts().AltiVec,
8604                                  /*AllowBoolConversions*/false);
8605     return InvalidOperands(Loc, LHS, RHS);
8606   }
8607 
8608   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8609   if (LHS.isInvalid() || RHS.isInvalid())
8610     return QualType();
8611 
8612   if (compType.isNull() || !compType->isIntegerType())
8613     return InvalidOperands(Loc, LHS, RHS);
8614   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8615   return compType;
8616 }
8617 
8618 /// Diagnose invalid arithmetic on two void pointers.
8619 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8620                                                 Expr *LHSExpr, Expr *RHSExpr) {
8621   S.Diag(Loc, S.getLangOpts().CPlusPlus
8622                 ? diag::err_typecheck_pointer_arith_void_type
8623                 : diag::ext_gnu_void_ptr)
8624     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8625                             << RHSExpr->getSourceRange();
8626 }
8627 
8628 /// Diagnose invalid arithmetic on a void pointer.
8629 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8630                                             Expr *Pointer) {
8631   S.Diag(Loc, S.getLangOpts().CPlusPlus
8632                 ? diag::err_typecheck_pointer_arith_void_type
8633                 : diag::ext_gnu_void_ptr)
8634     << 0 /* one pointer */ << Pointer->getSourceRange();
8635 }
8636 
8637 /// Diagnose invalid arithmetic on a null pointer.
8638 ///
8639 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8640 /// idiom, which we recognize as a GNU extension.
8641 ///
8642 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8643                                             Expr *Pointer, bool IsGNUIdiom) {
8644   if (IsGNUIdiom)
8645     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8646       << Pointer->getSourceRange();
8647   else
8648     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8649       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8650 }
8651 
8652 /// Diagnose invalid arithmetic on two function pointers.
8653 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8654                                                     Expr *LHS, Expr *RHS) {
8655   assert(LHS->getType()->isAnyPointerType());
8656   assert(RHS->getType()->isAnyPointerType());
8657   S.Diag(Loc, S.getLangOpts().CPlusPlus
8658                 ? diag::err_typecheck_pointer_arith_function_type
8659                 : diag::ext_gnu_ptr_func_arith)
8660     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8661     // We only show the second type if it differs from the first.
8662     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8663                                                    RHS->getType())
8664     << RHS->getType()->getPointeeType()
8665     << LHS->getSourceRange() << RHS->getSourceRange();
8666 }
8667 
8668 /// Diagnose invalid arithmetic on a function pointer.
8669 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8670                                                 Expr *Pointer) {
8671   assert(Pointer->getType()->isAnyPointerType());
8672   S.Diag(Loc, S.getLangOpts().CPlusPlus
8673                 ? diag::err_typecheck_pointer_arith_function_type
8674                 : diag::ext_gnu_ptr_func_arith)
8675     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8676     << 0 /* one pointer, so only one type */
8677     << Pointer->getSourceRange();
8678 }
8679 
8680 /// Emit error if Operand is incomplete pointer type
8681 ///
8682 /// \returns True if pointer has incomplete type
8683 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8684                                                  Expr *Operand) {
8685   QualType ResType = Operand->getType();
8686   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8687     ResType = ResAtomicType->getValueType();
8688 
8689   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8690   QualType PointeeTy = ResType->getPointeeType();
8691   return S.RequireCompleteType(Loc, PointeeTy,
8692                                diag::err_typecheck_arithmetic_incomplete_type,
8693                                PointeeTy, Operand->getSourceRange());
8694 }
8695 
8696 /// Check the validity of an arithmetic pointer operand.
8697 ///
8698 /// If the operand has pointer type, this code will check for pointer types
8699 /// which are invalid in arithmetic operations. These will be diagnosed
8700 /// appropriately, including whether or not the use is supported as an
8701 /// extension.
8702 ///
8703 /// \returns True when the operand is valid to use (even if as an extension).
8704 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8705                                             Expr *Operand) {
8706   QualType ResType = Operand->getType();
8707   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8708     ResType = ResAtomicType->getValueType();
8709 
8710   if (!ResType->isAnyPointerType()) return true;
8711 
8712   QualType PointeeTy = ResType->getPointeeType();
8713   if (PointeeTy->isVoidType()) {
8714     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8715     return !S.getLangOpts().CPlusPlus;
8716   }
8717   if (PointeeTy->isFunctionType()) {
8718     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8719     return !S.getLangOpts().CPlusPlus;
8720   }
8721 
8722   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8723 
8724   return true;
8725 }
8726 
8727 /// Check the validity of a binary arithmetic operation w.r.t. pointer
8728 /// operands.
8729 ///
8730 /// This routine will diagnose any invalid arithmetic on pointer operands much
8731 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8732 /// for emitting a single diagnostic even for operations where both LHS and RHS
8733 /// are (potentially problematic) pointers.
8734 ///
8735 /// \returns True when the operand is valid to use (even if as an extension).
8736 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8737                                                 Expr *LHSExpr, Expr *RHSExpr) {
8738   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8739   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8740   if (!isLHSPointer && !isRHSPointer) return true;
8741 
8742   QualType LHSPointeeTy, RHSPointeeTy;
8743   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8744   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8745 
8746   // if both are pointers check if operation is valid wrt address spaces
8747   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8748     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8749     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8750     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8751       S.Diag(Loc,
8752              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8753           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8754           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8755       return false;
8756     }
8757   }
8758 
8759   // Check for arithmetic on pointers to incomplete types.
8760   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8761   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8762   if (isLHSVoidPtr || isRHSVoidPtr) {
8763     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8764     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8765     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8766 
8767     return !S.getLangOpts().CPlusPlus;
8768   }
8769 
8770   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8771   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8772   if (isLHSFuncPtr || isRHSFuncPtr) {
8773     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8774     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8775                                                                 RHSExpr);
8776     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8777 
8778     return !S.getLangOpts().CPlusPlus;
8779   }
8780 
8781   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8782     return false;
8783   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8784     return false;
8785 
8786   return true;
8787 }
8788 
8789 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8790 /// literal.
8791 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8792                                   Expr *LHSExpr, Expr *RHSExpr) {
8793   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8794   Expr* IndexExpr = RHSExpr;
8795   if (!StrExpr) {
8796     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8797     IndexExpr = LHSExpr;
8798   }
8799 
8800   bool IsStringPlusInt = StrExpr &&
8801       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8802   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8803     return;
8804 
8805   llvm::APSInt index;
8806   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8807     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8808     if (index.isNonNegative() &&
8809         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8810                               index.isUnsigned()))
8811       return;
8812   }
8813 
8814   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8815   Self.Diag(OpLoc, diag::warn_string_plus_int)
8816       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8817 
8818   // Only print a fixit for "str" + int, not for int + "str".
8819   if (IndexExpr == RHSExpr) {
8820     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8821     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8822         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8823         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8824         << FixItHint::CreateInsertion(EndLoc, "]");
8825   } else
8826     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8827 }
8828 
8829 /// Emit a warning when adding a char literal to a string.
8830 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8831                                    Expr *LHSExpr, Expr *RHSExpr) {
8832   const Expr *StringRefExpr = LHSExpr;
8833   const CharacterLiteral *CharExpr =
8834       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8835 
8836   if (!CharExpr) {
8837     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8838     StringRefExpr = RHSExpr;
8839   }
8840 
8841   if (!CharExpr || !StringRefExpr)
8842     return;
8843 
8844   const QualType StringType = StringRefExpr->getType();
8845 
8846   // Return if not a PointerType.
8847   if (!StringType->isAnyPointerType())
8848     return;
8849 
8850   // Return if not a CharacterType.
8851   if (!StringType->getPointeeType()->isAnyCharacterType())
8852     return;
8853 
8854   ASTContext &Ctx = Self.getASTContext();
8855   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8856 
8857   const QualType CharType = CharExpr->getType();
8858   if (!CharType->isAnyCharacterType() &&
8859       CharType->isIntegerType() &&
8860       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8861     Self.Diag(OpLoc, diag::warn_string_plus_char)
8862         << DiagRange << Ctx.CharTy;
8863   } else {
8864     Self.Diag(OpLoc, diag::warn_string_plus_char)
8865         << DiagRange << CharExpr->getType();
8866   }
8867 
8868   // Only print a fixit for str + char, not for char + str.
8869   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8870     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8871     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8872         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8873         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8874         << FixItHint::CreateInsertion(EndLoc, "]");
8875   } else {
8876     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8877   }
8878 }
8879 
8880 /// Emit error when two pointers are incompatible.
8881 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8882                                            Expr *LHSExpr, Expr *RHSExpr) {
8883   assert(LHSExpr->getType()->isAnyPointerType());
8884   assert(RHSExpr->getType()->isAnyPointerType());
8885   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8886     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8887     << RHSExpr->getSourceRange();
8888 }
8889 
8890 // C99 6.5.6
8891 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8892                                      SourceLocation Loc, BinaryOperatorKind Opc,
8893                                      QualType* CompLHSTy) {
8894   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8895 
8896   if (LHS.get()->getType()->isVectorType() ||
8897       RHS.get()->getType()->isVectorType()) {
8898     QualType compType = CheckVectorOperands(
8899         LHS, RHS, Loc, CompLHSTy,
8900         /*AllowBothBool*/getLangOpts().AltiVec,
8901         /*AllowBoolConversions*/getLangOpts().ZVector);
8902     if (CompLHSTy) *CompLHSTy = compType;
8903     return compType;
8904   }
8905 
8906   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8907   if (LHS.isInvalid() || RHS.isInvalid())
8908     return QualType();
8909 
8910   // Diagnose "string literal" '+' int and string '+' "char literal".
8911   if (Opc == BO_Add) {
8912     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8913     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8914   }
8915 
8916   // handle the common case first (both operands are arithmetic).
8917   if (!compType.isNull() && compType->isArithmeticType()) {
8918     if (CompLHSTy) *CompLHSTy = compType;
8919     return compType;
8920   }
8921 
8922   // Type-checking.  Ultimately the pointer's going to be in PExp;
8923   // note that we bias towards the LHS being the pointer.
8924   Expr *PExp = LHS.get(), *IExp = RHS.get();
8925 
8926   bool isObjCPointer;
8927   if (PExp->getType()->isPointerType()) {
8928     isObjCPointer = false;
8929   } else if (PExp->getType()->isObjCObjectPointerType()) {
8930     isObjCPointer = true;
8931   } else {
8932     std::swap(PExp, IExp);
8933     if (PExp->getType()->isPointerType()) {
8934       isObjCPointer = false;
8935     } else if (PExp->getType()->isObjCObjectPointerType()) {
8936       isObjCPointer = true;
8937     } else {
8938       return InvalidOperands(Loc, LHS, RHS);
8939     }
8940   }
8941   assert(PExp->getType()->isAnyPointerType());
8942 
8943   if (!IExp->getType()->isIntegerType())
8944     return InvalidOperands(Loc, LHS, RHS);
8945 
8946   // Adding to a null pointer results in undefined behavior.
8947   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
8948           Context, Expr::NPC_ValueDependentIsNotNull)) {
8949     // In C++ adding zero to a null pointer is defined.
8950     llvm::APSInt KnownVal;
8951     if (!getLangOpts().CPlusPlus ||
8952         (!IExp->isValueDependent() &&
8953          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
8954       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
8955       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
8956           Context, BO_Add, PExp, IExp);
8957       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
8958     }
8959   }
8960 
8961   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8962     return QualType();
8963 
8964   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8965     return QualType();
8966 
8967   // Check array bounds for pointer arithemtic
8968   CheckArrayAccess(PExp, IExp);
8969 
8970   if (CompLHSTy) {
8971     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8972     if (LHSTy.isNull()) {
8973       LHSTy = LHS.get()->getType();
8974       if (LHSTy->isPromotableIntegerType())
8975         LHSTy = Context.getPromotedIntegerType(LHSTy);
8976     }
8977     *CompLHSTy = LHSTy;
8978   }
8979 
8980   return PExp->getType();
8981 }
8982 
8983 // C99 6.5.6
8984 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8985                                         SourceLocation Loc,
8986                                         QualType* CompLHSTy) {
8987   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8988 
8989   if (LHS.get()->getType()->isVectorType() ||
8990       RHS.get()->getType()->isVectorType()) {
8991     QualType compType = CheckVectorOperands(
8992         LHS, RHS, Loc, CompLHSTy,
8993         /*AllowBothBool*/getLangOpts().AltiVec,
8994         /*AllowBoolConversions*/getLangOpts().ZVector);
8995     if (CompLHSTy) *CompLHSTy = compType;
8996     return compType;
8997   }
8998 
8999   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
9000   if (LHS.isInvalid() || RHS.isInvalid())
9001     return QualType();
9002 
9003   // Enforce type constraints: C99 6.5.6p3.
9004 
9005   // Handle the common case first (both operands are arithmetic).
9006   if (!compType.isNull() && compType->isArithmeticType()) {
9007     if (CompLHSTy) *CompLHSTy = compType;
9008     return compType;
9009   }
9010 
9011   // Either ptr - int   or   ptr - ptr.
9012   if (LHS.get()->getType()->isAnyPointerType()) {
9013     QualType lpointee = LHS.get()->getType()->getPointeeType();
9014 
9015     // Diagnose bad cases where we step over interface counts.
9016     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9017         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9018       return QualType();
9019 
9020     // The result type of a pointer-int computation is the pointer type.
9021     if (RHS.get()->getType()->isIntegerType()) {
9022       // Subtracting from a null pointer should produce a warning.
9023       // The last argument to the diagnose call says this doesn't match the
9024       // GNU int-to-pointer idiom.
9025       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9026                                            Expr::NPC_ValueDependentIsNotNull)) {
9027         // In C++ adding zero to a null pointer is defined.
9028         llvm::APSInt KnownVal;
9029         if (!getLangOpts().CPlusPlus ||
9030             (!RHS.get()->isValueDependent() &&
9031              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9032           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9033         }
9034       }
9035 
9036       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9037         return QualType();
9038 
9039       // Check array bounds for pointer arithemtic
9040       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9041                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9042 
9043       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9044       return LHS.get()->getType();
9045     }
9046 
9047     // Handle pointer-pointer subtractions.
9048     if (const PointerType *RHSPTy
9049           = RHS.get()->getType()->getAs<PointerType>()) {
9050       QualType rpointee = RHSPTy->getPointeeType();
9051 
9052       if (getLangOpts().CPlusPlus) {
9053         // Pointee types must be the same: C++ [expr.add]
9054         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9055           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9056         }
9057       } else {
9058         // Pointee types must be compatible C99 6.5.6p3
9059         if (!Context.typesAreCompatible(
9060                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9061                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9062           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9063           return QualType();
9064         }
9065       }
9066 
9067       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9068                                                LHS.get(), RHS.get()))
9069         return QualType();
9070 
9071       // FIXME: Add warnings for nullptr - ptr.
9072 
9073       // The pointee type may have zero size.  As an extension, a structure or
9074       // union may have zero size or an array may have zero length.  In this
9075       // case subtraction does not make sense.
9076       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9077         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9078         if (ElementSize.isZero()) {
9079           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9080             << rpointee.getUnqualifiedType()
9081             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9082         }
9083       }
9084 
9085       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9086       return Context.getPointerDiffType();
9087     }
9088   }
9089 
9090   return InvalidOperands(Loc, LHS, RHS);
9091 }
9092 
9093 static bool isScopedEnumerationType(QualType T) {
9094   if (const EnumType *ET = T->getAs<EnumType>())
9095     return ET->getDecl()->isScoped();
9096   return false;
9097 }
9098 
9099 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9100                                    SourceLocation Loc, BinaryOperatorKind Opc,
9101                                    QualType LHSType) {
9102   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9103   // so skip remaining warnings as we don't want to modify values within Sema.
9104   if (S.getLangOpts().OpenCL)
9105     return;
9106 
9107   llvm::APSInt Right;
9108   // Check right/shifter operand
9109   if (RHS.get()->isValueDependent() ||
9110       !RHS.get()->EvaluateAsInt(Right, S.Context))
9111     return;
9112 
9113   if (Right.isNegative()) {
9114     S.DiagRuntimeBehavior(Loc, RHS.get(),
9115                           S.PDiag(diag::warn_shift_negative)
9116                             << RHS.get()->getSourceRange());
9117     return;
9118   }
9119   llvm::APInt LeftBits(Right.getBitWidth(),
9120                        S.Context.getTypeSize(LHS.get()->getType()));
9121   if (Right.uge(LeftBits)) {
9122     S.DiagRuntimeBehavior(Loc, RHS.get(),
9123                           S.PDiag(diag::warn_shift_gt_typewidth)
9124                             << RHS.get()->getSourceRange());
9125     return;
9126   }
9127   if (Opc != BO_Shl)
9128     return;
9129 
9130   // When left shifting an ICE which is signed, we can check for overflow which
9131   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9132   // integers have defined behavior modulo one more than the maximum value
9133   // representable in the result type, so never warn for those.
9134   llvm::APSInt Left;
9135   if (LHS.get()->isValueDependent() ||
9136       LHSType->hasUnsignedIntegerRepresentation() ||
9137       !LHS.get()->EvaluateAsInt(Left, S.Context))
9138     return;
9139 
9140   // If LHS does not have a signed type and non-negative value
9141   // then, the behavior is undefined. Warn about it.
9142   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9143     S.DiagRuntimeBehavior(Loc, LHS.get(),
9144                           S.PDiag(diag::warn_shift_lhs_negative)
9145                             << LHS.get()->getSourceRange());
9146     return;
9147   }
9148 
9149   llvm::APInt ResultBits =
9150       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9151   if (LeftBits.uge(ResultBits))
9152     return;
9153   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9154   Result = Result.shl(Right);
9155 
9156   // Print the bit representation of the signed integer as an unsigned
9157   // hexadecimal number.
9158   SmallString<40> HexResult;
9159   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9160 
9161   // If we are only missing a sign bit, this is less likely to result in actual
9162   // bugs -- if the result is cast back to an unsigned type, it will have the
9163   // expected value. Thus we place this behind a different warning that can be
9164   // turned off separately if needed.
9165   if (LeftBits == ResultBits - 1) {
9166     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9167         << HexResult << LHSType
9168         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9169     return;
9170   }
9171 
9172   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9173     << HexResult.str() << Result.getMinSignedBits() << LHSType
9174     << Left.getBitWidth() << LHS.get()->getSourceRange()
9175     << RHS.get()->getSourceRange();
9176 }
9177 
9178 /// Return the resulting type when a vector is shifted
9179 ///        by a scalar or vector shift amount.
9180 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9181                                  SourceLocation Loc, bool IsCompAssign) {
9182   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9183   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9184       !LHS.get()->getType()->isVectorType()) {
9185     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9186       << RHS.get()->getType() << LHS.get()->getType()
9187       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9188     return QualType();
9189   }
9190 
9191   if (!IsCompAssign) {
9192     LHS = S.UsualUnaryConversions(LHS.get());
9193     if (LHS.isInvalid()) return QualType();
9194   }
9195 
9196   RHS = S.UsualUnaryConversions(RHS.get());
9197   if (RHS.isInvalid()) return QualType();
9198 
9199   QualType LHSType = LHS.get()->getType();
9200   // Note that LHS might be a scalar because the routine calls not only in
9201   // OpenCL case.
9202   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9203   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9204 
9205   // Note that RHS might not be a vector.
9206   QualType RHSType = RHS.get()->getType();
9207   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9208   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9209 
9210   // The operands need to be integers.
9211   if (!LHSEleType->isIntegerType()) {
9212     S.Diag(Loc, diag::err_typecheck_expect_int)
9213       << LHS.get()->getType() << LHS.get()->getSourceRange();
9214     return QualType();
9215   }
9216 
9217   if (!RHSEleType->isIntegerType()) {
9218     S.Diag(Loc, diag::err_typecheck_expect_int)
9219       << RHS.get()->getType() << RHS.get()->getSourceRange();
9220     return QualType();
9221   }
9222 
9223   if (!LHSVecTy) {
9224     assert(RHSVecTy);
9225     if (IsCompAssign)
9226       return RHSType;
9227     if (LHSEleType != RHSEleType) {
9228       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9229       LHSEleType = RHSEleType;
9230     }
9231     QualType VecTy =
9232         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9233     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9234     LHSType = VecTy;
9235   } else if (RHSVecTy) {
9236     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9237     // are applied component-wise. So if RHS is a vector, then ensure
9238     // that the number of elements is the same as LHS...
9239     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9240       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9241         << LHS.get()->getType() << RHS.get()->getType()
9242         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9243       return QualType();
9244     }
9245     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9246       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9247       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9248       if (LHSBT != RHSBT &&
9249           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9250         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9251             << LHS.get()->getType() << RHS.get()->getType()
9252             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9253       }
9254     }
9255   } else {
9256     // ...else expand RHS to match the number of elements in LHS.
9257     QualType VecTy =
9258       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9259     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9260   }
9261 
9262   return LHSType;
9263 }
9264 
9265 // C99 6.5.7
9266 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9267                                   SourceLocation Loc, BinaryOperatorKind Opc,
9268                                   bool IsCompAssign) {
9269   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9270 
9271   // Vector shifts promote their scalar inputs to vector type.
9272   if (LHS.get()->getType()->isVectorType() ||
9273       RHS.get()->getType()->isVectorType()) {
9274     if (LangOpts.ZVector) {
9275       // The shift operators for the z vector extensions work basically
9276       // like general shifts, except that neither the LHS nor the RHS is
9277       // allowed to be a "vector bool".
9278       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9279         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9280           return InvalidOperands(Loc, LHS, RHS);
9281       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9282         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9283           return InvalidOperands(Loc, LHS, RHS);
9284     }
9285     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9286   }
9287 
9288   // Shifts don't perform usual arithmetic conversions, they just do integer
9289   // promotions on each operand. C99 6.5.7p3
9290 
9291   // For the LHS, do usual unary conversions, but then reset them away
9292   // if this is a compound assignment.
9293   ExprResult OldLHS = LHS;
9294   LHS = UsualUnaryConversions(LHS.get());
9295   if (LHS.isInvalid())
9296     return QualType();
9297   QualType LHSType = LHS.get()->getType();
9298   if (IsCompAssign) LHS = OldLHS;
9299 
9300   // The RHS is simpler.
9301   RHS = UsualUnaryConversions(RHS.get());
9302   if (RHS.isInvalid())
9303     return QualType();
9304   QualType RHSType = RHS.get()->getType();
9305 
9306   // C99 6.5.7p2: Each of the operands shall have integer type.
9307   if (!LHSType->hasIntegerRepresentation() ||
9308       !RHSType->hasIntegerRepresentation())
9309     return InvalidOperands(Loc, LHS, RHS);
9310 
9311   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9312   // hasIntegerRepresentation() above instead of this.
9313   if (isScopedEnumerationType(LHSType) ||
9314       isScopedEnumerationType(RHSType)) {
9315     return InvalidOperands(Loc, LHS, RHS);
9316   }
9317   // Sanity-check shift operands
9318   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9319 
9320   // "The type of the result is that of the promoted left operand."
9321   return LHSType;
9322 }
9323 
9324 /// If two different enums are compared, raise a warning.
9325 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9326                                 Expr *RHS) {
9327   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9328   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9329 
9330   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9331   if (!LHSEnumType)
9332     return;
9333   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9334   if (!RHSEnumType)
9335     return;
9336 
9337   // Ignore anonymous enums.
9338   if (!LHSEnumType->getDecl()->getIdentifier() &&
9339       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9340     return;
9341   if (!RHSEnumType->getDecl()->getIdentifier() &&
9342       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9343     return;
9344 
9345   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9346     return;
9347 
9348   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9349       << LHSStrippedType << RHSStrippedType
9350       << LHS->getSourceRange() << RHS->getSourceRange();
9351 }
9352 
9353 /// Diagnose bad pointer comparisons.
9354 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9355                                               ExprResult &LHS, ExprResult &RHS,
9356                                               bool IsError) {
9357   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9358                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9359     << LHS.get()->getType() << RHS.get()->getType()
9360     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9361 }
9362 
9363 /// Returns false if the pointers are converted to a composite type,
9364 /// true otherwise.
9365 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9366                                            ExprResult &LHS, ExprResult &RHS) {
9367   // C++ [expr.rel]p2:
9368   //   [...] Pointer conversions (4.10) and qualification
9369   //   conversions (4.4) are performed on pointer operands (or on
9370   //   a pointer operand and a null pointer constant) to bring
9371   //   them to their composite pointer type. [...]
9372   //
9373   // C++ [expr.eq]p1 uses the same notion for (in)equality
9374   // comparisons of pointers.
9375 
9376   QualType LHSType = LHS.get()->getType();
9377   QualType RHSType = RHS.get()->getType();
9378   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9379          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9380 
9381   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9382   if (T.isNull()) {
9383     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9384         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9385       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9386     else
9387       S.InvalidOperands(Loc, LHS, RHS);
9388     return true;
9389   }
9390 
9391   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9392   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9393   return false;
9394 }
9395 
9396 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9397                                                     ExprResult &LHS,
9398                                                     ExprResult &RHS,
9399                                                     bool IsError) {
9400   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9401                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9402     << LHS.get()->getType() << RHS.get()->getType()
9403     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9404 }
9405 
9406 static bool isObjCObjectLiteral(ExprResult &E) {
9407   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9408   case Stmt::ObjCArrayLiteralClass:
9409   case Stmt::ObjCDictionaryLiteralClass:
9410   case Stmt::ObjCStringLiteralClass:
9411   case Stmt::ObjCBoxedExprClass:
9412     return true;
9413   default:
9414     // Note that ObjCBoolLiteral is NOT an object literal!
9415     return false;
9416   }
9417 }
9418 
9419 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9420   const ObjCObjectPointerType *Type =
9421     LHS->getType()->getAs<ObjCObjectPointerType>();
9422 
9423   // If this is not actually an Objective-C object, bail out.
9424   if (!Type)
9425     return false;
9426 
9427   // Get the LHS object's interface type.
9428   QualType InterfaceType = Type->getPointeeType();
9429 
9430   // If the RHS isn't an Objective-C object, bail out.
9431   if (!RHS->getType()->isObjCObjectPointerType())
9432     return false;
9433 
9434   // Try to find the -isEqual: method.
9435   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9436   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9437                                                       InterfaceType,
9438                                                       /*instance=*/true);
9439   if (!Method) {
9440     if (Type->isObjCIdType()) {
9441       // For 'id', just check the global pool.
9442       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9443                                                   /*receiverId=*/true);
9444     } else {
9445       // Check protocols.
9446       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9447                                              /*instance=*/true);
9448     }
9449   }
9450 
9451   if (!Method)
9452     return false;
9453 
9454   QualType T = Method->parameters()[0]->getType();
9455   if (!T->isObjCObjectPointerType())
9456     return false;
9457 
9458   QualType R = Method->getReturnType();
9459   if (!R->isScalarType())
9460     return false;
9461 
9462   return true;
9463 }
9464 
9465 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9466   FromE = FromE->IgnoreParenImpCasts();
9467   switch (FromE->getStmtClass()) {
9468     default:
9469       break;
9470     case Stmt::ObjCStringLiteralClass:
9471       // "string literal"
9472       return LK_String;
9473     case Stmt::ObjCArrayLiteralClass:
9474       // "array literal"
9475       return LK_Array;
9476     case Stmt::ObjCDictionaryLiteralClass:
9477       // "dictionary literal"
9478       return LK_Dictionary;
9479     case Stmt::BlockExprClass:
9480       return LK_Block;
9481     case Stmt::ObjCBoxedExprClass: {
9482       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9483       switch (Inner->getStmtClass()) {
9484         case Stmt::IntegerLiteralClass:
9485         case Stmt::FloatingLiteralClass:
9486         case Stmt::CharacterLiteralClass:
9487         case Stmt::ObjCBoolLiteralExprClass:
9488         case Stmt::CXXBoolLiteralExprClass:
9489           // "numeric literal"
9490           return LK_Numeric;
9491         case Stmt::ImplicitCastExprClass: {
9492           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9493           // Boolean literals can be represented by implicit casts.
9494           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9495             return LK_Numeric;
9496           break;
9497         }
9498         default:
9499           break;
9500       }
9501       return LK_Boxed;
9502     }
9503   }
9504   return LK_None;
9505 }
9506 
9507 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9508                                           ExprResult &LHS, ExprResult &RHS,
9509                                           BinaryOperator::Opcode Opc){
9510   Expr *Literal;
9511   Expr *Other;
9512   if (isObjCObjectLiteral(LHS)) {
9513     Literal = LHS.get();
9514     Other = RHS.get();
9515   } else {
9516     Literal = RHS.get();
9517     Other = LHS.get();
9518   }
9519 
9520   // Don't warn on comparisons against nil.
9521   Other = Other->IgnoreParenCasts();
9522   if (Other->isNullPointerConstant(S.getASTContext(),
9523                                    Expr::NPC_ValueDependentIsNotNull))
9524     return;
9525 
9526   // This should be kept in sync with warn_objc_literal_comparison.
9527   // LK_String should always be after the other literals, since it has its own
9528   // warning flag.
9529   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9530   assert(LiteralKind != Sema::LK_Block);
9531   if (LiteralKind == Sema::LK_None) {
9532     llvm_unreachable("Unknown Objective-C object literal kind");
9533   }
9534 
9535   if (LiteralKind == Sema::LK_String)
9536     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9537       << Literal->getSourceRange();
9538   else
9539     S.Diag(Loc, diag::warn_objc_literal_comparison)
9540       << LiteralKind << Literal->getSourceRange();
9541 
9542   if (BinaryOperator::isEqualityOp(Opc) &&
9543       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9544     SourceLocation Start = LHS.get()->getLocStart();
9545     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9546     CharSourceRange OpRange =
9547       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9548 
9549     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9550       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9551       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9552       << FixItHint::CreateInsertion(End, "]");
9553   }
9554 }
9555 
9556 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9557 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9558                                            ExprResult &RHS, SourceLocation Loc,
9559                                            BinaryOperatorKind Opc) {
9560   // Check that left hand side is !something.
9561   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9562   if (!UO || UO->getOpcode() != UO_LNot) return;
9563 
9564   // Only check if the right hand side is non-bool arithmetic type.
9565   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9566 
9567   // Make sure that the something in !something is not bool.
9568   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9569   if (SubExpr->isKnownToHaveBooleanValue()) return;
9570 
9571   // Emit warning.
9572   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9573   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9574       << Loc << IsBitwiseOp;
9575 
9576   // First note suggest !(x < y)
9577   SourceLocation FirstOpen = SubExpr->getLocStart();
9578   SourceLocation FirstClose = RHS.get()->getLocEnd();
9579   FirstClose = S.getLocForEndOfToken(FirstClose);
9580   if (FirstClose.isInvalid())
9581     FirstOpen = SourceLocation();
9582   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9583       << IsBitwiseOp
9584       << FixItHint::CreateInsertion(FirstOpen, "(")
9585       << FixItHint::CreateInsertion(FirstClose, ")");
9586 
9587   // Second note suggests (!x) < y
9588   SourceLocation SecondOpen = LHS.get()->getLocStart();
9589   SourceLocation SecondClose = LHS.get()->getLocEnd();
9590   SecondClose = S.getLocForEndOfToken(SecondClose);
9591   if (SecondClose.isInvalid())
9592     SecondOpen = SourceLocation();
9593   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9594       << FixItHint::CreateInsertion(SecondOpen, "(")
9595       << FixItHint::CreateInsertion(SecondClose, ")");
9596 }
9597 
9598 // Get the decl for a simple expression: a reference to a variable,
9599 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9600 static ValueDecl *getCompareDecl(Expr *E) {
9601   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9602     return DR->getDecl();
9603   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9604     if (Ivar->isFreeIvar())
9605       return Ivar->getDecl();
9606   }
9607   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9608     if (Mem->isImplicitAccess())
9609       return Mem->getMemberDecl();
9610   }
9611   return nullptr;
9612 }
9613 
9614 /// Diagnose some forms of syntactically-obvious tautological comparison.
9615 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9616                                            Expr *LHS, Expr *RHS,
9617                                            BinaryOperatorKind Opc) {
9618   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9619   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9620 
9621   QualType LHSType = LHS->getType();
9622   QualType RHSType = RHS->getType();
9623   if (LHSType->hasFloatingRepresentation() ||
9624       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9625       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9626       S.inTemplateInstantiation())
9627     return;
9628 
9629   // Comparisons between two array types are ill-formed for operator<=>, so
9630   // we shouldn't emit any additional warnings about it.
9631   if (Opc == BO_Cmp && LHSType->isArrayType() && RHSType->isArrayType())
9632     return;
9633 
9634   // For non-floating point types, check for self-comparisons of the form
9635   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9636   // often indicate logic errors in the program.
9637   //
9638   // NOTE: Don't warn about comparison expressions resulting from macro
9639   // expansion. Also don't warn about comparisons which are only self
9640   // comparisons within a template instantiation. The warnings should catch
9641   // obvious cases in the definition of the template anyways. The idea is to
9642   // warn when the typed comparison operator will always evaluate to the same
9643   // result.
9644   ValueDecl *DL = getCompareDecl(LHSStripped);
9645   ValueDecl *DR = getCompareDecl(RHSStripped);
9646   if (DL && DR && declaresSameEntity(DL, DR)) {
9647     StringRef Result;
9648     switch (Opc) {
9649     case BO_EQ: case BO_LE: case BO_GE:
9650       Result = "true";
9651       break;
9652     case BO_NE: case BO_LT: case BO_GT:
9653       Result = "false";
9654       break;
9655     case BO_Cmp:
9656       Result = "'std::strong_ordering::equal'";
9657       break;
9658     default:
9659       break;
9660     }
9661     S.DiagRuntimeBehavior(Loc, nullptr,
9662                           S.PDiag(diag::warn_comparison_always)
9663                               << 0 /*self-comparison*/ << !Result.empty()
9664                               << Result);
9665   } else if (DL && DR &&
9666              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9667              !DL->isWeak() && !DR->isWeak()) {
9668     // What is it always going to evaluate to?
9669     StringRef Result;
9670     switch(Opc) {
9671     case BO_EQ: // e.g. array1 == array2
9672       Result = "false";
9673       break;
9674     case BO_NE: // e.g. array1 != array2
9675       Result = "true";
9676       break;
9677     default: // e.g. array1 <= array2
9678       // The best we can say is 'a constant'
9679       break;
9680     }
9681     S.DiagRuntimeBehavior(Loc, nullptr,
9682                           S.PDiag(diag::warn_comparison_always)
9683                               << 1 /*array comparison*/
9684                               << !Result.empty() << Result);
9685   }
9686 
9687   if (isa<CastExpr>(LHSStripped))
9688     LHSStripped = LHSStripped->IgnoreParenCasts();
9689   if (isa<CastExpr>(RHSStripped))
9690     RHSStripped = RHSStripped->IgnoreParenCasts();
9691 
9692   // Warn about comparisons against a string constant (unless the other
9693   // operand is null); the user probably wants strcmp.
9694   Expr *LiteralString = nullptr;
9695   Expr *LiteralStringStripped = nullptr;
9696   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9697       !RHSStripped->isNullPointerConstant(S.Context,
9698                                           Expr::NPC_ValueDependentIsNull)) {
9699     LiteralString = LHS;
9700     LiteralStringStripped = LHSStripped;
9701   } else if ((isa<StringLiteral>(RHSStripped) ||
9702               isa<ObjCEncodeExpr>(RHSStripped)) &&
9703              !LHSStripped->isNullPointerConstant(S.Context,
9704                                           Expr::NPC_ValueDependentIsNull)) {
9705     LiteralString = RHS;
9706     LiteralStringStripped = RHSStripped;
9707   }
9708 
9709   if (LiteralString) {
9710     S.DiagRuntimeBehavior(Loc, nullptr,
9711                           S.PDiag(diag::warn_stringcompare)
9712                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9713                               << LiteralString->getSourceRange());
9714   }
9715 }
9716 
9717 static ImplicitConversionKind castKindToImplicitConversionKind(CastKind CK) {
9718   switch (CK) {
9719   default: {
9720 #ifndef NDEBUG
9721     llvm::errs() << "unhandled cast kind: " << CastExpr::getCastKindName(CK)
9722                  << "\n";
9723 #endif
9724     llvm_unreachable("unhandled cast kind");
9725   }
9726   case CK_UserDefinedConversion:
9727     return ICK_Identity;
9728   case CK_LValueToRValue:
9729     return ICK_Lvalue_To_Rvalue;
9730   case CK_ArrayToPointerDecay:
9731     return ICK_Array_To_Pointer;
9732   case CK_FunctionToPointerDecay:
9733     return ICK_Function_To_Pointer;
9734   case CK_IntegralCast:
9735     return ICK_Integral_Conversion;
9736   case CK_FloatingCast:
9737     return ICK_Floating_Conversion;
9738   case CK_IntegralToFloating:
9739   case CK_FloatingToIntegral:
9740     return ICK_Floating_Integral;
9741   case CK_IntegralComplexCast:
9742   case CK_FloatingComplexCast:
9743   case CK_FloatingComplexToIntegralComplex:
9744   case CK_IntegralComplexToFloatingComplex:
9745     return ICK_Complex_Conversion;
9746   case CK_FloatingComplexToReal:
9747   case CK_FloatingRealToComplex:
9748   case CK_IntegralComplexToReal:
9749   case CK_IntegralRealToComplex:
9750     return ICK_Complex_Real;
9751   }
9752 }
9753 
9754 static bool checkThreeWayNarrowingConversion(Sema &S, QualType ToType, Expr *E,
9755                                              QualType FromType,
9756                                              SourceLocation Loc) {
9757   // Check for a narrowing implicit conversion.
9758   StandardConversionSequence SCS;
9759   SCS.setAsIdentityConversion();
9760   SCS.setToType(0, FromType);
9761   SCS.setToType(1, ToType);
9762   if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
9763     SCS.Second = castKindToImplicitConversionKind(ICE->getCastKind());
9764 
9765   APValue PreNarrowingValue;
9766   QualType PreNarrowingType;
9767   switch (SCS.getNarrowingKind(S.Context, E, PreNarrowingValue,
9768                                PreNarrowingType,
9769                                /*IgnoreFloatToIntegralConversion*/ true)) {
9770   case NK_Dependent_Narrowing:
9771     // Implicit conversion to a narrower type, but the expression is
9772     // value-dependent so we can't tell whether it's actually narrowing.
9773   case NK_Not_Narrowing:
9774     return false;
9775 
9776   case NK_Constant_Narrowing:
9777     // Implicit conversion to a narrower type, and the value is not a constant
9778     // expression.
9779     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9780         << /*Constant*/ 1
9781         << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << ToType;
9782     return true;
9783 
9784   case NK_Variable_Narrowing:
9785     // Implicit conversion to a narrower type, and the value is not a constant
9786     // expression.
9787   case NK_Type_Narrowing:
9788     S.Diag(E->getLocStart(), diag::err_spaceship_argument_narrowing)
9789         << /*Constant*/ 0 << FromType << ToType;
9790     // TODO: It's not a constant expression, but what if the user intended it
9791     // to be? Can we produce notes to help them figure out why it isn't?
9792     return true;
9793   }
9794   llvm_unreachable("unhandled case in switch");
9795 }
9796 
9797 static QualType checkArithmeticOrEnumeralThreeWayCompare(Sema &S,
9798                                                          ExprResult &LHS,
9799                                                          ExprResult &RHS,
9800                                                          SourceLocation Loc) {
9801   using CCT = ComparisonCategoryType;
9802 
9803   QualType LHSType = LHS.get()->getType();
9804   QualType RHSType = RHS.get()->getType();
9805   // Dig out the original argument type and expression before implicit casts
9806   // were applied. These are the types/expressions we need to check the
9807   // [expr.spaceship] requirements against.
9808   ExprResult LHSStripped = LHS.get()->IgnoreParenImpCasts();
9809   ExprResult RHSStripped = RHS.get()->IgnoreParenImpCasts();
9810   QualType LHSStrippedType = LHSStripped.get()->getType();
9811   QualType RHSStrippedType = RHSStripped.get()->getType();
9812 
9813   // C++2a [expr.spaceship]p3: If one of the operands is of type bool and the
9814   // other is not, the program is ill-formed.
9815   if (LHSStrippedType->isBooleanType() != RHSStrippedType->isBooleanType()) {
9816     S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9817     return QualType();
9818   }
9819 
9820   int NumEnumArgs = (int)LHSStrippedType->isEnumeralType() +
9821                     RHSStrippedType->isEnumeralType();
9822   if (NumEnumArgs == 1) {
9823     bool LHSIsEnum = LHSStrippedType->isEnumeralType();
9824     QualType OtherTy = LHSIsEnum ? RHSStrippedType : LHSStrippedType;
9825     if (OtherTy->hasFloatingRepresentation()) {
9826       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9827       return QualType();
9828     }
9829   }
9830   if (NumEnumArgs == 2) {
9831     // C++2a [expr.spaceship]p5: If both operands have the same enumeration
9832     // type E, the operator yields the result of converting the operands
9833     // to the underlying type of E and applying <=> to the converted operands.
9834     if (!S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType)) {
9835       S.InvalidOperands(Loc, LHSStripped, RHSStripped);
9836       return QualType();
9837     }
9838     QualType IntType =
9839         LHSStrippedType->getAs<EnumType>()->getDecl()->getIntegerType();
9840     assert(IntType->isArithmeticType());
9841 
9842     // We can't use `CK_IntegralCast` when the underlying type is 'bool', so we
9843     // promote the boolean type, and all other promotable integer types, to
9844     // avoid this.
9845     if (IntType->isPromotableIntegerType())
9846       IntType = S.Context.getPromotedIntegerType(IntType);
9847 
9848     LHS = S.ImpCastExprToType(LHS.get(), IntType, CK_IntegralCast);
9849     RHS = S.ImpCastExprToType(RHS.get(), IntType, CK_IntegralCast);
9850     LHSType = RHSType = IntType;
9851   }
9852 
9853   // C++2a [expr.spaceship]p4: If both operands have arithmetic types, the
9854   // usual arithmetic conversions are applied to the operands.
9855   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9856   if (LHS.isInvalid() || RHS.isInvalid())
9857     return QualType();
9858   if (Type.isNull())
9859     return S.InvalidOperands(Loc, LHS, RHS);
9860   assert(Type->isArithmeticType() || Type->isEnumeralType());
9861 
9862   bool HasNarrowing = checkThreeWayNarrowingConversion(
9863       S, Type, LHS.get(), LHSType, LHS.get()->getLocStart());
9864   HasNarrowing |= checkThreeWayNarrowingConversion(
9865       S, Type, RHS.get(), RHSType, RHS.get()->getLocStart());
9866   if (HasNarrowing)
9867     return QualType();
9868 
9869   assert(!Type.isNull() && "composite type for <=> has not been set");
9870 
9871   auto TypeKind = [&]() {
9872     if (const ComplexType *CT = Type->getAs<ComplexType>()) {
9873       if (CT->getElementType()->hasFloatingRepresentation())
9874         return CCT::WeakEquality;
9875       return CCT::StrongEquality;
9876     }
9877     if (Type->isIntegralOrEnumerationType())
9878       return CCT::StrongOrdering;
9879     if (Type->hasFloatingRepresentation())
9880       return CCT::PartialOrdering;
9881     llvm_unreachable("other types are unimplemented");
9882   }();
9883 
9884   return S.CheckComparisonCategoryType(TypeKind, Loc);
9885 }
9886 
9887 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9888                                                  ExprResult &RHS,
9889                                                  SourceLocation Loc,
9890                                                  BinaryOperatorKind Opc) {
9891   if (Opc == BO_Cmp)
9892     return checkArithmeticOrEnumeralThreeWayCompare(S, LHS, RHS, Loc);
9893 
9894   // C99 6.5.8p3 / C99 6.5.9p4
9895   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9896   if (LHS.isInvalid() || RHS.isInvalid())
9897     return QualType();
9898   if (Type.isNull())
9899     return S.InvalidOperands(Loc, LHS, RHS);
9900   assert(Type->isArithmeticType() || Type->isEnumeralType());
9901 
9902   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
9903 
9904   if (Type->isAnyComplexType() && BinaryOperator::isRelationalOp(Opc))
9905     return S.InvalidOperands(Loc, LHS, RHS);
9906 
9907   // Check for comparisons of floating point operands using != and ==.
9908   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
9909     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
9910 
9911   // The result of comparisons is 'bool' in C++, 'int' in C.
9912   return S.Context.getLogicalOperationType();
9913 }
9914 
9915 // C99 6.5.8, C++ [expr.rel]
9916 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9917                                     SourceLocation Loc,
9918                                     BinaryOperatorKind Opc) {
9919   bool IsRelational = BinaryOperator::isRelationalOp(Opc);
9920   bool IsThreeWay = Opc == BO_Cmp;
9921   auto IsAnyPointerType = [](ExprResult E) {
9922     QualType Ty = E.get()->getType();
9923     return Ty->isPointerType() || Ty->isMemberPointerType();
9924   };
9925 
9926   // C++2a [expr.spaceship]p6: If at least one of the operands is of pointer
9927   // type, array-to-pointer, ..., conversions are performed on both operands to
9928   // bring them to their composite type.
9929   // Otherwise, all comparisons expect an rvalue, so convert to rvalue before
9930   // any type-related checks.
9931   if (!IsThreeWay || IsAnyPointerType(LHS) || IsAnyPointerType(RHS)) {
9932     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9933     if (LHS.isInvalid())
9934       return QualType();
9935     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9936     if (RHS.isInvalid())
9937       return QualType();
9938   } else {
9939     LHS = DefaultLvalueConversion(LHS.get());
9940     if (LHS.isInvalid())
9941       return QualType();
9942     RHS = DefaultLvalueConversion(RHS.get());
9943     if (RHS.isInvalid())
9944       return QualType();
9945   }
9946 
9947   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9948 
9949   // Handle vector comparisons separately.
9950   if (LHS.get()->getType()->isVectorType() ||
9951       RHS.get()->getType()->isVectorType())
9952     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
9953 
9954   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9955   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
9956 
9957   QualType LHSType = LHS.get()->getType();
9958   QualType RHSType = RHS.get()->getType();
9959   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
9960       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
9961     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
9962 
9963   const Expr::NullPointerConstantKind LHSNullKind =
9964       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9965   const Expr::NullPointerConstantKind RHSNullKind =
9966       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9967   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9968   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9969 
9970   auto computeResultTy = [&]() {
9971     if (Opc != BO_Cmp)
9972       return Context.getLogicalOperationType();
9973     assert(getLangOpts().CPlusPlus);
9974     assert(Context.hasSameType(LHS.get()->getType(), RHS.get()->getType()));
9975 
9976     QualType CompositeTy = LHS.get()->getType();
9977     assert(!CompositeTy->isReferenceType());
9978 
9979     auto buildResultTy = [&](ComparisonCategoryType Kind) {
9980       return CheckComparisonCategoryType(Kind, Loc);
9981     };
9982 
9983     // C++2a [expr.spaceship]p7: If the composite pointer type is a function
9984     // pointer type, a pointer-to-member type, or std::nullptr_t, the
9985     // result is of type std::strong_equality
9986     if (CompositeTy->isFunctionPointerType() ||
9987         CompositeTy->isMemberPointerType() || CompositeTy->isNullPtrType())
9988       // FIXME: consider making the function pointer case produce
9989       // strong_ordering not strong_equality, per P0946R0-Jax18 discussion
9990       // and direction polls
9991       return buildResultTy(ComparisonCategoryType::StrongEquality);
9992 
9993     // C++2a [expr.spaceship]p8: If the composite pointer type is an object
9994     // pointer type, p <=> q is of type std::strong_ordering.
9995     if (CompositeTy->isPointerType()) {
9996       // P0946R0: Comparisons between a null pointer constant and an object
9997       // pointer result in std::strong_equality
9998       if (LHSIsNull != RHSIsNull)
9999         return buildResultTy(ComparisonCategoryType::StrongEquality);
10000       return buildResultTy(ComparisonCategoryType::StrongOrdering);
10001     }
10002     // C++2a [expr.spaceship]p9: Otherwise, the program is ill-formed.
10003     // TODO: Extend support for operator<=> to ObjC types.
10004     return InvalidOperands(Loc, LHS, RHS);
10005   };
10006 
10007 
10008   if (!IsRelational && LHSIsNull != RHSIsNull) {
10009     bool IsEquality = Opc == BO_EQ;
10010     if (RHSIsNull)
10011       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
10012                                    RHS.get()->getSourceRange());
10013     else
10014       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
10015                                    LHS.get()->getSourceRange());
10016   }
10017 
10018   if ((LHSType->isIntegerType() && !LHSIsNull) ||
10019       (RHSType->isIntegerType() && !RHSIsNull)) {
10020     // Skip normal pointer conversion checks in this case; we have better
10021     // diagnostics for this below.
10022   } else if (getLangOpts().CPlusPlus) {
10023     // Equality comparison of a function pointer to a void pointer is invalid,
10024     // but we allow it as an extension.
10025     // FIXME: If we really want to allow this, should it be part of composite
10026     // pointer type computation so it works in conditionals too?
10027     if (!IsRelational &&
10028         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
10029          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
10030       // This is a gcc extension compatibility comparison.
10031       // In a SFINAE context, we treat this as a hard error to maintain
10032       // conformance with the C++ standard.
10033       diagnoseFunctionPointerToVoidComparison(
10034           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
10035 
10036       if (isSFINAEContext())
10037         return QualType();
10038 
10039       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10040       return computeResultTy();
10041     }
10042 
10043     // C++ [expr.eq]p2:
10044     //   If at least one operand is a pointer [...] bring them to their
10045     //   composite pointer type.
10046     // C++ [expr.spaceship]p6
10047     //  If at least one of the operands is of pointer type, [...] bring them
10048     //  to their composite pointer type.
10049     // C++ [expr.rel]p2:
10050     //   If both operands are pointers, [...] bring them to their composite
10051     //   pointer type.
10052     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
10053             (IsRelational ? 2 : 1) &&
10054         (!LangOpts.ObjCAutoRefCount || !(LHSType->isObjCObjectPointerType() ||
10055                                          RHSType->isObjCObjectPointerType()))) {
10056       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10057         return QualType();
10058       return computeResultTy();
10059     }
10060   } else if (LHSType->isPointerType() &&
10061              RHSType->isPointerType()) { // C99 6.5.8p2
10062     // All of the following pointer-related warnings are GCC extensions, except
10063     // when handling null pointer constants.
10064     QualType LCanPointeeTy =
10065       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10066     QualType RCanPointeeTy =
10067       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
10068 
10069     // C99 6.5.9p2 and C99 6.5.8p2
10070     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
10071                                    RCanPointeeTy.getUnqualifiedType())) {
10072       // Valid unless a relational comparison of function pointers
10073       if (IsRelational && LCanPointeeTy->isFunctionType()) {
10074         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
10075           << LHSType << RHSType << LHS.get()->getSourceRange()
10076           << RHS.get()->getSourceRange();
10077       }
10078     } else if (!IsRelational &&
10079                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
10080       // Valid unless comparison between non-null pointer and function pointer
10081       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
10082           && !LHSIsNull && !RHSIsNull)
10083         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
10084                                                 /*isError*/false);
10085     } else {
10086       // Invalid
10087       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
10088     }
10089     if (LCanPointeeTy != RCanPointeeTy) {
10090       // Treat NULL constant as a special case in OpenCL.
10091       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
10092         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
10093         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
10094           Diag(Loc,
10095                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
10096               << LHSType << RHSType << 0 /* comparison */
10097               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
10098         }
10099       }
10100       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
10101       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
10102       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
10103                                                : CK_BitCast;
10104       if (LHSIsNull && !RHSIsNull)
10105         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
10106       else
10107         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
10108     }
10109     return computeResultTy();
10110   }
10111 
10112   if (getLangOpts().CPlusPlus) {
10113     // C++ [expr.eq]p4:
10114     //   Two operands of type std::nullptr_t or one operand of type
10115     //   std::nullptr_t and the other a null pointer constant compare equal.
10116     if (!IsRelational && LHSIsNull && RHSIsNull) {
10117       if (LHSType->isNullPtrType()) {
10118         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10119         return computeResultTy();
10120       }
10121       if (RHSType->isNullPtrType()) {
10122         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10123         return computeResultTy();
10124       }
10125     }
10126 
10127     // Comparison of Objective-C pointers and block pointers against nullptr_t.
10128     // These aren't covered by the composite pointer type rules.
10129     if (!IsRelational && RHSType->isNullPtrType() &&
10130         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
10131       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10132       return computeResultTy();
10133     }
10134     if (!IsRelational && LHSType->isNullPtrType() &&
10135         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
10136       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10137       return computeResultTy();
10138     }
10139 
10140     if (IsRelational &&
10141         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
10142          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
10143       // HACK: Relational comparison of nullptr_t against a pointer type is
10144       // invalid per DR583, but we allow it within std::less<> and friends,
10145       // since otherwise common uses of it break.
10146       // FIXME: Consider removing this hack once LWG fixes std::less<> and
10147       // friends to have std::nullptr_t overload candidates.
10148       DeclContext *DC = CurContext;
10149       if (isa<FunctionDecl>(DC))
10150         DC = DC->getParent();
10151       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
10152         if (CTSD->isInStdNamespace() &&
10153             llvm::StringSwitch<bool>(CTSD->getName())
10154                 .Cases("less", "less_equal", "greater", "greater_equal", true)
10155                 .Default(false)) {
10156           if (RHSType->isNullPtrType())
10157             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10158           else
10159             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10160           return computeResultTy();
10161         }
10162       }
10163     }
10164 
10165     // C++ [expr.eq]p2:
10166     //   If at least one operand is a pointer to member, [...] bring them to
10167     //   their composite pointer type.
10168     if (!IsRelational &&
10169         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
10170       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
10171         return QualType();
10172       else
10173         return computeResultTy();
10174     }
10175   }
10176 
10177   // Handle block pointer types.
10178   if (!IsRelational && LHSType->isBlockPointerType() &&
10179       RHSType->isBlockPointerType()) {
10180     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
10181     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
10182 
10183     if (!LHSIsNull && !RHSIsNull &&
10184         !Context.typesAreCompatible(lpointee, rpointee)) {
10185       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10186         << LHSType << RHSType << LHS.get()->getSourceRange()
10187         << RHS.get()->getSourceRange();
10188     }
10189     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10190     return computeResultTy();
10191   }
10192 
10193   // Allow block pointers to be compared with null pointer constants.
10194   if (!IsRelational
10195       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
10196           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
10197     if (!LHSIsNull && !RHSIsNull) {
10198       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
10199              ->getPointeeType()->isVoidType())
10200             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
10201                 ->getPointeeType()->isVoidType())))
10202         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
10203           << LHSType << RHSType << LHS.get()->getSourceRange()
10204           << RHS.get()->getSourceRange();
10205     }
10206     if (LHSIsNull && !RHSIsNull)
10207       LHS = ImpCastExprToType(LHS.get(), RHSType,
10208                               RHSType->isPointerType() ? CK_BitCast
10209                                 : CK_AnyPointerToBlockPointerCast);
10210     else
10211       RHS = ImpCastExprToType(RHS.get(), LHSType,
10212                               LHSType->isPointerType() ? CK_BitCast
10213                                 : CK_AnyPointerToBlockPointerCast);
10214     return computeResultTy();
10215   }
10216 
10217   if (LHSType->isObjCObjectPointerType() ||
10218       RHSType->isObjCObjectPointerType()) {
10219     const PointerType *LPT = LHSType->getAs<PointerType>();
10220     const PointerType *RPT = RHSType->getAs<PointerType>();
10221     if (LPT || RPT) {
10222       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
10223       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
10224 
10225       if (!LPtrToVoid && !RPtrToVoid &&
10226           !Context.typesAreCompatible(LHSType, RHSType)) {
10227         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10228                                           /*isError*/false);
10229       }
10230       if (LHSIsNull && !RHSIsNull) {
10231         Expr *E = LHS.get();
10232         if (getLangOpts().ObjCAutoRefCount)
10233           CheckObjCConversion(SourceRange(), RHSType, E,
10234                               CCK_ImplicitConversion);
10235         LHS = ImpCastExprToType(E, RHSType,
10236                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10237       }
10238       else {
10239         Expr *E = RHS.get();
10240         if (getLangOpts().ObjCAutoRefCount)
10241           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10242                               /*Diagnose=*/true,
10243                               /*DiagnoseCFAudited=*/false, Opc);
10244         RHS = ImpCastExprToType(E, LHSType,
10245                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10246       }
10247       return computeResultTy();
10248     }
10249     if (LHSType->isObjCObjectPointerType() &&
10250         RHSType->isObjCObjectPointerType()) {
10251       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10252         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10253                                           /*isError*/false);
10254       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10255         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10256 
10257       if (LHSIsNull && !RHSIsNull)
10258         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10259       else
10260         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10261       return computeResultTy();
10262     }
10263 
10264     if (!IsRelational && LHSType->isBlockPointerType() &&
10265         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10266       LHS = ImpCastExprToType(LHS.get(), RHSType,
10267                               CK_BlockPointerToObjCPointerCast);
10268       return computeResultTy();
10269     } else if (!IsRelational &&
10270                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10271                RHSType->isBlockPointerType()) {
10272       RHS = ImpCastExprToType(RHS.get(), LHSType,
10273                               CK_BlockPointerToObjCPointerCast);
10274       return computeResultTy();
10275     }
10276   }
10277   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10278       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10279     unsigned DiagID = 0;
10280     bool isError = false;
10281     if (LangOpts.DebuggerSupport) {
10282       // Under a debugger, allow the comparison of pointers to integers,
10283       // since users tend to want to compare addresses.
10284     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10285                (RHSIsNull && RHSType->isIntegerType())) {
10286       if (IsRelational) {
10287         isError = getLangOpts().CPlusPlus;
10288         DiagID =
10289           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10290                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10291       }
10292     } else if (getLangOpts().CPlusPlus) {
10293       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10294       isError = true;
10295     } else if (IsRelational)
10296       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10297     else
10298       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10299 
10300     if (DiagID) {
10301       Diag(Loc, DiagID)
10302         << LHSType << RHSType << LHS.get()->getSourceRange()
10303         << RHS.get()->getSourceRange();
10304       if (isError)
10305         return QualType();
10306     }
10307 
10308     if (LHSType->isIntegerType())
10309       LHS = ImpCastExprToType(LHS.get(), RHSType,
10310                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10311     else
10312       RHS = ImpCastExprToType(RHS.get(), LHSType,
10313                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10314     return computeResultTy();
10315   }
10316 
10317   // Handle block pointers.
10318   if (!IsRelational && RHSIsNull
10319       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10320     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10321     return computeResultTy();
10322   }
10323   if (!IsRelational && LHSIsNull
10324       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10325     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10326     return computeResultTy();
10327   }
10328 
10329   if (getLangOpts().OpenCLVersion >= 200) {
10330     if (LHSIsNull && RHSType->isQueueT()) {
10331       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10332       return computeResultTy();
10333     }
10334 
10335     if (LHSType->isQueueT() && RHSIsNull) {
10336       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10337       return computeResultTy();
10338     }
10339   }
10340 
10341   return InvalidOperands(Loc, LHS, RHS);
10342 }
10343 
10344 // Return a signed ext_vector_type that is of identical size and number of
10345 // elements. For floating point vectors, return an integer type of identical
10346 // size and number of elements. In the non ext_vector_type case, search from
10347 // the largest type to the smallest type to avoid cases where long long == long,
10348 // where long gets picked over long long.
10349 QualType Sema::GetSignedVectorType(QualType V) {
10350   const VectorType *VTy = V->getAs<VectorType>();
10351   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10352 
10353   if (isa<ExtVectorType>(VTy)) {
10354     if (TypeSize == Context.getTypeSize(Context.CharTy))
10355       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10356     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10357       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10358     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10359       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10360     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10361       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10362     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10363            "Unhandled vector element size in vector compare");
10364     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10365   }
10366 
10367   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10368     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10369                                  VectorType::GenericVector);
10370   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10371     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10372                                  VectorType::GenericVector);
10373   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10374     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10375                                  VectorType::GenericVector);
10376   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10377     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10378                                  VectorType::GenericVector);
10379   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10380          "Unhandled vector element size in vector compare");
10381   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10382                                VectorType::GenericVector);
10383 }
10384 
10385 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10386 /// operates on extended vector types.  Instead of producing an IntTy result,
10387 /// like a scalar comparison, a vector comparison produces a vector of integer
10388 /// types.
10389 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10390                                           SourceLocation Loc,
10391                                           BinaryOperatorKind Opc) {
10392   // Check to make sure we're operating on vectors of the same type and width,
10393   // Allowing one side to be a scalar of element type.
10394   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10395                               /*AllowBothBool*/true,
10396                               /*AllowBoolConversions*/getLangOpts().ZVector);
10397   if (vType.isNull())
10398     return vType;
10399 
10400   QualType LHSType = LHS.get()->getType();
10401 
10402   // If AltiVec, the comparison results in a numeric type, i.e.
10403   // bool for C++, int for C
10404   if (getLangOpts().AltiVec &&
10405       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10406     return Context.getLogicalOperationType();
10407 
10408   // For non-floating point types, check for self-comparisons of the form
10409   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10410   // often indicate logic errors in the program.
10411   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10412 
10413   // Check for comparisons of floating point operands using != and ==.
10414   if (BinaryOperator::isEqualityOp(Opc) &&
10415       LHSType->hasFloatingRepresentation()) {
10416     assert(RHS.get()->getType()->hasFloatingRepresentation());
10417     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10418   }
10419 
10420   // Return a signed type for the vector.
10421   return GetSignedVectorType(vType);
10422 }
10423 
10424 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10425                                           SourceLocation Loc) {
10426   // Ensure that either both operands are of the same vector type, or
10427   // one operand is of a vector type and the other is of its element type.
10428   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10429                                        /*AllowBothBool*/true,
10430                                        /*AllowBoolConversions*/false);
10431   if (vType.isNull())
10432     return InvalidOperands(Loc, LHS, RHS);
10433   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10434       vType->hasFloatingRepresentation())
10435     return InvalidOperands(Loc, LHS, RHS);
10436   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10437   //        usage of the logical operators && and || with vectors in C. This
10438   //        check could be notionally dropped.
10439   if (!getLangOpts().CPlusPlus &&
10440       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10441     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10442 
10443   return GetSignedVectorType(LHS.get()->getType());
10444 }
10445 
10446 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10447                                            SourceLocation Loc,
10448                                            BinaryOperatorKind Opc) {
10449   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10450 
10451   bool IsCompAssign =
10452       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10453 
10454   if (LHS.get()->getType()->isVectorType() ||
10455       RHS.get()->getType()->isVectorType()) {
10456     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10457         RHS.get()->getType()->hasIntegerRepresentation())
10458       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10459                         /*AllowBothBool*/true,
10460                         /*AllowBoolConversions*/getLangOpts().ZVector);
10461     return InvalidOperands(Loc, LHS, RHS);
10462   }
10463 
10464   if (Opc == BO_And)
10465     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10466 
10467   ExprResult LHSResult = LHS, RHSResult = RHS;
10468   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10469                                                  IsCompAssign);
10470   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10471     return QualType();
10472   LHS = LHSResult.get();
10473   RHS = RHSResult.get();
10474 
10475   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10476     return compType;
10477   return InvalidOperands(Loc, LHS, RHS);
10478 }
10479 
10480 // C99 6.5.[13,14]
10481 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10482                                            SourceLocation Loc,
10483                                            BinaryOperatorKind Opc) {
10484   // Check vector operands differently.
10485   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10486     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10487 
10488   // Diagnose cases where the user write a logical and/or but probably meant a
10489   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10490   // is a constant.
10491   if (LHS.get()->getType()->isIntegerType() &&
10492       !LHS.get()->getType()->isBooleanType() &&
10493       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10494       // Don't warn in macros or template instantiations.
10495       !Loc.isMacroID() && !inTemplateInstantiation()) {
10496     // If the RHS can be constant folded, and if it constant folds to something
10497     // that isn't 0 or 1 (which indicate a potential logical operation that
10498     // happened to fold to true/false) then warn.
10499     // Parens on the RHS are ignored.
10500     llvm::APSInt Result;
10501     if (RHS.get()->EvaluateAsInt(Result, Context))
10502       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10503            !RHS.get()->getExprLoc().isMacroID()) ||
10504           (Result != 0 && Result != 1)) {
10505         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10506           << RHS.get()->getSourceRange()
10507           << (Opc == BO_LAnd ? "&&" : "||");
10508         // Suggest replacing the logical operator with the bitwise version
10509         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10510             << (Opc == BO_LAnd ? "&" : "|")
10511             << FixItHint::CreateReplacement(SourceRange(
10512                                                  Loc, getLocForEndOfToken(Loc)),
10513                                             Opc == BO_LAnd ? "&" : "|");
10514         if (Opc == BO_LAnd)
10515           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10516           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10517               << FixItHint::CreateRemoval(
10518                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10519                               RHS.get()->getLocEnd()));
10520       }
10521   }
10522 
10523   if (!Context.getLangOpts().CPlusPlus) {
10524     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10525     // not operate on the built-in scalar and vector float types.
10526     if (Context.getLangOpts().OpenCL &&
10527         Context.getLangOpts().OpenCLVersion < 120) {
10528       if (LHS.get()->getType()->isFloatingType() ||
10529           RHS.get()->getType()->isFloatingType())
10530         return InvalidOperands(Loc, LHS, RHS);
10531     }
10532 
10533     LHS = UsualUnaryConversions(LHS.get());
10534     if (LHS.isInvalid())
10535       return QualType();
10536 
10537     RHS = UsualUnaryConversions(RHS.get());
10538     if (RHS.isInvalid())
10539       return QualType();
10540 
10541     if (!LHS.get()->getType()->isScalarType() ||
10542         !RHS.get()->getType()->isScalarType())
10543       return InvalidOperands(Loc, LHS, RHS);
10544 
10545     return Context.IntTy;
10546   }
10547 
10548   // The following is safe because we only use this method for
10549   // non-overloadable operands.
10550 
10551   // C++ [expr.log.and]p1
10552   // C++ [expr.log.or]p1
10553   // The operands are both contextually converted to type bool.
10554   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10555   if (LHSRes.isInvalid())
10556     return InvalidOperands(Loc, LHS, RHS);
10557   LHS = LHSRes;
10558 
10559   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10560   if (RHSRes.isInvalid())
10561     return InvalidOperands(Loc, LHS, RHS);
10562   RHS = RHSRes;
10563 
10564   // C++ [expr.log.and]p2
10565   // C++ [expr.log.or]p2
10566   // The result is a bool.
10567   return Context.BoolTy;
10568 }
10569 
10570 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10571   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10572   if (!ME) return false;
10573   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10574   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10575       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10576   if (!Base) return false;
10577   return Base->getMethodDecl() != nullptr;
10578 }
10579 
10580 /// Is the given expression (which must be 'const') a reference to a
10581 /// variable which was originally non-const, but which has become
10582 /// 'const' due to being captured within a block?
10583 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10584 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10585   assert(E->isLValue() && E->getType().isConstQualified());
10586   E = E->IgnoreParens();
10587 
10588   // Must be a reference to a declaration from an enclosing scope.
10589   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10590   if (!DRE) return NCCK_None;
10591   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10592 
10593   // The declaration must be a variable which is not declared 'const'.
10594   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10595   if (!var) return NCCK_None;
10596   if (var->getType().isConstQualified()) return NCCK_None;
10597   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10598 
10599   // Decide whether the first capture was for a block or a lambda.
10600   DeclContext *DC = S.CurContext, *Prev = nullptr;
10601   // Decide whether the first capture was for a block or a lambda.
10602   while (DC) {
10603     // For init-capture, it is possible that the variable belongs to the
10604     // template pattern of the current context.
10605     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10606       if (var->isInitCapture() &&
10607           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10608         break;
10609     if (DC == var->getDeclContext())
10610       break;
10611     Prev = DC;
10612     DC = DC->getParent();
10613   }
10614   // Unless we have an init-capture, we've gone one step too far.
10615   if (!var->isInitCapture())
10616     DC = Prev;
10617   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10618 }
10619 
10620 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10621   Ty = Ty.getNonReferenceType();
10622   if (IsDereference && Ty->isPointerType())
10623     Ty = Ty->getPointeeType();
10624   return !Ty.isConstQualified();
10625 }
10626 
10627 // Update err_typecheck_assign_const and note_typecheck_assign_const
10628 // when this enum is changed.
10629 enum {
10630   ConstFunction,
10631   ConstVariable,
10632   ConstMember,
10633   ConstMethod,
10634   NestedConstMember,
10635   ConstUnknown,  // Keep as last element
10636 };
10637 
10638 /// Emit the "read-only variable not assignable" error and print notes to give
10639 /// more information about why the variable is not assignable, such as pointing
10640 /// to the declaration of a const variable, showing that a method is const, or
10641 /// that the function is returning a const reference.
10642 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10643                                     SourceLocation Loc) {
10644   SourceRange ExprRange = E->getSourceRange();
10645 
10646   // Only emit one error on the first const found.  All other consts will emit
10647   // a note to the error.
10648   bool DiagnosticEmitted = false;
10649 
10650   // Track if the current expression is the result of a dereference, and if the
10651   // next checked expression is the result of a dereference.
10652   bool IsDereference = false;
10653   bool NextIsDereference = false;
10654 
10655   // Loop to process MemberExpr chains.
10656   while (true) {
10657     IsDereference = NextIsDereference;
10658 
10659     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10660     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10661       NextIsDereference = ME->isArrow();
10662       const ValueDecl *VD = ME->getMemberDecl();
10663       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10664         // Mutable fields can be modified even if the class is const.
10665         if (Field->isMutable()) {
10666           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10667           break;
10668         }
10669 
10670         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10671           if (!DiagnosticEmitted) {
10672             S.Diag(Loc, diag::err_typecheck_assign_const)
10673                 << ExprRange << ConstMember << false /*static*/ << Field
10674                 << Field->getType();
10675             DiagnosticEmitted = true;
10676           }
10677           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10678               << ConstMember << false /*static*/ << Field << Field->getType()
10679               << Field->getSourceRange();
10680         }
10681         E = ME->getBase();
10682         continue;
10683       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10684         if (VDecl->getType().isConstQualified()) {
10685           if (!DiagnosticEmitted) {
10686             S.Diag(Loc, diag::err_typecheck_assign_const)
10687                 << ExprRange << ConstMember << true /*static*/ << VDecl
10688                 << VDecl->getType();
10689             DiagnosticEmitted = true;
10690           }
10691           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10692               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10693               << VDecl->getSourceRange();
10694         }
10695         // Static fields do not inherit constness from parents.
10696         break;
10697       }
10698       break; // End MemberExpr
10699     } else if (const ArraySubscriptExpr *ASE =
10700                    dyn_cast<ArraySubscriptExpr>(E)) {
10701       E = ASE->getBase()->IgnoreParenImpCasts();
10702       continue;
10703     } else if (const ExtVectorElementExpr *EVE =
10704                    dyn_cast<ExtVectorElementExpr>(E)) {
10705       E = EVE->getBase()->IgnoreParenImpCasts();
10706       continue;
10707     }
10708     break;
10709   }
10710 
10711   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10712     // Function calls
10713     const FunctionDecl *FD = CE->getDirectCallee();
10714     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10715       if (!DiagnosticEmitted) {
10716         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10717                                                       << ConstFunction << FD;
10718         DiagnosticEmitted = true;
10719       }
10720       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10721              diag::note_typecheck_assign_const)
10722           << ConstFunction << FD << FD->getReturnType()
10723           << FD->getReturnTypeSourceRange();
10724     }
10725   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10726     // Point to variable declaration.
10727     if (const ValueDecl *VD = DRE->getDecl()) {
10728       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10729         if (!DiagnosticEmitted) {
10730           S.Diag(Loc, diag::err_typecheck_assign_const)
10731               << ExprRange << ConstVariable << VD << VD->getType();
10732           DiagnosticEmitted = true;
10733         }
10734         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10735             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10736       }
10737     }
10738   } else if (isa<CXXThisExpr>(E)) {
10739     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10740       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10741         if (MD->isConst()) {
10742           if (!DiagnosticEmitted) {
10743             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10744                                                           << ConstMethod << MD;
10745             DiagnosticEmitted = true;
10746           }
10747           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10748               << ConstMethod << MD << MD->getSourceRange();
10749         }
10750       }
10751     }
10752   }
10753 
10754   if (DiagnosticEmitted)
10755     return;
10756 
10757   // Can't determine a more specific message, so display the generic error.
10758   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10759 }
10760 
10761 enum OriginalExprKind {
10762   OEK_Variable,
10763   OEK_Member,
10764   OEK_LValue
10765 };
10766 
10767 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10768                                          const RecordType *Ty,
10769                                          SourceLocation Loc, SourceRange Range,
10770                                          OriginalExprKind OEK,
10771                                          bool &DiagnosticEmitted,
10772                                          bool IsNested = false) {
10773   // We walk the record hierarchy breadth-first to ensure that we print
10774   // diagnostics in field nesting order.
10775   // First, check every field for constness.
10776   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10777     if (Field->getType().isConstQualified()) {
10778       if (!DiagnosticEmitted) {
10779         S.Diag(Loc, diag::err_typecheck_assign_const)
10780             << Range << NestedConstMember << OEK << VD
10781             << IsNested << Field;
10782         DiagnosticEmitted = true;
10783       }
10784       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10785           << NestedConstMember << IsNested << Field
10786           << Field->getType() << Field->getSourceRange();
10787     }
10788   }
10789   // Then, recurse.
10790   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10791     QualType FTy = Field->getType();
10792     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10793       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10794                                    OEK, DiagnosticEmitted, true);
10795   }
10796 }
10797 
10798 /// Emit an error for the case where a record we are trying to assign to has a
10799 /// const-qualified field somewhere in its hierarchy.
10800 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10801                                          SourceLocation Loc) {
10802   QualType Ty = E->getType();
10803   assert(Ty->isRecordType() && "lvalue was not record?");
10804   SourceRange Range = E->getSourceRange();
10805   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10806   bool DiagEmitted = false;
10807 
10808   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10809     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10810             Range, OEK_Member, DiagEmitted);
10811   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10812     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10813             Range, OEK_Variable, DiagEmitted);
10814   else
10815     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10816             Range, OEK_LValue, DiagEmitted);
10817   if (!DiagEmitted)
10818     DiagnoseConstAssignment(S, E, Loc);
10819 }
10820 
10821 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10822 /// emit an error and return true.  If so, return false.
10823 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10824   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10825 
10826   S.CheckShadowingDeclModification(E, Loc);
10827 
10828   SourceLocation OrigLoc = Loc;
10829   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10830                                                               &Loc);
10831   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10832     IsLV = Expr::MLV_InvalidMessageExpression;
10833   if (IsLV == Expr::MLV_Valid)
10834     return false;
10835 
10836   unsigned DiagID = 0;
10837   bool NeedType = false;
10838   switch (IsLV) { // C99 6.5.16p2
10839   case Expr::MLV_ConstQualified:
10840     // Use a specialized diagnostic when we're assigning to an object
10841     // from an enclosing function or block.
10842     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10843       if (NCCK == NCCK_Block)
10844         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10845       else
10846         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10847       break;
10848     }
10849 
10850     // In ARC, use some specialized diagnostics for occasions where we
10851     // infer 'const'.  These are always pseudo-strong variables.
10852     if (S.getLangOpts().ObjCAutoRefCount) {
10853       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10854       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10855         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10856 
10857         // Use the normal diagnostic if it's pseudo-__strong but the
10858         // user actually wrote 'const'.
10859         if (var->isARCPseudoStrong() &&
10860             (!var->getTypeSourceInfo() ||
10861              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10862           // There are two pseudo-strong cases:
10863           //  - self
10864           ObjCMethodDecl *method = S.getCurMethodDecl();
10865           if (method && var == method->getSelfDecl())
10866             DiagID = method->isClassMethod()
10867               ? diag::err_typecheck_arc_assign_self_class_method
10868               : diag::err_typecheck_arc_assign_self;
10869 
10870           //  - fast enumeration variables
10871           else
10872             DiagID = diag::err_typecheck_arr_assign_enumeration;
10873 
10874           SourceRange Assign;
10875           if (Loc != OrigLoc)
10876             Assign = SourceRange(OrigLoc, OrigLoc);
10877           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10878           // We need to preserve the AST regardless, so migration tool
10879           // can do its job.
10880           return false;
10881         }
10882       }
10883     }
10884 
10885     // If none of the special cases above are triggered, then this is a
10886     // simple const assignment.
10887     if (DiagID == 0) {
10888       DiagnoseConstAssignment(S, E, Loc);
10889       return true;
10890     }
10891 
10892     break;
10893   case Expr::MLV_ConstAddrSpace:
10894     DiagnoseConstAssignment(S, E, Loc);
10895     return true;
10896   case Expr::MLV_ConstQualifiedField:
10897     DiagnoseRecursiveConstFields(S, E, Loc);
10898     return true;
10899   case Expr::MLV_ArrayType:
10900   case Expr::MLV_ArrayTemporary:
10901     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10902     NeedType = true;
10903     break;
10904   case Expr::MLV_NotObjectType:
10905     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10906     NeedType = true;
10907     break;
10908   case Expr::MLV_LValueCast:
10909     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10910     break;
10911   case Expr::MLV_Valid:
10912     llvm_unreachable("did not take early return for MLV_Valid");
10913   case Expr::MLV_InvalidExpression:
10914   case Expr::MLV_MemberFunction:
10915   case Expr::MLV_ClassTemporary:
10916     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10917     break;
10918   case Expr::MLV_IncompleteType:
10919   case Expr::MLV_IncompleteVoidType:
10920     return S.RequireCompleteType(Loc, E->getType(),
10921              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10922   case Expr::MLV_DuplicateVectorComponents:
10923     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10924     break;
10925   case Expr::MLV_NoSetterProperty:
10926     llvm_unreachable("readonly properties should be processed differently");
10927   case Expr::MLV_InvalidMessageExpression:
10928     DiagID = diag::err_readonly_message_assignment;
10929     break;
10930   case Expr::MLV_SubObjCPropertySetting:
10931     DiagID = diag::err_no_subobject_property_setting;
10932     break;
10933   }
10934 
10935   SourceRange Assign;
10936   if (Loc != OrigLoc)
10937     Assign = SourceRange(OrigLoc, OrigLoc);
10938   if (NeedType)
10939     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10940   else
10941     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10942   return true;
10943 }
10944 
10945 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10946                                          SourceLocation Loc,
10947                                          Sema &Sema) {
10948   if (Sema.inTemplateInstantiation())
10949     return;
10950   if (Sema.isUnevaluatedContext())
10951     return;
10952   if (Loc.isInvalid() || Loc.isMacroID())
10953     return;
10954   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
10955     return;
10956 
10957   // C / C++ fields
10958   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10959   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10960   if (ML && MR) {
10961     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
10962       return;
10963     const ValueDecl *LHSDecl =
10964         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
10965     const ValueDecl *RHSDecl =
10966         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
10967     if (LHSDecl != RHSDecl)
10968       return;
10969     if (LHSDecl->getType().isVolatileQualified())
10970       return;
10971     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10972       if (RefTy->getPointeeType().isVolatileQualified())
10973         return;
10974 
10975     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10976   }
10977 
10978   // Objective-C instance variables
10979   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10980   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10981   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10982     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10983     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10984     if (RL && RR && RL->getDecl() == RR->getDecl())
10985       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10986   }
10987 }
10988 
10989 // C99 6.5.16.1
10990 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10991                                        SourceLocation Loc,
10992                                        QualType CompoundType) {
10993   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10994 
10995   // Verify that LHS is a modifiable lvalue, and emit error if not.
10996   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10997     return QualType();
10998 
10999   QualType LHSType = LHSExpr->getType();
11000   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
11001                                              CompoundType;
11002   // OpenCL v1.2 s6.1.1.1 p2:
11003   // The half data type can only be used to declare a pointer to a buffer that
11004   // contains half values
11005   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
11006     LHSType->isHalfType()) {
11007     Diag(Loc, diag::err_opencl_half_load_store) << 1
11008         << LHSType.getUnqualifiedType();
11009     return QualType();
11010   }
11011 
11012   AssignConvertType ConvTy;
11013   if (CompoundType.isNull()) {
11014     Expr *RHSCheck = RHS.get();
11015 
11016     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
11017 
11018     QualType LHSTy(LHSType);
11019     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
11020     if (RHS.isInvalid())
11021       return QualType();
11022     // Special case of NSObject attributes on c-style pointer types.
11023     if (ConvTy == IncompatiblePointer &&
11024         ((Context.isObjCNSObjectType(LHSType) &&
11025           RHSType->isObjCObjectPointerType()) ||
11026          (Context.isObjCNSObjectType(RHSType) &&
11027           LHSType->isObjCObjectPointerType())))
11028       ConvTy = Compatible;
11029 
11030     if (ConvTy == Compatible &&
11031         LHSType->isObjCObjectType())
11032         Diag(Loc, diag::err_objc_object_assignment)
11033           << LHSType;
11034 
11035     // If the RHS is a unary plus or minus, check to see if they = and + are
11036     // right next to each other.  If so, the user may have typo'd "x =+ 4"
11037     // instead of "x += 4".
11038     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
11039       RHSCheck = ICE->getSubExpr();
11040     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
11041       if ((UO->getOpcode() == UO_Plus ||
11042            UO->getOpcode() == UO_Minus) &&
11043           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
11044           // Only if the two operators are exactly adjacent.
11045           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
11046           // And there is a space or other character before the subexpr of the
11047           // unary +/-.  We don't want to warn on "x=-1".
11048           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
11049           UO->getSubExpr()->getLocStart().isFileID()) {
11050         Diag(Loc, diag::warn_not_compound_assign)
11051           << (UO->getOpcode() == UO_Plus ? "+" : "-")
11052           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
11053       }
11054     }
11055 
11056     if (ConvTy == Compatible) {
11057       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
11058         // Warn about retain cycles where a block captures the LHS, but
11059         // not if the LHS is a simple variable into which the block is
11060         // being stored...unless that variable can be captured by reference!
11061         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
11062         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
11063         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
11064           checkRetainCycles(LHSExpr, RHS.get());
11065       }
11066 
11067       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
11068           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
11069         // It is safe to assign a weak reference into a strong variable.
11070         // Although this code can still have problems:
11071         //   id x = self.weakProp;
11072         //   id y = self.weakProp;
11073         // we do not warn to warn spuriously when 'x' and 'y' are on separate
11074         // paths through the function. This should be revisited if
11075         // -Wrepeated-use-of-weak is made flow-sensitive.
11076         // For ObjCWeak only, we do not warn if the assign is to a non-weak
11077         // variable, which will be valid for the current autorelease scope.
11078         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11079                              RHS.get()->getLocStart()))
11080           getCurFunction()->markSafeWeakUse(RHS.get());
11081 
11082       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
11083         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
11084       }
11085     }
11086   } else {
11087     // Compound assignment "x += y"
11088     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
11089   }
11090 
11091   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
11092                                RHS.get(), AA_Assigning))
11093     return QualType();
11094 
11095   CheckForNullPointerDereference(*this, LHSExpr);
11096 
11097   // C99 6.5.16p3: The type of an assignment expression is the type of the
11098   // left operand unless the left operand has qualified type, in which case
11099   // it is the unqualified version of the type of the left operand.
11100   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
11101   // is converted to the type of the assignment expression (above).
11102   // C++ 5.17p1: the type of the assignment expression is that of its left
11103   // operand.
11104   return (getLangOpts().CPlusPlus
11105           ? LHSType : LHSType.getUnqualifiedType());
11106 }
11107 
11108 // Only ignore explicit casts to void.
11109 static bool IgnoreCommaOperand(const Expr *E) {
11110   E = E->IgnoreParens();
11111 
11112   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
11113     if (CE->getCastKind() == CK_ToVoid) {
11114       return true;
11115     }
11116   }
11117 
11118   return false;
11119 }
11120 
11121 // Look for instances where it is likely the comma operator is confused with
11122 // another operator.  There is a whitelist of acceptable expressions for the
11123 // left hand side of the comma operator, otherwise emit a warning.
11124 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
11125   // No warnings in macros
11126   if (Loc.isMacroID())
11127     return;
11128 
11129   // Don't warn in template instantiations.
11130   if (inTemplateInstantiation())
11131     return;
11132 
11133   // Scope isn't fine-grained enough to whitelist the specific cases, so
11134   // instead, skip more than needed, then call back into here with the
11135   // CommaVisitor in SemaStmt.cpp.
11136   // The whitelisted locations are the initialization and increment portions
11137   // of a for loop.  The additional checks are on the condition of
11138   // if statements, do/while loops, and for loops.
11139   const unsigned ForIncrementFlags =
11140       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
11141   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
11142   const unsigned ScopeFlags = getCurScope()->getFlags();
11143   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
11144       (ScopeFlags & ForInitFlags) == ForInitFlags)
11145     return;
11146 
11147   // If there are multiple comma operators used together, get the RHS of the
11148   // of the comma operator as the LHS.
11149   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
11150     if (BO->getOpcode() != BO_Comma)
11151       break;
11152     LHS = BO->getRHS();
11153   }
11154 
11155   // Only allow some expressions on LHS to not warn.
11156   if (IgnoreCommaOperand(LHS))
11157     return;
11158 
11159   Diag(Loc, diag::warn_comma_operator);
11160   Diag(LHS->getLocStart(), diag::note_cast_to_void)
11161       << LHS->getSourceRange()
11162       << FixItHint::CreateInsertion(LHS->getLocStart(),
11163                                     LangOpts.CPlusPlus ? "static_cast<void>("
11164                                                        : "(void)(")
11165       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
11166                                     ")");
11167 }
11168 
11169 // C99 6.5.17
11170 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
11171                                    SourceLocation Loc) {
11172   LHS = S.CheckPlaceholderExpr(LHS.get());
11173   RHS = S.CheckPlaceholderExpr(RHS.get());
11174   if (LHS.isInvalid() || RHS.isInvalid())
11175     return QualType();
11176 
11177   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
11178   // operands, but not unary promotions.
11179   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
11180 
11181   // So we treat the LHS as a ignored value, and in C++ we allow the
11182   // containing site to determine what should be done with the RHS.
11183   LHS = S.IgnoredValueConversions(LHS.get());
11184   if (LHS.isInvalid())
11185     return QualType();
11186 
11187   S.DiagnoseUnusedExprResult(LHS.get());
11188 
11189   if (!S.getLangOpts().CPlusPlus) {
11190     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
11191     if (RHS.isInvalid())
11192       return QualType();
11193     if (!RHS.get()->getType()->isVoidType())
11194       S.RequireCompleteType(Loc, RHS.get()->getType(),
11195                             diag::err_incomplete_type);
11196   }
11197 
11198   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
11199     S.DiagnoseCommaOperator(LHS.get(), Loc);
11200 
11201   return RHS.get()->getType();
11202 }
11203 
11204 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
11205 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
11206 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
11207                                                ExprValueKind &VK,
11208                                                ExprObjectKind &OK,
11209                                                SourceLocation OpLoc,
11210                                                bool IsInc, bool IsPrefix) {
11211   if (Op->isTypeDependent())
11212     return S.Context.DependentTy;
11213 
11214   QualType ResType = Op->getType();
11215   // Atomic types can be used for increment / decrement where the non-atomic
11216   // versions can, so ignore the _Atomic() specifier for the purpose of
11217   // checking.
11218   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
11219     ResType = ResAtomicType->getValueType();
11220 
11221   assert(!ResType.isNull() && "no type for increment/decrement expression");
11222 
11223   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
11224     // Decrement of bool is not allowed.
11225     if (!IsInc) {
11226       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
11227       return QualType();
11228     }
11229     // Increment of bool sets it to true, but is deprecated.
11230     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11231                                               : diag::warn_increment_bool)
11232       << Op->getSourceRange();
11233   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11234     // Error on enum increments and decrements in C++ mode
11235     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11236     return QualType();
11237   } else if (ResType->isRealType()) {
11238     // OK!
11239   } else if (ResType->isPointerType()) {
11240     // C99 6.5.2.4p2, 6.5.6p2
11241     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11242       return QualType();
11243   } else if (ResType->isObjCObjectPointerType()) {
11244     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11245     // Otherwise, we just need a complete type.
11246     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11247         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11248       return QualType();
11249   } else if (ResType->isAnyComplexType()) {
11250     // C99 does not support ++/-- on complex types, we allow as an extension.
11251     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11252       << ResType << Op->getSourceRange();
11253   } else if (ResType->isPlaceholderType()) {
11254     ExprResult PR = S.CheckPlaceholderExpr(Op);
11255     if (PR.isInvalid()) return QualType();
11256     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11257                                           IsInc, IsPrefix);
11258   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11259     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11260   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11261              (ResType->getAs<VectorType>()->getVectorKind() !=
11262               VectorType::AltiVecBool)) {
11263     // The z vector extensions allow ++ and -- for non-bool vectors.
11264   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11265             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11266     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11267   } else {
11268     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11269       << ResType << int(IsInc) << Op->getSourceRange();
11270     return QualType();
11271   }
11272   // At this point, we know we have a real, complex or pointer type.
11273   // Now make sure the operand is a modifiable lvalue.
11274   if (CheckForModifiableLvalue(Op, OpLoc, S))
11275     return QualType();
11276   // In C++, a prefix increment is the same type as the operand. Otherwise
11277   // (in C or with postfix), the increment is the unqualified type of the
11278   // operand.
11279   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11280     VK = VK_LValue;
11281     OK = Op->getObjectKind();
11282     return ResType;
11283   } else {
11284     VK = VK_RValue;
11285     return ResType.getUnqualifiedType();
11286   }
11287 }
11288 
11289 
11290 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11291 /// This routine allows us to typecheck complex/recursive expressions
11292 /// where the declaration is needed for type checking. We only need to
11293 /// handle cases when the expression references a function designator
11294 /// or is an lvalue. Here are some examples:
11295 ///  - &(x) => x
11296 ///  - &*****f => f for f a function designator.
11297 ///  - &s.xx => s
11298 ///  - &s.zz[1].yy -> s, if zz is an array
11299 ///  - *(x + 1) -> x, if x is an array
11300 ///  - &"123"[2] -> 0
11301 ///  - & __real__ x -> x
11302 static ValueDecl *getPrimaryDecl(Expr *E) {
11303   switch (E->getStmtClass()) {
11304   case Stmt::DeclRefExprClass:
11305     return cast<DeclRefExpr>(E)->getDecl();
11306   case Stmt::MemberExprClass:
11307     // If this is an arrow operator, the address is an offset from
11308     // the base's value, so the object the base refers to is
11309     // irrelevant.
11310     if (cast<MemberExpr>(E)->isArrow())
11311       return nullptr;
11312     // Otherwise, the expression refers to a part of the base
11313     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11314   case Stmt::ArraySubscriptExprClass: {
11315     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11316     // promotion of register arrays earlier.
11317     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11318     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11319       if (ICE->getSubExpr()->getType()->isArrayType())
11320         return getPrimaryDecl(ICE->getSubExpr());
11321     }
11322     return nullptr;
11323   }
11324   case Stmt::UnaryOperatorClass: {
11325     UnaryOperator *UO = cast<UnaryOperator>(E);
11326 
11327     switch(UO->getOpcode()) {
11328     case UO_Real:
11329     case UO_Imag:
11330     case UO_Extension:
11331       return getPrimaryDecl(UO->getSubExpr());
11332     default:
11333       return nullptr;
11334     }
11335   }
11336   case Stmt::ParenExprClass:
11337     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11338   case Stmt::ImplicitCastExprClass:
11339     // If the result of an implicit cast is an l-value, we care about
11340     // the sub-expression; otherwise, the result here doesn't matter.
11341     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11342   default:
11343     return nullptr;
11344   }
11345 }
11346 
11347 namespace {
11348   enum {
11349     AO_Bit_Field = 0,
11350     AO_Vector_Element = 1,
11351     AO_Property_Expansion = 2,
11352     AO_Register_Variable = 3,
11353     AO_No_Error = 4
11354   };
11355 }
11356 /// Diagnose invalid operand for address of operations.
11357 ///
11358 /// \param Type The type of operand which cannot have its address taken.
11359 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11360                                          Expr *E, unsigned Type) {
11361   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11362 }
11363 
11364 /// CheckAddressOfOperand - The operand of & must be either a function
11365 /// designator or an lvalue designating an object. If it is an lvalue, the
11366 /// object cannot be declared with storage class register or be a bit field.
11367 /// Note: The usual conversions are *not* applied to the operand of the &
11368 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11369 /// In C++, the operand might be an overloaded function name, in which case
11370 /// we allow the '&' but retain the overloaded-function type.
11371 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11372   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11373     if (PTy->getKind() == BuiltinType::Overload) {
11374       Expr *E = OrigOp.get()->IgnoreParens();
11375       if (!isa<OverloadExpr>(E)) {
11376         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11377         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11378           << OrigOp.get()->getSourceRange();
11379         return QualType();
11380       }
11381 
11382       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11383       if (isa<UnresolvedMemberExpr>(Ovl))
11384         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11385           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11386             << OrigOp.get()->getSourceRange();
11387           return QualType();
11388         }
11389 
11390       return Context.OverloadTy;
11391     }
11392 
11393     if (PTy->getKind() == BuiltinType::UnknownAny)
11394       return Context.UnknownAnyTy;
11395 
11396     if (PTy->getKind() == BuiltinType::BoundMember) {
11397       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11398         << OrigOp.get()->getSourceRange();
11399       return QualType();
11400     }
11401 
11402     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11403     if (OrigOp.isInvalid()) return QualType();
11404   }
11405 
11406   if (OrigOp.get()->isTypeDependent())
11407     return Context.DependentTy;
11408 
11409   assert(!OrigOp.get()->getType()->isPlaceholderType());
11410 
11411   // Make sure to ignore parentheses in subsequent checks
11412   Expr *op = OrigOp.get()->IgnoreParens();
11413 
11414   // In OpenCL captures for blocks called as lambda functions
11415   // are located in the private address space. Blocks used in
11416   // enqueue_kernel can be located in a different address space
11417   // depending on a vendor implementation. Thus preventing
11418   // taking an address of the capture to avoid invalid AS casts.
11419   if (LangOpts.OpenCL) {
11420     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11421     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11422       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11423       return QualType();
11424     }
11425   }
11426 
11427   if (getLangOpts().C99) {
11428     // Implement C99-only parts of addressof rules.
11429     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11430       if (uOp->getOpcode() == UO_Deref)
11431         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11432         // (assuming the deref expression is valid).
11433         return uOp->getSubExpr()->getType();
11434     }
11435     // Technically, there should be a check for array subscript
11436     // expressions here, but the result of one is always an lvalue anyway.
11437   }
11438   ValueDecl *dcl = getPrimaryDecl(op);
11439 
11440   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11441     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11442                                            op->getLocStart()))
11443       return QualType();
11444 
11445   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11446   unsigned AddressOfError = AO_No_Error;
11447 
11448   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11449     bool sfinae = (bool)isSFINAEContext();
11450     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11451                                   : diag::ext_typecheck_addrof_temporary)
11452       << op->getType() << op->getSourceRange();
11453     if (sfinae)
11454       return QualType();
11455     // Materialize the temporary as an lvalue so that we can take its address.
11456     OrigOp = op =
11457         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11458   } else if (isa<ObjCSelectorExpr>(op)) {
11459     return Context.getPointerType(op->getType());
11460   } else if (lval == Expr::LV_MemberFunction) {
11461     // If it's an instance method, make a member pointer.
11462     // The expression must have exactly the form &A::foo.
11463 
11464     // If the underlying expression isn't a decl ref, give up.
11465     if (!isa<DeclRefExpr>(op)) {
11466       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11467         << OrigOp.get()->getSourceRange();
11468       return QualType();
11469     }
11470     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11471     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11472 
11473     // The id-expression was parenthesized.
11474     if (OrigOp.get() != DRE) {
11475       Diag(OpLoc, diag::err_parens_pointer_member_function)
11476         << OrigOp.get()->getSourceRange();
11477 
11478     // The method was named without a qualifier.
11479     } else if (!DRE->getQualifier()) {
11480       if (MD->getParent()->getName().empty())
11481         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11482           << op->getSourceRange();
11483       else {
11484         SmallString<32> Str;
11485         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11486         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11487           << op->getSourceRange()
11488           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11489       }
11490     }
11491 
11492     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11493     if (isa<CXXDestructorDecl>(MD))
11494       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11495 
11496     QualType MPTy = Context.getMemberPointerType(
11497         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11498     // Under the MS ABI, lock down the inheritance model now.
11499     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11500       (void)isCompleteType(OpLoc, MPTy);
11501     return MPTy;
11502   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11503     // C99 6.5.3.2p1
11504     // The operand must be either an l-value or a function designator
11505     if (!op->getType()->isFunctionType()) {
11506       // Use a special diagnostic for loads from property references.
11507       if (isa<PseudoObjectExpr>(op)) {
11508         AddressOfError = AO_Property_Expansion;
11509       } else {
11510         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11511           << op->getType() << op->getSourceRange();
11512         return QualType();
11513       }
11514     }
11515   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11516     // The operand cannot be a bit-field
11517     AddressOfError = AO_Bit_Field;
11518   } else if (op->getObjectKind() == OK_VectorComponent) {
11519     // The operand cannot be an element of a vector
11520     AddressOfError = AO_Vector_Element;
11521   } else if (dcl) { // C99 6.5.3.2p1
11522     // We have an lvalue with a decl. Make sure the decl is not declared
11523     // with the register storage-class specifier.
11524     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11525       // in C++ it is not error to take address of a register
11526       // variable (c++03 7.1.1P3)
11527       if (vd->getStorageClass() == SC_Register &&
11528           !getLangOpts().CPlusPlus) {
11529         AddressOfError = AO_Register_Variable;
11530       }
11531     } else if (isa<MSPropertyDecl>(dcl)) {
11532       AddressOfError = AO_Property_Expansion;
11533     } else if (isa<FunctionTemplateDecl>(dcl)) {
11534       return Context.OverloadTy;
11535     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11536       // Okay: we can take the address of a field.
11537       // Could be a pointer to member, though, if there is an explicit
11538       // scope qualifier for the class.
11539       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11540         DeclContext *Ctx = dcl->getDeclContext();
11541         if (Ctx && Ctx->isRecord()) {
11542           if (dcl->getType()->isReferenceType()) {
11543             Diag(OpLoc,
11544                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11545               << dcl->getDeclName() << dcl->getType();
11546             return QualType();
11547           }
11548 
11549           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11550             Ctx = Ctx->getParent();
11551 
11552           QualType MPTy = Context.getMemberPointerType(
11553               op->getType(),
11554               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11555           // Under the MS ABI, lock down the inheritance model now.
11556           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11557             (void)isCompleteType(OpLoc, MPTy);
11558           return MPTy;
11559         }
11560       }
11561     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11562                !isa<BindingDecl>(dcl))
11563       llvm_unreachable("Unknown/unexpected decl type");
11564   }
11565 
11566   if (AddressOfError != AO_No_Error) {
11567     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11568     return QualType();
11569   }
11570 
11571   if (lval == Expr::LV_IncompleteVoidType) {
11572     // Taking the address of a void variable is technically illegal, but we
11573     // allow it in cases which are otherwise valid.
11574     // Example: "extern void x; void* y = &x;".
11575     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11576   }
11577 
11578   // If the operand has type "type", the result has type "pointer to type".
11579   if (op->getType()->isObjCObjectType())
11580     return Context.getObjCObjectPointerType(op->getType());
11581 
11582   CheckAddressOfPackedMember(op);
11583 
11584   return Context.getPointerType(op->getType());
11585 }
11586 
11587 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11588   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11589   if (!DRE)
11590     return;
11591   const Decl *D = DRE->getDecl();
11592   if (!D)
11593     return;
11594   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11595   if (!Param)
11596     return;
11597   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11598     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11599       return;
11600   if (FunctionScopeInfo *FD = S.getCurFunction())
11601     if (!FD->ModifiedNonNullParams.count(Param))
11602       FD->ModifiedNonNullParams.insert(Param);
11603 }
11604 
11605 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11606 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11607                                         SourceLocation OpLoc) {
11608   if (Op->isTypeDependent())
11609     return S.Context.DependentTy;
11610 
11611   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11612   if (ConvResult.isInvalid())
11613     return QualType();
11614   Op = ConvResult.get();
11615   QualType OpTy = Op->getType();
11616   QualType Result;
11617 
11618   if (isa<CXXReinterpretCastExpr>(Op)) {
11619     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11620     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11621                                      Op->getSourceRange());
11622   }
11623 
11624   if (const PointerType *PT = OpTy->getAs<PointerType>())
11625   {
11626     Result = PT->getPointeeType();
11627   }
11628   else if (const ObjCObjectPointerType *OPT =
11629              OpTy->getAs<ObjCObjectPointerType>())
11630     Result = OPT->getPointeeType();
11631   else {
11632     ExprResult PR = S.CheckPlaceholderExpr(Op);
11633     if (PR.isInvalid()) return QualType();
11634     if (PR.get() != Op)
11635       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11636   }
11637 
11638   if (Result.isNull()) {
11639     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11640       << OpTy << Op->getSourceRange();
11641     return QualType();
11642   }
11643 
11644   // Note that per both C89 and C99, indirection is always legal, even if Result
11645   // is an incomplete type or void.  It would be possible to warn about
11646   // dereferencing a void pointer, but it's completely well-defined, and such a
11647   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11648   // for pointers to 'void' but is fine for any other pointer type:
11649   //
11650   // C++ [expr.unary.op]p1:
11651   //   [...] the expression to which [the unary * operator] is applied shall
11652   //   be a pointer to an object type, or a pointer to a function type
11653   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11654     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11655       << OpTy << Op->getSourceRange();
11656 
11657   // Dereferences are usually l-values...
11658   VK = VK_LValue;
11659 
11660   // ...except that certain expressions are never l-values in C.
11661   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11662     VK = VK_RValue;
11663 
11664   return Result;
11665 }
11666 
11667 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11668   BinaryOperatorKind Opc;
11669   switch (Kind) {
11670   default: llvm_unreachable("Unknown binop!");
11671   case tok::periodstar:           Opc = BO_PtrMemD; break;
11672   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11673   case tok::star:                 Opc = BO_Mul; break;
11674   case tok::slash:                Opc = BO_Div; break;
11675   case tok::percent:              Opc = BO_Rem; break;
11676   case tok::plus:                 Opc = BO_Add; break;
11677   case tok::minus:                Opc = BO_Sub; break;
11678   case tok::lessless:             Opc = BO_Shl; break;
11679   case tok::greatergreater:       Opc = BO_Shr; break;
11680   case tok::lessequal:            Opc = BO_LE; break;
11681   case tok::less:                 Opc = BO_LT; break;
11682   case tok::greaterequal:         Opc = BO_GE; break;
11683   case tok::greater:              Opc = BO_GT; break;
11684   case tok::exclaimequal:         Opc = BO_NE; break;
11685   case tok::equalequal:           Opc = BO_EQ; break;
11686   case tok::spaceship:            Opc = BO_Cmp; break;
11687   case tok::amp:                  Opc = BO_And; break;
11688   case tok::caret:                Opc = BO_Xor; break;
11689   case tok::pipe:                 Opc = BO_Or; break;
11690   case tok::ampamp:               Opc = BO_LAnd; break;
11691   case tok::pipepipe:             Opc = BO_LOr; break;
11692   case tok::equal:                Opc = BO_Assign; break;
11693   case tok::starequal:            Opc = BO_MulAssign; break;
11694   case tok::slashequal:           Opc = BO_DivAssign; break;
11695   case tok::percentequal:         Opc = BO_RemAssign; break;
11696   case tok::plusequal:            Opc = BO_AddAssign; break;
11697   case tok::minusequal:           Opc = BO_SubAssign; break;
11698   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11699   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11700   case tok::ampequal:             Opc = BO_AndAssign; break;
11701   case tok::caretequal:           Opc = BO_XorAssign; break;
11702   case tok::pipeequal:            Opc = BO_OrAssign; break;
11703   case tok::comma:                Opc = BO_Comma; break;
11704   }
11705   return Opc;
11706 }
11707 
11708 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11709   tok::TokenKind Kind) {
11710   UnaryOperatorKind Opc;
11711   switch (Kind) {
11712   default: llvm_unreachable("Unknown unary op!");
11713   case tok::plusplus:     Opc = UO_PreInc; break;
11714   case tok::minusminus:   Opc = UO_PreDec; break;
11715   case tok::amp:          Opc = UO_AddrOf; break;
11716   case tok::star:         Opc = UO_Deref; break;
11717   case tok::plus:         Opc = UO_Plus; break;
11718   case tok::minus:        Opc = UO_Minus; break;
11719   case tok::tilde:        Opc = UO_Not; break;
11720   case tok::exclaim:      Opc = UO_LNot; break;
11721   case tok::kw___real:    Opc = UO_Real; break;
11722   case tok::kw___imag:    Opc = UO_Imag; break;
11723   case tok::kw___extension__: Opc = UO_Extension; break;
11724   }
11725   return Opc;
11726 }
11727 
11728 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11729 /// This warning suppressed in the event of macro expansions.
11730 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11731                                    SourceLocation OpLoc, bool IsBuiltin) {
11732   if (S.inTemplateInstantiation())
11733     return;
11734   if (S.isUnevaluatedContext())
11735     return;
11736   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11737     return;
11738   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11739   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11740   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11741   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11742   if (!LHSDeclRef || !RHSDeclRef ||
11743       LHSDeclRef->getLocation().isMacroID() ||
11744       RHSDeclRef->getLocation().isMacroID())
11745     return;
11746   const ValueDecl *LHSDecl =
11747     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11748   const ValueDecl *RHSDecl =
11749     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11750   if (LHSDecl != RHSDecl)
11751     return;
11752   if (LHSDecl->getType().isVolatileQualified())
11753     return;
11754   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11755     if (RefTy->getPointeeType().isVolatileQualified())
11756       return;
11757 
11758   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11759                           : diag::warn_self_assignment_overloaded)
11760       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11761       << RHSExpr->getSourceRange();
11762 }
11763 
11764 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11765 /// is usually indicative of introspection within the Objective-C pointer.
11766 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11767                                           SourceLocation OpLoc) {
11768   if (!S.getLangOpts().ObjC1)
11769     return;
11770 
11771   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11772   const Expr *LHS = L.get();
11773   const Expr *RHS = R.get();
11774 
11775   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11776     ObjCPointerExpr = LHS;
11777     OtherExpr = RHS;
11778   }
11779   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11780     ObjCPointerExpr = RHS;
11781     OtherExpr = LHS;
11782   }
11783 
11784   // This warning is deliberately made very specific to reduce false
11785   // positives with logic that uses '&' for hashing.  This logic mainly
11786   // looks for code trying to introspect into tagged pointers, which
11787   // code should generally never do.
11788   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11789     unsigned Diag = diag::warn_objc_pointer_masking;
11790     // Determine if we are introspecting the result of performSelectorXXX.
11791     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11792     // Special case messages to -performSelector and friends, which
11793     // can return non-pointer values boxed in a pointer value.
11794     // Some clients may wish to silence warnings in this subcase.
11795     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11796       Selector S = ME->getSelector();
11797       StringRef SelArg0 = S.getNameForSlot(0);
11798       if (SelArg0.startswith("performSelector"))
11799         Diag = diag::warn_objc_pointer_masking_performSelector;
11800     }
11801 
11802     S.Diag(OpLoc, Diag)
11803       << ObjCPointerExpr->getSourceRange();
11804   }
11805 }
11806 
11807 static NamedDecl *getDeclFromExpr(Expr *E) {
11808   if (!E)
11809     return nullptr;
11810   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11811     return DRE->getDecl();
11812   if (auto *ME = dyn_cast<MemberExpr>(E))
11813     return ME->getMemberDecl();
11814   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11815     return IRE->getDecl();
11816   return nullptr;
11817 }
11818 
11819 // This helper function promotes a binary operator's operands (which are of a
11820 // half vector type) to a vector of floats and then truncates the result to
11821 // a vector of either half or short.
11822 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11823                                       BinaryOperatorKind Opc, QualType ResultTy,
11824                                       ExprValueKind VK, ExprObjectKind OK,
11825                                       bool IsCompAssign, SourceLocation OpLoc,
11826                                       FPOptions FPFeatures) {
11827   auto &Context = S.getASTContext();
11828   assert((isVector(ResultTy, Context.HalfTy) ||
11829           isVector(ResultTy, Context.ShortTy)) &&
11830          "Result must be a vector of half or short");
11831   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11832          isVector(RHS.get()->getType(), Context.HalfTy) &&
11833          "both operands expected to be a half vector");
11834 
11835   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11836   QualType BinOpResTy = RHS.get()->getType();
11837 
11838   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11839   // change BinOpResTy to a vector of ints.
11840   if (isVector(ResultTy, Context.ShortTy))
11841     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11842 
11843   if (IsCompAssign)
11844     return new (Context) CompoundAssignOperator(
11845         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11846         OpLoc, FPFeatures);
11847 
11848   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11849   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11850                                           VK, OK, OpLoc, FPFeatures);
11851   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11852 }
11853 
11854 static std::pair<ExprResult, ExprResult>
11855 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11856                            Expr *RHSExpr) {
11857   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11858   if (!S.getLangOpts().CPlusPlus) {
11859     // C cannot handle TypoExpr nodes on either side of a binop because it
11860     // doesn't handle dependent types properly, so make sure any TypoExprs have
11861     // been dealt with before checking the operands.
11862     LHS = S.CorrectDelayedTyposInExpr(LHS);
11863     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11864       if (Opc != BO_Assign)
11865         return ExprResult(E);
11866       // Avoid correcting the RHS to the same Expr as the LHS.
11867       Decl *D = getDeclFromExpr(E);
11868       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11869     });
11870   }
11871   return std::make_pair(LHS, RHS);
11872 }
11873 
11874 /// Returns true if conversion between vectors of halfs and vectors of floats
11875 /// is needed.
11876 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11877                                      QualType SrcType) {
11878   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11879          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11880          isVector(SrcType, Ctx.HalfTy);
11881 }
11882 
11883 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11884 /// operator @p Opc at location @c TokLoc. This routine only supports
11885 /// built-in operations; ActOnBinOp handles overloaded operators.
11886 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11887                                     BinaryOperatorKind Opc,
11888                                     Expr *LHSExpr, Expr *RHSExpr) {
11889   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11890     // The syntax only allows initializer lists on the RHS of assignment,
11891     // so we don't need to worry about accepting invalid code for
11892     // non-assignment operators.
11893     // C++11 5.17p9:
11894     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11895     //   of x = {} is x = T().
11896     InitializationKind Kind = InitializationKind::CreateDirectList(
11897         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
11898     InitializedEntity Entity =
11899         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11900     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11901     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11902     if (Init.isInvalid())
11903       return Init;
11904     RHSExpr = Init.get();
11905   }
11906 
11907   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11908   QualType ResultTy;     // Result type of the binary operator.
11909   // The following two variables are used for compound assignment operators
11910   QualType CompLHSTy;    // Type of LHS after promotions for computation
11911   QualType CompResultTy; // Type of computation result
11912   ExprValueKind VK = VK_RValue;
11913   ExprObjectKind OK = OK_Ordinary;
11914   bool ConvertHalfVec = false;
11915 
11916   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11917   if (!LHS.isUsable() || !RHS.isUsable())
11918     return ExprError();
11919 
11920   if (getLangOpts().OpenCL) {
11921     QualType LHSTy = LHSExpr->getType();
11922     QualType RHSTy = RHSExpr->getType();
11923     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11924     // the ATOMIC_VAR_INIT macro.
11925     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11926       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11927       if (BO_Assign == Opc)
11928         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11929       else
11930         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11931       return ExprError();
11932     }
11933 
11934     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11935     // only with a builtin functions and therefore should be disallowed here.
11936     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11937         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11938         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11939         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11940       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11941       return ExprError();
11942     }
11943   }
11944 
11945   switch (Opc) {
11946   case BO_Assign:
11947     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11948     if (getLangOpts().CPlusPlus &&
11949         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11950       VK = LHS.get()->getValueKind();
11951       OK = LHS.get()->getObjectKind();
11952     }
11953     if (!ResultTy.isNull()) {
11954       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
11955       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11956     }
11957     RecordModifiableNonNullParam(*this, LHS.get());
11958     break;
11959   case BO_PtrMemD:
11960   case BO_PtrMemI:
11961     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11962                                             Opc == BO_PtrMemI);
11963     break;
11964   case BO_Mul:
11965   case BO_Div:
11966     ConvertHalfVec = true;
11967     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11968                                            Opc == BO_Div);
11969     break;
11970   case BO_Rem:
11971     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11972     break;
11973   case BO_Add:
11974     ConvertHalfVec = true;
11975     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11976     break;
11977   case BO_Sub:
11978     ConvertHalfVec = true;
11979     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11980     break;
11981   case BO_Shl:
11982   case BO_Shr:
11983     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11984     break;
11985   case BO_LE:
11986   case BO_LT:
11987   case BO_GE:
11988   case BO_GT:
11989     ConvertHalfVec = true;
11990     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
11991     break;
11992   case BO_EQ:
11993   case BO_NE:
11994     ConvertHalfVec = true;
11995     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
11996     break;
11997   case BO_Cmp:
11998     ConvertHalfVec = true;
11999     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc);
12000     assert(ResultTy.isNull() || ResultTy->getAsCXXRecordDecl());
12001     break;
12002   case BO_And:
12003     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
12004     LLVM_FALLTHROUGH;
12005   case BO_Xor:
12006   case BO_Or:
12007     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12008     break;
12009   case BO_LAnd:
12010   case BO_LOr:
12011     ConvertHalfVec = true;
12012     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
12013     break;
12014   case BO_MulAssign:
12015   case BO_DivAssign:
12016     ConvertHalfVec = true;
12017     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
12018                                                Opc == BO_DivAssign);
12019     CompLHSTy = CompResultTy;
12020     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12021       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12022     break;
12023   case BO_RemAssign:
12024     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
12025     CompLHSTy = CompResultTy;
12026     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12027       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12028     break;
12029   case BO_AddAssign:
12030     ConvertHalfVec = true;
12031     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
12032     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12033       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12034     break;
12035   case BO_SubAssign:
12036     ConvertHalfVec = true;
12037     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
12038     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12039       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12040     break;
12041   case BO_ShlAssign:
12042   case BO_ShrAssign:
12043     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
12044     CompLHSTy = CompResultTy;
12045     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12046       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12047     break;
12048   case BO_AndAssign:
12049   case BO_OrAssign: // fallthrough
12050     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
12051     LLVM_FALLTHROUGH;
12052   case BO_XorAssign:
12053     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
12054     CompLHSTy = CompResultTy;
12055     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
12056       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
12057     break;
12058   case BO_Comma:
12059     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
12060     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
12061       VK = RHS.get()->getValueKind();
12062       OK = RHS.get()->getObjectKind();
12063     }
12064     break;
12065   }
12066   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
12067     return ExprError();
12068 
12069   // Some of the binary operations require promoting operands of half vector to
12070   // float vectors and truncating the result back to half vector. For now, we do
12071   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
12072   // arm64).
12073   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
12074          isVector(LHS.get()->getType(), Context.HalfTy) &&
12075          "both sides are half vectors or neither sides are");
12076   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
12077                                             LHS.get()->getType());
12078 
12079   // Check for array bounds violations for both sides of the BinaryOperator
12080   CheckArrayAccess(LHS.get());
12081   CheckArrayAccess(RHS.get());
12082 
12083   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
12084     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
12085                                                  &Context.Idents.get("object_setClass"),
12086                                                  SourceLocation(), LookupOrdinaryName);
12087     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
12088       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
12089       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
12090       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
12091       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
12092       FixItHint::CreateInsertion(RHSLocEnd, ")");
12093     }
12094     else
12095       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
12096   }
12097   else if (const ObjCIvarRefExpr *OIRE =
12098            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
12099     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
12100 
12101   // Opc is not a compound assignment if CompResultTy is null.
12102   if (CompResultTy.isNull()) {
12103     if (ConvertHalfVec)
12104       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
12105                                  OpLoc, FPFeatures);
12106     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
12107                                         OK, OpLoc, FPFeatures);
12108   }
12109 
12110   // Handle compound assignments.
12111   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
12112       OK_ObjCProperty) {
12113     VK = VK_LValue;
12114     OK = LHS.get()->getObjectKind();
12115   }
12116 
12117   if (ConvertHalfVec)
12118     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
12119                                OpLoc, FPFeatures);
12120 
12121   return new (Context) CompoundAssignOperator(
12122       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
12123       OpLoc, FPFeatures);
12124 }
12125 
12126 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
12127 /// operators are mixed in a way that suggests that the programmer forgot that
12128 /// comparison operators have higher precedence. The most typical example of
12129 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
12130 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
12131                                       SourceLocation OpLoc, Expr *LHSExpr,
12132                                       Expr *RHSExpr) {
12133   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
12134   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
12135 
12136   // Check that one of the sides is a comparison operator and the other isn't.
12137   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
12138   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
12139   if (isLeftComp == isRightComp)
12140     return;
12141 
12142   // Bitwise operations are sometimes used as eager logical ops.
12143   // Don't diagnose this.
12144   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
12145   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
12146   if (isLeftBitwise || isRightBitwise)
12147     return;
12148 
12149   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
12150                                                    OpLoc)
12151                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
12152   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
12153   SourceRange ParensRange = isLeftComp ?
12154       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
12155     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
12156 
12157   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
12158     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
12159   SuggestParentheses(Self, OpLoc,
12160     Self.PDiag(diag::note_precedence_silence) << OpStr,
12161     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
12162   SuggestParentheses(Self, OpLoc,
12163     Self.PDiag(diag::note_precedence_bitwise_first)
12164       << BinaryOperator::getOpcodeStr(Opc),
12165     ParensRange);
12166 }
12167 
12168 /// It accepts a '&&' expr that is inside a '||' one.
12169 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
12170 /// in parentheses.
12171 static void
12172 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
12173                                        BinaryOperator *Bop) {
12174   assert(Bop->getOpcode() == BO_LAnd);
12175   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
12176       << Bop->getSourceRange() << OpLoc;
12177   SuggestParentheses(Self, Bop->getOperatorLoc(),
12178     Self.PDiag(diag::note_precedence_silence)
12179       << Bop->getOpcodeStr(),
12180     Bop->getSourceRange());
12181 }
12182 
12183 /// Returns true if the given expression can be evaluated as a constant
12184 /// 'true'.
12185 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
12186   bool Res;
12187   return !E->isValueDependent() &&
12188          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
12189 }
12190 
12191 /// Returns true if the given expression can be evaluated as a constant
12192 /// 'false'.
12193 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
12194   bool Res;
12195   return !E->isValueDependent() &&
12196          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
12197 }
12198 
12199 /// Look for '&&' in the left hand of a '||' expr.
12200 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
12201                                              Expr *LHSExpr, Expr *RHSExpr) {
12202   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
12203     if (Bop->getOpcode() == BO_LAnd) {
12204       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
12205       if (EvaluatesAsFalse(S, RHSExpr))
12206         return;
12207       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
12208       if (!EvaluatesAsTrue(S, Bop->getLHS()))
12209         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12210     } else if (Bop->getOpcode() == BO_LOr) {
12211       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
12212         // If it's "a || b && 1 || c" we didn't warn earlier for
12213         // "a || b && 1", but warn now.
12214         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
12215           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
12216       }
12217     }
12218   }
12219 }
12220 
12221 /// Look for '&&' in the right hand of a '||' expr.
12222 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
12223                                              Expr *LHSExpr, Expr *RHSExpr) {
12224   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
12225     if (Bop->getOpcode() == BO_LAnd) {
12226       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
12227       if (EvaluatesAsFalse(S, LHSExpr))
12228         return;
12229       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12230       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12231         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12232     }
12233   }
12234 }
12235 
12236 /// Look for bitwise op in the left or right hand of a bitwise op with
12237 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12238 /// the '&' expression in parentheses.
12239 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12240                                          SourceLocation OpLoc, Expr *SubExpr) {
12241   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12242     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12243       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12244         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12245         << Bop->getSourceRange() << OpLoc;
12246       SuggestParentheses(S, Bop->getOperatorLoc(),
12247         S.PDiag(diag::note_precedence_silence)
12248           << Bop->getOpcodeStr(),
12249         Bop->getSourceRange());
12250     }
12251   }
12252 }
12253 
12254 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12255                                     Expr *SubExpr, StringRef Shift) {
12256   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12257     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12258       StringRef Op = Bop->getOpcodeStr();
12259       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12260           << Bop->getSourceRange() << OpLoc << Shift << Op;
12261       SuggestParentheses(S, Bop->getOperatorLoc(),
12262           S.PDiag(diag::note_precedence_silence) << Op,
12263           Bop->getSourceRange());
12264     }
12265   }
12266 }
12267 
12268 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12269                                  Expr *LHSExpr, Expr *RHSExpr) {
12270   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12271   if (!OCE)
12272     return;
12273 
12274   FunctionDecl *FD = OCE->getDirectCallee();
12275   if (!FD || !FD->isOverloadedOperator())
12276     return;
12277 
12278   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12279   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12280     return;
12281 
12282   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12283       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12284       << (Kind == OO_LessLess);
12285   SuggestParentheses(S, OCE->getOperatorLoc(),
12286                      S.PDiag(diag::note_precedence_silence)
12287                          << (Kind == OO_LessLess ? "<<" : ">>"),
12288                      OCE->getSourceRange());
12289   SuggestParentheses(S, OpLoc,
12290                      S.PDiag(diag::note_evaluate_comparison_first),
12291                      SourceRange(OCE->getArg(1)->getLocStart(),
12292                                  RHSExpr->getLocEnd()));
12293 }
12294 
12295 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12296 /// precedence.
12297 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12298                                     SourceLocation OpLoc, Expr *LHSExpr,
12299                                     Expr *RHSExpr){
12300   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12301   if (BinaryOperator::isBitwiseOp(Opc))
12302     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12303 
12304   // Diagnose "arg1 & arg2 | arg3"
12305   if ((Opc == BO_Or || Opc == BO_Xor) &&
12306       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12307     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12308     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12309   }
12310 
12311   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12312   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12313   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12314     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12315     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12316   }
12317 
12318   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12319       || Opc == BO_Shr) {
12320     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12321     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12322     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12323   }
12324 
12325   // Warn on overloaded shift operators and comparisons, such as:
12326   // cout << 5 == 4;
12327   if (BinaryOperator::isComparisonOp(Opc))
12328     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12329 }
12330 
12331 // Binary Operators.  'Tok' is the token for the operator.
12332 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12333                             tok::TokenKind Kind,
12334                             Expr *LHSExpr, Expr *RHSExpr) {
12335   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12336   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12337   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12338 
12339   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12340   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12341 
12342   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12343 }
12344 
12345 /// Build an overloaded binary operator expression in the given scope.
12346 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12347                                        BinaryOperatorKind Opc,
12348                                        Expr *LHS, Expr *RHS) {
12349   switch (Opc) {
12350   case BO_Assign:
12351   case BO_DivAssign:
12352   case BO_RemAssign:
12353   case BO_SubAssign:
12354   case BO_AndAssign:
12355   case BO_OrAssign:
12356   case BO_XorAssign:
12357     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12358     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12359     break;
12360   default:
12361     break;
12362   }
12363 
12364   // Find all of the overloaded operators visible from this
12365   // point. We perform both an operator-name lookup from the local
12366   // scope and an argument-dependent lookup based on the types of
12367   // the arguments.
12368   UnresolvedSet<16> Functions;
12369   OverloadedOperatorKind OverOp
12370     = BinaryOperator::getOverloadedOperator(Opc);
12371   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12372     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12373                                    RHS->getType(), Functions);
12374 
12375   // Build the (potentially-overloaded, potentially-dependent)
12376   // binary operation.
12377   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12378 }
12379 
12380 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12381                             BinaryOperatorKind Opc,
12382                             Expr *LHSExpr, Expr *RHSExpr) {
12383   ExprResult LHS, RHS;
12384   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12385   if (!LHS.isUsable() || !RHS.isUsable())
12386     return ExprError();
12387   LHSExpr = LHS.get();
12388   RHSExpr = RHS.get();
12389 
12390   // We want to end up calling one of checkPseudoObjectAssignment
12391   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12392   // both expressions are overloadable or either is type-dependent),
12393   // or CreateBuiltinBinOp (in any other case).  We also want to get
12394   // any placeholder types out of the way.
12395 
12396   // Handle pseudo-objects in the LHS.
12397   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12398     // Assignments with a pseudo-object l-value need special analysis.
12399     if (pty->getKind() == BuiltinType::PseudoObject &&
12400         BinaryOperator::isAssignmentOp(Opc))
12401       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12402 
12403     // Don't resolve overloads if the other type is overloadable.
12404     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12405       // We can't actually test that if we still have a placeholder,
12406       // though.  Fortunately, none of the exceptions we see in that
12407       // code below are valid when the LHS is an overload set.  Note
12408       // that an overload set can be dependently-typed, but it never
12409       // instantiates to having an overloadable type.
12410       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12411       if (resolvedRHS.isInvalid()) return ExprError();
12412       RHSExpr = resolvedRHS.get();
12413 
12414       if (RHSExpr->isTypeDependent() ||
12415           RHSExpr->getType()->isOverloadableType())
12416         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12417     }
12418 
12419     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12420     // template, diagnose the missing 'template' keyword instead of diagnosing
12421     // an invalid use of a bound member function.
12422     //
12423     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12424     // to C++1z [over.over]/1.4, but we already checked for that case above.
12425     if (Opc == BO_LT && inTemplateInstantiation() &&
12426         (pty->getKind() == BuiltinType::BoundMember ||
12427          pty->getKind() == BuiltinType::Overload)) {
12428       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12429       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12430           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12431             return isa<FunctionTemplateDecl>(ND);
12432           })) {
12433         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12434                                 : OE->getNameLoc(),
12435              diag::err_template_kw_missing)
12436           << OE->getName().getAsString() << "";
12437         return ExprError();
12438       }
12439     }
12440 
12441     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12442     if (LHS.isInvalid()) return ExprError();
12443     LHSExpr = LHS.get();
12444   }
12445 
12446   // Handle pseudo-objects in the RHS.
12447   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12448     // An overload in the RHS can potentially be resolved by the type
12449     // being assigned to.
12450     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12451       if (getLangOpts().CPlusPlus &&
12452           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12453            LHSExpr->getType()->isOverloadableType()))
12454         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12455 
12456       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12457     }
12458 
12459     // Don't resolve overloads if the other type is overloadable.
12460     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12461         LHSExpr->getType()->isOverloadableType())
12462       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12463 
12464     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12465     if (!resolvedRHS.isUsable()) return ExprError();
12466     RHSExpr = resolvedRHS.get();
12467   }
12468 
12469   if (getLangOpts().CPlusPlus) {
12470     // If either expression is type-dependent, always build an
12471     // overloaded op.
12472     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12473       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12474 
12475     // Otherwise, build an overloaded op if either expression has an
12476     // overloadable type.
12477     if (LHSExpr->getType()->isOverloadableType() ||
12478         RHSExpr->getType()->isOverloadableType())
12479       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12480   }
12481 
12482   // Build a built-in binary operation.
12483   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12484 }
12485 
12486 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12487   if (T.isNull() || T->isDependentType())
12488     return false;
12489 
12490   if (!T->isPromotableIntegerType())
12491     return true;
12492 
12493   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12494 }
12495 
12496 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12497                                       UnaryOperatorKind Opc,
12498                                       Expr *InputExpr) {
12499   ExprResult Input = InputExpr;
12500   ExprValueKind VK = VK_RValue;
12501   ExprObjectKind OK = OK_Ordinary;
12502   QualType resultType;
12503   bool CanOverflow = false;
12504 
12505   bool ConvertHalfVec = false;
12506   if (getLangOpts().OpenCL) {
12507     QualType Ty = InputExpr->getType();
12508     // The only legal unary operation for atomics is '&'.
12509     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12510     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12511     // only with a builtin functions and therefore should be disallowed here.
12512         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12513         || Ty->isBlockPointerType())) {
12514       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12515                        << InputExpr->getType()
12516                        << Input.get()->getSourceRange());
12517     }
12518   }
12519   switch (Opc) {
12520   case UO_PreInc:
12521   case UO_PreDec:
12522   case UO_PostInc:
12523   case UO_PostDec:
12524     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12525                                                 OpLoc,
12526                                                 Opc == UO_PreInc ||
12527                                                 Opc == UO_PostInc,
12528                                                 Opc == UO_PreInc ||
12529                                                 Opc == UO_PreDec);
12530     CanOverflow = isOverflowingIntegerType(Context, resultType);
12531     break;
12532   case UO_AddrOf:
12533     resultType = CheckAddressOfOperand(Input, OpLoc);
12534     RecordModifiableNonNullParam(*this, InputExpr);
12535     break;
12536   case UO_Deref: {
12537     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12538     if (Input.isInvalid()) return ExprError();
12539     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12540     break;
12541   }
12542   case UO_Plus:
12543   case UO_Minus:
12544     CanOverflow = Opc == UO_Minus &&
12545                   isOverflowingIntegerType(Context, Input.get()->getType());
12546     Input = UsualUnaryConversions(Input.get());
12547     if (Input.isInvalid()) return ExprError();
12548     // Unary plus and minus require promoting an operand of half vector to a
12549     // float vector and truncating the result back to a half vector. For now, we
12550     // do this only when HalfArgsAndReturns is set (that is, when the target is
12551     // arm or arm64).
12552     ConvertHalfVec =
12553         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12554 
12555     // If the operand is a half vector, promote it to a float vector.
12556     if (ConvertHalfVec)
12557       Input = convertVector(Input.get(), Context.FloatTy, *this);
12558     resultType = Input.get()->getType();
12559     if (resultType->isDependentType())
12560       break;
12561     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12562       break;
12563     else if (resultType->isVectorType() &&
12564              // The z vector extensions don't allow + or - with bool vectors.
12565              (!Context.getLangOpts().ZVector ||
12566               resultType->getAs<VectorType>()->getVectorKind() !=
12567               VectorType::AltiVecBool))
12568       break;
12569     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12570              Opc == UO_Plus &&
12571              resultType->isPointerType())
12572       break;
12573 
12574     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12575       << resultType << Input.get()->getSourceRange());
12576 
12577   case UO_Not: // bitwise complement
12578     Input = UsualUnaryConversions(Input.get());
12579     if (Input.isInvalid())
12580       return ExprError();
12581     resultType = Input.get()->getType();
12582 
12583     if (resultType->isDependentType())
12584       break;
12585     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12586     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12587       // C99 does not support '~' for complex conjugation.
12588       Diag(OpLoc, diag::ext_integer_complement_complex)
12589           << resultType << Input.get()->getSourceRange();
12590     else if (resultType->hasIntegerRepresentation())
12591       break;
12592     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12593       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12594       // on vector float types.
12595       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12596       if (!T->isIntegerType())
12597         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12598                           << resultType << Input.get()->getSourceRange());
12599     } else {
12600       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12601                        << resultType << Input.get()->getSourceRange());
12602     }
12603     break;
12604 
12605   case UO_LNot: // logical negation
12606     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12607     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12608     if (Input.isInvalid()) return ExprError();
12609     resultType = Input.get()->getType();
12610 
12611     // Though we still have to promote half FP to float...
12612     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12613       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12614       resultType = Context.FloatTy;
12615     }
12616 
12617     if (resultType->isDependentType())
12618       break;
12619     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12620       // C99 6.5.3.3p1: ok, fallthrough;
12621       if (Context.getLangOpts().CPlusPlus) {
12622         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12623         // operand contextually converted to bool.
12624         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12625                                   ScalarTypeToBooleanCastKind(resultType));
12626       } else if (Context.getLangOpts().OpenCL &&
12627                  Context.getLangOpts().OpenCLVersion < 120) {
12628         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12629         // operate on scalar float types.
12630         if (!resultType->isIntegerType() && !resultType->isPointerType())
12631           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12632                            << resultType << Input.get()->getSourceRange());
12633       }
12634     } else if (resultType->isExtVectorType()) {
12635       if (Context.getLangOpts().OpenCL &&
12636           Context.getLangOpts().OpenCLVersion < 120) {
12637         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12638         // operate on vector float types.
12639         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12640         if (!T->isIntegerType())
12641           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12642                            << resultType << Input.get()->getSourceRange());
12643       }
12644       // Vector logical not returns the signed variant of the operand type.
12645       resultType = GetSignedVectorType(resultType);
12646       break;
12647     } else {
12648       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12649       //        type in C++. We should allow that here too.
12650       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12651         << resultType << Input.get()->getSourceRange());
12652     }
12653 
12654     // LNot always has type int. C99 6.5.3.3p5.
12655     // In C++, it's bool. C++ 5.3.1p8
12656     resultType = Context.getLogicalOperationType();
12657     break;
12658   case UO_Real:
12659   case UO_Imag:
12660     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12661     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12662     // complex l-values to ordinary l-values and all other values to r-values.
12663     if (Input.isInvalid()) return ExprError();
12664     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12665       if (Input.get()->getValueKind() != VK_RValue &&
12666           Input.get()->getObjectKind() == OK_Ordinary)
12667         VK = Input.get()->getValueKind();
12668     } else if (!getLangOpts().CPlusPlus) {
12669       // In C, a volatile scalar is read by __imag. In C++, it is not.
12670       Input = DefaultLvalueConversion(Input.get());
12671     }
12672     break;
12673   case UO_Extension:
12674     resultType = Input.get()->getType();
12675     VK = Input.get()->getValueKind();
12676     OK = Input.get()->getObjectKind();
12677     break;
12678   case UO_Coawait:
12679     // It's unnecessary to represent the pass-through operator co_await in the
12680     // AST; just return the input expression instead.
12681     assert(!Input.get()->getType()->isDependentType() &&
12682                    "the co_await expression must be non-dependant before "
12683                    "building operator co_await");
12684     return Input;
12685   }
12686   if (resultType.isNull() || Input.isInvalid())
12687     return ExprError();
12688 
12689   // Check for array bounds violations in the operand of the UnaryOperator,
12690   // except for the '*' and '&' operators that have to be handled specially
12691   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12692   // that are explicitly defined as valid by the standard).
12693   if (Opc != UO_AddrOf && Opc != UO_Deref)
12694     CheckArrayAccess(Input.get());
12695 
12696   auto *UO = new (Context)
12697       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12698   // Convert the result back to a half vector.
12699   if (ConvertHalfVec)
12700     return convertVector(UO, Context.HalfTy, *this);
12701   return UO;
12702 }
12703 
12704 /// Determine whether the given expression is a qualified member
12705 /// access expression, of a form that could be turned into a pointer to member
12706 /// with the address-of operator.
12707 static bool isQualifiedMemberAccess(Expr *E) {
12708   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12709     if (!DRE->getQualifier())
12710       return false;
12711 
12712     ValueDecl *VD = DRE->getDecl();
12713     if (!VD->isCXXClassMember())
12714       return false;
12715 
12716     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12717       return true;
12718     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12719       return Method->isInstance();
12720 
12721     return false;
12722   }
12723 
12724   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12725     if (!ULE->getQualifier())
12726       return false;
12727 
12728     for (NamedDecl *D : ULE->decls()) {
12729       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12730         if (Method->isInstance())
12731           return true;
12732       } else {
12733         // Overload set does not contain methods.
12734         break;
12735       }
12736     }
12737 
12738     return false;
12739   }
12740 
12741   return false;
12742 }
12743 
12744 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12745                               UnaryOperatorKind Opc, Expr *Input) {
12746   // First things first: handle placeholders so that the
12747   // overloaded-operator check considers the right type.
12748   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12749     // Increment and decrement of pseudo-object references.
12750     if (pty->getKind() == BuiltinType::PseudoObject &&
12751         UnaryOperator::isIncrementDecrementOp(Opc))
12752       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12753 
12754     // extension is always a builtin operator.
12755     if (Opc == UO_Extension)
12756       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12757 
12758     // & gets special logic for several kinds of placeholder.
12759     // The builtin code knows what to do.
12760     if (Opc == UO_AddrOf &&
12761         (pty->getKind() == BuiltinType::Overload ||
12762          pty->getKind() == BuiltinType::UnknownAny ||
12763          pty->getKind() == BuiltinType::BoundMember))
12764       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12765 
12766     // Anything else needs to be handled now.
12767     ExprResult Result = CheckPlaceholderExpr(Input);
12768     if (Result.isInvalid()) return ExprError();
12769     Input = Result.get();
12770   }
12771 
12772   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12773       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12774       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12775     // Find all of the overloaded operators visible from this
12776     // point. We perform both an operator-name lookup from the local
12777     // scope and an argument-dependent lookup based on the types of
12778     // the arguments.
12779     UnresolvedSet<16> Functions;
12780     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12781     if (S && OverOp != OO_None)
12782       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12783                                    Functions);
12784 
12785     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12786   }
12787 
12788   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12789 }
12790 
12791 // Unary Operators.  'Tok' is the token for the operator.
12792 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12793                               tok::TokenKind Op, Expr *Input) {
12794   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12795 }
12796 
12797 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12798 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12799                                 LabelDecl *TheDecl) {
12800   TheDecl->markUsed(Context);
12801   // Create the AST node.  The address of a label always has type 'void*'.
12802   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12803                                      Context.getPointerType(Context.VoidTy));
12804 }
12805 
12806 /// Given the last statement in a statement-expression, check whether
12807 /// the result is a producing expression (like a call to an
12808 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12809 /// release out of the full-expression.  Otherwise, return null.
12810 /// Cannot fail.
12811 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12812   // Should always be wrapped with one of these.
12813   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12814   if (!cleanups) return nullptr;
12815 
12816   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12817   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12818     return nullptr;
12819 
12820   // Splice out the cast.  This shouldn't modify any interesting
12821   // features of the statement.
12822   Expr *producer = cast->getSubExpr();
12823   assert(producer->getType() == cast->getType());
12824   assert(producer->getValueKind() == cast->getValueKind());
12825   cleanups->setSubExpr(producer);
12826   return cleanups;
12827 }
12828 
12829 void Sema::ActOnStartStmtExpr() {
12830   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12831 }
12832 
12833 void Sema::ActOnStmtExprError() {
12834   // Note that function is also called by TreeTransform when leaving a
12835   // StmtExpr scope without rebuilding anything.
12836 
12837   DiscardCleanupsInEvaluationContext();
12838   PopExpressionEvaluationContext();
12839 }
12840 
12841 ExprResult
12842 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12843                     SourceLocation RPLoc) { // "({..})"
12844   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12845   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12846 
12847   if (hasAnyUnrecoverableErrorsInThisFunction())
12848     DiscardCleanupsInEvaluationContext();
12849   assert(!Cleanup.exprNeedsCleanups() &&
12850          "cleanups within StmtExpr not correctly bound!");
12851   PopExpressionEvaluationContext();
12852 
12853   // FIXME: there are a variety of strange constraints to enforce here, for
12854   // example, it is not possible to goto into a stmt expression apparently.
12855   // More semantic analysis is needed.
12856 
12857   // If there are sub-stmts in the compound stmt, take the type of the last one
12858   // as the type of the stmtexpr.
12859   QualType Ty = Context.VoidTy;
12860   bool StmtExprMayBindToTemp = false;
12861   if (!Compound->body_empty()) {
12862     Stmt *LastStmt = Compound->body_back();
12863     LabelStmt *LastLabelStmt = nullptr;
12864     // If LastStmt is a label, skip down through into the body.
12865     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12866       LastLabelStmt = Label;
12867       LastStmt = Label->getSubStmt();
12868     }
12869 
12870     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12871       // Do function/array conversion on the last expression, but not
12872       // lvalue-to-rvalue.  However, initialize an unqualified type.
12873       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12874       if (LastExpr.isInvalid())
12875         return ExprError();
12876       Ty = LastExpr.get()->getType().getUnqualifiedType();
12877 
12878       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12879         // In ARC, if the final expression ends in a consume, splice
12880         // the consume out and bind it later.  In the alternate case
12881         // (when dealing with a retainable type), the result
12882         // initialization will create a produce.  In both cases the
12883         // result will be +1, and we'll need to balance that out with
12884         // a bind.
12885         if (Expr *rebuiltLastStmt
12886               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12887           LastExpr = rebuiltLastStmt;
12888         } else {
12889           LastExpr = PerformCopyInitialization(
12890                             InitializedEntity::InitializeResult(LPLoc,
12891                                                                 Ty,
12892                                                                 false),
12893                                                    SourceLocation(),
12894                                                LastExpr);
12895         }
12896 
12897         if (LastExpr.isInvalid())
12898           return ExprError();
12899         if (LastExpr.get() != nullptr) {
12900           if (!LastLabelStmt)
12901             Compound->setLastStmt(LastExpr.get());
12902           else
12903             LastLabelStmt->setSubStmt(LastExpr.get());
12904           StmtExprMayBindToTemp = true;
12905         }
12906       }
12907     }
12908   }
12909 
12910   // FIXME: Check that expression type is complete/non-abstract; statement
12911   // expressions are not lvalues.
12912   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12913   if (StmtExprMayBindToTemp)
12914     return MaybeBindToTemporary(ResStmtExpr);
12915   return ResStmtExpr;
12916 }
12917 
12918 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12919                                       TypeSourceInfo *TInfo,
12920                                       ArrayRef<OffsetOfComponent> Components,
12921                                       SourceLocation RParenLoc) {
12922   QualType ArgTy = TInfo->getType();
12923   bool Dependent = ArgTy->isDependentType();
12924   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12925 
12926   // We must have at least one component that refers to the type, and the first
12927   // one is known to be a field designator.  Verify that the ArgTy represents
12928   // a struct/union/class.
12929   if (!Dependent && !ArgTy->isRecordType())
12930     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12931                        << ArgTy << TypeRange);
12932 
12933   // Type must be complete per C99 7.17p3 because a declaring a variable
12934   // with an incomplete type would be ill-formed.
12935   if (!Dependent
12936       && RequireCompleteType(BuiltinLoc, ArgTy,
12937                              diag::err_offsetof_incomplete_type, TypeRange))
12938     return ExprError();
12939 
12940   bool DidWarnAboutNonPOD = false;
12941   QualType CurrentType = ArgTy;
12942   SmallVector<OffsetOfNode, 4> Comps;
12943   SmallVector<Expr*, 4> Exprs;
12944   for (const OffsetOfComponent &OC : Components) {
12945     if (OC.isBrackets) {
12946       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12947       if (!CurrentType->isDependentType()) {
12948         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12949         if(!AT)
12950           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12951                            << CurrentType);
12952         CurrentType = AT->getElementType();
12953       } else
12954         CurrentType = Context.DependentTy;
12955 
12956       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12957       if (IdxRval.isInvalid())
12958         return ExprError();
12959       Expr *Idx = IdxRval.get();
12960 
12961       // The expression must be an integral expression.
12962       // FIXME: An integral constant expression?
12963       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12964           !Idx->getType()->isIntegerType())
12965         return ExprError(Diag(Idx->getLocStart(),
12966                               diag::err_typecheck_subscript_not_integer)
12967                          << Idx->getSourceRange());
12968 
12969       // Record this array index.
12970       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12971       Exprs.push_back(Idx);
12972       continue;
12973     }
12974 
12975     // Offset of a field.
12976     if (CurrentType->isDependentType()) {
12977       // We have the offset of a field, but we can't look into the dependent
12978       // type. Just record the identifier of the field.
12979       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12980       CurrentType = Context.DependentTy;
12981       continue;
12982     }
12983 
12984     // We need to have a complete type to look into.
12985     if (RequireCompleteType(OC.LocStart, CurrentType,
12986                             diag::err_offsetof_incomplete_type))
12987       return ExprError();
12988 
12989     // Look for the designated field.
12990     const RecordType *RC = CurrentType->getAs<RecordType>();
12991     if (!RC)
12992       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12993                        << CurrentType);
12994     RecordDecl *RD = RC->getDecl();
12995 
12996     // C++ [lib.support.types]p5:
12997     //   The macro offsetof accepts a restricted set of type arguments in this
12998     //   International Standard. type shall be a POD structure or a POD union
12999     //   (clause 9).
13000     // C++11 [support.types]p4:
13001     //   If type is not a standard-layout class (Clause 9), the results are
13002     //   undefined.
13003     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
13004       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
13005       unsigned DiagID =
13006         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
13007                             : diag::ext_offsetof_non_pod_type;
13008 
13009       if (!IsSafe && !DidWarnAboutNonPOD &&
13010           DiagRuntimeBehavior(BuiltinLoc, nullptr,
13011                               PDiag(DiagID)
13012                               << SourceRange(Components[0].LocStart, OC.LocEnd)
13013                               << CurrentType))
13014         DidWarnAboutNonPOD = true;
13015     }
13016 
13017     // Look for the field.
13018     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
13019     LookupQualifiedName(R, RD);
13020     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
13021     IndirectFieldDecl *IndirectMemberDecl = nullptr;
13022     if (!MemberDecl) {
13023       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
13024         MemberDecl = IndirectMemberDecl->getAnonField();
13025     }
13026 
13027     if (!MemberDecl)
13028       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
13029                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
13030                                                               OC.LocEnd));
13031 
13032     // C99 7.17p3:
13033     //   (If the specified member is a bit-field, the behavior is undefined.)
13034     //
13035     // We diagnose this as an error.
13036     if (MemberDecl->isBitField()) {
13037       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
13038         << MemberDecl->getDeclName()
13039         << SourceRange(BuiltinLoc, RParenLoc);
13040       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
13041       return ExprError();
13042     }
13043 
13044     RecordDecl *Parent = MemberDecl->getParent();
13045     if (IndirectMemberDecl)
13046       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
13047 
13048     // If the member was found in a base class, introduce OffsetOfNodes for
13049     // the base class indirections.
13050     CXXBasePaths Paths;
13051     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
13052                       Paths)) {
13053       if (Paths.getDetectedVirtual()) {
13054         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
13055           << MemberDecl->getDeclName()
13056           << SourceRange(BuiltinLoc, RParenLoc);
13057         return ExprError();
13058       }
13059 
13060       CXXBasePath &Path = Paths.front();
13061       for (const CXXBasePathElement &B : Path)
13062         Comps.push_back(OffsetOfNode(B.Base));
13063     }
13064 
13065     if (IndirectMemberDecl) {
13066       for (auto *FI : IndirectMemberDecl->chain()) {
13067         assert(isa<FieldDecl>(FI));
13068         Comps.push_back(OffsetOfNode(OC.LocStart,
13069                                      cast<FieldDecl>(FI), OC.LocEnd));
13070       }
13071     } else
13072       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
13073 
13074     CurrentType = MemberDecl->getType().getNonReferenceType();
13075   }
13076 
13077   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
13078                               Comps, Exprs, RParenLoc);
13079 }
13080 
13081 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
13082                                       SourceLocation BuiltinLoc,
13083                                       SourceLocation TypeLoc,
13084                                       ParsedType ParsedArgTy,
13085                                       ArrayRef<OffsetOfComponent> Components,
13086                                       SourceLocation RParenLoc) {
13087 
13088   TypeSourceInfo *ArgTInfo;
13089   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
13090   if (ArgTy.isNull())
13091     return ExprError();
13092 
13093   if (!ArgTInfo)
13094     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
13095 
13096   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
13097 }
13098 
13099 
13100 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
13101                                  Expr *CondExpr,
13102                                  Expr *LHSExpr, Expr *RHSExpr,
13103                                  SourceLocation RPLoc) {
13104   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
13105 
13106   ExprValueKind VK = VK_RValue;
13107   ExprObjectKind OK = OK_Ordinary;
13108   QualType resType;
13109   bool ValueDependent = false;
13110   bool CondIsTrue = false;
13111   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
13112     resType = Context.DependentTy;
13113     ValueDependent = true;
13114   } else {
13115     // The conditional expression is required to be a constant expression.
13116     llvm::APSInt condEval(32);
13117     ExprResult CondICE
13118       = VerifyIntegerConstantExpression(CondExpr, &condEval,
13119           diag::err_typecheck_choose_expr_requires_constant, false);
13120     if (CondICE.isInvalid())
13121       return ExprError();
13122     CondExpr = CondICE.get();
13123     CondIsTrue = condEval.getZExtValue();
13124 
13125     // If the condition is > zero, then the AST type is the same as the LSHExpr.
13126     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
13127 
13128     resType = ActiveExpr->getType();
13129     ValueDependent = ActiveExpr->isValueDependent();
13130     VK = ActiveExpr->getValueKind();
13131     OK = ActiveExpr->getObjectKind();
13132   }
13133 
13134   return new (Context)
13135       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
13136                  CondIsTrue, resType->isDependentType(), ValueDependent);
13137 }
13138 
13139 //===----------------------------------------------------------------------===//
13140 // Clang Extensions.
13141 //===----------------------------------------------------------------------===//
13142 
13143 /// ActOnBlockStart - This callback is invoked when a block literal is started.
13144 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
13145   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
13146 
13147   if (LangOpts.CPlusPlus) {
13148     Decl *ManglingContextDecl;
13149     if (MangleNumberingContext *MCtx =
13150             getCurrentMangleNumberContext(Block->getDeclContext(),
13151                                           ManglingContextDecl)) {
13152       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
13153       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
13154     }
13155   }
13156 
13157   PushBlockScope(CurScope, Block);
13158   CurContext->addDecl(Block);
13159   if (CurScope)
13160     PushDeclContext(CurScope, Block);
13161   else
13162     CurContext = Block;
13163 
13164   getCurBlock()->HasImplicitReturnType = true;
13165 
13166   // Enter a new evaluation context to insulate the block from any
13167   // cleanups from the enclosing full-expression.
13168   PushExpressionEvaluationContext(
13169       ExpressionEvaluationContext::PotentiallyEvaluated);
13170 }
13171 
13172 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
13173                                Scope *CurScope) {
13174   assert(ParamInfo.getIdentifier() == nullptr &&
13175          "block-id should have no identifier!");
13176   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
13177   BlockScopeInfo *CurBlock = getCurBlock();
13178 
13179   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
13180   QualType T = Sig->getType();
13181 
13182   // FIXME: We should allow unexpanded parameter packs here, but that would,
13183   // in turn, make the block expression contain unexpanded parameter packs.
13184   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
13185     // Drop the parameters.
13186     FunctionProtoType::ExtProtoInfo EPI;
13187     EPI.HasTrailingReturn = false;
13188     EPI.TypeQuals |= DeclSpec::TQ_const;
13189     T = Context.getFunctionType(Context.DependentTy, None, EPI);
13190     Sig = Context.getTrivialTypeSourceInfo(T);
13191   }
13192 
13193   // GetTypeForDeclarator always produces a function type for a block
13194   // literal signature.  Furthermore, it is always a FunctionProtoType
13195   // unless the function was written with a typedef.
13196   assert(T->isFunctionType() &&
13197          "GetTypeForDeclarator made a non-function block signature");
13198 
13199   // Look for an explicit signature in that function type.
13200   FunctionProtoTypeLoc ExplicitSignature;
13201 
13202   if ((ExplicitSignature =
13203            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
13204 
13205     // Check whether that explicit signature was synthesized by
13206     // GetTypeForDeclarator.  If so, don't save that as part of the
13207     // written signature.
13208     if (ExplicitSignature.getLocalRangeBegin() ==
13209         ExplicitSignature.getLocalRangeEnd()) {
13210       // This would be much cheaper if we stored TypeLocs instead of
13211       // TypeSourceInfos.
13212       TypeLoc Result = ExplicitSignature.getReturnLoc();
13213       unsigned Size = Result.getFullDataSize();
13214       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
13215       Sig->getTypeLoc().initializeFullCopy(Result, Size);
13216 
13217       ExplicitSignature = FunctionProtoTypeLoc();
13218     }
13219   }
13220 
13221   CurBlock->TheDecl->setSignatureAsWritten(Sig);
13222   CurBlock->FunctionType = T;
13223 
13224   const FunctionType *Fn = T->getAs<FunctionType>();
13225   QualType RetTy = Fn->getReturnType();
13226   bool isVariadic =
13227     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13228 
13229   CurBlock->TheDecl->setIsVariadic(isVariadic);
13230 
13231   // Context.DependentTy is used as a placeholder for a missing block
13232   // return type.  TODO:  what should we do with declarators like:
13233   //   ^ * { ... }
13234   // If the answer is "apply template argument deduction"....
13235   if (RetTy != Context.DependentTy) {
13236     CurBlock->ReturnType = RetTy;
13237     CurBlock->TheDecl->setBlockMissingReturnType(false);
13238     CurBlock->HasImplicitReturnType = false;
13239   }
13240 
13241   // Push block parameters from the declarator if we had them.
13242   SmallVector<ParmVarDecl*, 8> Params;
13243   if (ExplicitSignature) {
13244     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13245       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13246       if (Param->getIdentifier() == nullptr &&
13247           !Param->isImplicit() &&
13248           !Param->isInvalidDecl() &&
13249           !getLangOpts().CPlusPlus)
13250         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13251       Params.push_back(Param);
13252     }
13253 
13254   // Fake up parameter variables if we have a typedef, like
13255   //   ^ fntype { ... }
13256   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13257     for (const auto &I : Fn->param_types()) {
13258       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13259           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13260       Params.push_back(Param);
13261     }
13262   }
13263 
13264   // Set the parameters on the block decl.
13265   if (!Params.empty()) {
13266     CurBlock->TheDecl->setParams(Params);
13267     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13268                              /*CheckParameterNames=*/false);
13269   }
13270 
13271   // Finally we can process decl attributes.
13272   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13273 
13274   // Put the parameter variables in scope.
13275   for (auto AI : CurBlock->TheDecl->parameters()) {
13276     AI->setOwningFunction(CurBlock->TheDecl);
13277 
13278     // If this has an identifier, add it to the scope stack.
13279     if (AI->getIdentifier()) {
13280       CheckShadow(CurBlock->TheScope, AI);
13281 
13282       PushOnScopeChains(AI, CurBlock->TheScope);
13283     }
13284   }
13285 }
13286 
13287 /// ActOnBlockError - If there is an error parsing a block, this callback
13288 /// is invoked to pop the information about the block from the action impl.
13289 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13290   // Leave the expression-evaluation context.
13291   DiscardCleanupsInEvaluationContext();
13292   PopExpressionEvaluationContext();
13293 
13294   // Pop off CurBlock, handle nested blocks.
13295   PopDeclContext();
13296   PopFunctionScopeInfo();
13297 }
13298 
13299 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13300 /// literal was successfully completed.  ^(int x){...}
13301 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13302                                     Stmt *Body, Scope *CurScope) {
13303   // If blocks are disabled, emit an error.
13304   if (!LangOpts.Blocks)
13305     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13306 
13307   // Leave the expression-evaluation context.
13308   if (hasAnyUnrecoverableErrorsInThisFunction())
13309     DiscardCleanupsInEvaluationContext();
13310   assert(!Cleanup.exprNeedsCleanups() &&
13311          "cleanups within block not correctly bound!");
13312   PopExpressionEvaluationContext();
13313 
13314   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13315 
13316   if (BSI->HasImplicitReturnType)
13317     deduceClosureReturnType(*BSI);
13318 
13319   PopDeclContext();
13320 
13321   QualType RetTy = Context.VoidTy;
13322   if (!BSI->ReturnType.isNull())
13323     RetTy = BSI->ReturnType;
13324 
13325   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13326   QualType BlockTy;
13327 
13328   // Set the captured variables on the block.
13329   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13330   SmallVector<BlockDecl::Capture, 4> Captures;
13331   for (Capture &Cap : BSI->Captures) {
13332     if (Cap.isThisCapture())
13333       continue;
13334     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13335                               Cap.isNested(), Cap.getInitExpr());
13336     Captures.push_back(NewCap);
13337   }
13338   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13339 
13340   // If the user wrote a function type in some form, try to use that.
13341   if (!BSI->FunctionType.isNull()) {
13342     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13343 
13344     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13345     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13346 
13347     // Turn protoless block types into nullary block types.
13348     if (isa<FunctionNoProtoType>(FTy)) {
13349       FunctionProtoType::ExtProtoInfo EPI;
13350       EPI.ExtInfo = Ext;
13351       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13352 
13353     // Otherwise, if we don't need to change anything about the function type,
13354     // preserve its sugar structure.
13355     } else if (FTy->getReturnType() == RetTy &&
13356                (!NoReturn || FTy->getNoReturnAttr())) {
13357       BlockTy = BSI->FunctionType;
13358 
13359     // Otherwise, make the minimal modifications to the function type.
13360     } else {
13361       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13362       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13363       EPI.TypeQuals = 0; // FIXME: silently?
13364       EPI.ExtInfo = Ext;
13365       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13366     }
13367 
13368   // If we don't have a function type, just build one from nothing.
13369   } else {
13370     FunctionProtoType::ExtProtoInfo EPI;
13371     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13372     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13373   }
13374 
13375   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13376   BlockTy = Context.getBlockPointerType(BlockTy);
13377 
13378   // If needed, diagnose invalid gotos and switches in the block.
13379   if (getCurFunction()->NeedsScopeChecking() &&
13380       !PP.isCodeCompletionEnabled())
13381     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13382 
13383   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13384 
13385   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13386     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13387 
13388   // Try to apply the named return value optimization. We have to check again
13389   // if we can do this, though, because blocks keep return statements around
13390   // to deduce an implicit return type.
13391   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13392       !BSI->TheDecl->isDependentContext())
13393     computeNRVO(Body, BSI);
13394 
13395   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13396   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13397   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13398 
13399   // If the block isn't obviously global, i.e. it captures anything at
13400   // all, then we need to do a few things in the surrounding context:
13401   if (Result->getBlockDecl()->hasCaptures()) {
13402     // First, this expression has a new cleanup object.
13403     ExprCleanupObjects.push_back(Result->getBlockDecl());
13404     Cleanup.setExprNeedsCleanups(true);
13405 
13406     // It also gets a branch-protected scope if any of the captured
13407     // variables needs destruction.
13408     for (const auto &CI : Result->getBlockDecl()->captures()) {
13409       const VarDecl *var = CI.getVariable();
13410       if (var->getType().isDestructedType() != QualType::DK_none) {
13411         setFunctionHasBranchProtectedScope();
13412         break;
13413       }
13414     }
13415   }
13416 
13417   return Result;
13418 }
13419 
13420 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13421                             SourceLocation RPLoc) {
13422   TypeSourceInfo *TInfo;
13423   GetTypeFromParser(Ty, &TInfo);
13424   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13425 }
13426 
13427 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13428                                 Expr *E, TypeSourceInfo *TInfo,
13429                                 SourceLocation RPLoc) {
13430   Expr *OrigExpr = E;
13431   bool IsMS = false;
13432 
13433   // CUDA device code does not support varargs.
13434   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13435     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13436       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13437       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13438         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13439     }
13440   }
13441 
13442   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13443   // as Microsoft ABI on an actual Microsoft platform, where
13444   // __builtin_ms_va_list and __builtin_va_list are the same.)
13445   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13446       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13447     QualType MSVaListType = Context.getBuiltinMSVaListType();
13448     if (Context.hasSameType(MSVaListType, E->getType())) {
13449       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13450         return ExprError();
13451       IsMS = true;
13452     }
13453   }
13454 
13455   // Get the va_list type
13456   QualType VaListType = Context.getBuiltinVaListType();
13457   if (!IsMS) {
13458     if (VaListType->isArrayType()) {
13459       // Deal with implicit array decay; for example, on x86-64,
13460       // va_list is an array, but it's supposed to decay to
13461       // a pointer for va_arg.
13462       VaListType = Context.getArrayDecayedType(VaListType);
13463       // Make sure the input expression also decays appropriately.
13464       ExprResult Result = UsualUnaryConversions(E);
13465       if (Result.isInvalid())
13466         return ExprError();
13467       E = Result.get();
13468     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13469       // If va_list is a record type and we are compiling in C++ mode,
13470       // check the argument using reference binding.
13471       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13472           Context, Context.getLValueReferenceType(VaListType), false);
13473       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13474       if (Init.isInvalid())
13475         return ExprError();
13476       E = Init.getAs<Expr>();
13477     } else {
13478       // Otherwise, the va_list argument must be an l-value because
13479       // it is modified by va_arg.
13480       if (!E->isTypeDependent() &&
13481           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13482         return ExprError();
13483     }
13484   }
13485 
13486   if (!IsMS && !E->isTypeDependent() &&
13487       !Context.hasSameType(VaListType, E->getType()))
13488     return ExprError(Diag(E->getLocStart(),
13489                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13490       << OrigExpr->getType() << E->getSourceRange());
13491 
13492   if (!TInfo->getType()->isDependentType()) {
13493     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13494                             diag::err_second_parameter_to_va_arg_incomplete,
13495                             TInfo->getTypeLoc()))
13496       return ExprError();
13497 
13498     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13499                                TInfo->getType(),
13500                                diag::err_second_parameter_to_va_arg_abstract,
13501                                TInfo->getTypeLoc()))
13502       return ExprError();
13503 
13504     if (!TInfo->getType().isPODType(Context)) {
13505       Diag(TInfo->getTypeLoc().getBeginLoc(),
13506            TInfo->getType()->isObjCLifetimeType()
13507              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13508              : diag::warn_second_parameter_to_va_arg_not_pod)
13509         << TInfo->getType()
13510         << TInfo->getTypeLoc().getSourceRange();
13511     }
13512 
13513     // Check for va_arg where arguments of the given type will be promoted
13514     // (i.e. this va_arg is guaranteed to have undefined behavior).
13515     QualType PromoteType;
13516     if (TInfo->getType()->isPromotableIntegerType()) {
13517       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13518       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13519         PromoteType = QualType();
13520     }
13521     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13522       PromoteType = Context.DoubleTy;
13523     if (!PromoteType.isNull())
13524       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13525                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13526                           << TInfo->getType()
13527                           << PromoteType
13528                           << TInfo->getTypeLoc().getSourceRange());
13529   }
13530 
13531   QualType T = TInfo->getType().getNonLValueExprType(Context);
13532   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13533 }
13534 
13535 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13536   // The type of __null will be int or long, depending on the size of
13537   // pointers on the target.
13538   QualType Ty;
13539   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13540   if (pw == Context.getTargetInfo().getIntWidth())
13541     Ty = Context.IntTy;
13542   else if (pw == Context.getTargetInfo().getLongWidth())
13543     Ty = Context.LongTy;
13544   else if (pw == Context.getTargetInfo().getLongLongWidth())
13545     Ty = Context.LongLongTy;
13546   else {
13547     llvm_unreachable("I don't know size of pointer!");
13548   }
13549 
13550   return new (Context) GNUNullExpr(Ty, TokenLoc);
13551 }
13552 
13553 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13554                                               bool Diagnose) {
13555   if (!getLangOpts().ObjC1)
13556     return false;
13557 
13558   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13559   if (!PT)
13560     return false;
13561 
13562   if (!PT->isObjCIdType()) {
13563     // Check if the destination is the 'NSString' interface.
13564     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13565     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13566       return false;
13567   }
13568 
13569   // Ignore any parens, implicit casts (should only be
13570   // array-to-pointer decays), and not-so-opaque values.  The last is
13571   // important for making this trigger for property assignments.
13572   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13573   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13574     if (OV->getSourceExpr())
13575       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13576 
13577   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13578   if (!SL || !SL->isAscii())
13579     return false;
13580   if (Diagnose) {
13581     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13582       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13583     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13584   }
13585   return true;
13586 }
13587 
13588 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13589                                               const Expr *SrcExpr) {
13590   if (!DstType->isFunctionPointerType() ||
13591       !SrcExpr->getType()->isFunctionType())
13592     return false;
13593 
13594   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13595   if (!DRE)
13596     return false;
13597 
13598   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13599   if (!FD)
13600     return false;
13601 
13602   return !S.checkAddressOfFunctionIsAvailable(FD,
13603                                               /*Complain=*/true,
13604                                               SrcExpr->getLocStart());
13605 }
13606 
13607 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13608                                     SourceLocation Loc,
13609                                     QualType DstType, QualType SrcType,
13610                                     Expr *SrcExpr, AssignmentAction Action,
13611                                     bool *Complained) {
13612   if (Complained)
13613     *Complained = false;
13614 
13615   // Decode the result (notice that AST's are still created for extensions).
13616   bool CheckInferredResultType = false;
13617   bool isInvalid = false;
13618   unsigned DiagKind = 0;
13619   FixItHint Hint;
13620   ConversionFixItGenerator ConvHints;
13621   bool MayHaveConvFixit = false;
13622   bool MayHaveFunctionDiff = false;
13623   const ObjCInterfaceDecl *IFace = nullptr;
13624   const ObjCProtocolDecl *PDecl = nullptr;
13625 
13626   switch (ConvTy) {
13627   case Compatible:
13628       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13629       return false;
13630 
13631   case PointerToInt:
13632     DiagKind = diag::ext_typecheck_convert_pointer_int;
13633     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13634     MayHaveConvFixit = true;
13635     break;
13636   case IntToPointer:
13637     DiagKind = diag::ext_typecheck_convert_int_pointer;
13638     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13639     MayHaveConvFixit = true;
13640     break;
13641   case IncompatiblePointer:
13642     if (Action == AA_Passing_CFAudited)
13643       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13644     else if (SrcType->isFunctionPointerType() &&
13645              DstType->isFunctionPointerType())
13646       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13647     else
13648       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13649 
13650     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13651       SrcType->isObjCObjectPointerType();
13652     if (Hint.isNull() && !CheckInferredResultType) {
13653       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13654     }
13655     else if (CheckInferredResultType) {
13656       SrcType = SrcType.getUnqualifiedType();
13657       DstType = DstType.getUnqualifiedType();
13658     }
13659     MayHaveConvFixit = true;
13660     break;
13661   case IncompatiblePointerSign:
13662     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13663     break;
13664   case FunctionVoidPointer:
13665     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13666     break;
13667   case IncompatiblePointerDiscardsQualifiers: {
13668     // Perform array-to-pointer decay if necessary.
13669     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13670 
13671     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13672     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13673     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13674       DiagKind = diag::err_typecheck_incompatible_address_space;
13675       break;
13676 
13677     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13678       DiagKind = diag::err_typecheck_incompatible_ownership;
13679       break;
13680     }
13681 
13682     llvm_unreachable("unknown error case for discarding qualifiers!");
13683     // fallthrough
13684   }
13685   case CompatiblePointerDiscardsQualifiers:
13686     // If the qualifiers lost were because we were applying the
13687     // (deprecated) C++ conversion from a string literal to a char*
13688     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13689     // Ideally, this check would be performed in
13690     // checkPointerTypesForAssignment. However, that would require a
13691     // bit of refactoring (so that the second argument is an
13692     // expression, rather than a type), which should be done as part
13693     // of a larger effort to fix checkPointerTypesForAssignment for
13694     // C++ semantics.
13695     if (getLangOpts().CPlusPlus &&
13696         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13697       return false;
13698     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13699     break;
13700   case IncompatibleNestedPointerQualifiers:
13701     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13702     break;
13703   case IntToBlockPointer:
13704     DiagKind = diag::err_int_to_block_pointer;
13705     break;
13706   case IncompatibleBlockPointer:
13707     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13708     break;
13709   case IncompatibleObjCQualifiedId: {
13710     if (SrcType->isObjCQualifiedIdType()) {
13711       const ObjCObjectPointerType *srcOPT =
13712                 SrcType->getAs<ObjCObjectPointerType>();
13713       for (auto *srcProto : srcOPT->quals()) {
13714         PDecl = srcProto;
13715         break;
13716       }
13717       if (const ObjCInterfaceType *IFaceT =
13718             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13719         IFace = IFaceT->getDecl();
13720     }
13721     else if (DstType->isObjCQualifiedIdType()) {
13722       const ObjCObjectPointerType *dstOPT =
13723         DstType->getAs<ObjCObjectPointerType>();
13724       for (auto *dstProto : dstOPT->quals()) {
13725         PDecl = dstProto;
13726         break;
13727       }
13728       if (const ObjCInterfaceType *IFaceT =
13729             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13730         IFace = IFaceT->getDecl();
13731     }
13732     DiagKind = diag::warn_incompatible_qualified_id;
13733     break;
13734   }
13735   case IncompatibleVectors:
13736     DiagKind = diag::warn_incompatible_vectors;
13737     break;
13738   case IncompatibleObjCWeakRef:
13739     DiagKind = diag::err_arc_weak_unavailable_assign;
13740     break;
13741   case Incompatible:
13742     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13743       if (Complained)
13744         *Complained = true;
13745       return true;
13746     }
13747 
13748     DiagKind = diag::err_typecheck_convert_incompatible;
13749     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13750     MayHaveConvFixit = true;
13751     isInvalid = true;
13752     MayHaveFunctionDiff = true;
13753     break;
13754   }
13755 
13756   QualType FirstType, SecondType;
13757   switch (Action) {
13758   case AA_Assigning:
13759   case AA_Initializing:
13760     // The destination type comes first.
13761     FirstType = DstType;
13762     SecondType = SrcType;
13763     break;
13764 
13765   case AA_Returning:
13766   case AA_Passing:
13767   case AA_Passing_CFAudited:
13768   case AA_Converting:
13769   case AA_Sending:
13770   case AA_Casting:
13771     // The source type comes first.
13772     FirstType = SrcType;
13773     SecondType = DstType;
13774     break;
13775   }
13776 
13777   PartialDiagnostic FDiag = PDiag(DiagKind);
13778   if (Action == AA_Passing_CFAudited)
13779     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13780   else
13781     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13782 
13783   // If we can fix the conversion, suggest the FixIts.
13784   assert(ConvHints.isNull() || Hint.isNull());
13785   if (!ConvHints.isNull()) {
13786     for (FixItHint &H : ConvHints.Hints)
13787       FDiag << H;
13788   } else {
13789     FDiag << Hint;
13790   }
13791   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13792 
13793   if (MayHaveFunctionDiff)
13794     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13795 
13796   Diag(Loc, FDiag);
13797   if (DiagKind == diag::warn_incompatible_qualified_id &&
13798       PDecl && IFace && !IFace->hasDefinition())
13799       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13800         << IFace << PDecl;
13801 
13802   if (SecondType == Context.OverloadTy)
13803     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13804                               FirstType, /*TakingAddress=*/true);
13805 
13806   if (CheckInferredResultType)
13807     EmitRelatedResultTypeNote(SrcExpr);
13808 
13809   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13810     EmitRelatedResultTypeNoteForReturn(DstType);
13811 
13812   if (Complained)
13813     *Complained = true;
13814   return isInvalid;
13815 }
13816 
13817 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13818                                                  llvm::APSInt *Result) {
13819   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13820   public:
13821     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13822       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13823     }
13824   } Diagnoser;
13825 
13826   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13827 }
13828 
13829 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13830                                                  llvm::APSInt *Result,
13831                                                  unsigned DiagID,
13832                                                  bool AllowFold) {
13833   class IDDiagnoser : public VerifyICEDiagnoser {
13834     unsigned DiagID;
13835 
13836   public:
13837     IDDiagnoser(unsigned DiagID)
13838       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13839 
13840     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13841       S.Diag(Loc, DiagID) << SR;
13842     }
13843   } Diagnoser(DiagID);
13844 
13845   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13846 }
13847 
13848 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13849                                             SourceRange SR) {
13850   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13851 }
13852 
13853 ExprResult
13854 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13855                                       VerifyICEDiagnoser &Diagnoser,
13856                                       bool AllowFold) {
13857   SourceLocation DiagLoc = E->getLocStart();
13858 
13859   if (getLangOpts().CPlusPlus11) {
13860     // C++11 [expr.const]p5:
13861     //   If an expression of literal class type is used in a context where an
13862     //   integral constant expression is required, then that class type shall
13863     //   have a single non-explicit conversion function to an integral or
13864     //   unscoped enumeration type
13865     ExprResult Converted;
13866     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13867     public:
13868       CXX11ConvertDiagnoser(bool Silent)
13869           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13870                                 Silent, true) {}
13871 
13872       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13873                                            QualType T) override {
13874         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13875       }
13876 
13877       SemaDiagnosticBuilder diagnoseIncomplete(
13878           Sema &S, SourceLocation Loc, QualType T) override {
13879         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13880       }
13881 
13882       SemaDiagnosticBuilder diagnoseExplicitConv(
13883           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13884         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13885       }
13886 
13887       SemaDiagnosticBuilder noteExplicitConv(
13888           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13889         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13890                  << ConvTy->isEnumeralType() << ConvTy;
13891       }
13892 
13893       SemaDiagnosticBuilder diagnoseAmbiguous(
13894           Sema &S, SourceLocation Loc, QualType T) override {
13895         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13896       }
13897 
13898       SemaDiagnosticBuilder noteAmbiguous(
13899           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13900         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13901                  << ConvTy->isEnumeralType() << ConvTy;
13902       }
13903 
13904       SemaDiagnosticBuilder diagnoseConversion(
13905           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13906         llvm_unreachable("conversion functions are permitted");
13907       }
13908     } ConvertDiagnoser(Diagnoser.Suppress);
13909 
13910     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13911                                                     ConvertDiagnoser);
13912     if (Converted.isInvalid())
13913       return Converted;
13914     E = Converted.get();
13915     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13916       return ExprError();
13917   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13918     // An ICE must be of integral or unscoped enumeration type.
13919     if (!Diagnoser.Suppress)
13920       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13921     return ExprError();
13922   }
13923 
13924   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13925   // in the non-ICE case.
13926   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13927     if (Result)
13928       *Result = E->EvaluateKnownConstInt(Context);
13929     return E;
13930   }
13931 
13932   Expr::EvalResult EvalResult;
13933   SmallVector<PartialDiagnosticAt, 8> Notes;
13934   EvalResult.Diag = &Notes;
13935 
13936   // Try to evaluate the expression, and produce diagnostics explaining why it's
13937   // not a constant expression as a side-effect.
13938   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13939                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13940 
13941   // In C++11, we can rely on diagnostics being produced for any expression
13942   // which is not a constant expression. If no diagnostics were produced, then
13943   // this is a constant expression.
13944   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13945     if (Result)
13946       *Result = EvalResult.Val.getInt();
13947     return E;
13948   }
13949 
13950   // If our only note is the usual "invalid subexpression" note, just point
13951   // the caret at its location rather than producing an essentially
13952   // redundant note.
13953   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13954         diag::note_invalid_subexpr_in_const_expr) {
13955     DiagLoc = Notes[0].first;
13956     Notes.clear();
13957   }
13958 
13959   if (!Folded || !AllowFold) {
13960     if (!Diagnoser.Suppress) {
13961       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13962       for (const PartialDiagnosticAt &Note : Notes)
13963         Diag(Note.first, Note.second);
13964     }
13965 
13966     return ExprError();
13967   }
13968 
13969   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13970   for (const PartialDiagnosticAt &Note : Notes)
13971     Diag(Note.first, Note.second);
13972 
13973   if (Result)
13974     *Result = EvalResult.Val.getInt();
13975   return E;
13976 }
13977 
13978 namespace {
13979   // Handle the case where we conclude a expression which we speculatively
13980   // considered to be unevaluated is actually evaluated.
13981   class TransformToPE : public TreeTransform<TransformToPE> {
13982     typedef TreeTransform<TransformToPE> BaseTransform;
13983 
13984   public:
13985     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13986 
13987     // Make sure we redo semantic analysis
13988     bool AlwaysRebuild() { return true; }
13989 
13990     // Make sure we handle LabelStmts correctly.
13991     // FIXME: This does the right thing, but maybe we need a more general
13992     // fix to TreeTransform?
13993     StmtResult TransformLabelStmt(LabelStmt *S) {
13994       S->getDecl()->setStmt(nullptr);
13995       return BaseTransform::TransformLabelStmt(S);
13996     }
13997 
13998     // We need to special-case DeclRefExprs referring to FieldDecls which
13999     // are not part of a member pointer formation; normal TreeTransforming
14000     // doesn't catch this case because of the way we represent them in the AST.
14001     // FIXME: This is a bit ugly; is it really the best way to handle this
14002     // case?
14003     //
14004     // Error on DeclRefExprs referring to FieldDecls.
14005     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
14006       if (isa<FieldDecl>(E->getDecl()) &&
14007           !SemaRef.isUnevaluatedContext())
14008         return SemaRef.Diag(E->getLocation(),
14009                             diag::err_invalid_non_static_member_use)
14010             << E->getDecl() << E->getSourceRange();
14011 
14012       return BaseTransform::TransformDeclRefExpr(E);
14013     }
14014 
14015     // Exception: filter out member pointer formation
14016     ExprResult TransformUnaryOperator(UnaryOperator *E) {
14017       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
14018         return E;
14019 
14020       return BaseTransform::TransformUnaryOperator(E);
14021     }
14022 
14023     ExprResult TransformLambdaExpr(LambdaExpr *E) {
14024       // Lambdas never need to be transformed.
14025       return E;
14026     }
14027   };
14028 }
14029 
14030 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
14031   assert(isUnevaluatedContext() &&
14032          "Should only transform unevaluated expressions");
14033   ExprEvalContexts.back().Context =
14034       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
14035   if (isUnevaluatedContext())
14036     return E;
14037   return TransformToPE(*this).TransformExpr(E);
14038 }
14039 
14040 void
14041 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
14042                                       Decl *LambdaContextDecl,
14043                                       bool IsDecltype) {
14044   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
14045                                 LambdaContextDecl, IsDecltype);
14046   Cleanup.reset();
14047   if (!MaybeODRUseExprs.empty())
14048     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
14049 }
14050 
14051 void
14052 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
14053                                       ReuseLambdaContextDecl_t,
14054                                       bool IsDecltype) {
14055   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
14056   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
14057 }
14058 
14059 void Sema::PopExpressionEvaluationContext() {
14060   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
14061   unsigned NumTypos = Rec.NumTypos;
14062 
14063   if (!Rec.Lambdas.empty()) {
14064     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14065       unsigned D;
14066       if (Rec.isUnevaluated()) {
14067         // C++11 [expr.prim.lambda]p2:
14068         //   A lambda-expression shall not appear in an unevaluated operand
14069         //   (Clause 5).
14070         D = diag::err_lambda_unevaluated_operand;
14071       } else {
14072         // C++1y [expr.const]p2:
14073         //   A conditional-expression e is a core constant expression unless the
14074         //   evaluation of e, following the rules of the abstract machine, would
14075         //   evaluate [...] a lambda-expression.
14076         D = diag::err_lambda_in_constant_expression;
14077       }
14078 
14079       // C++1z allows lambda expressions as core constant expressions.
14080       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
14081       // 1607) from appearing within template-arguments and array-bounds that
14082       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
14083       // unevaluated contexts) might lift some of these restrictions in a
14084       // future version.
14085       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
14086         for (const auto *L : Rec.Lambdas)
14087           Diag(L->getLocStart(), D);
14088     } else {
14089       // Mark the capture expressions odr-used. This was deferred
14090       // during lambda expression creation.
14091       for (auto *Lambda : Rec.Lambdas) {
14092         for (auto *C : Lambda->capture_inits())
14093           MarkDeclarationsReferencedInExpr(C);
14094       }
14095     }
14096   }
14097 
14098   // When are coming out of an unevaluated context, clear out any
14099   // temporaries that we may have created as part of the evaluation of
14100   // the expression in that context: they aren't relevant because they
14101   // will never be constructed.
14102   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
14103     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
14104                              ExprCleanupObjects.end());
14105     Cleanup = Rec.ParentCleanup;
14106     CleanupVarDeclMarking();
14107     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
14108   // Otherwise, merge the contexts together.
14109   } else {
14110     Cleanup.mergeFrom(Rec.ParentCleanup);
14111     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
14112                             Rec.SavedMaybeODRUseExprs.end());
14113   }
14114 
14115   // Pop the current expression evaluation context off the stack.
14116   ExprEvalContexts.pop_back();
14117 
14118   if (!ExprEvalContexts.empty())
14119     ExprEvalContexts.back().NumTypos += NumTypos;
14120   else
14121     assert(NumTypos == 0 && "There are outstanding typos after popping the "
14122                             "last ExpressionEvaluationContextRecord");
14123 }
14124 
14125 void Sema::DiscardCleanupsInEvaluationContext() {
14126   ExprCleanupObjects.erase(
14127          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
14128          ExprCleanupObjects.end());
14129   Cleanup.reset();
14130   MaybeODRUseExprs.clear();
14131 }
14132 
14133 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
14134   if (!E->getType()->isVariablyModifiedType())
14135     return E;
14136   return TransformToPotentiallyEvaluated(E);
14137 }
14138 
14139 /// Are we within a context in which some evaluation could be performed (be it
14140 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
14141 /// captured by C++'s idea of an "unevaluated context".
14142 static bool isEvaluatableContext(Sema &SemaRef) {
14143   switch (SemaRef.ExprEvalContexts.back().Context) {
14144     case Sema::ExpressionEvaluationContext::Unevaluated:
14145     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14146     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14147       // Expressions in this context are never evaluated.
14148       return false;
14149 
14150     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14151     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14152     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14153       // Expressions in this context could be evaluated.
14154       return true;
14155 
14156     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14157       // Referenced declarations will only be used if the construct in the
14158       // containing expression is used, at which point we'll be given another
14159       // turn to mark them.
14160       return false;
14161   }
14162   llvm_unreachable("Invalid context");
14163 }
14164 
14165 /// Are we within a context in which references to resolved functions or to
14166 /// variables result in odr-use?
14167 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
14168   // An expression in a template is not really an expression until it's been
14169   // instantiated, so it doesn't trigger odr-use.
14170   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
14171     return false;
14172 
14173   switch (SemaRef.ExprEvalContexts.back().Context) {
14174     case Sema::ExpressionEvaluationContext::Unevaluated:
14175     case Sema::ExpressionEvaluationContext::UnevaluatedList:
14176     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
14177     case Sema::ExpressionEvaluationContext::DiscardedStatement:
14178       return false;
14179 
14180     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
14181     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
14182       return true;
14183 
14184     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
14185       return false;
14186   }
14187   llvm_unreachable("Invalid context");
14188 }
14189 
14190 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
14191   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
14192   return Func->isConstexpr() &&
14193          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
14194 }
14195 
14196 /// Mark a function referenced, and check whether it is odr-used
14197 /// (C++ [basic.def.odr]p2, C99 6.9p3)
14198 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
14199                                   bool MightBeOdrUse) {
14200   assert(Func && "No function?");
14201 
14202   Func->setReferenced();
14203 
14204   // C++11 [basic.def.odr]p3:
14205   //   A function whose name appears as a potentially-evaluated expression is
14206   //   odr-used if it is the unique lookup result or the selected member of a
14207   //   set of overloaded functions [...].
14208   //
14209   // We (incorrectly) mark overload resolution as an unevaluated context, so we
14210   // can just check that here.
14211   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
14212 
14213   // Determine whether we require a function definition to exist, per
14214   // C++11 [temp.inst]p3:
14215   //   Unless a function template specialization has been explicitly
14216   //   instantiated or explicitly specialized, the function template
14217   //   specialization is implicitly instantiated when the specialization is
14218   //   referenced in a context that requires a function definition to exist.
14219   //
14220   // That is either when this is an odr-use, or when a usage of a constexpr
14221   // function occurs within an evaluatable context.
14222   bool NeedDefinition =
14223       OdrUse || (isEvaluatableContext(*this) &&
14224                  isImplicitlyDefinableConstexprFunction(Func));
14225 
14226   // C++14 [temp.expl.spec]p6:
14227   //   If a template [...] is explicitly specialized then that specialization
14228   //   shall be declared before the first use of that specialization that would
14229   //   cause an implicit instantiation to take place, in every translation unit
14230   //   in which such a use occurs
14231   if (NeedDefinition &&
14232       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14233        Func->getMemberSpecializationInfo()))
14234     checkSpecializationVisibility(Loc, Func);
14235 
14236   // C++14 [except.spec]p17:
14237   //   An exception-specification is considered to be needed when:
14238   //   - the function is odr-used or, if it appears in an unevaluated operand,
14239   //     would be odr-used if the expression were potentially-evaluated;
14240   //
14241   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14242   // function is a pure virtual function we're calling, and in that case the
14243   // function was selected by overload resolution and we need to resolve its
14244   // exception specification for a different reason.
14245   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14246   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14247     ResolveExceptionSpec(Loc, FPT);
14248 
14249   // If we don't need to mark the function as used, and we don't need to
14250   // try to provide a definition, there's nothing more to do.
14251   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14252       (!NeedDefinition || Func->getBody()))
14253     return;
14254 
14255   // Note that this declaration has been used.
14256   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14257     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14258     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14259       if (Constructor->isDefaultConstructor()) {
14260         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14261           return;
14262         DefineImplicitDefaultConstructor(Loc, Constructor);
14263       } else if (Constructor->isCopyConstructor()) {
14264         DefineImplicitCopyConstructor(Loc, Constructor);
14265       } else if (Constructor->isMoveConstructor()) {
14266         DefineImplicitMoveConstructor(Loc, Constructor);
14267       }
14268     } else if (Constructor->getInheritedConstructor()) {
14269       DefineInheritingConstructor(Loc, Constructor);
14270     }
14271   } else if (CXXDestructorDecl *Destructor =
14272                  dyn_cast<CXXDestructorDecl>(Func)) {
14273     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14274     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14275       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14276         return;
14277       DefineImplicitDestructor(Loc, Destructor);
14278     }
14279     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14280       MarkVTableUsed(Loc, Destructor->getParent());
14281   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14282     if (MethodDecl->isOverloadedOperator() &&
14283         MethodDecl->getOverloadedOperator() == OO_Equal) {
14284       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14285       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14286         if (MethodDecl->isCopyAssignmentOperator())
14287           DefineImplicitCopyAssignment(Loc, MethodDecl);
14288         else if (MethodDecl->isMoveAssignmentOperator())
14289           DefineImplicitMoveAssignment(Loc, MethodDecl);
14290       }
14291     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14292                MethodDecl->getParent()->isLambda()) {
14293       CXXConversionDecl *Conversion =
14294           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14295       if (Conversion->isLambdaToBlockPointerConversion())
14296         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14297       else
14298         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14299     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14300       MarkVTableUsed(Loc, MethodDecl->getParent());
14301   }
14302 
14303   // Recursive functions should be marked when used from another function.
14304   // FIXME: Is this really right?
14305   if (CurContext == Func) return;
14306 
14307   // Implicit instantiation of function templates and member functions of
14308   // class templates.
14309   if (Func->isImplicitlyInstantiable()) {
14310     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14311     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14312     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14313     if (FirstInstantiation) {
14314       PointOfInstantiation = Loc;
14315       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14316     } else if (TSK != TSK_ImplicitInstantiation) {
14317       // Use the point of use as the point of instantiation, instead of the
14318       // point of explicit instantiation (which we track as the actual point of
14319       // instantiation). This gives better backtraces in diagnostics.
14320       PointOfInstantiation = Loc;
14321     }
14322 
14323     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14324         Func->isConstexpr()) {
14325       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14326           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14327           CodeSynthesisContexts.size())
14328         PendingLocalImplicitInstantiations.push_back(
14329             std::make_pair(Func, PointOfInstantiation));
14330       else if (Func->isConstexpr())
14331         // Do not defer instantiations of constexpr functions, to avoid the
14332         // expression evaluator needing to call back into Sema if it sees a
14333         // call to such a function.
14334         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14335       else {
14336         Func->setInstantiationIsPending(true);
14337         PendingInstantiations.push_back(std::make_pair(Func,
14338                                                        PointOfInstantiation));
14339         // Notify the consumer that a function was implicitly instantiated.
14340         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14341       }
14342     }
14343   } else {
14344     // Walk redefinitions, as some of them may be instantiable.
14345     for (auto i : Func->redecls()) {
14346       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14347         MarkFunctionReferenced(Loc, i, OdrUse);
14348     }
14349   }
14350 
14351   if (!OdrUse) return;
14352 
14353   // Keep track of used but undefined functions.
14354   if (!Func->isDefined()) {
14355     if (mightHaveNonExternalLinkage(Func))
14356       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14357     else if (Func->getMostRecentDecl()->isInlined() &&
14358              !LangOpts.GNUInline &&
14359              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14360       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14361     else if (isExternalWithNoLinkageType(Func))
14362       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14363   }
14364 
14365   Func->markUsed(Context);
14366 }
14367 
14368 static void
14369 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14370                                    ValueDecl *var, DeclContext *DC) {
14371   DeclContext *VarDC = var->getDeclContext();
14372 
14373   //  If the parameter still belongs to the translation unit, then
14374   //  we're actually just using one parameter in the declaration of
14375   //  the next.
14376   if (isa<ParmVarDecl>(var) &&
14377       isa<TranslationUnitDecl>(VarDC))
14378     return;
14379 
14380   // For C code, don't diagnose about capture if we're not actually in code
14381   // right now; it's impossible to write a non-constant expression outside of
14382   // function context, so we'll get other (more useful) diagnostics later.
14383   //
14384   // For C++, things get a bit more nasty... it would be nice to suppress this
14385   // diagnostic for certain cases like using a local variable in an array bound
14386   // for a member of a local class, but the correct predicate is not obvious.
14387   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14388     return;
14389 
14390   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14391   unsigned ContextKind = 3; // unknown
14392   if (isa<CXXMethodDecl>(VarDC) &&
14393       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14394     ContextKind = 2;
14395   } else if (isa<FunctionDecl>(VarDC)) {
14396     ContextKind = 0;
14397   } else if (isa<BlockDecl>(VarDC)) {
14398     ContextKind = 1;
14399   }
14400 
14401   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14402     << var << ValueKind << ContextKind << VarDC;
14403   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14404       << var;
14405 
14406   // FIXME: Add additional diagnostic info about class etc. which prevents
14407   // capture.
14408 }
14409 
14410 
14411 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14412                                       bool &SubCapturesAreNested,
14413                                       QualType &CaptureType,
14414                                       QualType &DeclRefType) {
14415    // Check whether we've already captured it.
14416   if (CSI->CaptureMap.count(Var)) {
14417     // If we found a capture, any subcaptures are nested.
14418     SubCapturesAreNested = true;
14419 
14420     // Retrieve the capture type for this variable.
14421     CaptureType = CSI->getCapture(Var).getCaptureType();
14422 
14423     // Compute the type of an expression that refers to this variable.
14424     DeclRefType = CaptureType.getNonReferenceType();
14425 
14426     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14427     // are mutable in the sense that user can change their value - they are
14428     // private instances of the captured declarations.
14429     const Capture &Cap = CSI->getCapture(Var);
14430     if (Cap.isCopyCapture() &&
14431         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14432         !(isa<CapturedRegionScopeInfo>(CSI) &&
14433           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14434       DeclRefType.addConst();
14435     return true;
14436   }
14437   return false;
14438 }
14439 
14440 // Only block literals, captured statements, and lambda expressions can
14441 // capture; other scopes don't work.
14442 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14443                                  SourceLocation Loc,
14444                                  const bool Diagnose, Sema &S) {
14445   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14446     return getLambdaAwareParentOfDeclContext(DC);
14447   else if (Var->hasLocalStorage()) {
14448     if (Diagnose)
14449        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14450   }
14451   return nullptr;
14452 }
14453 
14454 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14455 // certain types of variables (unnamed, variably modified types etc.)
14456 // so check for eligibility.
14457 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14458                                  SourceLocation Loc,
14459                                  const bool Diagnose, Sema &S) {
14460 
14461   bool IsBlock = isa<BlockScopeInfo>(CSI);
14462   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14463 
14464   // Lambdas are not allowed to capture unnamed variables
14465   // (e.g. anonymous unions).
14466   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14467   // assuming that's the intent.
14468   if (IsLambda && !Var->getDeclName()) {
14469     if (Diagnose) {
14470       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14471       S.Diag(Var->getLocation(), diag::note_declared_at);
14472     }
14473     return false;
14474   }
14475 
14476   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14477   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14478     if (Diagnose) {
14479       S.Diag(Loc, diag::err_ref_vm_type);
14480       S.Diag(Var->getLocation(), diag::note_previous_decl)
14481         << Var->getDeclName();
14482     }
14483     return false;
14484   }
14485   // Prohibit structs with flexible array members too.
14486   // We cannot capture what is in the tail end of the struct.
14487   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14488     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14489       if (Diagnose) {
14490         if (IsBlock)
14491           S.Diag(Loc, diag::err_ref_flexarray_type);
14492         else
14493           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14494             << Var->getDeclName();
14495         S.Diag(Var->getLocation(), diag::note_previous_decl)
14496           << Var->getDeclName();
14497       }
14498       return false;
14499     }
14500   }
14501   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14502   // Lambdas and captured statements are not allowed to capture __block
14503   // variables; they don't support the expected semantics.
14504   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14505     if (Diagnose) {
14506       S.Diag(Loc, diag::err_capture_block_variable)
14507         << Var->getDeclName() << !IsLambda;
14508       S.Diag(Var->getLocation(), diag::note_previous_decl)
14509         << Var->getDeclName();
14510     }
14511     return false;
14512   }
14513   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14514   if (S.getLangOpts().OpenCL && IsBlock &&
14515       Var->getType()->isBlockPointerType()) {
14516     if (Diagnose)
14517       S.Diag(Loc, diag::err_opencl_block_ref_block);
14518     return false;
14519   }
14520 
14521   return true;
14522 }
14523 
14524 // Returns true if the capture by block was successful.
14525 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14526                                  SourceLocation Loc,
14527                                  const bool BuildAndDiagnose,
14528                                  QualType &CaptureType,
14529                                  QualType &DeclRefType,
14530                                  const bool Nested,
14531                                  Sema &S) {
14532   Expr *CopyExpr = nullptr;
14533   bool ByRef = false;
14534 
14535   // Blocks are not allowed to capture arrays.
14536   if (CaptureType->isArrayType()) {
14537     if (BuildAndDiagnose) {
14538       S.Diag(Loc, diag::err_ref_array_type);
14539       S.Diag(Var->getLocation(), diag::note_previous_decl)
14540       << Var->getDeclName();
14541     }
14542     return false;
14543   }
14544 
14545   // Forbid the block-capture of autoreleasing variables.
14546   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14547     if (BuildAndDiagnose) {
14548       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14549         << /*block*/ 0;
14550       S.Diag(Var->getLocation(), diag::note_previous_decl)
14551         << Var->getDeclName();
14552     }
14553     return false;
14554   }
14555 
14556   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14557   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14558     // This function finds out whether there is an AttributedType of kind
14559     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14560     // attr_objc_ownership implies __autoreleasing was explicitly specified
14561     // rather than being added implicitly by the compiler.
14562     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14563       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14564         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14565           return true;
14566 
14567         // Peel off AttributedTypes that are not of kind objc_ownership.
14568         Ty = AttrTy->getModifiedType();
14569       }
14570 
14571       return false;
14572     };
14573 
14574     QualType PointeeTy = PT->getPointeeType();
14575 
14576     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14577         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14578         !IsObjCOwnershipAttributedType(PointeeTy)) {
14579       if (BuildAndDiagnose) {
14580         SourceLocation VarLoc = Var->getLocation();
14581         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14582         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14583       }
14584     }
14585   }
14586 
14587   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14588   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14589       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14590     // Block capture by reference does not change the capture or
14591     // declaration reference types.
14592     ByRef = true;
14593   } else {
14594     // Block capture by copy introduces 'const'.
14595     CaptureType = CaptureType.getNonReferenceType().withConst();
14596     DeclRefType = CaptureType;
14597 
14598     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14599       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14600         // The capture logic needs the destructor, so make sure we mark it.
14601         // Usually this is unnecessary because most local variables have
14602         // their destructors marked at declaration time, but parameters are
14603         // an exception because it's technically only the call site that
14604         // actually requires the destructor.
14605         if (isa<ParmVarDecl>(Var))
14606           S.FinalizeVarWithDestructor(Var, Record);
14607 
14608         // Enter a new evaluation context to insulate the copy
14609         // full-expression.
14610         EnterExpressionEvaluationContext scope(
14611             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14612 
14613         // According to the blocks spec, the capture of a variable from
14614         // the stack requires a const copy constructor.  This is not true
14615         // of the copy/move done to move a __block variable to the heap.
14616         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14617                                                   DeclRefType.withConst(),
14618                                                   VK_LValue, Loc);
14619 
14620         ExprResult Result
14621           = S.PerformCopyInitialization(
14622               InitializedEntity::InitializeBlock(Var->getLocation(),
14623                                                   CaptureType, false),
14624               Loc, DeclRef);
14625 
14626         // Build a full-expression copy expression if initialization
14627         // succeeded and used a non-trivial constructor.  Recover from
14628         // errors by pretending that the copy isn't necessary.
14629         if (!Result.isInvalid() &&
14630             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14631                 ->isTrivial()) {
14632           Result = S.MaybeCreateExprWithCleanups(Result);
14633           CopyExpr = Result.get();
14634         }
14635       }
14636     }
14637   }
14638 
14639   // Actually capture the variable.
14640   if (BuildAndDiagnose)
14641     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14642                     SourceLocation(), CaptureType, CopyExpr);
14643 
14644   return true;
14645 
14646 }
14647 
14648 
14649 /// Capture the given variable in the captured region.
14650 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14651                                     VarDecl *Var,
14652                                     SourceLocation Loc,
14653                                     const bool BuildAndDiagnose,
14654                                     QualType &CaptureType,
14655                                     QualType &DeclRefType,
14656                                     const bool RefersToCapturedVariable,
14657                                     Sema &S) {
14658   // By default, capture variables by reference.
14659   bool ByRef = true;
14660   // Using an LValue reference type is consistent with Lambdas (see below).
14661   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14662     if (S.isOpenMPCapturedDecl(Var)) {
14663       bool HasConst = DeclRefType.isConstQualified();
14664       DeclRefType = DeclRefType.getUnqualifiedType();
14665       // Don't lose diagnostics about assignments to const.
14666       if (HasConst)
14667         DeclRefType.addConst();
14668     }
14669     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14670   }
14671 
14672   if (ByRef)
14673     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14674   else
14675     CaptureType = DeclRefType;
14676 
14677   Expr *CopyExpr = nullptr;
14678   if (BuildAndDiagnose) {
14679     // The current implementation assumes that all variables are captured
14680     // by references. Since there is no capture by copy, no expression
14681     // evaluation will be needed.
14682     RecordDecl *RD = RSI->TheRecordDecl;
14683 
14684     FieldDecl *Field
14685       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14686                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14687                           nullptr, false, ICIS_NoInit);
14688     Field->setImplicit(true);
14689     Field->setAccess(AS_private);
14690     RD->addDecl(Field);
14691     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14692       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14693 
14694     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14695                                             DeclRefType, VK_LValue, Loc);
14696     Var->setReferenced(true);
14697     Var->markUsed(S.Context);
14698   }
14699 
14700   // Actually capture the variable.
14701   if (BuildAndDiagnose)
14702     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14703                     SourceLocation(), CaptureType, CopyExpr);
14704 
14705 
14706   return true;
14707 }
14708 
14709 /// Create a field within the lambda class for the variable
14710 /// being captured.
14711 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14712                                     QualType FieldType, QualType DeclRefType,
14713                                     SourceLocation Loc,
14714                                     bool RefersToCapturedVariable) {
14715   CXXRecordDecl *Lambda = LSI->Lambda;
14716 
14717   // Build the non-static data member.
14718   FieldDecl *Field
14719     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14720                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14721                         nullptr, false, ICIS_NoInit);
14722   Field->setImplicit(true);
14723   Field->setAccess(AS_private);
14724   Lambda->addDecl(Field);
14725 }
14726 
14727 /// Capture the given variable in the lambda.
14728 static bool captureInLambda(LambdaScopeInfo *LSI,
14729                             VarDecl *Var,
14730                             SourceLocation Loc,
14731                             const bool BuildAndDiagnose,
14732                             QualType &CaptureType,
14733                             QualType &DeclRefType,
14734                             const bool RefersToCapturedVariable,
14735                             const Sema::TryCaptureKind Kind,
14736                             SourceLocation EllipsisLoc,
14737                             const bool IsTopScope,
14738                             Sema &S) {
14739 
14740   // Determine whether we are capturing by reference or by value.
14741   bool ByRef = false;
14742   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14743     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14744   } else {
14745     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14746   }
14747 
14748   // Compute the type of the field that will capture this variable.
14749   if (ByRef) {
14750     // C++11 [expr.prim.lambda]p15:
14751     //   An entity is captured by reference if it is implicitly or
14752     //   explicitly captured but not captured by copy. It is
14753     //   unspecified whether additional unnamed non-static data
14754     //   members are declared in the closure type for entities
14755     //   captured by reference.
14756     //
14757     // FIXME: It is not clear whether we want to build an lvalue reference
14758     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14759     // to do the former, while EDG does the latter. Core issue 1249 will
14760     // clarify, but for now we follow GCC because it's a more permissive and
14761     // easily defensible position.
14762     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14763   } else {
14764     // C++11 [expr.prim.lambda]p14:
14765     //   For each entity captured by copy, an unnamed non-static
14766     //   data member is declared in the closure type. The
14767     //   declaration order of these members is unspecified. The type
14768     //   of such a data member is the type of the corresponding
14769     //   captured entity if the entity is not a reference to an
14770     //   object, or the referenced type otherwise. [Note: If the
14771     //   captured entity is a reference to a function, the
14772     //   corresponding data member is also a reference to a
14773     //   function. - end note ]
14774     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14775       if (!RefType->getPointeeType()->isFunctionType())
14776         CaptureType = RefType->getPointeeType();
14777     }
14778 
14779     // Forbid the lambda copy-capture of autoreleasing variables.
14780     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14781       if (BuildAndDiagnose) {
14782         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14783         S.Diag(Var->getLocation(), diag::note_previous_decl)
14784           << Var->getDeclName();
14785       }
14786       return false;
14787     }
14788 
14789     // Make sure that by-copy captures are of a complete and non-abstract type.
14790     if (BuildAndDiagnose) {
14791       if (!CaptureType->isDependentType() &&
14792           S.RequireCompleteType(Loc, CaptureType,
14793                                 diag::err_capture_of_incomplete_type,
14794                                 Var->getDeclName()))
14795         return false;
14796 
14797       if (S.RequireNonAbstractType(Loc, CaptureType,
14798                                    diag::err_capture_of_abstract_type))
14799         return false;
14800     }
14801   }
14802 
14803   // Capture this variable in the lambda.
14804   if (BuildAndDiagnose)
14805     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14806                             RefersToCapturedVariable);
14807 
14808   // Compute the type of a reference to this captured variable.
14809   if (ByRef)
14810     DeclRefType = CaptureType.getNonReferenceType();
14811   else {
14812     // C++ [expr.prim.lambda]p5:
14813     //   The closure type for a lambda-expression has a public inline
14814     //   function call operator [...]. This function call operator is
14815     //   declared const (9.3.1) if and only if the lambda-expression's
14816     //   parameter-declaration-clause is not followed by mutable.
14817     DeclRefType = CaptureType.getNonReferenceType();
14818     if (!LSI->Mutable && !CaptureType->isReferenceType())
14819       DeclRefType.addConst();
14820   }
14821 
14822   // Add the capture.
14823   if (BuildAndDiagnose)
14824     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14825                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14826 
14827   return true;
14828 }
14829 
14830 bool Sema::tryCaptureVariable(
14831     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14832     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14833     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14834   // An init-capture is notionally from the context surrounding its
14835   // declaration, but its parent DC is the lambda class.
14836   DeclContext *VarDC = Var->getDeclContext();
14837   if (Var->isInitCapture())
14838     VarDC = VarDC->getParent();
14839 
14840   DeclContext *DC = CurContext;
14841   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14842       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14843   // We need to sync up the Declaration Context with the
14844   // FunctionScopeIndexToStopAt
14845   if (FunctionScopeIndexToStopAt) {
14846     unsigned FSIndex = FunctionScopes.size() - 1;
14847     while (FSIndex != MaxFunctionScopesIndex) {
14848       DC = getLambdaAwareParentOfDeclContext(DC);
14849       --FSIndex;
14850     }
14851   }
14852 
14853 
14854   // If the variable is declared in the current context, there is no need to
14855   // capture it.
14856   if (VarDC == DC) return true;
14857 
14858   // Capture global variables if it is required to use private copy of this
14859   // variable.
14860   bool IsGlobal = !Var->hasLocalStorage();
14861   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14862     return true;
14863   Var = Var->getCanonicalDecl();
14864 
14865   // Walk up the stack to determine whether we can capture the variable,
14866   // performing the "simple" checks that don't depend on type. We stop when
14867   // we've either hit the declared scope of the variable or find an existing
14868   // capture of that variable.  We start from the innermost capturing-entity
14869   // (the DC) and ensure that all intervening capturing-entities
14870   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14871   // declcontext can either capture the variable or have already captured
14872   // the variable.
14873   CaptureType = Var->getType();
14874   DeclRefType = CaptureType.getNonReferenceType();
14875   bool Nested = false;
14876   bool Explicit = (Kind != TryCapture_Implicit);
14877   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14878   do {
14879     // Only block literals, captured statements, and lambda expressions can
14880     // capture; other scopes don't work.
14881     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14882                                                               ExprLoc,
14883                                                               BuildAndDiagnose,
14884                                                               *this);
14885     // We need to check for the parent *first* because, if we *have*
14886     // private-captured a global variable, we need to recursively capture it in
14887     // intermediate blocks, lambdas, etc.
14888     if (!ParentDC) {
14889       if (IsGlobal) {
14890         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14891         break;
14892       }
14893       return true;
14894     }
14895 
14896     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14897     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14898 
14899 
14900     // Check whether we've already captured it.
14901     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14902                                              DeclRefType)) {
14903       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14904       break;
14905     }
14906     // If we are instantiating a generic lambda call operator body,
14907     // we do not want to capture new variables.  What was captured
14908     // during either a lambdas transformation or initial parsing
14909     // should be used.
14910     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14911       if (BuildAndDiagnose) {
14912         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14913         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14914           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14915           Diag(Var->getLocation(), diag::note_previous_decl)
14916              << Var->getDeclName();
14917           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14918         } else
14919           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14920       }
14921       return true;
14922     }
14923     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14924     // certain types of variables (unnamed, variably modified types etc.)
14925     // so check for eligibility.
14926     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14927        return true;
14928 
14929     // Try to capture variable-length arrays types.
14930     if (Var->getType()->isVariablyModifiedType()) {
14931       // We're going to walk down into the type and look for VLA
14932       // expressions.
14933       QualType QTy = Var->getType();
14934       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14935         QTy = PVD->getOriginalType();
14936       captureVariablyModifiedType(Context, QTy, CSI);
14937     }
14938 
14939     if (getLangOpts().OpenMP) {
14940       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14941         // OpenMP private variables should not be captured in outer scope, so
14942         // just break here. Similarly, global variables that are captured in a
14943         // target region should not be captured outside the scope of the region.
14944         if (RSI->CapRegionKind == CR_OpenMP) {
14945           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
14946           auto IsTargetCap = !IsOpenMPPrivateDecl &&
14947                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14948           // When we detect target captures we are looking from inside the
14949           // target region, therefore we need to propagate the capture from the
14950           // enclosing region. Therefore, the capture is not initially nested.
14951           if (IsTargetCap)
14952             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
14953 
14954           if (IsTargetCap || IsOpenMPPrivateDecl) {
14955             Nested = !IsTargetCap;
14956             DeclRefType = DeclRefType.getUnqualifiedType();
14957             CaptureType = Context.getLValueReferenceType(DeclRefType);
14958             break;
14959           }
14960         }
14961       }
14962     }
14963     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14964       // No capture-default, and this is not an explicit capture
14965       // so cannot capture this variable.
14966       if (BuildAndDiagnose) {
14967         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14968         Diag(Var->getLocation(), diag::note_previous_decl)
14969           << Var->getDeclName();
14970         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14971           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14972                diag::note_lambda_decl);
14973         // FIXME: If we error out because an outer lambda can not implicitly
14974         // capture a variable that an inner lambda explicitly captures, we
14975         // should have the inner lambda do the explicit capture - because
14976         // it makes for cleaner diagnostics later.  This would purely be done
14977         // so that the diagnostic does not misleadingly claim that a variable
14978         // can not be captured by a lambda implicitly even though it is captured
14979         // explicitly.  Suggestion:
14980         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14981         //    at the function head
14982         //  - cache the StartingDeclContext - this must be a lambda
14983         //  - captureInLambda in the innermost lambda the variable.
14984       }
14985       return true;
14986     }
14987 
14988     FunctionScopesIndex--;
14989     DC = ParentDC;
14990     Explicit = false;
14991   } while (!VarDC->Equals(DC));
14992 
14993   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14994   // computing the type of the capture at each step, checking type-specific
14995   // requirements, and adding captures if requested.
14996   // If the variable had already been captured previously, we start capturing
14997   // at the lambda nested within that one.
14998   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14999        ++I) {
15000     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
15001 
15002     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
15003       if (!captureInBlock(BSI, Var, ExprLoc,
15004                           BuildAndDiagnose, CaptureType,
15005                           DeclRefType, Nested, *this))
15006         return true;
15007       Nested = true;
15008     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
15009       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
15010                                    BuildAndDiagnose, CaptureType,
15011                                    DeclRefType, Nested, *this))
15012         return true;
15013       Nested = true;
15014     } else {
15015       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
15016       if (!captureInLambda(LSI, Var, ExprLoc,
15017                            BuildAndDiagnose, CaptureType,
15018                            DeclRefType, Nested, Kind, EllipsisLoc,
15019                             /*IsTopScope*/I == N - 1, *this))
15020         return true;
15021       Nested = true;
15022     }
15023   }
15024   return false;
15025 }
15026 
15027 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
15028                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
15029   QualType CaptureType;
15030   QualType DeclRefType;
15031   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
15032                             /*BuildAndDiagnose=*/true, CaptureType,
15033                             DeclRefType, nullptr);
15034 }
15035 
15036 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
15037   QualType CaptureType;
15038   QualType DeclRefType;
15039   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15040                              /*BuildAndDiagnose=*/false, CaptureType,
15041                              DeclRefType, nullptr);
15042 }
15043 
15044 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
15045   QualType CaptureType;
15046   QualType DeclRefType;
15047 
15048   // Determine whether we can capture this variable.
15049   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
15050                          /*BuildAndDiagnose=*/false, CaptureType,
15051                          DeclRefType, nullptr))
15052     return QualType();
15053 
15054   return DeclRefType;
15055 }
15056 
15057 
15058 
15059 // If either the type of the variable or the initializer is dependent,
15060 // return false. Otherwise, determine whether the variable is a constant
15061 // expression. Use this if you need to know if a variable that might or
15062 // might not be dependent is truly a constant expression.
15063 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
15064     ASTContext &Context) {
15065 
15066   if (Var->getType()->isDependentType())
15067     return false;
15068   const VarDecl *DefVD = nullptr;
15069   Var->getAnyInitializer(DefVD);
15070   if (!DefVD)
15071     return false;
15072   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
15073   Expr *Init = cast<Expr>(Eval->Value);
15074   if (Init->isValueDependent())
15075     return false;
15076   return IsVariableAConstantExpression(Var, Context);
15077 }
15078 
15079 
15080 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
15081   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
15082   // an object that satisfies the requirements for appearing in a
15083   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
15084   // is immediately applied."  This function handles the lvalue-to-rvalue
15085   // conversion part.
15086   MaybeODRUseExprs.erase(E->IgnoreParens());
15087 
15088   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
15089   // to a variable that is a constant expression, and if so, identify it as
15090   // a reference to a variable that does not involve an odr-use of that
15091   // variable.
15092   if (LambdaScopeInfo *LSI = getCurLambda()) {
15093     Expr *SansParensExpr = E->IgnoreParens();
15094     VarDecl *Var = nullptr;
15095     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
15096       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
15097     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
15098       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
15099 
15100     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
15101       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
15102   }
15103 }
15104 
15105 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
15106   Res = CorrectDelayedTyposInExpr(Res);
15107 
15108   if (!Res.isUsable())
15109     return Res;
15110 
15111   // If a constant-expression is a reference to a variable where we delay
15112   // deciding whether it is an odr-use, just assume we will apply the
15113   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
15114   // (a non-type template argument), we have special handling anyway.
15115   UpdateMarkingForLValueToRValue(Res.get());
15116   return Res;
15117 }
15118 
15119 void Sema::CleanupVarDeclMarking() {
15120   for (Expr *E : MaybeODRUseExprs) {
15121     VarDecl *Var;
15122     SourceLocation Loc;
15123     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
15124       Var = cast<VarDecl>(DRE->getDecl());
15125       Loc = DRE->getLocation();
15126     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15127       Var = cast<VarDecl>(ME->getMemberDecl());
15128       Loc = ME->getMemberLoc();
15129     } else {
15130       llvm_unreachable("Unexpected expression");
15131     }
15132 
15133     MarkVarDeclODRUsed(Var, Loc, *this,
15134                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
15135   }
15136 
15137   MaybeODRUseExprs.clear();
15138 }
15139 
15140 
15141 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
15142                                     VarDecl *Var, Expr *E) {
15143   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
15144          "Invalid Expr argument to DoMarkVarDeclReferenced");
15145   Var->setReferenced();
15146 
15147   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
15148 
15149   bool OdrUseContext = isOdrUseContext(SemaRef);
15150   bool UsableInConstantExpr =
15151       Var->isUsableInConstantExpressions(SemaRef.Context);
15152   bool NeedDefinition =
15153       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
15154 
15155   VarTemplateSpecializationDecl *VarSpec =
15156       dyn_cast<VarTemplateSpecializationDecl>(Var);
15157   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
15158          "Can't instantiate a partial template specialization.");
15159 
15160   // If this might be a member specialization of a static data member, check
15161   // the specialization is visible. We already did the checks for variable
15162   // template specializations when we created them.
15163   if (NeedDefinition && TSK != TSK_Undeclared &&
15164       !isa<VarTemplateSpecializationDecl>(Var))
15165     SemaRef.checkSpecializationVisibility(Loc, Var);
15166 
15167   // Perform implicit instantiation of static data members, static data member
15168   // templates of class templates, and variable template specializations. Delay
15169   // instantiations of variable templates, except for those that could be used
15170   // in a constant expression.
15171   if (NeedDefinition && isTemplateInstantiation(TSK)) {
15172     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
15173     // instantiation declaration if a variable is usable in a constant
15174     // expression (among other cases).
15175     bool TryInstantiating =
15176         TSK == TSK_ImplicitInstantiation ||
15177         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
15178 
15179     if (TryInstantiating) {
15180       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
15181       bool FirstInstantiation = PointOfInstantiation.isInvalid();
15182       if (FirstInstantiation) {
15183         PointOfInstantiation = Loc;
15184         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
15185       }
15186 
15187       bool InstantiationDependent = false;
15188       bool IsNonDependent =
15189           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
15190                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
15191                   : true;
15192 
15193       // Do not instantiate specializations that are still type-dependent.
15194       if (IsNonDependent) {
15195         if (UsableInConstantExpr) {
15196           // Do not defer instantiations of variables that could be used in a
15197           // constant expression.
15198           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
15199         } else if (FirstInstantiation ||
15200                    isa<VarTemplateSpecializationDecl>(Var)) {
15201           // FIXME: For a specialization of a variable template, we don't
15202           // distinguish between "declaration and type implicitly instantiated"
15203           // and "implicit instantiation of definition requested", so we have
15204           // no direct way to avoid enqueueing the pending instantiation
15205           // multiple times.
15206           SemaRef.PendingInstantiations
15207               .push_back(std::make_pair(Var, PointOfInstantiation));
15208         }
15209       }
15210     }
15211   }
15212 
15213   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15214   // the requirements for appearing in a constant expression (5.19) and, if
15215   // it is an object, the lvalue-to-rvalue conversion (4.1)
15216   // is immediately applied."  We check the first part here, and
15217   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15218   // Note that we use the C++11 definition everywhere because nothing in
15219   // C++03 depends on whether we get the C++03 version correct. The second
15220   // part does not apply to references, since they are not objects.
15221   if (OdrUseContext && E &&
15222       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15223     // A reference initialized by a constant expression can never be
15224     // odr-used, so simply ignore it.
15225     if (!Var->getType()->isReferenceType() ||
15226         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15227       SemaRef.MaybeODRUseExprs.insert(E);
15228   } else if (OdrUseContext) {
15229     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15230                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15231   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15232     // If this is a dependent context, we don't need to mark variables as
15233     // odr-used, but we may still need to track them for lambda capture.
15234     // FIXME: Do we also need to do this inside dependent typeid expressions
15235     // (which are modeled as unevaluated at this point)?
15236     const bool RefersToEnclosingScope =
15237         (SemaRef.CurContext != Var->getDeclContext() &&
15238          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15239     if (RefersToEnclosingScope) {
15240       LambdaScopeInfo *const LSI =
15241           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15242       if (LSI && (!LSI->CallOperator ||
15243                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15244         // If a variable could potentially be odr-used, defer marking it so
15245         // until we finish analyzing the full expression for any
15246         // lvalue-to-rvalue
15247         // or discarded value conversions that would obviate odr-use.
15248         // Add it to the list of potential captures that will be analyzed
15249         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15250         // unless the variable is a reference that was initialized by a constant
15251         // expression (this will never need to be captured or odr-used).
15252         assert(E && "Capture variable should be used in an expression.");
15253         if (!Var->getType()->isReferenceType() ||
15254             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15255           LSI->addPotentialCapture(E->IgnoreParens());
15256       }
15257     }
15258   }
15259 }
15260 
15261 /// Mark a variable referenced, and check whether it is odr-used
15262 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15263 /// used directly for normal expressions referring to VarDecl.
15264 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15265   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15266 }
15267 
15268 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15269                                Decl *D, Expr *E, bool MightBeOdrUse) {
15270   if (SemaRef.isInOpenMPDeclareTargetContext())
15271     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15272 
15273   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15274     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15275     return;
15276   }
15277 
15278   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15279 
15280   // If this is a call to a method via a cast, also mark the method in the
15281   // derived class used in case codegen can devirtualize the call.
15282   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15283   if (!ME)
15284     return;
15285   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15286   if (!MD)
15287     return;
15288   // Only attempt to devirtualize if this is truly a virtual call.
15289   bool IsVirtualCall = MD->isVirtual() &&
15290                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15291   if (!IsVirtualCall)
15292     return;
15293 
15294   // If it's possible to devirtualize the call, mark the called function
15295   // referenced.
15296   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15297       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15298   if (DM)
15299     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15300 }
15301 
15302 /// Perform reference-marking and odr-use handling for a DeclRefExpr.
15303 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15304   // TODO: update this with DR# once a defect report is filed.
15305   // C++11 defect. The address of a pure member should not be an ODR use, even
15306   // if it's a qualified reference.
15307   bool OdrUse = true;
15308   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15309     if (Method->isVirtual() &&
15310         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15311       OdrUse = false;
15312   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15313 }
15314 
15315 /// Perform reference-marking and odr-use handling for a MemberExpr.
15316 void Sema::MarkMemberReferenced(MemberExpr *E) {
15317   // C++11 [basic.def.odr]p2:
15318   //   A non-overloaded function whose name appears as a potentially-evaluated
15319   //   expression or a member of a set of candidate functions, if selected by
15320   //   overload resolution when referred to from a potentially-evaluated
15321   //   expression, is odr-used, unless it is a pure virtual function and its
15322   //   name is not explicitly qualified.
15323   bool MightBeOdrUse = true;
15324   if (E->performsVirtualDispatch(getLangOpts())) {
15325     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15326       if (Method->isPure())
15327         MightBeOdrUse = false;
15328   }
15329   SourceLocation Loc = E->getMemberLoc().isValid() ?
15330                             E->getMemberLoc() : E->getLocStart();
15331   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15332 }
15333 
15334 /// Perform marking for a reference to an arbitrary declaration.  It
15335 /// marks the declaration referenced, and performs odr-use checking for
15336 /// functions and variables. This method should not be used when building a
15337 /// normal expression which refers to a variable.
15338 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15339                                  bool MightBeOdrUse) {
15340   if (MightBeOdrUse) {
15341     if (auto *VD = dyn_cast<VarDecl>(D)) {
15342       MarkVariableReferenced(Loc, VD);
15343       return;
15344     }
15345   }
15346   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15347     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15348     return;
15349   }
15350   D->setReferenced();
15351 }
15352 
15353 namespace {
15354   // Mark all of the declarations used by a type as referenced.
15355   // FIXME: Not fully implemented yet! We need to have a better understanding
15356   // of when we're entering a context we should not recurse into.
15357   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15358   // TreeTransforms rebuilding the type in a new context. Rather than
15359   // duplicating the TreeTransform logic, we should consider reusing it here.
15360   // Currently that causes problems when rebuilding LambdaExprs.
15361   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15362     Sema &S;
15363     SourceLocation Loc;
15364 
15365   public:
15366     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15367 
15368     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15369 
15370     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15371   };
15372 }
15373 
15374 bool MarkReferencedDecls::TraverseTemplateArgument(
15375     const TemplateArgument &Arg) {
15376   {
15377     // A non-type template argument is a constant-evaluated context.
15378     EnterExpressionEvaluationContext Evaluated(
15379         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15380     if (Arg.getKind() == TemplateArgument::Declaration) {
15381       if (Decl *D = Arg.getAsDecl())
15382         S.MarkAnyDeclReferenced(Loc, D, true);
15383     } else if (Arg.getKind() == TemplateArgument::Expression) {
15384       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15385     }
15386   }
15387 
15388   return Inherited::TraverseTemplateArgument(Arg);
15389 }
15390 
15391 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15392   MarkReferencedDecls Marker(*this, Loc);
15393   Marker.TraverseType(T);
15394 }
15395 
15396 namespace {
15397   /// Helper class that marks all of the declarations referenced by
15398   /// potentially-evaluated subexpressions as "referenced".
15399   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15400     Sema &S;
15401     bool SkipLocalVariables;
15402 
15403   public:
15404     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15405 
15406     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15407       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15408 
15409     void VisitDeclRefExpr(DeclRefExpr *E) {
15410       // If we were asked not to visit local variables, don't.
15411       if (SkipLocalVariables) {
15412         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15413           if (VD->hasLocalStorage())
15414             return;
15415       }
15416 
15417       S.MarkDeclRefReferenced(E);
15418     }
15419 
15420     void VisitMemberExpr(MemberExpr *E) {
15421       S.MarkMemberReferenced(E);
15422       Inherited::VisitMemberExpr(E);
15423     }
15424 
15425     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15426       S.MarkFunctionReferenced(E->getLocStart(),
15427             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15428       Visit(E->getSubExpr());
15429     }
15430 
15431     void VisitCXXNewExpr(CXXNewExpr *E) {
15432       if (E->getOperatorNew())
15433         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15434       if (E->getOperatorDelete())
15435         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15436       Inherited::VisitCXXNewExpr(E);
15437     }
15438 
15439     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15440       if (E->getOperatorDelete())
15441         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15442       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15443       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15444         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15445         S.MarkFunctionReferenced(E->getLocStart(),
15446                                     S.LookupDestructor(Record));
15447       }
15448 
15449       Inherited::VisitCXXDeleteExpr(E);
15450     }
15451 
15452     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15453       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15454       Inherited::VisitCXXConstructExpr(E);
15455     }
15456 
15457     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15458       Visit(E->getExpr());
15459     }
15460 
15461     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15462       Inherited::VisitImplicitCastExpr(E);
15463 
15464       if (E->getCastKind() == CK_LValueToRValue)
15465         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15466     }
15467   };
15468 }
15469 
15470 /// Mark any declarations that appear within this expression or any
15471 /// potentially-evaluated subexpressions as "referenced".
15472 ///
15473 /// \param SkipLocalVariables If true, don't mark local variables as
15474 /// 'referenced'.
15475 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15476                                             bool SkipLocalVariables) {
15477   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15478 }
15479 
15480 /// Emit a diagnostic that describes an effect on the run-time behavior
15481 /// of the program being compiled.
15482 ///
15483 /// This routine emits the given diagnostic when the code currently being
15484 /// type-checked is "potentially evaluated", meaning that there is a
15485 /// possibility that the code will actually be executable. Code in sizeof()
15486 /// expressions, code used only during overload resolution, etc., are not
15487 /// potentially evaluated. This routine will suppress such diagnostics or,
15488 /// in the absolutely nutty case of potentially potentially evaluated
15489 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15490 /// later.
15491 ///
15492 /// This routine should be used for all diagnostics that describe the run-time
15493 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15494 /// Failure to do so will likely result in spurious diagnostics or failures
15495 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15496 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15497                                const PartialDiagnostic &PD) {
15498   switch (ExprEvalContexts.back().Context) {
15499   case ExpressionEvaluationContext::Unevaluated:
15500   case ExpressionEvaluationContext::UnevaluatedList:
15501   case ExpressionEvaluationContext::UnevaluatedAbstract:
15502   case ExpressionEvaluationContext::DiscardedStatement:
15503     // The argument will never be evaluated, so don't complain.
15504     break;
15505 
15506   case ExpressionEvaluationContext::ConstantEvaluated:
15507     // Relevant diagnostics should be produced by constant evaluation.
15508     break;
15509 
15510   case ExpressionEvaluationContext::PotentiallyEvaluated:
15511   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15512     if (Statement && getCurFunctionOrMethodDecl()) {
15513       FunctionScopes.back()->PossiblyUnreachableDiags.
15514         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15515       return true;
15516     }
15517 
15518     // The initializer of a constexpr variable or of the first declaration of a
15519     // static data member is not syntactically a constant evaluated constant,
15520     // but nonetheless is always required to be a constant expression, so we
15521     // can skip diagnosing.
15522     // FIXME: Using the mangling context here is a hack.
15523     if (auto *VD = dyn_cast_or_null<VarDecl>(
15524             ExprEvalContexts.back().ManglingContextDecl)) {
15525       if (VD->isConstexpr() ||
15526           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15527         break;
15528       // FIXME: For any other kind of variable, we should build a CFG for its
15529       // initializer and check whether the context in question is reachable.
15530     }
15531 
15532     Diag(Loc, PD);
15533     return true;
15534   }
15535 
15536   return false;
15537 }
15538 
15539 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15540                                CallExpr *CE, FunctionDecl *FD) {
15541   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15542     return false;
15543 
15544   // If we're inside a decltype's expression, don't check for a valid return
15545   // type or construct temporaries until we know whether this is the last call.
15546   if (ExprEvalContexts.back().IsDecltype) {
15547     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15548     return false;
15549   }
15550 
15551   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15552     FunctionDecl *FD;
15553     CallExpr *CE;
15554 
15555   public:
15556     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15557       : FD(FD), CE(CE) { }
15558 
15559     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15560       if (!FD) {
15561         S.Diag(Loc, diag::err_call_incomplete_return)
15562           << T << CE->getSourceRange();
15563         return;
15564       }
15565 
15566       S.Diag(Loc, diag::err_call_function_incomplete_return)
15567         << CE->getSourceRange() << FD->getDeclName() << T;
15568       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15569           << FD->getDeclName();
15570     }
15571   } Diagnoser(FD, CE);
15572 
15573   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15574     return true;
15575 
15576   return false;
15577 }
15578 
15579 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15580 // will prevent this condition from triggering, which is what we want.
15581 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15582   SourceLocation Loc;
15583 
15584   unsigned diagnostic = diag::warn_condition_is_assignment;
15585   bool IsOrAssign = false;
15586 
15587   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15588     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15589       return;
15590 
15591     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15592 
15593     // Greylist some idioms by putting them into a warning subcategory.
15594     if (ObjCMessageExpr *ME
15595           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15596       Selector Sel = ME->getSelector();
15597 
15598       // self = [<foo> init...]
15599       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15600         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15601 
15602       // <foo> = [<bar> nextObject]
15603       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15604         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15605     }
15606 
15607     Loc = Op->getOperatorLoc();
15608   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15609     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15610       return;
15611 
15612     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15613     Loc = Op->getOperatorLoc();
15614   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15615     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15616   else {
15617     // Not an assignment.
15618     return;
15619   }
15620 
15621   Diag(Loc, diagnostic) << E->getSourceRange();
15622 
15623   SourceLocation Open = E->getLocStart();
15624   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15625   Diag(Loc, diag::note_condition_assign_silence)
15626         << FixItHint::CreateInsertion(Open, "(")
15627         << FixItHint::CreateInsertion(Close, ")");
15628 
15629   if (IsOrAssign)
15630     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15631       << FixItHint::CreateReplacement(Loc, "!=");
15632   else
15633     Diag(Loc, diag::note_condition_assign_to_comparison)
15634       << FixItHint::CreateReplacement(Loc, "==");
15635 }
15636 
15637 /// Redundant parentheses over an equality comparison can indicate
15638 /// that the user intended an assignment used as condition.
15639 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15640   // Don't warn if the parens came from a macro.
15641   SourceLocation parenLoc = ParenE->getLocStart();
15642   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15643     return;
15644   // Don't warn for dependent expressions.
15645   if (ParenE->isTypeDependent())
15646     return;
15647 
15648   Expr *E = ParenE->IgnoreParens();
15649 
15650   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15651     if (opE->getOpcode() == BO_EQ &&
15652         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15653                                                            == Expr::MLV_Valid) {
15654       SourceLocation Loc = opE->getOperatorLoc();
15655 
15656       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15657       SourceRange ParenERange = ParenE->getSourceRange();
15658       Diag(Loc, diag::note_equality_comparison_silence)
15659         << FixItHint::CreateRemoval(ParenERange.getBegin())
15660         << FixItHint::CreateRemoval(ParenERange.getEnd());
15661       Diag(Loc, diag::note_equality_comparison_to_assign)
15662         << FixItHint::CreateReplacement(Loc, "=");
15663     }
15664 }
15665 
15666 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15667                                        bool IsConstexpr) {
15668   DiagnoseAssignmentAsCondition(E);
15669   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15670     DiagnoseEqualityWithExtraParens(parenE);
15671 
15672   ExprResult result = CheckPlaceholderExpr(E);
15673   if (result.isInvalid()) return ExprError();
15674   E = result.get();
15675 
15676   if (!E->isTypeDependent()) {
15677     if (getLangOpts().CPlusPlus)
15678       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15679 
15680     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15681     if (ERes.isInvalid())
15682       return ExprError();
15683     E = ERes.get();
15684 
15685     QualType T = E->getType();
15686     if (!T->isScalarType()) { // C99 6.8.4.1p1
15687       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15688         << T << E->getSourceRange();
15689       return ExprError();
15690     }
15691     CheckBoolLikeConversion(E, Loc);
15692   }
15693 
15694   return E;
15695 }
15696 
15697 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15698                                            Expr *SubExpr, ConditionKind CK) {
15699   // Empty conditions are valid in for-statements.
15700   if (!SubExpr)
15701     return ConditionResult();
15702 
15703   ExprResult Cond;
15704   switch (CK) {
15705   case ConditionKind::Boolean:
15706     Cond = CheckBooleanCondition(Loc, SubExpr);
15707     break;
15708 
15709   case ConditionKind::ConstexprIf:
15710     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15711     break;
15712 
15713   case ConditionKind::Switch:
15714     Cond = CheckSwitchCondition(Loc, SubExpr);
15715     break;
15716   }
15717   if (Cond.isInvalid())
15718     return ConditionError();
15719 
15720   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15721   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15722   if (!FullExpr.get())
15723     return ConditionError();
15724 
15725   return ConditionResult(*this, nullptr, FullExpr,
15726                          CK == ConditionKind::ConstexprIf);
15727 }
15728 
15729 namespace {
15730   /// A visitor for rebuilding a call to an __unknown_any expression
15731   /// to have an appropriate type.
15732   struct RebuildUnknownAnyFunction
15733     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15734 
15735     Sema &S;
15736 
15737     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15738 
15739     ExprResult VisitStmt(Stmt *S) {
15740       llvm_unreachable("unexpected statement!");
15741     }
15742 
15743     ExprResult VisitExpr(Expr *E) {
15744       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15745         << E->getSourceRange();
15746       return ExprError();
15747     }
15748 
15749     /// Rebuild an expression which simply semantically wraps another
15750     /// expression which it shares the type and value kind of.
15751     template <class T> ExprResult rebuildSugarExpr(T *E) {
15752       ExprResult SubResult = Visit(E->getSubExpr());
15753       if (SubResult.isInvalid()) return ExprError();
15754 
15755       Expr *SubExpr = SubResult.get();
15756       E->setSubExpr(SubExpr);
15757       E->setType(SubExpr->getType());
15758       E->setValueKind(SubExpr->getValueKind());
15759       assert(E->getObjectKind() == OK_Ordinary);
15760       return E;
15761     }
15762 
15763     ExprResult VisitParenExpr(ParenExpr *E) {
15764       return rebuildSugarExpr(E);
15765     }
15766 
15767     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15768       return rebuildSugarExpr(E);
15769     }
15770 
15771     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15772       ExprResult SubResult = Visit(E->getSubExpr());
15773       if (SubResult.isInvalid()) return ExprError();
15774 
15775       Expr *SubExpr = SubResult.get();
15776       E->setSubExpr(SubExpr);
15777       E->setType(S.Context.getPointerType(SubExpr->getType()));
15778       assert(E->getValueKind() == VK_RValue);
15779       assert(E->getObjectKind() == OK_Ordinary);
15780       return E;
15781     }
15782 
15783     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15784       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15785 
15786       E->setType(VD->getType());
15787 
15788       assert(E->getValueKind() == VK_RValue);
15789       if (S.getLangOpts().CPlusPlus &&
15790           !(isa<CXXMethodDecl>(VD) &&
15791             cast<CXXMethodDecl>(VD)->isInstance()))
15792         E->setValueKind(VK_LValue);
15793 
15794       return E;
15795     }
15796 
15797     ExprResult VisitMemberExpr(MemberExpr *E) {
15798       return resolveDecl(E, E->getMemberDecl());
15799     }
15800 
15801     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15802       return resolveDecl(E, E->getDecl());
15803     }
15804   };
15805 }
15806 
15807 /// Given a function expression of unknown-any type, try to rebuild it
15808 /// to have a function type.
15809 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15810   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15811   if (Result.isInvalid()) return ExprError();
15812   return S.DefaultFunctionArrayConversion(Result.get());
15813 }
15814 
15815 namespace {
15816   /// A visitor for rebuilding an expression of type __unknown_anytype
15817   /// into one which resolves the type directly on the referring
15818   /// expression.  Strict preservation of the original source
15819   /// structure is not a goal.
15820   struct RebuildUnknownAnyExpr
15821     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15822 
15823     Sema &S;
15824 
15825     /// The current destination type.
15826     QualType DestType;
15827 
15828     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15829       : S(S), DestType(CastType) {}
15830 
15831     ExprResult VisitStmt(Stmt *S) {
15832       llvm_unreachable("unexpected statement!");
15833     }
15834 
15835     ExprResult VisitExpr(Expr *E) {
15836       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15837         << E->getSourceRange();
15838       return ExprError();
15839     }
15840 
15841     ExprResult VisitCallExpr(CallExpr *E);
15842     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15843 
15844     /// Rebuild an expression which simply semantically wraps another
15845     /// expression which it shares the type and value kind of.
15846     template <class T> ExprResult rebuildSugarExpr(T *E) {
15847       ExprResult SubResult = Visit(E->getSubExpr());
15848       if (SubResult.isInvalid()) return ExprError();
15849       Expr *SubExpr = SubResult.get();
15850       E->setSubExpr(SubExpr);
15851       E->setType(SubExpr->getType());
15852       E->setValueKind(SubExpr->getValueKind());
15853       assert(E->getObjectKind() == OK_Ordinary);
15854       return E;
15855     }
15856 
15857     ExprResult VisitParenExpr(ParenExpr *E) {
15858       return rebuildSugarExpr(E);
15859     }
15860 
15861     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15862       return rebuildSugarExpr(E);
15863     }
15864 
15865     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15866       const PointerType *Ptr = DestType->getAs<PointerType>();
15867       if (!Ptr) {
15868         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15869           << E->getSourceRange();
15870         return ExprError();
15871       }
15872 
15873       if (isa<CallExpr>(E->getSubExpr())) {
15874         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15875           << E->getSourceRange();
15876         return ExprError();
15877       }
15878 
15879       assert(E->getValueKind() == VK_RValue);
15880       assert(E->getObjectKind() == OK_Ordinary);
15881       E->setType(DestType);
15882 
15883       // Build the sub-expression as if it were an object of the pointee type.
15884       DestType = Ptr->getPointeeType();
15885       ExprResult SubResult = Visit(E->getSubExpr());
15886       if (SubResult.isInvalid()) return ExprError();
15887       E->setSubExpr(SubResult.get());
15888       return E;
15889     }
15890 
15891     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15892 
15893     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15894 
15895     ExprResult VisitMemberExpr(MemberExpr *E) {
15896       return resolveDecl(E, E->getMemberDecl());
15897     }
15898 
15899     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15900       return resolveDecl(E, E->getDecl());
15901     }
15902   };
15903 }
15904 
15905 /// Rebuilds a call expression which yielded __unknown_anytype.
15906 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15907   Expr *CalleeExpr = E->getCallee();
15908 
15909   enum FnKind {
15910     FK_MemberFunction,
15911     FK_FunctionPointer,
15912     FK_BlockPointer
15913   };
15914 
15915   FnKind Kind;
15916   QualType CalleeType = CalleeExpr->getType();
15917   if (CalleeType == S.Context.BoundMemberTy) {
15918     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15919     Kind = FK_MemberFunction;
15920     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15921   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15922     CalleeType = Ptr->getPointeeType();
15923     Kind = FK_FunctionPointer;
15924   } else {
15925     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15926     Kind = FK_BlockPointer;
15927   }
15928   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15929 
15930   // Verify that this is a legal result type of a function.
15931   if (DestType->isArrayType() || DestType->isFunctionType()) {
15932     unsigned diagID = diag::err_func_returning_array_function;
15933     if (Kind == FK_BlockPointer)
15934       diagID = diag::err_block_returning_array_function;
15935 
15936     S.Diag(E->getExprLoc(), diagID)
15937       << DestType->isFunctionType() << DestType;
15938     return ExprError();
15939   }
15940 
15941   // Otherwise, go ahead and set DestType as the call's result.
15942   E->setType(DestType.getNonLValueExprType(S.Context));
15943   E->setValueKind(Expr::getValueKindForType(DestType));
15944   assert(E->getObjectKind() == OK_Ordinary);
15945 
15946   // Rebuild the function type, replacing the result type with DestType.
15947   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15948   if (Proto) {
15949     // __unknown_anytype(...) is a special case used by the debugger when
15950     // it has no idea what a function's signature is.
15951     //
15952     // We want to build this call essentially under the K&R
15953     // unprototyped rules, but making a FunctionNoProtoType in C++
15954     // would foul up all sorts of assumptions.  However, we cannot
15955     // simply pass all arguments as variadic arguments, nor can we
15956     // portably just call the function under a non-variadic type; see
15957     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15958     // However, it turns out that in practice it is generally safe to
15959     // call a function declared as "A foo(B,C,D);" under the prototype
15960     // "A foo(B,C,D,...);".  The only known exception is with the
15961     // Windows ABI, where any variadic function is implicitly cdecl
15962     // regardless of its normal CC.  Therefore we change the parameter
15963     // types to match the types of the arguments.
15964     //
15965     // This is a hack, but it is far superior to moving the
15966     // corresponding target-specific code from IR-gen to Sema/AST.
15967 
15968     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15969     SmallVector<QualType, 8> ArgTypes;
15970     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15971       ArgTypes.reserve(E->getNumArgs());
15972       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15973         Expr *Arg = E->getArg(i);
15974         QualType ArgType = Arg->getType();
15975         if (E->isLValue()) {
15976           ArgType = S.Context.getLValueReferenceType(ArgType);
15977         } else if (E->isXValue()) {
15978           ArgType = S.Context.getRValueReferenceType(ArgType);
15979         }
15980         ArgTypes.push_back(ArgType);
15981       }
15982       ParamTypes = ArgTypes;
15983     }
15984     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15985                                          Proto->getExtProtoInfo());
15986   } else {
15987     DestType = S.Context.getFunctionNoProtoType(DestType,
15988                                                 FnType->getExtInfo());
15989   }
15990 
15991   // Rebuild the appropriate pointer-to-function type.
15992   switch (Kind) {
15993   case FK_MemberFunction:
15994     // Nothing to do.
15995     break;
15996 
15997   case FK_FunctionPointer:
15998     DestType = S.Context.getPointerType(DestType);
15999     break;
16000 
16001   case FK_BlockPointer:
16002     DestType = S.Context.getBlockPointerType(DestType);
16003     break;
16004   }
16005 
16006   // Finally, we can recurse.
16007   ExprResult CalleeResult = Visit(CalleeExpr);
16008   if (!CalleeResult.isUsable()) return ExprError();
16009   E->setCallee(CalleeResult.get());
16010 
16011   // Bind a temporary if necessary.
16012   return S.MaybeBindToTemporary(E);
16013 }
16014 
16015 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
16016   // Verify that this is a legal result type of a call.
16017   if (DestType->isArrayType() || DestType->isFunctionType()) {
16018     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
16019       << DestType->isFunctionType() << DestType;
16020     return ExprError();
16021   }
16022 
16023   // Rewrite the method result type if available.
16024   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
16025     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
16026     Method->setReturnType(DestType);
16027   }
16028 
16029   // Change the type of the message.
16030   E->setType(DestType.getNonReferenceType());
16031   E->setValueKind(Expr::getValueKindForType(DestType));
16032 
16033   return S.MaybeBindToTemporary(E);
16034 }
16035 
16036 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
16037   // The only case we should ever see here is a function-to-pointer decay.
16038   if (E->getCastKind() == CK_FunctionToPointerDecay) {
16039     assert(E->getValueKind() == VK_RValue);
16040     assert(E->getObjectKind() == OK_Ordinary);
16041 
16042     E->setType(DestType);
16043 
16044     // Rebuild the sub-expression as the pointee (function) type.
16045     DestType = DestType->castAs<PointerType>()->getPointeeType();
16046 
16047     ExprResult Result = Visit(E->getSubExpr());
16048     if (!Result.isUsable()) return ExprError();
16049 
16050     E->setSubExpr(Result.get());
16051     return E;
16052   } else if (E->getCastKind() == CK_LValueToRValue) {
16053     assert(E->getValueKind() == VK_RValue);
16054     assert(E->getObjectKind() == OK_Ordinary);
16055 
16056     assert(isa<BlockPointerType>(E->getType()));
16057 
16058     E->setType(DestType);
16059 
16060     // The sub-expression has to be a lvalue reference, so rebuild it as such.
16061     DestType = S.Context.getLValueReferenceType(DestType);
16062 
16063     ExprResult Result = Visit(E->getSubExpr());
16064     if (!Result.isUsable()) return ExprError();
16065 
16066     E->setSubExpr(Result.get());
16067     return E;
16068   } else {
16069     llvm_unreachable("Unhandled cast type!");
16070   }
16071 }
16072 
16073 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
16074   ExprValueKind ValueKind = VK_LValue;
16075   QualType Type = DestType;
16076 
16077   // We know how to make this work for certain kinds of decls:
16078 
16079   //  - functions
16080   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
16081     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
16082       DestType = Ptr->getPointeeType();
16083       ExprResult Result = resolveDecl(E, VD);
16084       if (Result.isInvalid()) return ExprError();
16085       return S.ImpCastExprToType(Result.get(), Type,
16086                                  CK_FunctionToPointerDecay, VK_RValue);
16087     }
16088 
16089     if (!Type->isFunctionType()) {
16090       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
16091         << VD << E->getSourceRange();
16092       return ExprError();
16093     }
16094     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
16095       // We must match the FunctionDecl's type to the hack introduced in
16096       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
16097       // type. See the lengthy commentary in that routine.
16098       QualType FDT = FD->getType();
16099       const FunctionType *FnType = FDT->castAs<FunctionType>();
16100       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
16101       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
16102       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
16103         SourceLocation Loc = FD->getLocation();
16104         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
16105                                       FD->getDeclContext(),
16106                                       Loc, Loc, FD->getNameInfo().getName(),
16107                                       DestType, FD->getTypeSourceInfo(),
16108                                       SC_None, false/*isInlineSpecified*/,
16109                                       FD->hasPrototype(),
16110                                       false/*isConstexprSpecified*/);
16111 
16112         if (FD->getQualifier())
16113           NewFD->setQualifierInfo(FD->getQualifierLoc());
16114 
16115         SmallVector<ParmVarDecl*, 16> Params;
16116         for (const auto &AI : FT->param_types()) {
16117           ParmVarDecl *Param =
16118             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
16119           Param->setScopeInfo(0, Params.size());
16120           Params.push_back(Param);
16121         }
16122         NewFD->setParams(Params);
16123         DRE->setDecl(NewFD);
16124         VD = DRE->getDecl();
16125       }
16126     }
16127 
16128     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
16129       if (MD->isInstance()) {
16130         ValueKind = VK_RValue;
16131         Type = S.Context.BoundMemberTy;
16132       }
16133 
16134     // Function references aren't l-values in C.
16135     if (!S.getLangOpts().CPlusPlus)
16136       ValueKind = VK_RValue;
16137 
16138   //  - variables
16139   } else if (isa<VarDecl>(VD)) {
16140     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
16141       Type = RefTy->getPointeeType();
16142     } else if (Type->isFunctionType()) {
16143       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
16144         << VD << E->getSourceRange();
16145       return ExprError();
16146     }
16147 
16148   //  - nothing else
16149   } else {
16150     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
16151       << VD << E->getSourceRange();
16152     return ExprError();
16153   }
16154 
16155   // Modifying the declaration like this is friendly to IR-gen but
16156   // also really dangerous.
16157   VD->setType(DestType);
16158   E->setType(Type);
16159   E->setValueKind(ValueKind);
16160   return E;
16161 }
16162 
16163 /// Check a cast of an unknown-any type.  We intentionally only
16164 /// trigger this for C-style casts.
16165 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
16166                                      Expr *CastExpr, CastKind &CastKind,
16167                                      ExprValueKind &VK, CXXCastPath &Path) {
16168   // The type we're casting to must be either void or complete.
16169   if (!CastType->isVoidType() &&
16170       RequireCompleteType(TypeRange.getBegin(), CastType,
16171                           diag::err_typecheck_cast_to_incomplete))
16172     return ExprError();
16173 
16174   // Rewrite the casted expression from scratch.
16175   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
16176   if (!result.isUsable()) return ExprError();
16177 
16178   CastExpr = result.get();
16179   VK = CastExpr->getValueKind();
16180   CastKind = CK_NoOp;
16181 
16182   return CastExpr;
16183 }
16184 
16185 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
16186   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
16187 }
16188 
16189 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
16190                                     Expr *arg, QualType &paramType) {
16191   // If the syntactic form of the argument is not an explicit cast of
16192   // any sort, just do default argument promotion.
16193   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
16194   if (!castArg) {
16195     ExprResult result = DefaultArgumentPromotion(arg);
16196     if (result.isInvalid()) return ExprError();
16197     paramType = result.get()->getType();
16198     return result;
16199   }
16200 
16201   // Otherwise, use the type that was written in the explicit cast.
16202   assert(!arg->hasPlaceholderType());
16203   paramType = castArg->getTypeAsWritten();
16204 
16205   // Copy-initialize a parameter of that type.
16206   InitializedEntity entity =
16207     InitializedEntity::InitializeParameter(Context, paramType,
16208                                            /*consumed*/ false);
16209   return PerformCopyInitialization(entity, callLoc, arg);
16210 }
16211 
16212 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16213   Expr *orig = E;
16214   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16215   while (true) {
16216     E = E->IgnoreParenImpCasts();
16217     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16218       E = call->getCallee();
16219       diagID = diag::err_uncasted_call_of_unknown_any;
16220     } else {
16221       break;
16222     }
16223   }
16224 
16225   SourceLocation loc;
16226   NamedDecl *d;
16227   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16228     loc = ref->getLocation();
16229     d = ref->getDecl();
16230   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16231     loc = mem->getMemberLoc();
16232     d = mem->getMemberDecl();
16233   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16234     diagID = diag::err_uncasted_call_of_unknown_any;
16235     loc = msg->getSelectorStartLoc();
16236     d = msg->getMethodDecl();
16237     if (!d) {
16238       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16239         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16240         << orig->getSourceRange();
16241       return ExprError();
16242     }
16243   } else {
16244     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16245       << E->getSourceRange();
16246     return ExprError();
16247   }
16248 
16249   S.Diag(loc, diagID) << d << orig->getSourceRange();
16250 
16251   // Never recoverable.
16252   return ExprError();
16253 }
16254 
16255 /// Check for operands with placeholder types and complain if found.
16256 /// Returns ExprError() if there was an error and no recovery was possible.
16257 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16258   if (!getLangOpts().CPlusPlus) {
16259     // C cannot handle TypoExpr nodes on either side of a binop because it
16260     // doesn't handle dependent types properly, so make sure any TypoExprs have
16261     // been dealt with before checking the operands.
16262     ExprResult Result = CorrectDelayedTyposInExpr(E);
16263     if (!Result.isUsable()) return ExprError();
16264     E = Result.get();
16265   }
16266 
16267   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16268   if (!placeholderType) return E;
16269 
16270   switch (placeholderType->getKind()) {
16271 
16272   // Overloaded expressions.
16273   case BuiltinType::Overload: {
16274     // Try to resolve a single function template specialization.
16275     // This is obligatory.
16276     ExprResult Result = E;
16277     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16278       return Result;
16279 
16280     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16281     // leaves Result unchanged on failure.
16282     Result = E;
16283     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16284       return Result;
16285 
16286     // If that failed, try to recover with a call.
16287     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16288                          /*complain*/ true);
16289     return Result;
16290   }
16291 
16292   // Bound member functions.
16293   case BuiltinType::BoundMember: {
16294     ExprResult result = E;
16295     const Expr *BME = E->IgnoreParens();
16296     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16297     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16298     if (isa<CXXPseudoDestructorExpr>(BME)) {
16299       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16300     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16301       if (ME->getMemberNameInfo().getName().getNameKind() ==
16302           DeclarationName::CXXDestructorName)
16303         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16304     }
16305     tryToRecoverWithCall(result, PD,
16306                          /*complain*/ true);
16307     return result;
16308   }
16309 
16310   // ARC unbridged casts.
16311   case BuiltinType::ARCUnbridgedCast: {
16312     Expr *realCast = stripARCUnbridgedCast(E);
16313     diagnoseARCUnbridgedCast(realCast);
16314     return realCast;
16315   }
16316 
16317   // Expressions of unknown type.
16318   case BuiltinType::UnknownAny:
16319     return diagnoseUnknownAnyExpr(*this, E);
16320 
16321   // Pseudo-objects.
16322   case BuiltinType::PseudoObject:
16323     return checkPseudoObjectRValue(E);
16324 
16325   case BuiltinType::BuiltinFn: {
16326     // Accept __noop without parens by implicitly converting it to a call expr.
16327     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16328     if (DRE) {
16329       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16330       if (FD->getBuiltinID() == Builtin::BI__noop) {
16331         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16332                               CK_BuiltinFnToFnPtr).get();
16333         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16334                                       VK_RValue, SourceLocation());
16335       }
16336     }
16337 
16338     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16339     return ExprError();
16340   }
16341 
16342   // Expressions of unknown type.
16343   case BuiltinType::OMPArraySection:
16344     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16345     return ExprError();
16346 
16347   // Everything else should be impossible.
16348 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16349   case BuiltinType::Id:
16350 #include "clang/Basic/OpenCLImageTypes.def"
16351 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16352 #define PLACEHOLDER_TYPE(Id, SingletonId)
16353 #include "clang/AST/BuiltinTypes.def"
16354     break;
16355   }
16356 
16357   llvm_unreachable("invalid placeholder type!");
16358 }
16359 
16360 bool Sema::CheckCaseExpression(Expr *E) {
16361   if (E->isTypeDependent())
16362     return true;
16363   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16364     return E->getType()->isIntegralOrEnumerationType();
16365   return false;
16366 }
16367 
16368 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16369 ExprResult
16370 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16371   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16372          "Unknown Objective-C Boolean value!");
16373   QualType BoolT = Context.ObjCBuiltinBoolTy;
16374   if (!Context.getBOOLDecl()) {
16375     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16376                         Sema::LookupOrdinaryName);
16377     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16378       NamedDecl *ND = Result.getFoundDecl();
16379       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16380         Context.setBOOLDecl(TD);
16381     }
16382   }
16383   if (Context.getBOOLDecl())
16384     BoolT = Context.getBOOLType();
16385   return new (Context)
16386       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16387 }
16388 
16389 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16390     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16391     SourceLocation RParen) {
16392 
16393   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16394 
16395   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16396                            [&](const AvailabilitySpec &Spec) {
16397                              return Spec.getPlatform() == Platform;
16398                            });
16399 
16400   VersionTuple Version;
16401   if (Spec != AvailSpecs.end())
16402     Version = Spec->getVersion();
16403 
16404   // The use of `@available` in the enclosing function should be analyzed to
16405   // warn when it's used inappropriately (i.e. not if(@available)).
16406   if (getCurFunctionOrMethodDecl())
16407     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16408   else if (getCurBlock() || getCurLambda())
16409     getCurFunction()->HasPotentialAvailabilityViolations = true;
16410 
16411   return new (Context)
16412       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16413 }
16414