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/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/SemaInternal.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/Support/ConvertUTF.h"
47 using namespace clang;
48 using namespace sema;
49 
50 /// \brief Determine whether the use of this declaration is valid, without
51 /// emitting diagnostics.
52 bool Sema::CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid) {
53   // See if this is an auto-typed variable whose initializer we are parsing.
54   if (ParsingInitForAutoVars.count(D))
55     return false;
56 
57   // See if this is a deleted function.
58   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
59     if (FD->isDeleted())
60       return false;
61 
62     // If the function has a deduced return type, and we can't deduce it,
63     // then we can't use it either.
64     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
65         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
66       return false;
67   }
68 
69   // See if this function is unavailable.
70   if (TreatUnavailableAsInvalid && D->getAvailability() == AR_Unavailable &&
71       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
72     return false;
73 
74   return true;
75 }
76 
77 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
78   // Warn if this is used but marked unused.
79   if (const auto *A = D->getAttr<UnusedAttr>()) {
80     // [[maybe_unused]] should not diagnose uses, but __attribute__((unused))
81     // should diagnose them.
82     if (A->getSemanticSpelling() != UnusedAttr::CXX11_maybe_unused &&
83         A->getSemanticSpelling() != UnusedAttr::C2x_maybe_unused) {
84       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
85       if (DC && !DC->hasAttr<UnusedAttr>())
86         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
87     }
88   }
89 }
90 
91 /// \brief Emit a note explaining that this function is deleted.
92 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
93   assert(Decl->isDeleted());
94 
95   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
96 
97   if (Method && Method->isDeleted() && Method->isDefaulted()) {
98     // If the method was explicitly defaulted, point at that declaration.
99     if (!Method->isImplicit())
100       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
101 
102     // Try to diagnose why this special member function was implicitly
103     // deleted. This might fail, if that reason no longer applies.
104     CXXSpecialMember CSM = getSpecialMember(Method);
105     if (CSM != CXXInvalid)
106       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
107 
108     return;
109   }
110 
111   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
112   if (Ctor && Ctor->isInheritingConstructor())
113     return NoteDeletedInheritingConstructor(Ctor);
114 
115   Diag(Decl->getLocation(), diag::note_availability_specified_here)
116     << Decl << true;
117 }
118 
119 /// \brief Determine whether a FunctionDecl was ever declared with an
120 /// explicit storage class.
121 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
122   for (auto I : D->redecls()) {
123     if (I->getStorageClass() != SC_None)
124       return true;
125   }
126   return false;
127 }
128 
129 /// \brief Check whether we're in an extern inline function and referring to a
130 /// variable or function with internal linkage (C11 6.7.4p3).
131 ///
132 /// This is only a warning because we used to silently accept this code, but
133 /// in many cases it will not behave correctly. This is not enabled in C++ mode
134 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
135 /// and so while there may still be user mistakes, most of the time we can't
136 /// prove that there are errors.
137 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
138                                                       const NamedDecl *D,
139                                                       SourceLocation Loc) {
140   // This is disabled under C++; there are too many ways for this to fire in
141   // contexts where the warning is a false positive, or where it is technically
142   // correct but benign.
143   if (S.getLangOpts().CPlusPlus)
144     return;
145 
146   // Check if this is an inlined function or method.
147   FunctionDecl *Current = S.getCurFunctionDecl();
148   if (!Current)
149     return;
150   if (!Current->isInlined())
151     return;
152   if (!Current->isExternallyVisible())
153     return;
154 
155   // Check if the decl has internal linkage.
156   if (D->getFormalLinkage() != InternalLinkage)
157     return;
158 
159   // Downgrade from ExtWarn to Extension if
160   //  (1) the supposedly external inline function is in the main file,
161   //      and probably won't be included anywhere else.
162   //  (2) the thing we're referencing is a pure function.
163   //  (3) the thing we're referencing is another inline function.
164   // This last can give us false negatives, but it's better than warning on
165   // wrappers for simple C library functions.
166   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
167   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
168   if (!DowngradeWarning && UsedFn)
169     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
170 
171   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
172                                : diag::ext_internal_in_extern_inline)
173     << /*IsVar=*/!UsedFn << D;
174 
175   S.MaybeSuggestAddingStaticToDecl(Current);
176 
177   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
178       << D;
179 }
180 
181 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
182   const FunctionDecl *First = Cur->getFirstDecl();
183 
184   // Suggest "static" on the function, if possible.
185   if (!hasAnyExplicitStorageClass(First)) {
186     SourceLocation DeclBegin = First->getSourceRange().getBegin();
187     Diag(DeclBegin, diag::note_convert_inline_to_static)
188       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
189   }
190 }
191 
192 /// \brief Determine whether the use of this declaration is valid, and
193 /// emit any corresponding diagnostics.
194 ///
195 /// This routine diagnoses various problems with referencing
196 /// declarations that can occur when using a declaration. For example,
197 /// it might warn if a deprecated or unavailable declaration is being
198 /// used, or produce an error (and return true) if a C++0x deleted
199 /// function is being used.
200 ///
201 /// \returns true if there was an error (this declaration cannot be
202 /// referenced), false otherwise.
203 ///
204 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs,
205                              const ObjCInterfaceDecl *UnknownObjCClass,
206                              bool ObjCPropertyAccess,
207                              bool AvoidPartialAvailabilityChecks) {
208   SourceLocation Loc = Locs.front();
209   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
210     // If there were any diagnostics suppressed by template argument deduction,
211     // emit them now.
212     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
213     if (Pos != SuppressedDiagnostics.end()) {
214       for (const PartialDiagnosticAt &Suppressed : Pos->second)
215         Diag(Suppressed.first, Suppressed.second);
216 
217       // Clear out the list of suppressed diagnostics, so that we don't emit
218       // them again for this specialization. However, we don't obsolete this
219       // entry from the table, because we want to avoid ever emitting these
220       // diagnostics again.
221       Pos->second.clear();
222     }
223 
224     // C++ [basic.start.main]p3:
225     //   The function 'main' shall not be used within a program.
226     if (cast<FunctionDecl>(D)->isMain())
227       Diag(Loc, diag::ext_main_used);
228   }
229 
230   // See if this is an auto-typed variable whose initializer we are parsing.
231   if (ParsingInitForAutoVars.count(D)) {
232     if (isa<BindingDecl>(D)) {
233       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
234         << D->getDeclName();
235     } else {
236       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
237         << D->getDeclName() << cast<VarDecl>(D)->getType();
238     }
239     return true;
240   }
241 
242   // See if this is a deleted function.
243   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
244     if (FD->isDeleted()) {
245       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
246       if (Ctor && Ctor->isInheritingConstructor())
247         Diag(Loc, diag::err_deleted_inherited_ctor_use)
248             << Ctor->getParent()
249             << Ctor->getInheritedConstructor().getConstructor()->getParent();
250       else
251         Diag(Loc, diag::err_deleted_function_use);
252       NoteDeletedFunction(FD);
253       return true;
254     }
255 
256     // If the function has a deduced return type, and we can't deduce it,
257     // then we can't use it either.
258     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
259         DeduceReturnType(FD, Loc))
260       return true;
261 
262     if (getLangOpts().CUDA && !CheckCUDACall(Loc, FD))
263       return true;
264   }
265 
266   auto getReferencedObjCProp = [](const NamedDecl *D) ->
267                                       const ObjCPropertyDecl * {
268     if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
269       return MD->findPropertyDecl();
270     return nullptr;
271   };
272   if (const ObjCPropertyDecl *ObjCPDecl = getReferencedObjCProp(D)) {
273     if (diagnoseArgIndependentDiagnoseIfAttrs(ObjCPDecl, Loc))
274       return true;
275   } else if (diagnoseArgIndependentDiagnoseIfAttrs(D, Loc)) {
276       return true;
277   }
278 
279   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
280   // Only the variables omp_in and omp_out are allowed in the combiner.
281   // Only the variables omp_priv and omp_orig are allowed in the
282   // initializer-clause.
283   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
284   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
285       isa<VarDecl>(D)) {
286     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
287         << getCurFunction()->HasOMPDeclareReductionCombiner;
288     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
289     return true;
290   }
291 
292   DiagnoseAvailabilityOfDecl(D, Locs, UnknownObjCClass, ObjCPropertyAccess,
293                              AvoidPartialAvailabilityChecks);
294 
295   DiagnoseUnusedOfDecl(*this, D, Loc);
296 
297   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
298 
299   return false;
300 }
301 
302 /// \brief Retrieve the message suffix that should be added to a
303 /// diagnostic complaining about the given function being deleted or
304 /// unavailable.
305 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
306   std::string Message;
307   if (FD->getAvailability(&Message))
308     return ": " + Message;
309 
310   return std::string();
311 }
312 
313 /// DiagnoseSentinelCalls - This routine checks whether a call or
314 /// message-send is to a declaration with the sentinel attribute, and
315 /// if so, it checks that the requirements of the sentinel are
316 /// satisfied.
317 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
318                                  ArrayRef<Expr *> Args) {
319   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
320   if (!attr)
321     return;
322 
323   // The number of formal parameters of the declaration.
324   unsigned numFormalParams;
325 
326   // The kind of declaration.  This is also an index into a %select in
327   // the diagnostic.
328   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
329 
330   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
331     numFormalParams = MD->param_size();
332     calleeType = CT_Method;
333   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
334     numFormalParams = FD->param_size();
335     calleeType = CT_Function;
336   } else if (isa<VarDecl>(D)) {
337     QualType type = cast<ValueDecl>(D)->getType();
338     const FunctionType *fn = nullptr;
339     if (const PointerType *ptr = type->getAs<PointerType>()) {
340       fn = ptr->getPointeeType()->getAs<FunctionType>();
341       if (!fn) return;
342       calleeType = CT_Function;
343     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
344       fn = ptr->getPointeeType()->castAs<FunctionType>();
345       calleeType = CT_Block;
346     } else {
347       return;
348     }
349 
350     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
351       numFormalParams = proto->getNumParams();
352     } else {
353       numFormalParams = 0;
354     }
355   } else {
356     return;
357   }
358 
359   // "nullPos" is the number of formal parameters at the end which
360   // effectively count as part of the variadic arguments.  This is
361   // useful if you would prefer to not have *any* formal parameters,
362   // but the language forces you to have at least one.
363   unsigned nullPos = attr->getNullPos();
364   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
365   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
366 
367   // The number of arguments which should follow the sentinel.
368   unsigned numArgsAfterSentinel = attr->getSentinel();
369 
370   // If there aren't enough arguments for all the formal parameters,
371   // the sentinel, and the args after the sentinel, complain.
372   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
373     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
374     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
375     return;
376   }
377 
378   // Otherwise, find the sentinel expression.
379   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
380   if (!sentinelExpr) return;
381   if (sentinelExpr->isValueDependent()) return;
382   if (Context.isSentinelNullExpr(sentinelExpr)) return;
383 
384   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
385   // or 'NULL' if those are actually defined in the context.  Only use
386   // 'nil' for ObjC methods, where it's much more likely that the
387   // variadic arguments form a list of object pointers.
388   SourceLocation MissingNilLoc
389     = getLocForEndOfToken(sentinelExpr->getLocEnd());
390   std::string NullValue;
391   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
392     NullValue = "nil";
393   else if (getLangOpts().CPlusPlus11)
394     NullValue = "nullptr";
395   else if (PP.isMacroDefined("NULL"))
396     NullValue = "NULL";
397   else
398     NullValue = "(void*) 0";
399 
400   if (MissingNilLoc.isInvalid())
401     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
402   else
403     Diag(MissingNilLoc, diag::warn_missing_sentinel)
404       << int(calleeType)
405       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
406   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
407 }
408 
409 SourceRange Sema::getExprRange(Expr *E) const {
410   return E ? E->getSourceRange() : SourceRange();
411 }
412 
413 //===----------------------------------------------------------------------===//
414 //  Standard Promotions and Conversions
415 //===----------------------------------------------------------------------===//
416 
417 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
418 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
419   // Handle any placeholder expressions which made it here.
420   if (E->getType()->isPlaceholderType()) {
421     ExprResult result = CheckPlaceholderExpr(E);
422     if (result.isInvalid()) return ExprError();
423     E = result.get();
424   }
425 
426   QualType Ty = E->getType();
427   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
428 
429   if (Ty->isFunctionType()) {
430     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
431       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
432         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
433           return ExprError();
434 
435     E = ImpCastExprToType(E, Context.getPointerType(Ty),
436                           CK_FunctionToPointerDecay).get();
437   } else if (Ty->isArrayType()) {
438     // In C90 mode, arrays only promote to pointers if the array expression is
439     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
440     // type 'array of type' is converted to an expression that has type 'pointer
441     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
442     // that has type 'array of type' ...".  The relevant change is "an lvalue"
443     // (C90) to "an expression" (C99).
444     //
445     // C++ 4.2p1:
446     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
447     // T" can be converted to an rvalue of type "pointer to T".
448     //
449     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
450       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
451                             CK_ArrayToPointerDecay).get();
452   }
453   return E;
454 }
455 
456 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
457   // Check to see if we are dereferencing a null pointer.  If so,
458   // and if not volatile-qualified, this is undefined behavior that the
459   // optimizer will delete, so warn about it.  People sometimes try to use this
460   // to get a deterministic trap and are surprised by clang's behavior.  This
461   // only handles the pattern "*null", which is a very syntactic check.
462   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
463     if (UO->getOpcode() == UO_Deref &&
464         UO->getSubExpr()->IgnoreParenCasts()->
465           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
466         !UO->getType().isVolatileQualified()) {
467     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
468                           S.PDiag(diag::warn_indirection_through_null)
469                             << UO->getSubExpr()->getSourceRange());
470     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
471                         S.PDiag(diag::note_indirection_through_null));
472   }
473 }
474 
475 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
476                                     SourceLocation AssignLoc,
477                                     const Expr* RHS) {
478   const ObjCIvarDecl *IV = OIRE->getDecl();
479   if (!IV)
480     return;
481 
482   DeclarationName MemberName = IV->getDeclName();
483   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
484   if (!Member || !Member->isStr("isa"))
485     return;
486 
487   const Expr *Base = OIRE->getBase();
488   QualType BaseType = Base->getType();
489   if (OIRE->isArrow())
490     BaseType = BaseType->getPointeeType();
491   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
492     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
493       ObjCInterfaceDecl *ClassDeclared = nullptr;
494       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
495       if (!ClassDeclared->getSuperClass()
496           && (*ClassDeclared->ivar_begin()) == IV) {
497         if (RHS) {
498           NamedDecl *ObjectSetClass =
499             S.LookupSingleName(S.TUScope,
500                                &S.Context.Idents.get("object_setClass"),
501                                SourceLocation(), S.LookupOrdinaryName);
502           if (ObjectSetClass) {
503             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
504             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
505             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
506             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
507                                                      AssignLoc), ",") <<
508             FixItHint::CreateInsertion(RHSLocEnd, ")");
509           }
510           else
511             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
512         } else {
513           NamedDecl *ObjectGetClass =
514             S.LookupSingleName(S.TUScope,
515                                &S.Context.Idents.get("object_getClass"),
516                                SourceLocation(), S.LookupOrdinaryName);
517           if (ObjectGetClass)
518             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
519             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
520             FixItHint::CreateReplacement(
521                                          SourceRange(OIRE->getOpLoc(),
522                                                      OIRE->getLocEnd()), ")");
523           else
524             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
525         }
526         S.Diag(IV->getLocation(), diag::note_ivar_decl);
527       }
528     }
529 }
530 
531 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
532   // Handle any placeholder expressions which made it here.
533   if (E->getType()->isPlaceholderType()) {
534     ExprResult result = CheckPlaceholderExpr(E);
535     if (result.isInvalid()) return ExprError();
536     E = result.get();
537   }
538 
539   // C++ [conv.lval]p1:
540   //   A glvalue of a non-function, non-array type T can be
541   //   converted to a prvalue.
542   if (!E->isGLValue()) return E;
543 
544   QualType T = E->getType();
545   assert(!T.isNull() && "r-value conversion on typeless expression?");
546 
547   // We don't want to throw lvalue-to-rvalue casts on top of
548   // expressions of certain types in C++.
549   if (getLangOpts().CPlusPlus &&
550       (E->getType() == Context.OverloadTy ||
551        T->isDependentType() ||
552        T->isRecordType()))
553     return E;
554 
555   // The C standard is actually really unclear on this point, and
556   // DR106 tells us what the result should be but not why.  It's
557   // generally best to say that void types just doesn't undergo
558   // lvalue-to-rvalue at all.  Note that expressions of unqualified
559   // 'void' type are never l-values, but qualified void can be.
560   if (T->isVoidType())
561     return E;
562 
563   // OpenCL usually rejects direct accesses to values of 'half' type.
564   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
565       T->isHalfType()) {
566     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
567       << 0 << T;
568     return ExprError();
569   }
570 
571   CheckForNullPointerDereference(*this, E);
572   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
573     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
574                                      &Context.Idents.get("object_getClass"),
575                                      SourceLocation(), LookupOrdinaryName);
576     if (ObjectGetClass)
577       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
578         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
579         FixItHint::CreateReplacement(
580                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
581     else
582       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
583   }
584   else if (const ObjCIvarRefExpr *OIRE =
585             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
586     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
587 
588   // C++ [conv.lval]p1:
589   //   [...] If T is a non-class type, the type of the prvalue is the
590   //   cv-unqualified version of T. Otherwise, the type of the
591   //   rvalue is T.
592   //
593   // C99 6.3.2.1p2:
594   //   If the lvalue has qualified type, the value has the unqualified
595   //   version of the type of the lvalue; otherwise, the value has the
596   //   type of the lvalue.
597   if (T.hasQualifiers())
598     T = T.getUnqualifiedType();
599 
600   // Under the MS ABI, lock down the inheritance model now.
601   if (T->isMemberPointerType() &&
602       Context.getTargetInfo().getCXXABI().isMicrosoft())
603     (void)isCompleteType(E->getExprLoc(), T);
604 
605   UpdateMarkingForLValueToRValue(E);
606 
607   // Loading a __weak object implicitly retains the value, so we need a cleanup to
608   // balance that.
609   if (E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
610     Cleanup.setExprNeedsCleanups(true);
611 
612   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
613                                             nullptr, VK_RValue);
614 
615   // C11 6.3.2.1p2:
616   //   ... if the lvalue has atomic type, the value has the non-atomic version
617   //   of the type of the lvalue ...
618   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
619     T = Atomic->getValueType().getUnqualifiedType();
620     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
621                                    nullptr, VK_RValue);
622   }
623 
624   return Res;
625 }
626 
627 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
628   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
629   if (Res.isInvalid())
630     return ExprError();
631   Res = DefaultLvalueConversion(Res.get());
632   if (Res.isInvalid())
633     return ExprError();
634   return Res;
635 }
636 
637 /// CallExprUnaryConversions - a special case of an unary conversion
638 /// performed on a function designator of a call expression.
639 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
640   QualType Ty = E->getType();
641   ExprResult Res = E;
642   // Only do implicit cast for a function type, but not for a pointer
643   // to function type.
644   if (Ty->isFunctionType()) {
645     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
646                             CK_FunctionToPointerDecay).get();
647     if (Res.isInvalid())
648       return ExprError();
649   }
650   Res = DefaultLvalueConversion(Res.get());
651   if (Res.isInvalid())
652     return ExprError();
653   return Res.get();
654 }
655 
656 /// UsualUnaryConversions - Performs various conversions that are common to most
657 /// operators (C99 6.3). The conversions of array and function types are
658 /// sometimes suppressed. For example, the array->pointer conversion doesn't
659 /// apply if the array is an argument to the sizeof or address (&) operators.
660 /// In these instances, this routine should *not* be called.
661 ExprResult Sema::UsualUnaryConversions(Expr *E) {
662   // First, convert to an r-value.
663   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
664   if (Res.isInvalid())
665     return ExprError();
666   E = Res.get();
667 
668   QualType Ty = E->getType();
669   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
670 
671   // Half FP have to be promoted to float unless it is natively supported
672   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
673     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
674 
675   // Try to perform integral promotions if the object has a theoretically
676   // promotable type.
677   if (Ty->isIntegralOrUnscopedEnumerationType()) {
678     // C99 6.3.1.1p2:
679     //
680     //   The following may be used in an expression wherever an int or
681     //   unsigned int may be used:
682     //     - an object or expression with an integer type whose integer
683     //       conversion rank is less than or equal to the rank of int
684     //       and unsigned int.
685     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
686     //
687     //   If an int can represent all values of the original type, the
688     //   value is converted to an int; otherwise, it is converted to an
689     //   unsigned int. These are called the integer promotions. All
690     //   other types are unchanged by the integer promotions.
691 
692     QualType PTy = Context.isPromotableBitField(E);
693     if (!PTy.isNull()) {
694       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
695       return E;
696     }
697     if (Ty->isPromotableIntegerType()) {
698       QualType PT = Context.getPromotedIntegerType(Ty);
699       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
700       return E;
701     }
702   }
703   return E;
704 }
705 
706 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
707 /// do not have a prototype. Arguments that have type float or __fp16
708 /// are promoted to double. All other argument types are converted by
709 /// UsualUnaryConversions().
710 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
711   QualType Ty = E->getType();
712   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
713 
714   ExprResult Res = UsualUnaryConversions(E);
715   if (Res.isInvalid())
716     return ExprError();
717   E = Res.get();
718 
719   // If this is a 'float'  or '__fp16' (CVR qualified or typedef)
720   // promote to double.
721   // Note that default argument promotion applies only to float (and
722   // half/fp16); it does not apply to _Float16.
723   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
724   if (BTy && (BTy->getKind() == BuiltinType::Half ||
725               BTy->getKind() == BuiltinType::Float)) {
726     if (getLangOpts().OpenCL &&
727         !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
728         if (BTy->getKind() == BuiltinType::Half) {
729             E = ImpCastExprToType(E, Context.FloatTy, CK_FloatingCast).get();
730         }
731     } else {
732       E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
733     }
734   }
735 
736   // C++ performs lvalue-to-rvalue conversion as a default argument
737   // promotion, even on class types, but note:
738   //   C++11 [conv.lval]p2:
739   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
740   //     operand or a subexpression thereof the value contained in the
741   //     referenced object is not accessed. Otherwise, if the glvalue
742   //     has a class type, the conversion copy-initializes a temporary
743   //     of type T from the glvalue and the result of the conversion
744   //     is a prvalue for the temporary.
745   // FIXME: add some way to gate this entire thing for correctness in
746   // potentially potentially evaluated contexts.
747   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
748     ExprResult Temp = PerformCopyInitialization(
749                        InitializedEntity::InitializeTemporary(E->getType()),
750                                                 E->getExprLoc(), E);
751     if (Temp.isInvalid())
752       return ExprError();
753     E = Temp.get();
754   }
755 
756   return E;
757 }
758 
759 /// Determine the degree of POD-ness for an expression.
760 /// Incomplete types are considered POD, since this check can be performed
761 /// when we're in an unevaluated context.
762 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
763   if (Ty->isIncompleteType()) {
764     // C++11 [expr.call]p7:
765     //   After these conversions, if the argument does not have arithmetic,
766     //   enumeration, pointer, pointer to member, or class type, the program
767     //   is ill-formed.
768     //
769     // Since we've already performed array-to-pointer and function-to-pointer
770     // decay, the only such type in C++ is cv void. This also handles
771     // initializer lists as variadic arguments.
772     if (Ty->isVoidType())
773       return VAK_Invalid;
774 
775     if (Ty->isObjCObjectType())
776       return VAK_Invalid;
777     return VAK_Valid;
778   }
779 
780   if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
781     return VAK_Invalid;
782 
783   if (Ty.isCXX98PODType(Context))
784     return VAK_Valid;
785 
786   // C++11 [expr.call]p7:
787   //   Passing a potentially-evaluated argument of class type (Clause 9)
788   //   having a non-trivial copy constructor, a non-trivial move constructor,
789   //   or a non-trivial destructor, with no corresponding parameter,
790   //   is conditionally-supported with implementation-defined semantics.
791   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
792     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
793       if (!Record->hasNonTrivialCopyConstructor() &&
794           !Record->hasNonTrivialMoveConstructor() &&
795           !Record->hasNonTrivialDestructor())
796         return VAK_ValidInCXX11;
797 
798   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
799     return VAK_Valid;
800 
801   if (Ty->isObjCObjectType())
802     return VAK_Invalid;
803 
804   if (getLangOpts().MSVCCompat)
805     return VAK_MSVCUndefined;
806 
807   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
808   // permitted to reject them. We should consider doing so.
809   return VAK_Undefined;
810 }
811 
812 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
813   // Don't allow one to pass an Objective-C interface to a vararg.
814   const QualType &Ty = E->getType();
815   VarArgKind VAK = isValidVarArgType(Ty);
816 
817   // Complain about passing non-POD types through varargs.
818   switch (VAK) {
819   case VAK_ValidInCXX11:
820     DiagRuntimeBehavior(
821         E->getLocStart(), nullptr,
822         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
823           << Ty << CT);
824     LLVM_FALLTHROUGH;
825   case VAK_Valid:
826     if (Ty->isRecordType()) {
827       // This is unlikely to be what the user intended. If the class has a
828       // 'c_str' member function, the user probably meant to call that.
829       DiagRuntimeBehavior(E->getLocStart(), nullptr,
830                           PDiag(diag::warn_pass_class_arg_to_vararg)
831                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
832     }
833     break;
834 
835   case VAK_Undefined:
836   case VAK_MSVCUndefined:
837     DiagRuntimeBehavior(
838         E->getLocStart(), nullptr,
839         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
840           << getLangOpts().CPlusPlus11 << Ty << CT);
841     break;
842 
843   case VAK_Invalid:
844     if (Ty.isDestructedType() == QualType::DK_nontrivial_c_struct)
845       Diag(E->getLocStart(),
846            diag::err_cannot_pass_non_trivial_c_struct_to_vararg) << Ty << CT;
847     else if (Ty->isObjCObjectType())
848       DiagRuntimeBehavior(
849           E->getLocStart(), nullptr,
850           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
851             << Ty << CT);
852     else
853       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
854         << isa<InitListExpr>(E) << Ty << CT;
855     break;
856   }
857 }
858 
859 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
860 /// will create a trap if the resulting type is not a POD type.
861 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
862                                                   FunctionDecl *FDecl) {
863   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
864     // Strip the unbridged-cast placeholder expression off, if applicable.
865     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
866         (CT == VariadicMethod ||
867          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
868       E = stripARCUnbridgedCast(E);
869 
870     // Otherwise, do normal placeholder checking.
871     } else {
872       ExprResult ExprRes = CheckPlaceholderExpr(E);
873       if (ExprRes.isInvalid())
874         return ExprError();
875       E = ExprRes.get();
876     }
877   }
878 
879   ExprResult ExprRes = DefaultArgumentPromotion(E);
880   if (ExprRes.isInvalid())
881     return ExprError();
882   E = ExprRes.get();
883 
884   // Diagnostics regarding non-POD argument types are
885   // emitted along with format string checking in Sema::CheckFunctionCall().
886   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
887     // Turn this into a trap.
888     CXXScopeSpec SS;
889     SourceLocation TemplateKWLoc;
890     UnqualifiedId Name;
891     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
892                        E->getLocStart());
893     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
894                                           Name, true, false);
895     if (TrapFn.isInvalid())
896       return ExprError();
897 
898     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
899                                     E->getLocStart(), None,
900                                     E->getLocEnd());
901     if (Call.isInvalid())
902       return ExprError();
903 
904     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
905                                   Call.get(), E);
906     if (Comma.isInvalid())
907       return ExprError();
908     return Comma.get();
909   }
910 
911   if (!getLangOpts().CPlusPlus &&
912       RequireCompleteType(E->getExprLoc(), E->getType(),
913                           diag::err_call_incomplete_argument))
914     return ExprError();
915 
916   return E;
917 }
918 
919 /// \brief Converts an integer to complex float type.  Helper function of
920 /// UsualArithmeticConversions()
921 ///
922 /// \return false if the integer expression is an integer type and is
923 /// successfully converted to the complex type.
924 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
925                                                   ExprResult &ComplexExpr,
926                                                   QualType IntTy,
927                                                   QualType ComplexTy,
928                                                   bool SkipCast) {
929   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
930   if (SkipCast) return false;
931   if (IntTy->isIntegerType()) {
932     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
933     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
934     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
935                                   CK_FloatingRealToComplex);
936   } else {
937     assert(IntTy->isComplexIntegerType());
938     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
939                                   CK_IntegralComplexToFloatingComplex);
940   }
941   return false;
942 }
943 
944 /// \brief Handle arithmetic conversion with complex types.  Helper function of
945 /// UsualArithmeticConversions()
946 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
947                                              ExprResult &RHS, QualType LHSType,
948                                              QualType RHSType,
949                                              bool IsCompAssign) {
950   // if we have an integer operand, the result is the complex type.
951   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
952                                              /*skipCast*/false))
953     return LHSType;
954   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
955                                              /*skipCast*/IsCompAssign))
956     return RHSType;
957 
958   // This handles complex/complex, complex/float, or float/complex.
959   // When both operands are complex, the shorter operand is converted to the
960   // type of the longer, and that is the type of the result. This corresponds
961   // to what is done when combining two real floating-point operands.
962   // The fun begins when size promotion occur across type domains.
963   // From H&S 6.3.4: When one operand is complex and the other is a real
964   // floating-point type, the less precise type is converted, within it's
965   // real or complex domain, to the precision of the other type. For example,
966   // when combining a "long double" with a "double _Complex", the
967   // "double _Complex" is promoted to "long double _Complex".
968 
969   // Compute the rank of the two types, regardless of whether they are complex.
970   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
971 
972   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
973   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
974   QualType LHSElementType =
975       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
976   QualType RHSElementType =
977       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
978 
979   QualType ResultType = S.Context.getComplexType(LHSElementType);
980   if (Order < 0) {
981     // Promote the precision of the LHS if not an assignment.
982     ResultType = S.Context.getComplexType(RHSElementType);
983     if (!IsCompAssign) {
984       if (LHSComplexType)
985         LHS =
986             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
987       else
988         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
989     }
990   } else if (Order > 0) {
991     // Promote the precision of the RHS.
992     if (RHSComplexType)
993       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
994     else
995       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
996   }
997   return ResultType;
998 }
999 
1000 /// \brief Handle arithmetic conversion from integer to float.  Helper function
1001 /// of UsualArithmeticConversions()
1002 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1003                                            ExprResult &IntExpr,
1004                                            QualType FloatTy, QualType IntTy,
1005                                            bool ConvertFloat, bool ConvertInt) {
1006   if (IntTy->isIntegerType()) {
1007     if (ConvertInt)
1008       // Convert intExpr to the lhs floating point type.
1009       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1010                                     CK_IntegralToFloating);
1011     return FloatTy;
1012   }
1013 
1014   // Convert both sides to the appropriate complex float.
1015   assert(IntTy->isComplexIntegerType());
1016   QualType result = S.Context.getComplexType(FloatTy);
1017 
1018   // _Complex int -> _Complex float
1019   if (ConvertInt)
1020     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1021                                   CK_IntegralComplexToFloatingComplex);
1022 
1023   // float -> _Complex float
1024   if (ConvertFloat)
1025     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1026                                     CK_FloatingRealToComplex);
1027 
1028   return result;
1029 }
1030 
1031 /// \brief Handle arithmethic conversion with floating point types.  Helper
1032 /// function of UsualArithmeticConversions()
1033 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1034                                       ExprResult &RHS, QualType LHSType,
1035                                       QualType RHSType, bool IsCompAssign) {
1036   bool LHSFloat = LHSType->isRealFloatingType();
1037   bool RHSFloat = RHSType->isRealFloatingType();
1038 
1039   // If we have two real floating types, convert the smaller operand
1040   // to the bigger result.
1041   if (LHSFloat && RHSFloat) {
1042     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1043     if (order > 0) {
1044       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1045       return LHSType;
1046     }
1047 
1048     assert(order < 0 && "illegal float comparison");
1049     if (!IsCompAssign)
1050       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1051     return RHSType;
1052   }
1053 
1054   if (LHSFloat) {
1055     // Half FP has to be promoted to float unless it is natively supported
1056     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1057       LHSType = S.Context.FloatTy;
1058 
1059     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1060                                       /*convertFloat=*/!IsCompAssign,
1061                                       /*convertInt=*/ true);
1062   }
1063   assert(RHSFloat);
1064   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1065                                     /*convertInt=*/ true,
1066                                     /*convertFloat=*/!IsCompAssign);
1067 }
1068 
1069 /// \brief Diagnose attempts to convert between __float128 and long double if
1070 /// there is no support for such conversion. Helper function of
1071 /// UsualArithmeticConversions().
1072 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1073                                       QualType RHSType) {
1074   /*  No issue converting if at least one of the types is not a floating point
1075       type or the two types have the same rank.
1076   */
1077   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1078       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1079     return false;
1080 
1081   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1082          "The remaining types must be floating point types.");
1083 
1084   auto *LHSComplex = LHSType->getAs<ComplexType>();
1085   auto *RHSComplex = RHSType->getAs<ComplexType>();
1086 
1087   QualType LHSElemType = LHSComplex ?
1088     LHSComplex->getElementType() : LHSType;
1089   QualType RHSElemType = RHSComplex ?
1090     RHSComplex->getElementType() : RHSType;
1091 
1092   // No issue if the two types have the same representation
1093   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1094       &S.Context.getFloatTypeSemantics(RHSElemType))
1095     return false;
1096 
1097   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1098                                 RHSElemType == S.Context.LongDoubleTy);
1099   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1100                             RHSElemType == S.Context.Float128Ty);
1101 
1102   // We've handled the situation where __float128 and long double have the same
1103   // representation. We allow all conversions for all possible long double types
1104   // except PPC's double double.
1105   return Float128AndLongDouble &&
1106     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1107      &llvm::APFloat::PPCDoubleDouble());
1108 }
1109 
1110 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1111 
1112 namespace {
1113 /// These helper callbacks are placed in an anonymous namespace to
1114 /// permit their use as function template parameters.
1115 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1116   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1117 }
1118 
1119 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1120   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1121                              CK_IntegralComplexCast);
1122 }
1123 }
1124 
1125 /// \brief Handle integer arithmetic conversions.  Helper function of
1126 /// UsualArithmeticConversions()
1127 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1128 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1129                                         ExprResult &RHS, QualType LHSType,
1130                                         QualType RHSType, bool IsCompAssign) {
1131   // The rules for this case are in C99 6.3.1.8
1132   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1133   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1134   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1135   if (LHSSigned == RHSSigned) {
1136     // Same signedness; use the higher-ranked type
1137     if (order >= 0) {
1138       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1139       return LHSType;
1140     } else if (!IsCompAssign)
1141       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1142     return RHSType;
1143   } else if (order != (LHSSigned ? 1 : -1)) {
1144     // The unsigned type has greater than or equal rank to the
1145     // signed type, so use the unsigned type
1146     if (RHSSigned) {
1147       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1148       return LHSType;
1149     } else if (!IsCompAssign)
1150       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1151     return RHSType;
1152   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1153     // The two types are different widths; if we are here, that
1154     // means the signed type is larger than the unsigned type, so
1155     // use the signed type.
1156     if (LHSSigned) {
1157       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1158       return LHSType;
1159     } else if (!IsCompAssign)
1160       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1161     return RHSType;
1162   } else {
1163     // The signed type is higher-ranked than the unsigned type,
1164     // but isn't actually any bigger (like unsigned int and long
1165     // on most 32-bit systems).  Use the unsigned type corresponding
1166     // to the signed type.
1167     QualType result =
1168       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1169     RHS = (*doRHSCast)(S, RHS.get(), result);
1170     if (!IsCompAssign)
1171       LHS = (*doLHSCast)(S, LHS.get(), result);
1172     return result;
1173   }
1174 }
1175 
1176 /// \brief Handle conversions with GCC complex int extension.  Helper function
1177 /// of UsualArithmeticConversions()
1178 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1179                                            ExprResult &RHS, QualType LHSType,
1180                                            QualType RHSType,
1181                                            bool IsCompAssign) {
1182   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1183   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1184 
1185   if (LHSComplexInt && RHSComplexInt) {
1186     QualType LHSEltType = LHSComplexInt->getElementType();
1187     QualType RHSEltType = RHSComplexInt->getElementType();
1188     QualType ScalarType =
1189       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1190         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1191 
1192     return S.Context.getComplexType(ScalarType);
1193   }
1194 
1195   if (LHSComplexInt) {
1196     QualType LHSEltType = LHSComplexInt->getElementType();
1197     QualType ScalarType =
1198       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1199         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1200     QualType ComplexType = S.Context.getComplexType(ScalarType);
1201     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1202                               CK_IntegralRealToComplex);
1203 
1204     return ComplexType;
1205   }
1206 
1207   assert(RHSComplexInt);
1208 
1209   QualType RHSEltType = RHSComplexInt->getElementType();
1210   QualType ScalarType =
1211     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1212       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1213   QualType ComplexType = S.Context.getComplexType(ScalarType);
1214 
1215   if (!IsCompAssign)
1216     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1217                               CK_IntegralRealToComplex);
1218   return ComplexType;
1219 }
1220 
1221 /// UsualArithmeticConversions - Performs various conversions that are common to
1222 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1223 /// routine returns the first non-arithmetic type found. The client is
1224 /// responsible for emitting appropriate error diagnostics.
1225 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1226                                           bool IsCompAssign) {
1227   if (!IsCompAssign) {
1228     LHS = UsualUnaryConversions(LHS.get());
1229     if (LHS.isInvalid())
1230       return QualType();
1231   }
1232 
1233   RHS = UsualUnaryConversions(RHS.get());
1234   if (RHS.isInvalid())
1235     return QualType();
1236 
1237   // For conversion purposes, we ignore any qualifiers.
1238   // For example, "const float" and "float" are equivalent.
1239   QualType LHSType =
1240     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1241   QualType RHSType =
1242     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1243 
1244   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1245   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1246     LHSType = AtomicLHS->getValueType();
1247 
1248   // If both types are identical, no conversion is needed.
1249   if (LHSType == RHSType)
1250     return LHSType;
1251 
1252   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1253   // The caller can deal with this (e.g. pointer + int).
1254   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1255     return QualType();
1256 
1257   // Apply unary and bitfield promotions to the LHS's type.
1258   QualType LHSUnpromotedType = LHSType;
1259   if (LHSType->isPromotableIntegerType())
1260     LHSType = Context.getPromotedIntegerType(LHSType);
1261   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1262   if (!LHSBitfieldPromoteTy.isNull())
1263     LHSType = LHSBitfieldPromoteTy;
1264   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1265     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1266 
1267   // If both types are identical, no conversion is needed.
1268   if (LHSType == RHSType)
1269     return LHSType;
1270 
1271   // At this point, we have two different arithmetic types.
1272 
1273   // Diagnose attempts to convert between __float128 and long double where
1274   // such conversions currently can't be handled.
1275   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1276     return QualType();
1277 
1278   // Handle complex types first (C99 6.3.1.8p1).
1279   if (LHSType->isComplexType() || RHSType->isComplexType())
1280     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1281                                         IsCompAssign);
1282 
1283   // Now handle "real" floating types (i.e. float, double, long double).
1284   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1285     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1286                                  IsCompAssign);
1287 
1288   // Handle GCC complex int extension.
1289   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1290     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1291                                       IsCompAssign);
1292 
1293   // Finally, we have two differing integer types.
1294   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1295            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1296 }
1297 
1298 
1299 //===----------------------------------------------------------------------===//
1300 //  Semantic Analysis for various Expression Types
1301 //===----------------------------------------------------------------------===//
1302 
1303 
1304 ExprResult
1305 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1306                                 SourceLocation DefaultLoc,
1307                                 SourceLocation RParenLoc,
1308                                 Expr *ControllingExpr,
1309                                 ArrayRef<ParsedType> ArgTypes,
1310                                 ArrayRef<Expr *> ArgExprs) {
1311   unsigned NumAssocs = ArgTypes.size();
1312   assert(NumAssocs == ArgExprs.size());
1313 
1314   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1315   for (unsigned i = 0; i < NumAssocs; ++i) {
1316     if (ArgTypes[i])
1317       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1318     else
1319       Types[i] = nullptr;
1320   }
1321 
1322   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1323                                              ControllingExpr,
1324                                              llvm::makeArrayRef(Types, NumAssocs),
1325                                              ArgExprs);
1326   delete [] Types;
1327   return ER;
1328 }
1329 
1330 ExprResult
1331 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1332                                  SourceLocation DefaultLoc,
1333                                  SourceLocation RParenLoc,
1334                                  Expr *ControllingExpr,
1335                                  ArrayRef<TypeSourceInfo *> Types,
1336                                  ArrayRef<Expr *> Exprs) {
1337   unsigned NumAssocs = Types.size();
1338   assert(NumAssocs == Exprs.size());
1339 
1340   // Decay and strip qualifiers for the controlling expression type, and handle
1341   // placeholder type replacement. See committee discussion from WG14 DR423.
1342   {
1343     EnterExpressionEvaluationContext Unevaluated(
1344         *this, Sema::ExpressionEvaluationContext::Unevaluated);
1345     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1346     if (R.isInvalid())
1347       return ExprError();
1348     ControllingExpr = R.get();
1349   }
1350 
1351   // The controlling expression is an unevaluated operand, so side effects are
1352   // likely unintended.
1353   if (!inTemplateInstantiation() &&
1354       ControllingExpr->HasSideEffects(Context, false))
1355     Diag(ControllingExpr->getExprLoc(),
1356          diag::warn_side_effects_unevaluated_context);
1357 
1358   bool TypeErrorFound = false,
1359        IsResultDependent = ControllingExpr->isTypeDependent(),
1360        ContainsUnexpandedParameterPack
1361          = ControllingExpr->containsUnexpandedParameterPack();
1362 
1363   for (unsigned i = 0; i < NumAssocs; ++i) {
1364     if (Exprs[i]->containsUnexpandedParameterPack())
1365       ContainsUnexpandedParameterPack = true;
1366 
1367     if (Types[i]) {
1368       if (Types[i]->getType()->containsUnexpandedParameterPack())
1369         ContainsUnexpandedParameterPack = true;
1370 
1371       if (Types[i]->getType()->isDependentType()) {
1372         IsResultDependent = true;
1373       } else {
1374         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1375         // complete object type other than a variably modified type."
1376         unsigned D = 0;
1377         if (Types[i]->getType()->isIncompleteType())
1378           D = diag::err_assoc_type_incomplete;
1379         else if (!Types[i]->getType()->isObjectType())
1380           D = diag::err_assoc_type_nonobject;
1381         else if (Types[i]->getType()->isVariablyModifiedType())
1382           D = diag::err_assoc_type_variably_modified;
1383 
1384         if (D != 0) {
1385           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1386             << Types[i]->getTypeLoc().getSourceRange()
1387             << Types[i]->getType();
1388           TypeErrorFound = true;
1389         }
1390 
1391         // C11 6.5.1.1p2 "No two generic associations in the same generic
1392         // selection shall specify compatible types."
1393         for (unsigned j = i+1; j < NumAssocs; ++j)
1394           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1395               Context.typesAreCompatible(Types[i]->getType(),
1396                                          Types[j]->getType())) {
1397             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1398                  diag::err_assoc_compatible_types)
1399               << Types[j]->getTypeLoc().getSourceRange()
1400               << Types[j]->getType()
1401               << Types[i]->getType();
1402             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1403                  diag::note_compat_assoc)
1404               << Types[i]->getTypeLoc().getSourceRange()
1405               << Types[i]->getType();
1406             TypeErrorFound = true;
1407           }
1408       }
1409     }
1410   }
1411   if (TypeErrorFound)
1412     return ExprError();
1413 
1414   // If we determined that the generic selection is result-dependent, don't
1415   // try to compute the result expression.
1416   if (IsResultDependent)
1417     return new (Context) GenericSelectionExpr(
1418         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1419         ContainsUnexpandedParameterPack);
1420 
1421   SmallVector<unsigned, 1> CompatIndices;
1422   unsigned DefaultIndex = -1U;
1423   for (unsigned i = 0; i < NumAssocs; ++i) {
1424     if (!Types[i])
1425       DefaultIndex = i;
1426     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1427                                         Types[i]->getType()))
1428       CompatIndices.push_back(i);
1429   }
1430 
1431   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1432   // type compatible with at most one of the types named in its generic
1433   // association list."
1434   if (CompatIndices.size() > 1) {
1435     // We strip parens here because the controlling expression is typically
1436     // parenthesized in macro definitions.
1437     ControllingExpr = ControllingExpr->IgnoreParens();
1438     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1439       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1440       << (unsigned) CompatIndices.size();
1441     for (unsigned I : CompatIndices) {
1442       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1443            diag::note_compat_assoc)
1444         << Types[I]->getTypeLoc().getSourceRange()
1445         << Types[I]->getType();
1446     }
1447     return ExprError();
1448   }
1449 
1450   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1451   // its controlling expression shall have type compatible with exactly one of
1452   // the types named in its generic association list."
1453   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1454     // We strip parens here because the controlling expression is typically
1455     // parenthesized in macro definitions.
1456     ControllingExpr = ControllingExpr->IgnoreParens();
1457     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1458       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1459     return ExprError();
1460   }
1461 
1462   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1463   // type name that is compatible with the type of the controlling expression,
1464   // then the result expression of the generic selection is the expression
1465   // in that generic association. Otherwise, the result expression of the
1466   // generic selection is the expression in the default generic association."
1467   unsigned ResultIndex =
1468     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1469 
1470   return new (Context) GenericSelectionExpr(
1471       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1472       ContainsUnexpandedParameterPack, ResultIndex);
1473 }
1474 
1475 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1476 /// location of the token and the offset of the ud-suffix within it.
1477 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1478                                      unsigned Offset) {
1479   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1480                                         S.getLangOpts());
1481 }
1482 
1483 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1484 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1485 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1486                                                  IdentifierInfo *UDSuffix,
1487                                                  SourceLocation UDSuffixLoc,
1488                                                  ArrayRef<Expr*> Args,
1489                                                  SourceLocation LitEndLoc) {
1490   assert(Args.size() <= 2 && "too many arguments for literal operator");
1491 
1492   QualType ArgTy[2];
1493   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1494     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1495     if (ArgTy[ArgIdx]->isArrayType())
1496       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1497   }
1498 
1499   DeclarationName OpName =
1500     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1501   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1502   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1503 
1504   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1505   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1506                               /*AllowRaw*/ false, /*AllowTemplate*/ false,
1507                               /*AllowStringTemplate*/ false,
1508                               /*DiagnoseMissing*/ true) == Sema::LOLR_Error)
1509     return ExprError();
1510 
1511   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1512 }
1513 
1514 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1515 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1516 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1517 /// multiple tokens.  However, the common case is that StringToks points to one
1518 /// string.
1519 ///
1520 ExprResult
1521 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1522   assert(!StringToks.empty() && "Must have at least one string!");
1523 
1524   StringLiteralParser Literal(StringToks, PP);
1525   if (Literal.hadError)
1526     return ExprError();
1527 
1528   SmallVector<SourceLocation, 4> StringTokLocs;
1529   for (const Token &Tok : StringToks)
1530     StringTokLocs.push_back(Tok.getLocation());
1531 
1532   QualType CharTy = Context.CharTy;
1533   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1534   if (Literal.isWide()) {
1535     CharTy = Context.getWideCharType();
1536     Kind = StringLiteral::Wide;
1537   } else if (Literal.isUTF8()) {
1538     Kind = StringLiteral::UTF8;
1539   } else if (Literal.isUTF16()) {
1540     CharTy = Context.Char16Ty;
1541     Kind = StringLiteral::UTF16;
1542   } else if (Literal.isUTF32()) {
1543     CharTy = Context.Char32Ty;
1544     Kind = StringLiteral::UTF32;
1545   } else if (Literal.isPascal()) {
1546     CharTy = Context.UnsignedCharTy;
1547   }
1548 
1549   QualType CharTyConst = CharTy;
1550   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1551   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1552     CharTyConst.addConst();
1553 
1554   // Get an array type for the string, according to C99 6.4.5.  This includes
1555   // the nul terminator character as well as the string length for pascal
1556   // strings.
1557   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1558                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1559                                  ArrayType::Normal, 0);
1560 
1561   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1562   if (getLangOpts().OpenCL) {
1563     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1564   }
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     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2091                        MemberOfUnknownSpecialization);
2092 
2093     if (MemberOfUnknownSpecialization ||
2094         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2095       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2096                                         IsAddressOfOperand, TemplateArgs);
2097   } else {
2098     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2099     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2100 
2101     // If the result might be in a dependent base class, this is a dependent
2102     // id-expression.
2103     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2104       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2105                                         IsAddressOfOperand, TemplateArgs);
2106 
2107     // If this reference is in an Objective-C method, then we need to do
2108     // some special Objective-C lookup, too.
2109     if (IvarLookupFollowUp) {
2110       ExprResult E(LookupInObjCMethod(R, S, II, true));
2111       if (E.isInvalid())
2112         return ExprError();
2113 
2114       if (Expr *Ex = E.getAs<Expr>())
2115         return Ex;
2116     }
2117   }
2118 
2119   if (R.isAmbiguous())
2120     return ExprError();
2121 
2122   // This could be an implicitly declared function reference (legal in C90,
2123   // extension in C99, forbidden in C++).
2124   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2125     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2126     if (D) R.addDecl(D);
2127   }
2128 
2129   // Determine whether this name might be a candidate for
2130   // argument-dependent lookup.
2131   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2132 
2133   if (R.empty() && !ADL) {
2134     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2135       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2136                                                    TemplateKWLoc, TemplateArgs))
2137         return E;
2138     }
2139 
2140     // Don't diagnose an empty lookup for inline assembly.
2141     if (IsInlineAsmIdentifier)
2142       return ExprError();
2143 
2144     // If this name wasn't predeclared and if this is not a function
2145     // call, diagnose the problem.
2146     TypoExpr *TE = nullptr;
2147     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2148         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2149     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2150     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2151            "Typo correction callback misconfigured");
2152     if (CCC) {
2153       // Make sure the callback knows what the typo being diagnosed is.
2154       CCC->setTypoName(II);
2155       if (SS.isValid())
2156         CCC->setTypoNNS(SS.getScopeRep());
2157     }
2158     // FIXME: DiagnoseEmptyLookup produces bad diagnostics if we're looking for
2159     // a template name, but we happen to have always already looked up the name
2160     // before we get here if it must be a template name.
2161     if (DiagnoseEmptyLookup(S, SS, R,
2162                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2163                             nullptr, None, &TE)) {
2164       if (TE && KeywordReplacement) {
2165         auto &State = getTypoExprState(TE);
2166         auto BestTC = State.Consumer->getNextCorrection();
2167         if (BestTC.isKeyword()) {
2168           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2169           if (State.DiagHandler)
2170             State.DiagHandler(BestTC);
2171           KeywordReplacement->startToken();
2172           KeywordReplacement->setKind(II->getTokenID());
2173           KeywordReplacement->setIdentifierInfo(II);
2174           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2175           // Clean up the state associated with the TypoExpr, since it has
2176           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2177           clearDelayedTypo(TE);
2178           // Signal that a correction to a keyword was performed by returning a
2179           // valid-but-null ExprResult.
2180           return (Expr*)nullptr;
2181         }
2182         State.Consumer->resetCorrectionStream();
2183       }
2184       return TE ? TE : ExprError();
2185     }
2186 
2187     assert(!R.empty() &&
2188            "DiagnoseEmptyLookup returned false but added no results");
2189 
2190     // If we found an Objective-C instance variable, let
2191     // LookupInObjCMethod build the appropriate expression to
2192     // reference the ivar.
2193     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2194       R.clear();
2195       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2196       // In a hopelessly buggy code, Objective-C instance variable
2197       // lookup fails and no expression will be built to reference it.
2198       if (!E.isInvalid() && !E.get())
2199         return ExprError();
2200       return E;
2201     }
2202   }
2203 
2204   // This is guaranteed from this point on.
2205   assert(!R.empty() || ADL);
2206 
2207   // Check whether this might be a C++ implicit instance member access.
2208   // C++ [class.mfct.non-static]p3:
2209   //   When an id-expression that is not part of a class member access
2210   //   syntax and not used to form a pointer to member is used in the
2211   //   body of a non-static member function of class X, if name lookup
2212   //   resolves the name in the id-expression to a non-static non-type
2213   //   member of some class C, the id-expression is transformed into a
2214   //   class member access expression using (*this) as the
2215   //   postfix-expression to the left of the . operator.
2216   //
2217   // But we don't actually need to do this for '&' operands if R
2218   // resolved to a function or overloaded function set, because the
2219   // expression is ill-formed if it actually works out to be a
2220   // non-static member function:
2221   //
2222   // C++ [expr.ref]p4:
2223   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2224   //   [t]he expression can be used only as the left-hand operand of a
2225   //   member function call.
2226   //
2227   // There are other safeguards against such uses, but it's important
2228   // to get this right here so that we don't end up making a
2229   // spuriously dependent expression if we're inside a dependent
2230   // instance method.
2231   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2232     bool MightBeImplicitMember;
2233     if (!IsAddressOfOperand)
2234       MightBeImplicitMember = true;
2235     else if (!SS.isEmpty())
2236       MightBeImplicitMember = false;
2237     else if (R.isOverloadedResult())
2238       MightBeImplicitMember = false;
2239     else if (R.isUnresolvableResult())
2240       MightBeImplicitMember = true;
2241     else
2242       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2243                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2244                               isa<MSPropertyDecl>(R.getFoundDecl());
2245 
2246     if (MightBeImplicitMember)
2247       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2248                                              R, TemplateArgs, S);
2249   }
2250 
2251   if (TemplateArgs || TemplateKWLoc.isValid()) {
2252 
2253     // In C++1y, if this is a variable template id, then check it
2254     // in BuildTemplateIdExpr().
2255     // The single lookup result must be a variable template declaration.
2256     if (Id.getKind() == UnqualifiedIdKind::IK_TemplateId && Id.TemplateId &&
2257         Id.TemplateId->Kind == TNK_Var_template) {
2258       assert(R.getAsSingle<VarTemplateDecl>() &&
2259              "There should only be one declaration found.");
2260     }
2261 
2262     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2263   }
2264 
2265   return BuildDeclarationNameExpr(SS, R, ADL);
2266 }
2267 
2268 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2269 /// declaration name, generally during template instantiation.
2270 /// There's a large number of things which don't need to be done along
2271 /// this path.
2272 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2273     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2274     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2275   DeclContext *DC = computeDeclContext(SS, false);
2276   if (!DC)
2277     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2278                                      NameInfo, /*TemplateArgs=*/nullptr);
2279 
2280   if (RequireCompleteDeclContext(SS, DC))
2281     return ExprError();
2282 
2283   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2284   LookupQualifiedName(R, DC);
2285 
2286   if (R.isAmbiguous())
2287     return ExprError();
2288 
2289   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2290     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2291                                      NameInfo, /*TemplateArgs=*/nullptr);
2292 
2293   if (R.empty()) {
2294     Diag(NameInfo.getLoc(), diag::err_no_member)
2295       << NameInfo.getName() << DC << SS.getRange();
2296     return ExprError();
2297   }
2298 
2299   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2300     // Diagnose a missing typename if this resolved unambiguously to a type in
2301     // a dependent context.  If we can recover with a type, downgrade this to
2302     // a warning in Microsoft compatibility mode.
2303     unsigned DiagID = diag::err_typename_missing;
2304     if (RecoveryTSI && getLangOpts().MSVCCompat)
2305       DiagID = diag::ext_typename_missing;
2306     SourceLocation Loc = SS.getBeginLoc();
2307     auto D = Diag(Loc, DiagID);
2308     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2309       << SourceRange(Loc, NameInfo.getEndLoc());
2310 
2311     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2312     // context.
2313     if (!RecoveryTSI)
2314       return ExprError();
2315 
2316     // Only issue the fixit if we're prepared to recover.
2317     D << FixItHint::CreateInsertion(Loc, "typename ");
2318 
2319     // Recover by pretending this was an elaborated type.
2320     QualType Ty = Context.getTypeDeclType(TD);
2321     TypeLocBuilder TLB;
2322     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2323 
2324     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2325     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2326     QTL.setElaboratedKeywordLoc(SourceLocation());
2327     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2328 
2329     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2330 
2331     return ExprEmpty();
2332   }
2333 
2334   // Defend against this resolving to an implicit member access. We usually
2335   // won't get here if this might be a legitimate a class member (we end up in
2336   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2337   // a pointer-to-member or in an unevaluated context in C++11.
2338   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2339     return BuildPossibleImplicitMemberExpr(SS,
2340                                            /*TemplateKWLoc=*/SourceLocation(),
2341                                            R, /*TemplateArgs=*/nullptr, S);
2342 
2343   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2344 }
2345 
2346 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2347 /// detected that we're currently inside an ObjC method.  Perform some
2348 /// additional lookup.
2349 ///
2350 /// Ideally, most of this would be done by lookup, but there's
2351 /// actually quite a lot of extra work involved.
2352 ///
2353 /// Returns a null sentinel to indicate trivial success.
2354 ExprResult
2355 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2356                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2357   SourceLocation Loc = Lookup.getNameLoc();
2358   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2359 
2360   // Check for error condition which is already reported.
2361   if (!CurMethod)
2362     return ExprError();
2363 
2364   // There are two cases to handle here.  1) scoped lookup could have failed,
2365   // in which case we should look for an ivar.  2) scoped lookup could have
2366   // found a decl, but that decl is outside the current instance method (i.e.
2367   // a global variable).  In these two cases, we do a lookup for an ivar with
2368   // this name, if the lookup sucedes, we replace it our current decl.
2369 
2370   // If we're in a class method, we don't normally want to look for
2371   // ivars.  But if we don't find anything else, and there's an
2372   // ivar, that's an error.
2373   bool IsClassMethod = CurMethod->isClassMethod();
2374 
2375   bool LookForIvars;
2376   if (Lookup.empty())
2377     LookForIvars = true;
2378   else if (IsClassMethod)
2379     LookForIvars = false;
2380   else
2381     LookForIvars = (Lookup.isSingleResult() &&
2382                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2383   ObjCInterfaceDecl *IFace = nullptr;
2384   if (LookForIvars) {
2385     IFace = CurMethod->getClassInterface();
2386     ObjCInterfaceDecl *ClassDeclared;
2387     ObjCIvarDecl *IV = nullptr;
2388     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2389       // Diagnose using an ivar in a class method.
2390       if (IsClassMethod)
2391         return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2392                          << IV->getDeclName());
2393 
2394       // If we're referencing an invalid decl, just return this as a silent
2395       // error node.  The error diagnostic was already emitted on the decl.
2396       if (IV->isInvalidDecl())
2397         return ExprError();
2398 
2399       // Check if referencing a field with __attribute__((deprecated)).
2400       if (DiagnoseUseOfDecl(IV, Loc))
2401         return ExprError();
2402 
2403       // Diagnose the use of an ivar outside of the declaring class.
2404       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2405           !declaresSameEntity(ClassDeclared, IFace) &&
2406           !getLangOpts().DebuggerSupport)
2407         Diag(Loc, diag::err_private_ivar_access) << IV->getDeclName();
2408 
2409       // FIXME: This should use a new expr for a direct reference, don't
2410       // turn this into Self->ivar, just return a BareIVarExpr or something.
2411       IdentifierInfo &II = Context.Idents.get("self");
2412       UnqualifiedId SelfName;
2413       SelfName.setIdentifier(&II, SourceLocation());
2414       SelfName.setKind(UnqualifiedIdKind::IK_ImplicitSelfParam);
2415       CXXScopeSpec SelfScopeSpec;
2416       SourceLocation TemplateKWLoc;
2417       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2418                                               SelfName, false, false);
2419       if (SelfExpr.isInvalid())
2420         return ExprError();
2421 
2422       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2423       if (SelfExpr.isInvalid())
2424         return ExprError();
2425 
2426       MarkAnyDeclReferenced(Loc, IV, true);
2427 
2428       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2429       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2430           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2431         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2432 
2433       ObjCIvarRefExpr *Result = new (Context)
2434           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2435                           IV->getLocation(), SelfExpr.get(), true, true);
2436 
2437       if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2438         if (!isUnevaluatedContext() &&
2439             !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2440           getCurFunction()->recordUseOfWeak(Result);
2441       }
2442       if (getLangOpts().ObjCAutoRefCount) {
2443         if (CurContext->isClosure())
2444           Diag(Loc, diag::warn_implicitly_retains_self)
2445             << FixItHint::CreateInsertion(Loc, "self->");
2446       }
2447 
2448       return Result;
2449     }
2450   } else if (CurMethod->isInstanceMethod()) {
2451     // We should warn if a local variable hides an ivar.
2452     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2453       ObjCInterfaceDecl *ClassDeclared;
2454       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2455         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2456             declaresSameEntity(IFace, ClassDeclared))
2457           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2458       }
2459     }
2460   } else if (Lookup.isSingleResult() &&
2461              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2462     // If accessing a stand-alone ivar in a class method, this is an error.
2463     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2464       return ExprError(Diag(Loc, diag::err_ivar_use_in_class_method)
2465                        << IV->getDeclName());
2466   }
2467 
2468   if (Lookup.empty() && II && AllowBuiltinCreation) {
2469     // FIXME. Consolidate this with similar code in LookupName.
2470     if (unsigned BuiltinID = II->getBuiltinID()) {
2471       if (!(getLangOpts().CPlusPlus &&
2472             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2473         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2474                                            S, Lookup.isForRedeclaration(),
2475                                            Lookup.getNameLoc());
2476         if (D) Lookup.addDecl(D);
2477       }
2478     }
2479   }
2480   // Sentinel value saying that we didn't do anything special.
2481   return ExprResult((Expr *)nullptr);
2482 }
2483 
2484 /// \brief Cast a base object to a member's actual type.
2485 ///
2486 /// Logically this happens in three phases:
2487 ///
2488 /// * First we cast from the base type to the naming class.
2489 ///   The naming class is the class into which we were looking
2490 ///   when we found the member;  it's the qualifier type if a
2491 ///   qualifier was provided, and otherwise it's the base type.
2492 ///
2493 /// * Next we cast from the naming class to the declaring class.
2494 ///   If the member we found was brought into a class's scope by
2495 ///   a using declaration, this is that class;  otherwise it's
2496 ///   the class declaring the member.
2497 ///
2498 /// * Finally we cast from the declaring class to the "true"
2499 ///   declaring class of the member.  This conversion does not
2500 ///   obey access control.
2501 ExprResult
2502 Sema::PerformObjectMemberConversion(Expr *From,
2503                                     NestedNameSpecifier *Qualifier,
2504                                     NamedDecl *FoundDecl,
2505                                     NamedDecl *Member) {
2506   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2507   if (!RD)
2508     return From;
2509 
2510   QualType DestRecordType;
2511   QualType DestType;
2512   QualType FromRecordType;
2513   QualType FromType = From->getType();
2514   bool PointerConversions = false;
2515   if (isa<FieldDecl>(Member)) {
2516     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2517 
2518     if (FromType->getAs<PointerType>()) {
2519       DestType = Context.getPointerType(DestRecordType);
2520       FromRecordType = FromType->getPointeeType();
2521       PointerConversions = true;
2522     } else {
2523       DestType = DestRecordType;
2524       FromRecordType = FromType;
2525     }
2526   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2527     if (Method->isStatic())
2528       return From;
2529 
2530     DestType = Method->getThisType(Context);
2531     DestRecordType = DestType->getPointeeType();
2532 
2533     if (FromType->getAs<PointerType>()) {
2534       FromRecordType = FromType->getPointeeType();
2535       PointerConversions = true;
2536     } else {
2537       FromRecordType = FromType;
2538       DestType = DestRecordType;
2539     }
2540   } else {
2541     // No conversion necessary.
2542     return From;
2543   }
2544 
2545   if (DestType->isDependentType() || FromType->isDependentType())
2546     return From;
2547 
2548   // If the unqualified types are the same, no conversion is necessary.
2549   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2550     return From;
2551 
2552   SourceRange FromRange = From->getSourceRange();
2553   SourceLocation FromLoc = FromRange.getBegin();
2554 
2555   ExprValueKind VK = From->getValueKind();
2556 
2557   // C++ [class.member.lookup]p8:
2558   //   [...] Ambiguities can often be resolved by qualifying a name with its
2559   //   class name.
2560   //
2561   // If the member was a qualified name and the qualified referred to a
2562   // specific base subobject type, we'll cast to that intermediate type
2563   // first and then to the object in which the member is declared. That allows
2564   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2565   //
2566   //   class Base { public: int x; };
2567   //   class Derived1 : public Base { };
2568   //   class Derived2 : public Base { };
2569   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2570   //
2571   //   void VeryDerived::f() {
2572   //     x = 17; // error: ambiguous base subobjects
2573   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2574   //   }
2575   if (Qualifier && Qualifier->getAsType()) {
2576     QualType QType = QualType(Qualifier->getAsType(), 0);
2577     assert(QType->isRecordType() && "lookup done with non-record type");
2578 
2579     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2580 
2581     // In C++98, the qualifier type doesn't actually have to be a base
2582     // type of the object type, in which case we just ignore it.
2583     // Otherwise build the appropriate casts.
2584     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2585       CXXCastPath BasePath;
2586       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2587                                        FromLoc, FromRange, &BasePath))
2588         return ExprError();
2589 
2590       if (PointerConversions)
2591         QType = Context.getPointerType(QType);
2592       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2593                                VK, &BasePath).get();
2594 
2595       FromType = QType;
2596       FromRecordType = QRecordType;
2597 
2598       // If the qualifier type was the same as the destination type,
2599       // we're done.
2600       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2601         return From;
2602     }
2603   }
2604 
2605   bool IgnoreAccess = false;
2606 
2607   // If we actually found the member through a using declaration, cast
2608   // down to the using declaration's type.
2609   //
2610   // Pointer equality is fine here because only one declaration of a
2611   // class ever has member declarations.
2612   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2613     assert(isa<UsingShadowDecl>(FoundDecl));
2614     QualType URecordType = Context.getTypeDeclType(
2615                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2616 
2617     // We only need to do this if the naming-class to declaring-class
2618     // conversion is non-trivial.
2619     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2620       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2621       CXXCastPath BasePath;
2622       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2623                                        FromLoc, FromRange, &BasePath))
2624         return ExprError();
2625 
2626       QualType UType = URecordType;
2627       if (PointerConversions)
2628         UType = Context.getPointerType(UType);
2629       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2630                                VK, &BasePath).get();
2631       FromType = UType;
2632       FromRecordType = URecordType;
2633     }
2634 
2635     // We don't do access control for the conversion from the
2636     // declaring class to the true declaring class.
2637     IgnoreAccess = true;
2638   }
2639 
2640   CXXCastPath BasePath;
2641   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2642                                    FromLoc, FromRange, &BasePath,
2643                                    IgnoreAccess))
2644     return ExprError();
2645 
2646   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2647                            VK, &BasePath);
2648 }
2649 
2650 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2651                                       const LookupResult &R,
2652                                       bool HasTrailingLParen) {
2653   // Only when used directly as the postfix-expression of a call.
2654   if (!HasTrailingLParen)
2655     return false;
2656 
2657   // Never if a scope specifier was provided.
2658   if (SS.isSet())
2659     return false;
2660 
2661   // Only in C++ or ObjC++.
2662   if (!getLangOpts().CPlusPlus)
2663     return false;
2664 
2665   // Turn off ADL when we find certain kinds of declarations during
2666   // normal lookup:
2667   for (NamedDecl *D : R) {
2668     // C++0x [basic.lookup.argdep]p3:
2669     //     -- a declaration of a class member
2670     // Since using decls preserve this property, we check this on the
2671     // original decl.
2672     if (D->isCXXClassMember())
2673       return false;
2674 
2675     // C++0x [basic.lookup.argdep]p3:
2676     //     -- a block-scope function declaration that is not a
2677     //        using-declaration
2678     // NOTE: we also trigger this for function templates (in fact, we
2679     // don't check the decl type at all, since all other decl types
2680     // turn off ADL anyway).
2681     if (isa<UsingShadowDecl>(D))
2682       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2683     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2684       return false;
2685 
2686     // C++0x [basic.lookup.argdep]p3:
2687     //     -- a declaration that is neither a function or a function
2688     //        template
2689     // And also for builtin functions.
2690     if (isa<FunctionDecl>(D)) {
2691       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2692 
2693       // But also builtin functions.
2694       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2695         return false;
2696     } else if (!isa<FunctionTemplateDecl>(D))
2697       return false;
2698   }
2699 
2700   return true;
2701 }
2702 
2703 
2704 /// Diagnoses obvious problems with the use of the given declaration
2705 /// as an expression.  This is only actually called for lookups that
2706 /// were not overloaded, and it doesn't promise that the declaration
2707 /// will in fact be used.
2708 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2709   if (D->isInvalidDecl())
2710     return true;
2711 
2712   if (isa<TypedefNameDecl>(D)) {
2713     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2714     return true;
2715   }
2716 
2717   if (isa<ObjCInterfaceDecl>(D)) {
2718     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2719     return true;
2720   }
2721 
2722   if (isa<NamespaceDecl>(D)) {
2723     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2724     return true;
2725   }
2726 
2727   return false;
2728 }
2729 
2730 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2731                                           LookupResult &R, bool NeedsADL,
2732                                           bool AcceptInvalidDecl) {
2733   // If this is a single, fully-resolved result and we don't need ADL,
2734   // just build an ordinary singleton decl ref.
2735   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2736     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2737                                     R.getRepresentativeDecl(), nullptr,
2738                                     AcceptInvalidDecl);
2739 
2740   // We only need to check the declaration if there's exactly one
2741   // result, because in the overloaded case the results can only be
2742   // functions and function templates.
2743   if (R.isSingleResult() &&
2744       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2745     return ExprError();
2746 
2747   // Otherwise, just build an unresolved lookup expression.  Suppress
2748   // any lookup-related diagnostics; we'll hash these out later, when
2749   // we've picked a target.
2750   R.suppressDiagnostics();
2751 
2752   UnresolvedLookupExpr *ULE
2753     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2754                                    SS.getWithLocInContext(Context),
2755                                    R.getLookupNameInfo(),
2756                                    NeedsADL, R.isOverloadedResult(),
2757                                    R.begin(), R.end());
2758 
2759   return ULE;
2760 }
2761 
2762 static void
2763 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2764                                    ValueDecl *var, DeclContext *DC);
2765 
2766 /// \brief Complete semantic analysis for a reference to the given declaration.
2767 ExprResult Sema::BuildDeclarationNameExpr(
2768     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2769     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2770     bool AcceptInvalidDecl) {
2771   assert(D && "Cannot refer to a NULL declaration");
2772   assert(!isa<FunctionTemplateDecl>(D) &&
2773          "Cannot refer unambiguously to a function template");
2774 
2775   SourceLocation Loc = NameInfo.getLoc();
2776   if (CheckDeclInExpr(*this, Loc, D))
2777     return ExprError();
2778 
2779   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2780     // Specifically diagnose references to class templates that are missing
2781     // a template argument list.
2782     diagnoseMissingTemplateArguments(TemplateName(Template), Loc);
2783     return ExprError();
2784   }
2785 
2786   // Make sure that we're referring to a value.
2787   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2788   if (!VD) {
2789     Diag(Loc, diag::err_ref_non_value)
2790       << D << SS.getRange();
2791     Diag(D->getLocation(), diag::note_declared_at);
2792     return ExprError();
2793   }
2794 
2795   // Check whether this declaration can be used. Note that we suppress
2796   // this check when we're going to perform argument-dependent lookup
2797   // on this function name, because this might not be the function
2798   // that overload resolution actually selects.
2799   if (DiagnoseUseOfDecl(VD, Loc))
2800     return ExprError();
2801 
2802   // Only create DeclRefExpr's for valid Decl's.
2803   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2804     return ExprError();
2805 
2806   // Handle members of anonymous structs and unions.  If we got here,
2807   // and the reference is to a class member indirect field, then this
2808   // must be the subject of a pointer-to-member expression.
2809   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2810     if (!indirectField->isCXXClassMember())
2811       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2812                                                       indirectField);
2813 
2814   {
2815     QualType type = VD->getType();
2816     if (type.isNull())
2817       return ExprError();
2818     if (auto *FPT = type->getAs<FunctionProtoType>()) {
2819       // C++ [except.spec]p17:
2820       //   An exception-specification is considered to be needed when:
2821       //   - in an expression, the function is the unique lookup result or
2822       //     the selected member of a set of overloaded functions.
2823       ResolveExceptionSpec(Loc, FPT);
2824       type = VD->getType();
2825     }
2826     ExprValueKind valueKind = VK_RValue;
2827 
2828     switch (D->getKind()) {
2829     // Ignore all the non-ValueDecl kinds.
2830 #define ABSTRACT_DECL(kind)
2831 #define VALUE(type, base)
2832 #define DECL(type, base) \
2833     case Decl::type:
2834 #include "clang/AST/DeclNodes.inc"
2835       llvm_unreachable("invalid value decl kind");
2836 
2837     // These shouldn't make it here.
2838     case Decl::ObjCAtDefsField:
2839     case Decl::ObjCIvar:
2840       llvm_unreachable("forming non-member reference to ivar?");
2841 
2842     // Enum constants are always r-values and never references.
2843     // Unresolved using declarations are dependent.
2844     case Decl::EnumConstant:
2845     case Decl::UnresolvedUsingValue:
2846     case Decl::OMPDeclareReduction:
2847       valueKind = VK_RValue;
2848       break;
2849 
2850     // Fields and indirect fields that got here must be for
2851     // pointer-to-member expressions; we just call them l-values for
2852     // internal consistency, because this subexpression doesn't really
2853     // exist in the high-level semantics.
2854     case Decl::Field:
2855     case Decl::IndirectField:
2856       assert(getLangOpts().CPlusPlus &&
2857              "building reference to field in C?");
2858 
2859       // These can't have reference type in well-formed programs, but
2860       // for internal consistency we do this anyway.
2861       type = type.getNonReferenceType();
2862       valueKind = VK_LValue;
2863       break;
2864 
2865     // Non-type template parameters are either l-values or r-values
2866     // depending on the type.
2867     case Decl::NonTypeTemplateParm: {
2868       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2869         type = reftype->getPointeeType();
2870         valueKind = VK_LValue; // even if the parameter is an r-value reference
2871         break;
2872       }
2873 
2874       // For non-references, we need to strip qualifiers just in case
2875       // the template parameter was declared as 'const int' or whatever.
2876       valueKind = VK_RValue;
2877       type = type.getUnqualifiedType();
2878       break;
2879     }
2880 
2881     case Decl::Var:
2882     case Decl::VarTemplateSpecialization:
2883     case Decl::VarTemplatePartialSpecialization:
2884     case Decl::Decomposition:
2885     case Decl::OMPCapturedExpr:
2886       // In C, "extern void blah;" is valid and is an r-value.
2887       if (!getLangOpts().CPlusPlus &&
2888           !type.hasQualifiers() &&
2889           type->isVoidType()) {
2890         valueKind = VK_RValue;
2891         break;
2892       }
2893       LLVM_FALLTHROUGH;
2894 
2895     case Decl::ImplicitParam:
2896     case Decl::ParmVar: {
2897       // These are always l-values.
2898       valueKind = VK_LValue;
2899       type = type.getNonReferenceType();
2900 
2901       // FIXME: Does the addition of const really only apply in
2902       // potentially-evaluated contexts? Since the variable isn't actually
2903       // captured in an unevaluated context, it seems that the answer is no.
2904       if (!isUnevaluatedContext()) {
2905         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2906         if (!CapturedType.isNull())
2907           type = CapturedType;
2908       }
2909 
2910       break;
2911     }
2912 
2913     case Decl::Binding: {
2914       // These are always lvalues.
2915       valueKind = VK_LValue;
2916       type = type.getNonReferenceType();
2917       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2918       // decides how that's supposed to work.
2919       auto *BD = cast<BindingDecl>(VD);
2920       if (BD->getDeclContext()->isFunctionOrMethod() &&
2921           BD->getDeclContext() != CurContext)
2922         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2923       break;
2924     }
2925 
2926     case Decl::Function: {
2927       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2928         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2929           type = Context.BuiltinFnTy;
2930           valueKind = VK_RValue;
2931           break;
2932         }
2933       }
2934 
2935       const FunctionType *fty = type->castAs<FunctionType>();
2936 
2937       // If we're referring to a function with an __unknown_anytype
2938       // result type, make the entire expression __unknown_anytype.
2939       if (fty->getReturnType() == Context.UnknownAnyTy) {
2940         type = Context.UnknownAnyTy;
2941         valueKind = VK_RValue;
2942         break;
2943       }
2944 
2945       // Functions are l-values in C++.
2946       if (getLangOpts().CPlusPlus) {
2947         valueKind = VK_LValue;
2948         break;
2949       }
2950 
2951       // C99 DR 316 says that, if a function type comes from a
2952       // function definition (without a prototype), that type is only
2953       // used for checking compatibility. Therefore, when referencing
2954       // the function, we pretend that we don't have the full function
2955       // type.
2956       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2957           isa<FunctionProtoType>(fty))
2958         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2959                                               fty->getExtInfo());
2960 
2961       // Functions are r-values in C.
2962       valueKind = VK_RValue;
2963       break;
2964     }
2965 
2966     case Decl::CXXDeductionGuide:
2967       llvm_unreachable("building reference to deduction guide");
2968 
2969     case Decl::MSProperty:
2970       valueKind = VK_LValue;
2971       break;
2972 
2973     case Decl::CXXMethod:
2974       // If we're referring to a method with an __unknown_anytype
2975       // result type, make the entire expression __unknown_anytype.
2976       // This should only be possible with a type written directly.
2977       if (const FunctionProtoType *proto
2978             = dyn_cast<FunctionProtoType>(VD->getType()))
2979         if (proto->getReturnType() == Context.UnknownAnyTy) {
2980           type = Context.UnknownAnyTy;
2981           valueKind = VK_RValue;
2982           break;
2983         }
2984 
2985       // C++ methods are l-values if static, r-values if non-static.
2986       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2987         valueKind = VK_LValue;
2988         break;
2989       }
2990       LLVM_FALLTHROUGH;
2991 
2992     case Decl::CXXConversion:
2993     case Decl::CXXDestructor:
2994     case Decl::CXXConstructor:
2995       valueKind = VK_RValue;
2996       break;
2997     }
2998 
2999     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3000                             TemplateArgs);
3001   }
3002 }
3003 
3004 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3005                                     SmallString<32> &Target) {
3006   Target.resize(CharByteWidth * (Source.size() + 1));
3007   char *ResultPtr = &Target[0];
3008   const llvm::UTF8 *ErrorPtr;
3009   bool success =
3010       llvm::ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3011   (void)success;
3012   assert(success);
3013   Target.resize(ResultPtr - &Target[0]);
3014 }
3015 
3016 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3017                                      PredefinedExpr::IdentType IT) {
3018   // Pick the current block, lambda, captured statement or function.
3019   Decl *currentDecl = nullptr;
3020   if (const BlockScopeInfo *BSI = getCurBlock())
3021     currentDecl = BSI->TheDecl;
3022   else if (const LambdaScopeInfo *LSI = getCurLambda())
3023     currentDecl = LSI->CallOperator;
3024   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3025     currentDecl = CSI->TheCapturedDecl;
3026   else
3027     currentDecl = getCurFunctionOrMethodDecl();
3028 
3029   if (!currentDecl) {
3030     Diag(Loc, diag::ext_predef_outside_function);
3031     currentDecl = Context.getTranslationUnitDecl();
3032   }
3033 
3034   QualType ResTy;
3035   StringLiteral *SL = nullptr;
3036   if (cast<DeclContext>(currentDecl)->isDependentContext())
3037     ResTy = Context.DependentTy;
3038   else {
3039     // Pre-defined identifiers are of type char[x], where x is the length of
3040     // the string.
3041     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3042     unsigned Length = Str.length();
3043 
3044     llvm::APInt LengthI(32, Length + 1);
3045     if (IT == PredefinedExpr::LFunction) {
3046       ResTy = Context.WideCharTy.withConst();
3047       SmallString<32> RawChars;
3048       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3049                               Str, RawChars);
3050       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3051                                            /*IndexTypeQuals*/ 0);
3052       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3053                                  /*Pascal*/ false, ResTy, Loc);
3054     } else {
3055       ResTy = Context.CharTy.withConst();
3056       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3057                                            /*IndexTypeQuals*/ 0);
3058       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3059                                  /*Pascal*/ false, ResTy, Loc);
3060     }
3061   }
3062 
3063   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3064 }
3065 
3066 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3067   PredefinedExpr::IdentType IT;
3068 
3069   switch (Kind) {
3070   default: llvm_unreachable("Unknown simple primary expr!");
3071   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3072   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3073   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3074   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3075   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3076   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3077   }
3078 
3079   return BuildPredefinedExpr(Loc, IT);
3080 }
3081 
3082 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3083   SmallString<16> CharBuffer;
3084   bool Invalid = false;
3085   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3086   if (Invalid)
3087     return ExprError();
3088 
3089   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3090                             PP, Tok.getKind());
3091   if (Literal.hadError())
3092     return ExprError();
3093 
3094   QualType Ty;
3095   if (Literal.isWide())
3096     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3097   else if (Literal.isUTF16())
3098     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3099   else if (Literal.isUTF32())
3100     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3101   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3102     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3103   else
3104     Ty = Context.CharTy;  // 'x' -> char in C++
3105 
3106   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3107   if (Literal.isWide())
3108     Kind = CharacterLiteral::Wide;
3109   else if (Literal.isUTF16())
3110     Kind = CharacterLiteral::UTF16;
3111   else if (Literal.isUTF32())
3112     Kind = CharacterLiteral::UTF32;
3113   else if (Literal.isUTF8())
3114     Kind = CharacterLiteral::UTF8;
3115 
3116   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3117                                              Tok.getLocation());
3118 
3119   if (Literal.getUDSuffix().empty())
3120     return Lit;
3121 
3122   // We're building a user-defined literal.
3123   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3124   SourceLocation UDSuffixLoc =
3125     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3126 
3127   // Make sure we're allowed user-defined literals here.
3128   if (!UDLScope)
3129     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3130 
3131   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3132   //   operator "" X (ch)
3133   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3134                                         Lit, Tok.getLocation());
3135 }
3136 
3137 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3138   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3139   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3140                                 Context.IntTy, Loc);
3141 }
3142 
3143 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3144                                   QualType Ty, SourceLocation Loc) {
3145   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3146 
3147   using llvm::APFloat;
3148   APFloat Val(Format);
3149 
3150   APFloat::opStatus result = Literal.GetFloatValue(Val);
3151 
3152   // Overflow is always an error, but underflow is only an error if
3153   // we underflowed to zero (APFloat reports denormals as underflow).
3154   if ((result & APFloat::opOverflow) ||
3155       ((result & APFloat::opUnderflow) && Val.isZero())) {
3156     unsigned diagnostic;
3157     SmallString<20> buffer;
3158     if (result & APFloat::opOverflow) {
3159       diagnostic = diag::warn_float_overflow;
3160       APFloat::getLargest(Format).toString(buffer);
3161     } else {
3162       diagnostic = diag::warn_float_underflow;
3163       APFloat::getSmallest(Format).toString(buffer);
3164     }
3165 
3166     S.Diag(Loc, diagnostic)
3167       << Ty
3168       << StringRef(buffer.data(), buffer.size());
3169   }
3170 
3171   bool isExact = (result == APFloat::opOK);
3172   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3173 }
3174 
3175 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3176   assert(E && "Invalid expression");
3177 
3178   if (E->isValueDependent())
3179     return false;
3180 
3181   QualType QT = E->getType();
3182   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3183     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3184     return true;
3185   }
3186 
3187   llvm::APSInt ValueAPS;
3188   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3189 
3190   if (R.isInvalid())
3191     return true;
3192 
3193   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3194   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3195     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3196         << ValueAPS.toString(10) << ValueIsPositive;
3197     return true;
3198   }
3199 
3200   return false;
3201 }
3202 
3203 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3204   // Fast path for a single digit (which is quite common).  A single digit
3205   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3206   if (Tok.getLength() == 1) {
3207     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3208     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3209   }
3210 
3211   SmallString<128> SpellingBuffer;
3212   // NumericLiteralParser wants to overread by one character.  Add padding to
3213   // the buffer in case the token is copied to the buffer.  If getSpelling()
3214   // returns a StringRef to the memory buffer, it should have a null char at
3215   // the EOF, so it is also safe.
3216   SpellingBuffer.resize(Tok.getLength() + 1);
3217 
3218   // Get the spelling of the token, which eliminates trigraphs, etc.
3219   bool Invalid = false;
3220   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3221   if (Invalid)
3222     return ExprError();
3223 
3224   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3225   if (Literal.hadError)
3226     return ExprError();
3227 
3228   if (Literal.hasUDSuffix()) {
3229     // We're building a user-defined literal.
3230     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3231     SourceLocation UDSuffixLoc =
3232       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3233 
3234     // Make sure we're allowed user-defined literals here.
3235     if (!UDLScope)
3236       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3237 
3238     QualType CookedTy;
3239     if (Literal.isFloatingLiteral()) {
3240       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3241       // long double, the literal is treated as a call of the form
3242       //   operator "" X (f L)
3243       CookedTy = Context.LongDoubleTy;
3244     } else {
3245       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3246       // unsigned long long, the literal is treated as a call of the form
3247       //   operator "" X (n ULL)
3248       CookedTy = Context.UnsignedLongLongTy;
3249     }
3250 
3251     DeclarationName OpName =
3252       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3253     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3254     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3255 
3256     SourceLocation TokLoc = Tok.getLocation();
3257 
3258     // Perform literal operator lookup to determine if we're building a raw
3259     // literal or a cooked one.
3260     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3261     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3262                                   /*AllowRaw*/ true, /*AllowTemplate*/ true,
3263                                   /*AllowStringTemplate*/ false,
3264                                   /*DiagnoseMissing*/ !Literal.isImaginary)) {
3265     case LOLR_ErrorNoDiagnostic:
3266       // Lookup failure for imaginary constants isn't fatal, there's still the
3267       // GNU extension producing _Complex types.
3268       break;
3269     case LOLR_Error:
3270       return ExprError();
3271     case LOLR_Cooked: {
3272       Expr *Lit;
3273       if (Literal.isFloatingLiteral()) {
3274         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3275       } else {
3276         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3277         if (Literal.GetIntegerValue(ResultVal))
3278           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3279               << /* Unsigned */ 1;
3280         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3281                                      Tok.getLocation());
3282       }
3283       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3284     }
3285 
3286     case LOLR_Raw: {
3287       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3288       // literal is treated as a call of the form
3289       //   operator "" X ("n")
3290       unsigned Length = Literal.getUDSuffixOffset();
3291       QualType StrTy = Context.getConstantArrayType(
3292           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3293           ArrayType::Normal, 0);
3294       Expr *Lit = StringLiteral::Create(
3295           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3296           /*Pascal*/false, StrTy, &TokLoc, 1);
3297       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3298     }
3299 
3300     case LOLR_Template: {
3301       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3302       // template), L is treated as a call fo the form
3303       //   operator "" X <'c1', 'c2', ... 'ck'>()
3304       // where n is the source character sequence c1 c2 ... ck.
3305       TemplateArgumentListInfo ExplicitArgs;
3306       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3307       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3308       llvm::APSInt Value(CharBits, CharIsUnsigned);
3309       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3310         Value = TokSpelling[I];
3311         TemplateArgument Arg(Context, Value, Context.CharTy);
3312         TemplateArgumentLocInfo ArgInfo;
3313         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3314       }
3315       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3316                                       &ExplicitArgs);
3317     }
3318     case LOLR_StringTemplate:
3319       llvm_unreachable("unexpected literal operator lookup result");
3320     }
3321   }
3322 
3323   Expr *Res;
3324 
3325   if (Literal.isFloatingLiteral()) {
3326     QualType Ty;
3327     if (Literal.isHalf){
3328       if (getOpenCLOptions().isEnabled("cl_khr_fp16"))
3329         Ty = Context.HalfTy;
3330       else {
3331         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3332         return ExprError();
3333       }
3334     } else if (Literal.isFloat)
3335       Ty = Context.FloatTy;
3336     else if (Literal.isLong)
3337       Ty = Context.LongDoubleTy;
3338     else if (Literal.isFloat16)
3339       Ty = Context.Float16Ty;
3340     else if (Literal.isFloat128)
3341       Ty = Context.Float128Ty;
3342     else
3343       Ty = Context.DoubleTy;
3344 
3345     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3346 
3347     if (Ty == Context.DoubleTy) {
3348       if (getLangOpts().SinglePrecisionConstants) {
3349         const BuiltinType *BTy = Ty->getAs<BuiltinType>();
3350         if (BTy->getKind() != BuiltinType::Float) {
3351           Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3352         }
3353       } else if (getLangOpts().OpenCL &&
3354                  !getOpenCLOptions().isEnabled("cl_khr_fp64")) {
3355         // Impose single-precision float type when cl_khr_fp64 is not enabled.
3356         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3357         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3358       }
3359     }
3360   } else if (!Literal.isIntegerLiteral()) {
3361     return ExprError();
3362   } else {
3363     QualType Ty;
3364 
3365     // 'long long' is a C99 or C++11 feature.
3366     if (!getLangOpts().C99 && Literal.isLongLong) {
3367       if (getLangOpts().CPlusPlus)
3368         Diag(Tok.getLocation(),
3369              getLangOpts().CPlusPlus11 ?
3370              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3371       else
3372         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3373     }
3374 
3375     // Get the value in the widest-possible width.
3376     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3377     llvm::APInt ResultVal(MaxWidth, 0);
3378 
3379     if (Literal.GetIntegerValue(ResultVal)) {
3380       // If this value didn't fit into uintmax_t, error and force to ull.
3381       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3382           << /* Unsigned */ 1;
3383       Ty = Context.UnsignedLongLongTy;
3384       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3385              "long long is not intmax_t?");
3386     } else {
3387       // If this value fits into a ULL, try to figure out what else it fits into
3388       // according to the rules of C99 6.4.4.1p5.
3389 
3390       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3391       // be an unsigned int.
3392       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3393 
3394       // Check from smallest to largest, picking the smallest type we can.
3395       unsigned Width = 0;
3396 
3397       // Microsoft specific integer suffixes are explicitly sized.
3398       if (Literal.MicrosoftInteger) {
3399         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3400           Width = 8;
3401           Ty = Context.CharTy;
3402         } else {
3403           Width = Literal.MicrosoftInteger;
3404           Ty = Context.getIntTypeForBitwidth(Width,
3405                                              /*Signed=*/!Literal.isUnsigned);
3406         }
3407       }
3408 
3409       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3410         // Are int/unsigned possibilities?
3411         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3412 
3413         // Does it fit in a unsigned int?
3414         if (ResultVal.isIntN(IntSize)) {
3415           // Does it fit in a signed int?
3416           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3417             Ty = Context.IntTy;
3418           else if (AllowUnsigned)
3419             Ty = Context.UnsignedIntTy;
3420           Width = IntSize;
3421         }
3422       }
3423 
3424       // Are long/unsigned long possibilities?
3425       if (Ty.isNull() && !Literal.isLongLong) {
3426         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3427 
3428         // Does it fit in a unsigned long?
3429         if (ResultVal.isIntN(LongSize)) {
3430           // Does it fit in a signed long?
3431           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3432             Ty = Context.LongTy;
3433           else if (AllowUnsigned)
3434             Ty = Context.UnsignedLongTy;
3435           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3436           // is compatible.
3437           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3438             const unsigned LongLongSize =
3439                 Context.getTargetInfo().getLongLongWidth();
3440             Diag(Tok.getLocation(),
3441                  getLangOpts().CPlusPlus
3442                      ? Literal.isLong
3443                            ? diag::warn_old_implicitly_unsigned_long_cxx
3444                            : /*C++98 UB*/ diag::
3445                                  ext_old_implicitly_unsigned_long_cxx
3446                      : diag::warn_old_implicitly_unsigned_long)
3447                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3448                                             : /*will be ill-formed*/ 1);
3449             Ty = Context.UnsignedLongTy;
3450           }
3451           Width = LongSize;
3452         }
3453       }
3454 
3455       // Check long long if needed.
3456       if (Ty.isNull()) {
3457         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3458 
3459         // Does it fit in a unsigned long long?
3460         if (ResultVal.isIntN(LongLongSize)) {
3461           // Does it fit in a signed long long?
3462           // To be compatible with MSVC, hex integer literals ending with the
3463           // LL or i64 suffix are always signed in Microsoft mode.
3464           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3465               (getLangOpts().MSVCCompat && Literal.isLongLong)))
3466             Ty = Context.LongLongTy;
3467           else if (AllowUnsigned)
3468             Ty = Context.UnsignedLongLongTy;
3469           Width = LongLongSize;
3470         }
3471       }
3472 
3473       // If we still couldn't decide a type, we probably have something that
3474       // does not fit in a signed long long, but has no U suffix.
3475       if (Ty.isNull()) {
3476         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3477         Ty = Context.UnsignedLongLongTy;
3478         Width = Context.getTargetInfo().getLongLongWidth();
3479       }
3480 
3481       if (ResultVal.getBitWidth() != Width)
3482         ResultVal = ResultVal.trunc(Width);
3483     }
3484     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3485   }
3486 
3487   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3488   if (Literal.isImaginary) {
3489     Res = new (Context) ImaginaryLiteral(Res,
3490                                         Context.getComplexType(Res->getType()));
3491 
3492     Diag(Tok.getLocation(), diag::ext_imaginary_constant);
3493   }
3494   return Res;
3495 }
3496 
3497 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3498   assert(E && "ActOnParenExpr() missing expr");
3499   return new (Context) ParenExpr(L, R, E);
3500 }
3501 
3502 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3503                                          SourceLocation Loc,
3504                                          SourceRange ArgRange) {
3505   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3506   // scalar or vector data type argument..."
3507   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3508   // type (C99 6.2.5p18) or void.
3509   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3510     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3511       << T << ArgRange;
3512     return true;
3513   }
3514 
3515   assert((T->isVoidType() || !T->isIncompleteType()) &&
3516          "Scalar types should always be complete");
3517   return false;
3518 }
3519 
3520 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3521                                            SourceLocation Loc,
3522                                            SourceRange ArgRange,
3523                                            UnaryExprOrTypeTrait TraitKind) {
3524   // Invalid types must be hard errors for SFINAE in C++.
3525   if (S.LangOpts.CPlusPlus)
3526     return true;
3527 
3528   // C99 6.5.3.4p1:
3529   if (T->isFunctionType() &&
3530       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3531     // sizeof(function)/alignof(function) is allowed as an extension.
3532     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3533       << TraitKind << ArgRange;
3534     return false;
3535   }
3536 
3537   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3538   // this is an error (OpenCL v1.1 s6.3.k)
3539   if (T->isVoidType()) {
3540     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3541                                         : diag::ext_sizeof_alignof_void_type;
3542     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3543     return false;
3544   }
3545 
3546   return true;
3547 }
3548 
3549 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3550                                              SourceLocation Loc,
3551                                              SourceRange ArgRange,
3552                                              UnaryExprOrTypeTrait TraitKind) {
3553   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3554   // runtime doesn't allow it.
3555   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3556     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3557       << T << (TraitKind == UETT_SizeOf)
3558       << ArgRange;
3559     return true;
3560   }
3561 
3562   return false;
3563 }
3564 
3565 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3566 /// pointer type is equal to T) and emit a warning if it is.
3567 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3568                                      Expr *E) {
3569   // Don't warn if the operation changed the type.
3570   if (T != E->getType())
3571     return;
3572 
3573   // Now look for array decays.
3574   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3575   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3576     return;
3577 
3578   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3579                                              << ICE->getType()
3580                                              << ICE->getSubExpr()->getType();
3581 }
3582 
3583 /// \brief Check the constraints on expression operands to unary type expression
3584 /// and type traits.
3585 ///
3586 /// Completes any types necessary and validates the constraints on the operand
3587 /// expression. The logic mostly mirrors the type-based overload, but may modify
3588 /// the expression as it completes the type for that expression through template
3589 /// instantiation, etc.
3590 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3591                                             UnaryExprOrTypeTrait ExprKind) {
3592   QualType ExprTy = E->getType();
3593   assert(!ExprTy->isReferenceType());
3594 
3595   if (ExprKind == UETT_VecStep)
3596     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3597                                         E->getSourceRange());
3598 
3599   // Whitelist some types as extensions
3600   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3601                                       E->getSourceRange(), ExprKind))
3602     return false;
3603 
3604   // 'alignof' applied to an expression only requires the base element type of
3605   // the expression to be complete. 'sizeof' requires the expression's type to
3606   // be complete (and will attempt to complete it if it's an array of unknown
3607   // bound).
3608   if (ExprKind == UETT_AlignOf) {
3609     if (RequireCompleteType(E->getExprLoc(),
3610                             Context.getBaseElementType(E->getType()),
3611                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3612                             E->getSourceRange()))
3613       return true;
3614   } else {
3615     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3616                                 ExprKind, E->getSourceRange()))
3617       return true;
3618   }
3619 
3620   // Completing the expression's type may have changed it.
3621   ExprTy = E->getType();
3622   assert(!ExprTy->isReferenceType());
3623 
3624   if (ExprTy->isFunctionType()) {
3625     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3626       << ExprKind << E->getSourceRange();
3627     return true;
3628   }
3629 
3630   // The operand for sizeof and alignof is in an unevaluated expression context,
3631   // so side effects could result in unintended consequences.
3632   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3633       !inTemplateInstantiation() && E->HasSideEffects(Context, false))
3634     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3635 
3636   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3637                                        E->getSourceRange(), ExprKind))
3638     return true;
3639 
3640   if (ExprKind == UETT_SizeOf) {
3641     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3642       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3643         QualType OType = PVD->getOriginalType();
3644         QualType Type = PVD->getType();
3645         if (Type->isPointerType() && OType->isArrayType()) {
3646           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3647             << Type << OType;
3648           Diag(PVD->getLocation(), diag::note_declared_at);
3649         }
3650       }
3651     }
3652 
3653     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3654     // decays into a pointer and returns an unintended result. This is most
3655     // likely a typo for "sizeof(array) op x".
3656     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3657       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3658                                BO->getLHS());
3659       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3660                                BO->getRHS());
3661     }
3662   }
3663 
3664   return false;
3665 }
3666 
3667 /// \brief Check the constraints on operands to unary expression and type
3668 /// traits.
3669 ///
3670 /// This will complete any types necessary, and validate the various constraints
3671 /// on those operands.
3672 ///
3673 /// The UsualUnaryConversions() function is *not* called by this routine.
3674 /// C99 6.3.2.1p[2-4] all state:
3675 ///   Except when it is the operand of the sizeof operator ...
3676 ///
3677 /// C++ [expr.sizeof]p4
3678 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3679 ///   standard conversions are not applied to the operand of sizeof.
3680 ///
3681 /// This policy is followed for all of the unary trait expressions.
3682 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3683                                             SourceLocation OpLoc,
3684                                             SourceRange ExprRange,
3685                                             UnaryExprOrTypeTrait ExprKind) {
3686   if (ExprType->isDependentType())
3687     return false;
3688 
3689   // C++ [expr.sizeof]p2:
3690   //     When applied to a reference or a reference type, the result
3691   //     is the size of the referenced type.
3692   // C++11 [expr.alignof]p3:
3693   //     When alignof is applied to a reference type, the result
3694   //     shall be the alignment of the referenced type.
3695   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3696     ExprType = Ref->getPointeeType();
3697 
3698   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3699   //   When alignof or _Alignof is applied to an array type, the result
3700   //   is the alignment of the element type.
3701   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3702     ExprType = Context.getBaseElementType(ExprType);
3703 
3704   if (ExprKind == UETT_VecStep)
3705     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3706 
3707   // Whitelist some types as extensions
3708   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3709                                       ExprKind))
3710     return false;
3711 
3712   if (RequireCompleteType(OpLoc, ExprType,
3713                           diag::err_sizeof_alignof_incomplete_type,
3714                           ExprKind, ExprRange))
3715     return true;
3716 
3717   if (ExprType->isFunctionType()) {
3718     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3719       << ExprKind << ExprRange;
3720     return true;
3721   }
3722 
3723   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3724                                        ExprKind))
3725     return true;
3726 
3727   return false;
3728 }
3729 
3730 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3731   E = E->IgnoreParens();
3732 
3733   // Cannot know anything else if the expression is dependent.
3734   if (E->isTypeDependent())
3735     return false;
3736 
3737   if (E->getObjectKind() == OK_BitField) {
3738     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3739        << 1 << E->getSourceRange();
3740     return true;
3741   }
3742 
3743   ValueDecl *D = nullptr;
3744   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3745     D = DRE->getDecl();
3746   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3747     D = ME->getMemberDecl();
3748   }
3749 
3750   // If it's a field, require the containing struct to have a
3751   // complete definition so that we can compute the layout.
3752   //
3753   // This can happen in C++11 onwards, either by naming the member
3754   // in a way that is not transformed into a member access expression
3755   // (in an unevaluated operand, for instance), or by naming the member
3756   // in a trailing-return-type.
3757   //
3758   // For the record, since __alignof__ on expressions is a GCC
3759   // extension, GCC seems to permit this but always gives the
3760   // nonsensical answer 0.
3761   //
3762   // We don't really need the layout here --- we could instead just
3763   // directly check for all the appropriate alignment-lowing
3764   // attributes --- but that would require duplicating a lot of
3765   // logic that just isn't worth duplicating for such a marginal
3766   // use-case.
3767   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3768     // Fast path this check, since we at least know the record has a
3769     // definition if we can find a member of it.
3770     if (!FD->getParent()->isCompleteDefinition()) {
3771       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3772         << E->getSourceRange();
3773       return true;
3774     }
3775 
3776     // Otherwise, if it's a field, and the field doesn't have
3777     // reference type, then it must have a complete type (or be a
3778     // flexible array member, which we explicitly want to
3779     // white-list anyway), which makes the following checks trivial.
3780     if (!FD->getType()->isReferenceType())
3781       return false;
3782   }
3783 
3784   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3785 }
3786 
3787 bool Sema::CheckVecStepExpr(Expr *E) {
3788   E = E->IgnoreParens();
3789 
3790   // Cannot know anything else if the expression is dependent.
3791   if (E->isTypeDependent())
3792     return false;
3793 
3794   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3795 }
3796 
3797 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3798                                         CapturingScopeInfo *CSI) {
3799   assert(T->isVariablyModifiedType());
3800   assert(CSI != nullptr);
3801 
3802   // We're going to walk down into the type and look for VLA expressions.
3803   do {
3804     const Type *Ty = T.getTypePtr();
3805     switch (Ty->getTypeClass()) {
3806 #define TYPE(Class, Base)
3807 #define ABSTRACT_TYPE(Class, Base)
3808 #define NON_CANONICAL_TYPE(Class, Base)
3809 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3810 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3811 #include "clang/AST/TypeNodes.def"
3812       T = QualType();
3813       break;
3814     // These types are never variably-modified.
3815     case Type::Builtin:
3816     case Type::Complex:
3817     case Type::Vector:
3818     case Type::ExtVector:
3819     case Type::Record:
3820     case Type::Enum:
3821     case Type::Elaborated:
3822     case Type::TemplateSpecialization:
3823     case Type::ObjCObject:
3824     case Type::ObjCInterface:
3825     case Type::ObjCObjectPointer:
3826     case Type::ObjCTypeParam:
3827     case Type::Pipe:
3828       llvm_unreachable("type class is never variably-modified!");
3829     case Type::Adjusted:
3830       T = cast<AdjustedType>(Ty)->getOriginalType();
3831       break;
3832     case Type::Decayed:
3833       T = cast<DecayedType>(Ty)->getPointeeType();
3834       break;
3835     case Type::Pointer:
3836       T = cast<PointerType>(Ty)->getPointeeType();
3837       break;
3838     case Type::BlockPointer:
3839       T = cast<BlockPointerType>(Ty)->getPointeeType();
3840       break;
3841     case Type::LValueReference:
3842     case Type::RValueReference:
3843       T = cast<ReferenceType>(Ty)->getPointeeType();
3844       break;
3845     case Type::MemberPointer:
3846       T = cast<MemberPointerType>(Ty)->getPointeeType();
3847       break;
3848     case Type::ConstantArray:
3849     case Type::IncompleteArray:
3850       // Losing element qualification here is fine.
3851       T = cast<ArrayType>(Ty)->getElementType();
3852       break;
3853     case Type::VariableArray: {
3854       // Losing element qualification here is fine.
3855       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3856 
3857       // Unknown size indication requires no size computation.
3858       // Otherwise, evaluate and record it.
3859       if (auto Size = VAT->getSizeExpr()) {
3860         if (!CSI->isVLATypeCaptured(VAT)) {
3861           RecordDecl *CapRecord = nullptr;
3862           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3863             CapRecord = LSI->Lambda;
3864           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3865             CapRecord = CRSI->TheRecordDecl;
3866           }
3867           if (CapRecord) {
3868             auto ExprLoc = Size->getExprLoc();
3869             auto SizeType = Context.getSizeType();
3870             // Build the non-static data member.
3871             auto Field =
3872                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3873                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3874                                   /*BW*/ nullptr, /*Mutable*/ false,
3875                                   /*InitStyle*/ ICIS_NoInit);
3876             Field->setImplicit(true);
3877             Field->setAccess(AS_private);
3878             Field->setCapturedVLAType(VAT);
3879             CapRecord->addDecl(Field);
3880 
3881             CSI->addVLATypeCapture(ExprLoc, SizeType);
3882           }
3883         }
3884       }
3885       T = VAT->getElementType();
3886       break;
3887     }
3888     case Type::FunctionProto:
3889     case Type::FunctionNoProto:
3890       T = cast<FunctionType>(Ty)->getReturnType();
3891       break;
3892     case Type::Paren:
3893     case Type::TypeOf:
3894     case Type::UnaryTransform:
3895     case Type::Attributed:
3896     case Type::SubstTemplateTypeParm:
3897     case Type::PackExpansion:
3898       // Keep walking after single level desugaring.
3899       T = T.getSingleStepDesugaredType(Context);
3900       break;
3901     case Type::Typedef:
3902       T = cast<TypedefType>(Ty)->desugar();
3903       break;
3904     case Type::Decltype:
3905       T = cast<DecltypeType>(Ty)->desugar();
3906       break;
3907     case Type::Auto:
3908     case Type::DeducedTemplateSpecialization:
3909       T = cast<DeducedType>(Ty)->getDeducedType();
3910       break;
3911     case Type::TypeOfExpr:
3912       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3913       break;
3914     case Type::Atomic:
3915       T = cast<AtomicType>(Ty)->getValueType();
3916       break;
3917     }
3918   } while (!T.isNull() && T->isVariablyModifiedType());
3919 }
3920 
3921 /// \brief Build a sizeof or alignof expression given a type operand.
3922 ExprResult
3923 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3924                                      SourceLocation OpLoc,
3925                                      UnaryExprOrTypeTrait ExprKind,
3926                                      SourceRange R) {
3927   if (!TInfo)
3928     return ExprError();
3929 
3930   QualType T = TInfo->getType();
3931 
3932   if (!T->isDependentType() &&
3933       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3934     return ExprError();
3935 
3936   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3937     if (auto *TT = T->getAs<TypedefType>()) {
3938       for (auto I = FunctionScopes.rbegin(),
3939                 E = std::prev(FunctionScopes.rend());
3940            I != E; ++I) {
3941         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3942         if (CSI == nullptr)
3943           break;
3944         DeclContext *DC = nullptr;
3945         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3946           DC = LSI->CallOperator;
3947         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3948           DC = CRSI->TheCapturedDecl;
3949         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
3950           DC = BSI->TheDecl;
3951         if (DC) {
3952           if (DC->containsDecl(TT->getDecl()))
3953             break;
3954           captureVariablyModifiedType(Context, T, CSI);
3955         }
3956       }
3957     }
3958   }
3959 
3960   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3961   return new (Context) UnaryExprOrTypeTraitExpr(
3962       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3963 }
3964 
3965 /// \brief Build a sizeof or alignof expression given an expression
3966 /// operand.
3967 ExprResult
3968 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3969                                      UnaryExprOrTypeTrait ExprKind) {
3970   ExprResult PE = CheckPlaceholderExpr(E);
3971   if (PE.isInvalid())
3972     return ExprError();
3973 
3974   E = PE.get();
3975 
3976   // Verify that the operand is valid.
3977   bool isInvalid = false;
3978   if (E->isTypeDependent()) {
3979     // Delay type-checking for type-dependent expressions.
3980   } else if (ExprKind == UETT_AlignOf) {
3981     isInvalid = CheckAlignOfExpr(*this, E);
3982   } else if (ExprKind == UETT_VecStep) {
3983     isInvalid = CheckVecStepExpr(E);
3984   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3985       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3986       isInvalid = true;
3987   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3988     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3989     isInvalid = true;
3990   } else {
3991     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3992   }
3993 
3994   if (isInvalid)
3995     return ExprError();
3996 
3997   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3998     PE = TransformToPotentiallyEvaluated(E);
3999     if (PE.isInvalid()) return ExprError();
4000     E = PE.get();
4001   }
4002 
4003   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4004   return new (Context) UnaryExprOrTypeTraitExpr(
4005       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4006 }
4007 
4008 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4009 /// expr and the same for @c alignof and @c __alignof
4010 /// Note that the ArgRange is invalid if isType is false.
4011 ExprResult
4012 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4013                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4014                                     void *TyOrEx, SourceRange ArgRange) {
4015   // If error parsing type, ignore.
4016   if (!TyOrEx) return ExprError();
4017 
4018   if (IsType) {
4019     TypeSourceInfo *TInfo;
4020     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4021     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4022   }
4023 
4024   Expr *ArgEx = (Expr *)TyOrEx;
4025   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4026   return Result;
4027 }
4028 
4029 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4030                                      bool IsReal) {
4031   if (V.get()->isTypeDependent())
4032     return S.Context.DependentTy;
4033 
4034   // _Real and _Imag are only l-values for normal l-values.
4035   if (V.get()->getObjectKind() != OK_Ordinary) {
4036     V = S.DefaultLvalueConversion(V.get());
4037     if (V.isInvalid())
4038       return QualType();
4039   }
4040 
4041   // These operators return the element type of a complex type.
4042   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4043     return CT->getElementType();
4044 
4045   // Otherwise they pass through real integer and floating point types here.
4046   if (V.get()->getType()->isArithmeticType())
4047     return V.get()->getType();
4048 
4049   // Test for placeholders.
4050   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4051   if (PR.isInvalid()) return QualType();
4052   if (PR.get() != V.get()) {
4053     V = PR;
4054     return CheckRealImagOperand(S, V, Loc, IsReal);
4055   }
4056 
4057   // Reject anything else.
4058   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4059     << (IsReal ? "__real" : "__imag");
4060   return QualType();
4061 }
4062 
4063 
4064 
4065 ExprResult
4066 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4067                           tok::TokenKind Kind, Expr *Input) {
4068   UnaryOperatorKind Opc;
4069   switch (Kind) {
4070   default: llvm_unreachable("Unknown unary op!");
4071   case tok::plusplus:   Opc = UO_PostInc; break;
4072   case tok::minusminus: Opc = UO_PostDec; break;
4073   }
4074 
4075   // Since this might is a postfix expression, get rid of ParenListExprs.
4076   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4077   if (Result.isInvalid()) return ExprError();
4078   Input = Result.get();
4079 
4080   return BuildUnaryOp(S, OpLoc, Opc, Input);
4081 }
4082 
4083 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4084 ///
4085 /// \return true on error
4086 static bool checkArithmeticOnObjCPointer(Sema &S,
4087                                          SourceLocation opLoc,
4088                                          Expr *op) {
4089   assert(op->getType()->isObjCObjectPointerType());
4090   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4091       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4092     return false;
4093 
4094   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4095     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4096     << op->getSourceRange();
4097   return true;
4098 }
4099 
4100 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4101   auto *BaseNoParens = Base->IgnoreParens();
4102   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4103     return MSProp->getPropertyDecl()->getType()->isArrayType();
4104   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4105 }
4106 
4107 ExprResult
4108 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4109                               Expr *idx, SourceLocation rbLoc) {
4110   if (base && !base->getType().isNull() &&
4111       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4112     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4113                                     /*Length=*/nullptr, rbLoc);
4114 
4115   // Since this might be a postfix expression, get rid of ParenListExprs.
4116   if (isa<ParenListExpr>(base)) {
4117     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4118     if (result.isInvalid()) return ExprError();
4119     base = result.get();
4120   }
4121 
4122   // Handle any non-overload placeholder types in the base and index
4123   // expressions.  We can't handle overloads here because the other
4124   // operand might be an overloadable type, in which case the overload
4125   // resolution for the operator overload should get the first crack
4126   // at the overload.
4127   bool IsMSPropertySubscript = false;
4128   if (base->getType()->isNonOverloadPlaceholderType()) {
4129     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4130     if (!IsMSPropertySubscript) {
4131       ExprResult result = CheckPlaceholderExpr(base);
4132       if (result.isInvalid())
4133         return ExprError();
4134       base = result.get();
4135     }
4136   }
4137   if (idx->getType()->isNonOverloadPlaceholderType()) {
4138     ExprResult result = CheckPlaceholderExpr(idx);
4139     if (result.isInvalid()) return ExprError();
4140     idx = result.get();
4141   }
4142 
4143   // Build an unanalyzed expression if either operand is type-dependent.
4144   if (getLangOpts().CPlusPlus &&
4145       (base->isTypeDependent() || idx->isTypeDependent())) {
4146     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4147                                             VK_LValue, OK_Ordinary, rbLoc);
4148   }
4149 
4150   // MSDN, property (C++)
4151   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4152   // This attribute can also be used in the declaration of an empty array in a
4153   // class or structure definition. For example:
4154   // __declspec(property(get=GetX, put=PutX)) int x[];
4155   // The above statement indicates that x[] can be used with one or more array
4156   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4157   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4158   if (IsMSPropertySubscript) {
4159     // Build MS property subscript expression if base is MS property reference
4160     // or MS property subscript.
4161     return new (Context) MSPropertySubscriptExpr(
4162         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4163   }
4164 
4165   // Use C++ overloaded-operator rules if either operand has record
4166   // type.  The spec says to do this if either type is *overloadable*,
4167   // but enum types can't declare subscript operators or conversion
4168   // operators, so there's nothing interesting for overload resolution
4169   // to do if there aren't any record types involved.
4170   //
4171   // ObjC pointers have their own subscripting logic that is not tied
4172   // to overload resolution and so should not take this path.
4173   if (getLangOpts().CPlusPlus &&
4174       (base->getType()->isRecordType() ||
4175        (!base->getType()->isObjCObjectPointerType() &&
4176         idx->getType()->isRecordType()))) {
4177     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4178   }
4179 
4180   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4181 }
4182 
4183 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4184                                           Expr *LowerBound,
4185                                           SourceLocation ColonLoc, Expr *Length,
4186                                           SourceLocation RBLoc) {
4187   if (Base->getType()->isPlaceholderType() &&
4188       !Base->getType()->isSpecificPlaceholderType(
4189           BuiltinType::OMPArraySection)) {
4190     ExprResult Result = CheckPlaceholderExpr(Base);
4191     if (Result.isInvalid())
4192       return ExprError();
4193     Base = Result.get();
4194   }
4195   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4196     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4197     if (Result.isInvalid())
4198       return ExprError();
4199     Result = DefaultLvalueConversion(Result.get());
4200     if (Result.isInvalid())
4201       return ExprError();
4202     LowerBound = Result.get();
4203   }
4204   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4205     ExprResult Result = CheckPlaceholderExpr(Length);
4206     if (Result.isInvalid())
4207       return ExprError();
4208     Result = DefaultLvalueConversion(Result.get());
4209     if (Result.isInvalid())
4210       return ExprError();
4211     Length = Result.get();
4212   }
4213 
4214   // Build an unanalyzed expression if either operand is type-dependent.
4215   if (Base->isTypeDependent() ||
4216       (LowerBound &&
4217        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4218       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4219     return new (Context)
4220         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4221                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4222   }
4223 
4224   // Perform default conversions.
4225   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4226   QualType ResultTy;
4227   if (OriginalTy->isAnyPointerType()) {
4228     ResultTy = OriginalTy->getPointeeType();
4229   } else if (OriginalTy->isArrayType()) {
4230     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4231   } else {
4232     return ExprError(
4233         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4234         << Base->getSourceRange());
4235   }
4236   // C99 6.5.2.1p1
4237   if (LowerBound) {
4238     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4239                                                       LowerBound);
4240     if (Res.isInvalid())
4241       return ExprError(Diag(LowerBound->getExprLoc(),
4242                             diag::err_omp_typecheck_section_not_integer)
4243                        << 0 << LowerBound->getSourceRange());
4244     LowerBound = Res.get();
4245 
4246     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4247         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4248       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4249           << 0 << LowerBound->getSourceRange();
4250   }
4251   if (Length) {
4252     auto Res =
4253         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4254     if (Res.isInvalid())
4255       return ExprError(Diag(Length->getExprLoc(),
4256                             diag::err_omp_typecheck_section_not_integer)
4257                        << 1 << Length->getSourceRange());
4258     Length = Res.get();
4259 
4260     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4261         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4262       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4263           << 1 << Length->getSourceRange();
4264   }
4265 
4266   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4267   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4268   // type. Note that functions are not objects, and that (in C99 parlance)
4269   // incomplete types are not object types.
4270   if (ResultTy->isFunctionType()) {
4271     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4272         << ResultTy << Base->getSourceRange();
4273     return ExprError();
4274   }
4275 
4276   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4277                           diag::err_omp_section_incomplete_type, Base))
4278     return ExprError();
4279 
4280   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4281     llvm::APSInt LowerBoundValue;
4282     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4283       // OpenMP 4.5, [2.4 Array Sections]
4284       // The array section must be a subset of the original array.
4285       if (LowerBoundValue.isNegative()) {
4286         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4287             << LowerBound->getSourceRange();
4288         return ExprError();
4289       }
4290     }
4291   }
4292 
4293   if (Length) {
4294     llvm::APSInt LengthValue;
4295     if (Length->EvaluateAsInt(LengthValue, Context)) {
4296       // OpenMP 4.5, [2.4 Array Sections]
4297       // The length must evaluate to non-negative integers.
4298       if (LengthValue.isNegative()) {
4299         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4300             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4301             << Length->getSourceRange();
4302         return ExprError();
4303       }
4304     }
4305   } else if (ColonLoc.isValid() &&
4306              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4307                                       !OriginalTy->isVariableArrayType()))) {
4308     // OpenMP 4.5, [2.4 Array Sections]
4309     // When the size of the array dimension is not known, the length must be
4310     // specified explicitly.
4311     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4312         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4313     return ExprError();
4314   }
4315 
4316   if (!Base->getType()->isSpecificPlaceholderType(
4317           BuiltinType::OMPArraySection)) {
4318     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4319     if (Result.isInvalid())
4320       return ExprError();
4321     Base = Result.get();
4322   }
4323   return new (Context)
4324       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4325                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4326 }
4327 
4328 ExprResult
4329 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4330                                       Expr *Idx, SourceLocation RLoc) {
4331   Expr *LHSExp = Base;
4332   Expr *RHSExp = Idx;
4333 
4334   ExprValueKind VK = VK_LValue;
4335   ExprObjectKind OK = OK_Ordinary;
4336 
4337   // Per C++ core issue 1213, the result is an xvalue if either operand is
4338   // a non-lvalue array, and an lvalue otherwise.
4339   if (getLangOpts().CPlusPlus11 &&
4340       ((LHSExp->getType()->isArrayType() && !LHSExp->isLValue()) ||
4341        (RHSExp->getType()->isArrayType() && !RHSExp->isLValue())))
4342     VK = VK_XValue;
4343 
4344   // Perform default conversions.
4345   if (!LHSExp->getType()->getAs<VectorType>()) {
4346     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4347     if (Result.isInvalid())
4348       return ExprError();
4349     LHSExp = Result.get();
4350   }
4351   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4352   if (Result.isInvalid())
4353     return ExprError();
4354   RHSExp = Result.get();
4355 
4356   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4357 
4358   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4359   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4360   // in the subscript position. As a result, we need to derive the array base
4361   // and index from the expression types.
4362   Expr *BaseExpr, *IndexExpr;
4363   QualType ResultType;
4364   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4365     BaseExpr = LHSExp;
4366     IndexExpr = RHSExp;
4367     ResultType = Context.DependentTy;
4368   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4369     BaseExpr = LHSExp;
4370     IndexExpr = RHSExp;
4371     ResultType = PTy->getPointeeType();
4372   } else if (const ObjCObjectPointerType *PTy =
4373                LHSTy->getAs<ObjCObjectPointerType>()) {
4374     BaseExpr = LHSExp;
4375     IndexExpr = RHSExp;
4376 
4377     // Use custom logic if this should be the pseudo-object subscript
4378     // expression.
4379     if (!LangOpts.isSubscriptPointerArithmetic())
4380       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4381                                           nullptr);
4382 
4383     ResultType = PTy->getPointeeType();
4384   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4385      // Handle the uncommon case of "123[Ptr]".
4386     BaseExpr = RHSExp;
4387     IndexExpr = LHSExp;
4388     ResultType = PTy->getPointeeType();
4389   } else if (const ObjCObjectPointerType *PTy =
4390                RHSTy->getAs<ObjCObjectPointerType>()) {
4391      // Handle the uncommon case of "123[Ptr]".
4392     BaseExpr = RHSExp;
4393     IndexExpr = LHSExp;
4394     ResultType = PTy->getPointeeType();
4395     if (!LangOpts.isSubscriptPointerArithmetic()) {
4396       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4397         << ResultType << BaseExpr->getSourceRange();
4398       return ExprError();
4399     }
4400   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4401     BaseExpr = LHSExp;    // vectors: V[123]
4402     IndexExpr = RHSExp;
4403     VK = LHSExp->getValueKind();
4404     if (VK != VK_RValue)
4405       OK = OK_VectorComponent;
4406 
4407     ResultType = VTy->getElementType();
4408     QualType BaseType = BaseExpr->getType();
4409     Qualifiers BaseQuals = BaseType.getQualifiers();
4410     Qualifiers MemberQuals = ResultType.getQualifiers();
4411     Qualifiers Combined = BaseQuals + MemberQuals;
4412     if (Combined != MemberQuals)
4413       ResultType = Context.getQualifiedType(ResultType, Combined);
4414   } else if (LHSTy->isArrayType()) {
4415     // If we see an array that wasn't promoted by
4416     // DefaultFunctionArrayLvalueConversion, it must be an array that
4417     // wasn't promoted because of the C90 rule that doesn't
4418     // allow promoting non-lvalue arrays.  Warn, then
4419     // force the promotion here.
4420     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4421         LHSExp->getSourceRange();
4422     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4423                                CK_ArrayToPointerDecay).get();
4424     LHSTy = LHSExp->getType();
4425 
4426     BaseExpr = LHSExp;
4427     IndexExpr = RHSExp;
4428     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4429   } else if (RHSTy->isArrayType()) {
4430     // Same as previous, except for 123[f().a] case
4431     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4432         RHSExp->getSourceRange();
4433     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4434                                CK_ArrayToPointerDecay).get();
4435     RHSTy = RHSExp->getType();
4436 
4437     BaseExpr = RHSExp;
4438     IndexExpr = LHSExp;
4439     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4440   } else {
4441     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4442        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4443   }
4444   // C99 6.5.2.1p1
4445   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4446     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4447                      << IndexExpr->getSourceRange());
4448 
4449   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4450        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4451          && !IndexExpr->isTypeDependent())
4452     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4453 
4454   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4455   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4456   // type. Note that Functions are not objects, and that (in C99 parlance)
4457   // incomplete types are not object types.
4458   if (ResultType->isFunctionType()) {
4459     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4460       << ResultType << BaseExpr->getSourceRange();
4461     return ExprError();
4462   }
4463 
4464   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4465     // GNU extension: subscripting on pointer to void
4466     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4467       << BaseExpr->getSourceRange();
4468 
4469     // C forbids expressions of unqualified void type from being l-values.
4470     // See IsCForbiddenLValueType.
4471     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4472   } else if (!ResultType->isDependentType() &&
4473       RequireCompleteType(LLoc, ResultType,
4474                           diag::err_subscript_incomplete_type, BaseExpr))
4475     return ExprError();
4476 
4477   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4478          !ResultType.isCForbiddenLValueType());
4479 
4480   return new (Context)
4481       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4482 }
4483 
4484 bool Sema::CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD,
4485                                   ParmVarDecl *Param) {
4486   if (Param->hasUnparsedDefaultArg()) {
4487     Diag(CallLoc,
4488          diag::err_use_of_default_argument_to_function_declared_later) <<
4489       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4490     Diag(UnparsedDefaultArgLocs[Param],
4491          diag::note_default_argument_declared_here);
4492     return true;
4493   }
4494 
4495   if (Param->hasUninstantiatedDefaultArg()) {
4496     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4497 
4498     EnterExpressionEvaluationContext EvalContext(
4499         *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
4500 
4501     // Instantiate the expression.
4502     //
4503     // FIXME: Pass in a correct Pattern argument, otherwise
4504     // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4505     //
4506     // template<typename T>
4507     // struct A {
4508     //   static int FooImpl();
4509     //
4510     //   template<typename Tp>
4511     //   // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4512     //   // template argument list [[T], [Tp]], should be [[Tp]].
4513     //   friend A<Tp> Foo(int a);
4514     // };
4515     //
4516     // template<typename T>
4517     // A<T> Foo(int a = A<T>::FooImpl());
4518     MultiLevelTemplateArgumentList MutiLevelArgList
4519       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4520 
4521     InstantiatingTemplate Inst(*this, CallLoc, Param,
4522                                MutiLevelArgList.getInnermost());
4523     if (Inst.isInvalid())
4524       return true;
4525     if (Inst.isAlreadyInstantiating()) {
4526       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4527       Param->setInvalidDecl();
4528       return true;
4529     }
4530 
4531     ExprResult Result;
4532     {
4533       // C++ [dcl.fct.default]p5:
4534       //   The names in the [default argument] expression are bound, and
4535       //   the semantic constraints are checked, at the point where the
4536       //   default argument expression appears.
4537       ContextRAII SavedContext(*this, FD);
4538       LocalInstantiationScope Local(*this);
4539       Result = SubstInitializer(UninstExpr, MutiLevelArgList,
4540                                 /*DirectInit*/false);
4541     }
4542     if (Result.isInvalid())
4543       return true;
4544 
4545     // Check the expression as an initializer for the parameter.
4546     InitializedEntity Entity
4547       = InitializedEntity::InitializeParameter(Context, Param);
4548     InitializationKind Kind
4549       = InitializationKind::CreateCopy(Param->getLocation(),
4550              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4551     Expr *ResultE = Result.getAs<Expr>();
4552 
4553     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4554     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4555     if (Result.isInvalid())
4556       return true;
4557 
4558     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4559                                  Param->getOuterLocStart());
4560     if (Result.isInvalid())
4561       return true;
4562 
4563     // Remember the instantiated default argument.
4564     Param->setDefaultArg(Result.getAs<Expr>());
4565     if (ASTMutationListener *L = getASTMutationListener()) {
4566       L->DefaultArgumentInstantiated(Param);
4567     }
4568   }
4569 
4570   // If the default argument expression is not set yet, we are building it now.
4571   if (!Param->hasInit()) {
4572     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4573     Param->setInvalidDecl();
4574     return true;
4575   }
4576 
4577   // If the default expression creates temporaries, we need to
4578   // push them to the current stack of expression temporaries so they'll
4579   // be properly destroyed.
4580   // FIXME: We should really be rebuilding the default argument with new
4581   // bound temporaries; see the comment in PR5810.
4582   // We don't need to do that with block decls, though, because
4583   // blocks in default argument expression can never capture anything.
4584   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4585     // Set the "needs cleanups" bit regardless of whether there are
4586     // any explicit objects.
4587     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4588 
4589     // Append all the objects to the cleanup list.  Right now, this
4590     // should always be a no-op, because blocks in default argument
4591     // expressions should never be able to capture anything.
4592     assert(!Init->getNumObjects() &&
4593            "default argument expression has capturing blocks?");
4594   }
4595 
4596   // We already type-checked the argument, so we know it works.
4597   // Just mark all of the declarations in this potentially-evaluated expression
4598   // as being "referenced".
4599   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4600                                    /*SkipLocalVariables=*/true);
4601   return false;
4602 }
4603 
4604 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4605                                         FunctionDecl *FD, ParmVarDecl *Param) {
4606   if (CheckCXXDefaultArgExpr(CallLoc, FD, Param))
4607     return ExprError();
4608   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4609 }
4610 
4611 Sema::VariadicCallType
4612 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4613                           Expr *Fn) {
4614   if (Proto && Proto->isVariadic()) {
4615     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4616       return VariadicConstructor;
4617     else if (Fn && Fn->getType()->isBlockPointerType())
4618       return VariadicBlock;
4619     else if (FDecl) {
4620       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4621         if (Method->isInstance())
4622           return VariadicMethod;
4623     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4624       return VariadicMethod;
4625     return VariadicFunction;
4626   }
4627   return VariadicDoesNotApply;
4628 }
4629 
4630 namespace {
4631 class FunctionCallCCC : public FunctionCallFilterCCC {
4632 public:
4633   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4634                   unsigned NumArgs, MemberExpr *ME)
4635       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4636         FunctionName(FuncName) {}
4637 
4638   bool ValidateCandidate(const TypoCorrection &candidate) override {
4639     if (!candidate.getCorrectionSpecifier() ||
4640         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4641       return false;
4642     }
4643 
4644     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4645   }
4646 
4647 private:
4648   const IdentifierInfo *const FunctionName;
4649 };
4650 }
4651 
4652 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4653                                                FunctionDecl *FDecl,
4654                                                ArrayRef<Expr *> Args) {
4655   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4656   DeclarationName FuncName = FDecl->getDeclName();
4657   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4658 
4659   if (TypoCorrection Corrected = S.CorrectTypo(
4660           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4661           S.getScopeForContext(S.CurContext), nullptr,
4662           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4663                                              Args.size(), ME),
4664           Sema::CTK_ErrorRecovery)) {
4665     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4666       if (Corrected.isOverloaded()) {
4667         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4668         OverloadCandidateSet::iterator Best;
4669         for (NamedDecl *CD : Corrected) {
4670           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4671             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4672                                    OCS);
4673         }
4674         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4675         case OR_Success:
4676           ND = Best->FoundDecl;
4677           Corrected.setCorrectionDecl(ND);
4678           break;
4679         default:
4680           break;
4681         }
4682       }
4683       ND = ND->getUnderlyingDecl();
4684       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4685         return Corrected;
4686     }
4687   }
4688   return TypoCorrection();
4689 }
4690 
4691 /// ConvertArgumentsForCall - Converts the arguments specified in
4692 /// Args/NumArgs to the parameter types of the function FDecl with
4693 /// function prototype Proto. Call is the call expression itself, and
4694 /// Fn is the function expression. For a C++ member function, this
4695 /// routine does not attempt to convert the object argument. Returns
4696 /// true if the call is ill-formed.
4697 bool
4698 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4699                               FunctionDecl *FDecl,
4700                               const FunctionProtoType *Proto,
4701                               ArrayRef<Expr *> Args,
4702                               SourceLocation RParenLoc,
4703                               bool IsExecConfig) {
4704   // Bail out early if calling a builtin with custom typechecking.
4705   if (FDecl)
4706     if (unsigned ID = FDecl->getBuiltinID())
4707       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4708         return false;
4709 
4710   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4711   // assignment, to the types of the corresponding parameter, ...
4712   unsigned NumParams = Proto->getNumParams();
4713   bool Invalid = false;
4714   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4715   unsigned FnKind = Fn->getType()->isBlockPointerType()
4716                        ? 1 /* block */
4717                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4718                                        : 0 /* function */);
4719 
4720   // If too few arguments are available (and we don't have default
4721   // arguments for the remaining parameters), don't make the call.
4722   if (Args.size() < NumParams) {
4723     if (Args.size() < MinArgs) {
4724       TypoCorrection TC;
4725       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4726         unsigned diag_id =
4727             MinArgs == NumParams && !Proto->isVariadic()
4728                 ? diag::err_typecheck_call_too_few_args_suggest
4729                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4730         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4731                                         << static_cast<unsigned>(Args.size())
4732                                         << TC.getCorrectionRange());
4733       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4734         Diag(RParenLoc,
4735              MinArgs == NumParams && !Proto->isVariadic()
4736                  ? diag::err_typecheck_call_too_few_args_one
4737                  : diag::err_typecheck_call_too_few_args_at_least_one)
4738             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4739       else
4740         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4741                             ? diag::err_typecheck_call_too_few_args
4742                             : diag::err_typecheck_call_too_few_args_at_least)
4743             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4744             << Fn->getSourceRange();
4745 
4746       // Emit the location of the prototype.
4747       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4748         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4749           << FDecl;
4750 
4751       return true;
4752     }
4753     Call->setNumArgs(Context, NumParams);
4754   }
4755 
4756   // If too many are passed and not variadic, error on the extras and drop
4757   // them.
4758   if (Args.size() > NumParams) {
4759     if (!Proto->isVariadic()) {
4760       TypoCorrection TC;
4761       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4762         unsigned diag_id =
4763             MinArgs == NumParams && !Proto->isVariadic()
4764                 ? diag::err_typecheck_call_too_many_args_suggest
4765                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4766         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4767                                         << static_cast<unsigned>(Args.size())
4768                                         << TC.getCorrectionRange());
4769       } else if (NumParams == 1 && FDecl &&
4770                  FDecl->getParamDecl(0)->getDeclName())
4771         Diag(Args[NumParams]->getLocStart(),
4772              MinArgs == NumParams
4773                  ? diag::err_typecheck_call_too_many_args_one
4774                  : diag::err_typecheck_call_too_many_args_at_most_one)
4775             << FnKind << FDecl->getParamDecl(0)
4776             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4777             << SourceRange(Args[NumParams]->getLocStart(),
4778                            Args.back()->getLocEnd());
4779       else
4780         Diag(Args[NumParams]->getLocStart(),
4781              MinArgs == NumParams
4782                  ? diag::err_typecheck_call_too_many_args
4783                  : diag::err_typecheck_call_too_many_args_at_most)
4784             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4785             << Fn->getSourceRange()
4786             << SourceRange(Args[NumParams]->getLocStart(),
4787                            Args.back()->getLocEnd());
4788 
4789       // Emit the location of the prototype.
4790       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4791         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4792           << FDecl;
4793 
4794       // This deletes the extra arguments.
4795       Call->setNumArgs(Context, NumParams);
4796       return true;
4797     }
4798   }
4799   SmallVector<Expr *, 8> AllArgs;
4800   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4801 
4802   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4803                                    Proto, 0, Args, AllArgs, CallType);
4804   if (Invalid)
4805     return true;
4806   unsigned TotalNumArgs = AllArgs.size();
4807   for (unsigned i = 0; i < TotalNumArgs; ++i)
4808     Call->setArg(i, AllArgs[i]);
4809 
4810   return false;
4811 }
4812 
4813 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4814                                   const FunctionProtoType *Proto,
4815                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4816                                   SmallVectorImpl<Expr *> &AllArgs,
4817                                   VariadicCallType CallType, bool AllowExplicit,
4818                                   bool IsListInitialization) {
4819   unsigned NumParams = Proto->getNumParams();
4820   bool Invalid = false;
4821   size_t ArgIx = 0;
4822   // Continue to check argument types (even if we have too few/many args).
4823   for (unsigned i = FirstParam; i < NumParams; i++) {
4824     QualType ProtoArgType = Proto->getParamType(i);
4825 
4826     Expr *Arg;
4827     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4828     if (ArgIx < Args.size()) {
4829       Arg = Args[ArgIx++];
4830 
4831       if (RequireCompleteType(Arg->getLocStart(),
4832                               ProtoArgType,
4833                               diag::err_call_incomplete_argument, Arg))
4834         return true;
4835 
4836       // Strip the unbridged-cast placeholder expression off, if applicable.
4837       bool CFAudited = false;
4838       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4839           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4840           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4841         Arg = stripARCUnbridgedCast(Arg);
4842       else if (getLangOpts().ObjCAutoRefCount &&
4843                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4844                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4845         CFAudited = true;
4846 
4847       if (Proto->getExtParameterInfo(i).isNoEscape())
4848         if (auto *BE = dyn_cast<BlockExpr>(Arg->IgnoreParenNoopCasts(Context)))
4849           BE->getBlockDecl()->setDoesNotEscape();
4850 
4851       InitializedEntity Entity =
4852           Param ? InitializedEntity::InitializeParameter(Context, Param,
4853                                                          ProtoArgType)
4854                 : InitializedEntity::InitializeParameter(
4855                       Context, ProtoArgType, Proto->isParamConsumed(i));
4856 
4857       // Remember that parameter belongs to a CF audited API.
4858       if (CFAudited)
4859         Entity.setParameterCFAudited();
4860 
4861       ExprResult ArgE = PerformCopyInitialization(
4862           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4863       if (ArgE.isInvalid())
4864         return true;
4865 
4866       Arg = ArgE.getAs<Expr>();
4867     } else {
4868       assert(Param && "can't use default arguments without a known callee");
4869 
4870       ExprResult ArgExpr =
4871         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4872       if (ArgExpr.isInvalid())
4873         return true;
4874 
4875       Arg = ArgExpr.getAs<Expr>();
4876     }
4877 
4878     // Check for array bounds violations for each argument to the call. This
4879     // check only triggers warnings when the argument isn't a more complex Expr
4880     // with its own checking, such as a BinaryOperator.
4881     CheckArrayAccess(Arg);
4882 
4883     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4884     CheckStaticArrayArgument(CallLoc, Param, Arg);
4885 
4886     AllArgs.push_back(Arg);
4887   }
4888 
4889   // If this is a variadic call, handle args passed through "...".
4890   if (CallType != VariadicDoesNotApply) {
4891     // Assume that extern "C" functions with variadic arguments that
4892     // return __unknown_anytype aren't *really* variadic.
4893     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4894         FDecl->isExternC()) {
4895       for (Expr *A : Args.slice(ArgIx)) {
4896         QualType paramType; // ignored
4897         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4898         Invalid |= arg.isInvalid();
4899         AllArgs.push_back(arg.get());
4900       }
4901 
4902     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4903     } else {
4904       for (Expr *A : Args.slice(ArgIx)) {
4905         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4906         Invalid |= Arg.isInvalid();
4907         AllArgs.push_back(Arg.get());
4908       }
4909     }
4910 
4911     // Check for array bounds violations.
4912     for (Expr *A : Args.slice(ArgIx))
4913       CheckArrayAccess(A);
4914   }
4915   return Invalid;
4916 }
4917 
4918 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4919   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4920   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4921     TL = DTL.getOriginalLoc();
4922   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4923     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4924       << ATL.getLocalSourceRange();
4925 }
4926 
4927 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4928 /// array parameter, check that it is non-null, and that if it is formed by
4929 /// array-to-pointer decay, the underlying array is sufficiently large.
4930 ///
4931 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4932 /// array type derivation, then for each call to the function, the value of the
4933 /// corresponding actual argument shall provide access to the first element of
4934 /// an array with at least as many elements as specified by the size expression.
4935 void
4936 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4937                                ParmVarDecl *Param,
4938                                const Expr *ArgExpr) {
4939   // Static array parameters are not supported in C++.
4940   if (!Param || getLangOpts().CPlusPlus)
4941     return;
4942 
4943   QualType OrigTy = Param->getOriginalType();
4944 
4945   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4946   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4947     return;
4948 
4949   if (ArgExpr->isNullPointerConstant(Context,
4950                                      Expr::NPC_NeverValueDependent)) {
4951     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4952     DiagnoseCalleeStaticArrayParam(*this, Param);
4953     return;
4954   }
4955 
4956   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4957   if (!CAT)
4958     return;
4959 
4960   const ConstantArrayType *ArgCAT =
4961     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4962   if (!ArgCAT)
4963     return;
4964 
4965   if (ArgCAT->getSize().ult(CAT->getSize())) {
4966     Diag(CallLoc, diag::warn_static_array_too_small)
4967       << ArgExpr->getSourceRange()
4968       << (unsigned) ArgCAT->getSize().getZExtValue()
4969       << (unsigned) CAT->getSize().getZExtValue();
4970     DiagnoseCalleeStaticArrayParam(*this, Param);
4971   }
4972 }
4973 
4974 /// Given a function expression of unknown-any type, try to rebuild it
4975 /// to have a function type.
4976 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4977 
4978 /// Is the given type a placeholder that we need to lower out
4979 /// immediately during argument processing?
4980 static bool isPlaceholderToRemoveAsArg(QualType type) {
4981   // Placeholders are never sugared.
4982   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4983   if (!placeholder) return false;
4984 
4985   switch (placeholder->getKind()) {
4986   // Ignore all the non-placeholder types.
4987 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
4988   case BuiltinType::Id:
4989 #include "clang/Basic/OpenCLImageTypes.def"
4990 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4991 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4992 #include "clang/AST/BuiltinTypes.def"
4993     return false;
4994 
4995   // We cannot lower out overload sets; they might validly be resolved
4996   // by the call machinery.
4997   case BuiltinType::Overload:
4998     return false;
4999 
5000   // Unbridged casts in ARC can be handled in some call positions and
5001   // should be left in place.
5002   case BuiltinType::ARCUnbridgedCast:
5003     return false;
5004 
5005   // Pseudo-objects should be converted as soon as possible.
5006   case BuiltinType::PseudoObject:
5007     return true;
5008 
5009   // The debugger mode could theoretically but currently does not try
5010   // to resolve unknown-typed arguments based on known parameter types.
5011   case BuiltinType::UnknownAny:
5012     return true;
5013 
5014   // These are always invalid as call arguments and should be reported.
5015   case BuiltinType::BoundMember:
5016   case BuiltinType::BuiltinFn:
5017   case BuiltinType::OMPArraySection:
5018     return true;
5019 
5020   }
5021   llvm_unreachable("bad builtin type kind");
5022 }
5023 
5024 /// Check an argument list for placeholders that we won't try to
5025 /// handle later.
5026 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5027   // Apply this processing to all the arguments at once instead of
5028   // dying at the first failure.
5029   bool hasInvalid = false;
5030   for (size_t i = 0, e = args.size(); i != e; i++) {
5031     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5032       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5033       if (result.isInvalid()) hasInvalid = true;
5034       else args[i] = result.get();
5035     } else if (hasInvalid) {
5036       (void)S.CorrectDelayedTyposInExpr(args[i]);
5037     }
5038   }
5039   return hasInvalid;
5040 }
5041 
5042 /// If a builtin function has a pointer argument with no explicit address
5043 /// space, then it should be able to accept a pointer to any address
5044 /// space as input.  In order to do this, we need to replace the
5045 /// standard builtin declaration with one that uses the same address space
5046 /// as the call.
5047 ///
5048 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5049 ///                  it does not contain any pointer arguments without
5050 ///                  an address space qualifer.  Otherwise the rewritten
5051 ///                  FunctionDecl is returned.
5052 /// TODO: Handle pointer return types.
5053 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5054                                                 const FunctionDecl *FDecl,
5055                                                 MultiExprArg ArgExprs) {
5056 
5057   QualType DeclType = FDecl->getType();
5058   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5059 
5060   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5061       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5062     return nullptr;
5063 
5064   bool NeedsNewDecl = false;
5065   unsigned i = 0;
5066   SmallVector<QualType, 8> OverloadParams;
5067 
5068   for (QualType ParamType : FT->param_types()) {
5069 
5070     // Convert array arguments to pointer to simplify type lookup.
5071     ExprResult ArgRes =
5072         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5073     if (ArgRes.isInvalid())
5074       return nullptr;
5075     Expr *Arg = ArgRes.get();
5076     QualType ArgType = Arg->getType();
5077     if (!ParamType->isPointerType() ||
5078         ParamType.getQualifiers().hasAddressSpace() ||
5079         !ArgType->isPointerType() ||
5080         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5081       OverloadParams.push_back(ParamType);
5082       continue;
5083     }
5084 
5085     NeedsNewDecl = true;
5086     LangAS AS = ArgType->getPointeeType().getAddressSpace();
5087 
5088     QualType PointeeType = ParamType->getPointeeType();
5089     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5090     OverloadParams.push_back(Context.getPointerType(PointeeType));
5091   }
5092 
5093   if (!NeedsNewDecl)
5094     return nullptr;
5095 
5096   FunctionProtoType::ExtProtoInfo EPI;
5097   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5098                                                 OverloadParams, EPI);
5099   DeclContext *Parent = Context.getTranslationUnitDecl();
5100   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5101                                                     FDecl->getLocation(),
5102                                                     FDecl->getLocation(),
5103                                                     FDecl->getIdentifier(),
5104                                                     OverloadTy,
5105                                                     /*TInfo=*/nullptr,
5106                                                     SC_Extern, false,
5107                                                     /*hasPrototype=*/true);
5108   SmallVector<ParmVarDecl*, 16> Params;
5109   FT = cast<FunctionProtoType>(OverloadTy);
5110   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5111     QualType ParamType = FT->getParamType(i);
5112     ParmVarDecl *Parm =
5113         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5114                                 SourceLocation(), nullptr, ParamType,
5115                                 /*TInfo=*/nullptr, SC_None, nullptr);
5116     Parm->setScopeInfo(0, i);
5117     Params.push_back(Parm);
5118   }
5119   OverloadDecl->setParams(Params);
5120   return OverloadDecl;
5121 }
5122 
5123 static void checkDirectCallValidity(Sema &S, const Expr *Fn,
5124                                     FunctionDecl *Callee,
5125                                     MultiExprArg ArgExprs) {
5126   // `Callee` (when called with ArgExprs) may be ill-formed. enable_if (and
5127   // similar attributes) really don't like it when functions are called with an
5128   // invalid number of args.
5129   if (S.TooManyArguments(Callee->getNumParams(), ArgExprs.size(),
5130                          /*PartialOverloading=*/false) &&
5131       !Callee->isVariadic())
5132     return;
5133   if (Callee->getMinRequiredArguments() > ArgExprs.size())
5134     return;
5135 
5136   if (const EnableIfAttr *Attr = S.CheckEnableIf(Callee, ArgExprs, true)) {
5137     S.Diag(Fn->getLocStart(),
5138            isa<CXXMethodDecl>(Callee)
5139                ? diag::err_ovl_no_viable_member_function_in_call
5140                : diag::err_ovl_no_viable_function_in_call)
5141         << Callee << Callee->getSourceRange();
5142     S.Diag(Callee->getLocation(),
5143            diag::note_ovl_candidate_disabled_by_function_cond_attr)
5144         << Attr->getCond()->getSourceRange() << Attr->getMessage();
5145     return;
5146   }
5147 }
5148 
5149 static bool enclosingClassIsRelatedToClassInWhichMembersWereFound(
5150     const UnresolvedMemberExpr *const UME, Sema &S) {
5151 
5152   const auto GetFunctionLevelDCIfCXXClass =
5153       [](Sema &S) -> const CXXRecordDecl * {
5154     const DeclContext *const DC = S.getFunctionLevelDeclContext();
5155     if (!DC || !DC->getParent())
5156       return nullptr;
5157 
5158     // If the call to some member function was made from within a member
5159     // function body 'M' return return 'M's parent.
5160     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
5161       return MD->getParent()->getCanonicalDecl();
5162     // else the call was made from within a default member initializer of a
5163     // class, so return the class.
5164     if (const auto *RD = dyn_cast<CXXRecordDecl>(DC))
5165       return RD->getCanonicalDecl();
5166     return nullptr;
5167   };
5168   // If our DeclContext is neither a member function nor a class (in the
5169   // case of a lambda in a default member initializer), we can't have an
5170   // enclosing 'this'.
5171 
5172   const CXXRecordDecl *const CurParentClass = GetFunctionLevelDCIfCXXClass(S);
5173   if (!CurParentClass)
5174     return false;
5175 
5176   // The naming class for implicit member functions call is the class in which
5177   // name lookup starts.
5178   const CXXRecordDecl *const NamingClass =
5179       UME->getNamingClass()->getCanonicalDecl();
5180   assert(NamingClass && "Must have naming class even for implicit access");
5181 
5182   // If the unresolved member functions were found in a 'naming class' that is
5183   // related (either the same or derived from) to the class that contains the
5184   // member function that itself contained the implicit member access.
5185 
5186   return CurParentClass == NamingClass ||
5187          CurParentClass->isDerivedFrom(NamingClass);
5188 }
5189 
5190 static void
5191 tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5192     Sema &S, const UnresolvedMemberExpr *const UME, SourceLocation CallLoc) {
5193 
5194   if (!UME)
5195     return;
5196 
5197   LambdaScopeInfo *const CurLSI = S.getCurLambda();
5198   // Only try and implicitly capture 'this' within a C++ Lambda if it hasn't
5199   // already been captured, or if this is an implicit member function call (if
5200   // it isn't, an attempt to capture 'this' should already have been made).
5201   if (!CurLSI || CurLSI->ImpCaptureStyle == CurLSI->ImpCap_None ||
5202       !UME->isImplicitAccess() || CurLSI->isCXXThisCaptured())
5203     return;
5204 
5205   // Check if the naming class in which the unresolved members were found is
5206   // related (same as or is a base of) to the enclosing class.
5207 
5208   if (!enclosingClassIsRelatedToClassInWhichMembersWereFound(UME, S))
5209     return;
5210 
5211 
5212   DeclContext *EnclosingFunctionCtx = S.CurContext->getParent()->getParent();
5213   // If the enclosing function is not dependent, then this lambda is
5214   // capture ready, so if we can capture this, do so.
5215   if (!EnclosingFunctionCtx->isDependentContext()) {
5216     // If the current lambda and all enclosing lambdas can capture 'this' -
5217     // then go ahead and capture 'this' (since our unresolved overload set
5218     // contains at least one non-static member function).
5219     if (!S.CheckCXXThisCapture(CallLoc, /*Explcit*/ false, /*Diagnose*/ false))
5220       S.CheckCXXThisCapture(CallLoc);
5221   } else if (S.CurContext->isDependentContext()) {
5222     // ... since this is an implicit member reference, that might potentially
5223     // involve a 'this' capture, mark 'this' for potential capture in
5224     // enclosing lambdas.
5225     if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
5226       CurLSI->addPotentialThisCapture(CallLoc);
5227   }
5228 }
5229 
5230 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5231 /// This provides the location of the left/right parens and a list of comma
5232 /// locations.
5233 ExprResult Sema::ActOnCallExpr(Scope *Scope, Expr *Fn, SourceLocation LParenLoc,
5234                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5235                                Expr *ExecConfig, bool IsExecConfig) {
5236   // Since this might be a postfix expression, get rid of ParenListExprs.
5237   ExprResult Result = MaybeConvertParenListExprToParenExpr(Scope, Fn);
5238   if (Result.isInvalid()) return ExprError();
5239   Fn = Result.get();
5240 
5241   if (checkArgsForPlaceholders(*this, ArgExprs))
5242     return ExprError();
5243 
5244   if (getLangOpts().CPlusPlus) {
5245     // If this is a pseudo-destructor expression, build the call immediately.
5246     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5247       if (!ArgExprs.empty()) {
5248         // Pseudo-destructor calls should not have any arguments.
5249         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5250             << FixItHint::CreateRemoval(
5251                    SourceRange(ArgExprs.front()->getLocStart(),
5252                                ArgExprs.back()->getLocEnd()));
5253       }
5254 
5255       return new (Context)
5256           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
5257     }
5258     if (Fn->getType() == Context.PseudoObjectTy) {
5259       ExprResult result = CheckPlaceholderExpr(Fn);
5260       if (result.isInvalid()) return ExprError();
5261       Fn = result.get();
5262     }
5263 
5264     // Determine whether this is a dependent call inside a C++ template,
5265     // in which case we won't do any semantic analysis now.
5266     bool Dependent = false;
5267     if (Fn->isTypeDependent())
5268       Dependent = true;
5269     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5270       Dependent = true;
5271 
5272     if (Dependent) {
5273       if (ExecConfig) {
5274         return new (Context) CUDAKernelCallExpr(
5275             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5276             Context.DependentTy, VK_RValue, RParenLoc);
5277       } else {
5278 
5279        tryImplicitlyCaptureThisIfImplicitMemberFunctionAccessWithDependentArgs(
5280             *this, dyn_cast<UnresolvedMemberExpr>(Fn->IgnoreParens()),
5281             Fn->getLocStart());
5282 
5283         return new (Context) CallExpr(
5284             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5285       }
5286     }
5287 
5288     // Determine whether this is a call to an object (C++ [over.call.object]).
5289     if (Fn->getType()->isRecordType())
5290       return BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5291                                           RParenLoc);
5292 
5293     if (Fn->getType() == Context.UnknownAnyTy) {
5294       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5295       if (result.isInvalid()) return ExprError();
5296       Fn = result.get();
5297     }
5298 
5299     if (Fn->getType() == Context.BoundMemberTy) {
5300       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5301                                        RParenLoc);
5302     }
5303   }
5304 
5305   // Check for overloaded calls.  This can happen even in C due to extensions.
5306   if (Fn->getType() == Context.OverloadTy) {
5307     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5308 
5309     // We aren't supposed to apply this logic if there's an '&' involved.
5310     if (!find.HasFormOfMemberPointer) {
5311       if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5312         return new (Context) CallExpr(
5313             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
5314       OverloadExpr *ovl = find.Expression;
5315       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5316         return BuildOverloadedCallExpr(
5317             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5318             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5319       return BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5320                                        RParenLoc);
5321     }
5322   }
5323 
5324   // If we're directly calling a function, get the appropriate declaration.
5325   if (Fn->getType() == Context.UnknownAnyTy) {
5326     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
5327     if (result.isInvalid()) return ExprError();
5328     Fn = result.get();
5329   }
5330 
5331   Expr *NakedFn = Fn->IgnoreParens();
5332 
5333   bool CallingNDeclIndirectly = false;
5334   NamedDecl *NDecl = nullptr;
5335   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5336     if (UnOp->getOpcode() == UO_AddrOf) {
5337       CallingNDeclIndirectly = true;
5338       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5339     }
5340   }
5341 
5342   if (isa<DeclRefExpr>(NakedFn)) {
5343     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5344 
5345     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5346     if (FDecl && FDecl->getBuiltinID()) {
5347       // Rewrite the function decl for this builtin by replacing parameters
5348       // with no explicit address space with the address space of the arguments
5349       // in ArgExprs.
5350       if ((FDecl =
5351                rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
5352         NDecl = FDecl;
5353         Fn = DeclRefExpr::Create(
5354             Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5355             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5356       }
5357     }
5358   } else if (isa<MemberExpr>(NakedFn))
5359     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5360 
5361   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5362     if (CallingNDeclIndirectly &&
5363         !checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5364                                            Fn->getLocStart()))
5365       return ExprError();
5366 
5367     if (getLangOpts().OpenCL && checkOpenCLDisabledDecl(*FD, *Fn))
5368       return ExprError();
5369 
5370     checkDirectCallValidity(*this, Fn, FD, ArgExprs);
5371   }
5372 
5373   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5374                                ExecConfig, IsExecConfig);
5375 }
5376 
5377 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5378 ///
5379 /// __builtin_astype( value, dst type )
5380 ///
5381 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5382                                  SourceLocation BuiltinLoc,
5383                                  SourceLocation RParenLoc) {
5384   ExprValueKind VK = VK_RValue;
5385   ExprObjectKind OK = OK_Ordinary;
5386   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5387   QualType SrcTy = E->getType();
5388   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5389     return ExprError(Diag(BuiltinLoc,
5390                           diag::err_invalid_astype_of_different_size)
5391                      << DstTy
5392                      << SrcTy
5393                      << E->getSourceRange());
5394   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5395 }
5396 
5397 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5398 /// provided arguments.
5399 ///
5400 /// __builtin_convertvector( value, dst type )
5401 ///
5402 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5403                                         SourceLocation BuiltinLoc,
5404                                         SourceLocation RParenLoc) {
5405   TypeSourceInfo *TInfo;
5406   GetTypeFromParser(ParsedDestTy, &TInfo);
5407   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5408 }
5409 
5410 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5411 /// i.e. an expression not of \p OverloadTy.  The expression should
5412 /// unary-convert to an expression of function-pointer or
5413 /// block-pointer type.
5414 ///
5415 /// \param NDecl the declaration being called, if available
5416 ExprResult
5417 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5418                             SourceLocation LParenLoc,
5419                             ArrayRef<Expr *> Args,
5420                             SourceLocation RParenLoc,
5421                             Expr *Config, bool IsExecConfig) {
5422   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5423   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5424 
5425   // Functions with 'interrupt' attribute cannot be called directly.
5426   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5427     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5428     return ExprError();
5429   }
5430 
5431   // Interrupt handlers don't save off the VFP regs automatically on ARM,
5432   // so there's some risk when calling out to non-interrupt handler functions
5433   // that the callee might not preserve them. This is easy to diagnose here,
5434   // but can be very challenging to debug.
5435   if (auto *Caller = getCurFunctionDecl())
5436     if (Caller->hasAttr<ARMInterruptAttr>()) {
5437       bool VFP = Context.getTargetInfo().hasFeature("vfp");
5438       if (VFP && (!FDecl || !FDecl->hasAttr<ARMInterruptAttr>()))
5439         Diag(Fn->getExprLoc(), diag::warn_arm_interrupt_calling_convention);
5440     }
5441 
5442   // Promote the function operand.
5443   // We special-case function promotion here because we only allow promoting
5444   // builtin functions to function pointers in the callee of a call.
5445   ExprResult Result;
5446   if (BuiltinID &&
5447       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5448     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5449                                CK_BuiltinFnToFnPtr).get();
5450   } else {
5451     Result = CallExprUnaryConversions(Fn);
5452   }
5453   if (Result.isInvalid())
5454     return ExprError();
5455   Fn = Result.get();
5456 
5457   // Make the call expr early, before semantic checks.  This guarantees cleanup
5458   // of arguments and function on error.
5459   CallExpr *TheCall;
5460   if (Config)
5461     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5462                                                cast<CallExpr>(Config), Args,
5463                                                Context.BoolTy, VK_RValue,
5464                                                RParenLoc);
5465   else
5466     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5467                                      VK_RValue, RParenLoc);
5468 
5469   if (!getLangOpts().CPlusPlus) {
5470     // C cannot always handle TypoExpr nodes in builtin calls and direct
5471     // function calls as their argument checking don't necessarily handle
5472     // dependent types properly, so make sure any TypoExprs have been
5473     // dealt with.
5474     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5475     if (!Result.isUsable()) return ExprError();
5476     TheCall = dyn_cast<CallExpr>(Result.get());
5477     if (!TheCall) return Result;
5478     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5479   }
5480 
5481   // Bail out early if calling a builtin with custom typechecking.
5482   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5483     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5484 
5485  retry:
5486   const FunctionType *FuncT;
5487   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5488     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5489     // have type pointer to function".
5490     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5491     if (!FuncT)
5492       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5493                          << Fn->getType() << Fn->getSourceRange());
5494   } else if (const BlockPointerType *BPT =
5495                Fn->getType()->getAs<BlockPointerType>()) {
5496     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5497   } else {
5498     // Handle calls to expressions of unknown-any type.
5499     if (Fn->getType() == Context.UnknownAnyTy) {
5500       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5501       if (rewrite.isInvalid()) return ExprError();
5502       Fn = rewrite.get();
5503       TheCall->setCallee(Fn);
5504       goto retry;
5505     }
5506 
5507     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5508       << Fn->getType() << Fn->getSourceRange());
5509   }
5510 
5511   if (getLangOpts().CUDA) {
5512     if (Config) {
5513       // CUDA: Kernel calls must be to global functions
5514       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5515         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5516             << FDecl << Fn->getSourceRange());
5517 
5518       // CUDA: Kernel function must have 'void' return type
5519       if (!FuncT->getReturnType()->isVoidType())
5520         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5521             << Fn->getType() << Fn->getSourceRange());
5522     } else {
5523       // CUDA: Calls to global functions must be configured
5524       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5525         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5526             << FDecl << Fn->getSourceRange());
5527     }
5528   }
5529 
5530   // Check for a valid return type
5531   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5532                           FDecl))
5533     return ExprError();
5534 
5535   // We know the result type of the call, set it.
5536   TheCall->setType(FuncT->getCallResultType(Context));
5537   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5538 
5539   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5540   if (Proto) {
5541     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5542                                 IsExecConfig))
5543       return ExprError();
5544   } else {
5545     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5546 
5547     if (FDecl) {
5548       // Check if we have too few/too many template arguments, based
5549       // on our knowledge of the function definition.
5550       const FunctionDecl *Def = nullptr;
5551       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5552         Proto = Def->getType()->getAs<FunctionProtoType>();
5553        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5554           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5555           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5556       }
5557 
5558       // If the function we're calling isn't a function prototype, but we have
5559       // a function prototype from a prior declaratiom, use that prototype.
5560       if (!FDecl->hasPrototype())
5561         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5562     }
5563 
5564     // Promote the arguments (C99 6.5.2.2p6).
5565     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5566       Expr *Arg = Args[i];
5567 
5568       if (Proto && i < Proto->getNumParams()) {
5569         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5570             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5571         ExprResult ArgE =
5572             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5573         if (ArgE.isInvalid())
5574           return true;
5575 
5576         Arg = ArgE.getAs<Expr>();
5577 
5578       } else {
5579         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5580 
5581         if (ArgE.isInvalid())
5582           return true;
5583 
5584         Arg = ArgE.getAs<Expr>();
5585       }
5586 
5587       if (RequireCompleteType(Arg->getLocStart(),
5588                               Arg->getType(),
5589                               diag::err_call_incomplete_argument, Arg))
5590         return ExprError();
5591 
5592       TheCall->setArg(i, Arg);
5593     }
5594   }
5595 
5596   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5597     if (!Method->isStatic())
5598       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5599         << Fn->getSourceRange());
5600 
5601   // Check for sentinels
5602   if (NDecl)
5603     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5604 
5605   // Do special checking on direct calls to functions.
5606   if (FDecl) {
5607     if (CheckFunctionCall(FDecl, TheCall, Proto))
5608       return ExprError();
5609 
5610     if (BuiltinID)
5611       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5612   } else if (NDecl) {
5613     if (CheckPointerCall(NDecl, TheCall, Proto))
5614       return ExprError();
5615   } else {
5616     if (CheckOtherCall(TheCall, Proto))
5617       return ExprError();
5618   }
5619 
5620   return MaybeBindToTemporary(TheCall);
5621 }
5622 
5623 ExprResult
5624 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5625                            SourceLocation RParenLoc, Expr *InitExpr) {
5626   assert(Ty && "ActOnCompoundLiteral(): missing type");
5627   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5628 
5629   TypeSourceInfo *TInfo;
5630   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5631   if (!TInfo)
5632     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5633 
5634   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5635 }
5636 
5637 ExprResult
5638 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5639                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5640   QualType literalType = TInfo->getType();
5641 
5642   if (literalType->isArrayType()) {
5643     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5644           diag::err_illegal_decl_array_incomplete_type,
5645           SourceRange(LParenLoc,
5646                       LiteralExpr->getSourceRange().getEnd())))
5647       return ExprError();
5648     if (literalType->isVariableArrayType())
5649       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5650         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5651   } else if (!literalType->isDependentType() &&
5652              RequireCompleteType(LParenLoc, literalType,
5653                diag::err_typecheck_decl_incomplete_type,
5654                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5655     return ExprError();
5656 
5657   InitializedEntity Entity
5658     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5659   InitializationKind Kind
5660     = InitializationKind::CreateCStyleCast(LParenLoc,
5661                                            SourceRange(LParenLoc, RParenLoc),
5662                                            /*InitList=*/true);
5663   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5664   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5665                                       &literalType);
5666   if (Result.isInvalid())
5667     return ExprError();
5668   LiteralExpr = Result.get();
5669 
5670   bool isFileScope = !CurContext->isFunctionOrMethod();
5671   if (isFileScope &&
5672       !LiteralExpr->isTypeDependent() &&
5673       !LiteralExpr->isValueDependent() &&
5674       !literalType->isDependentType()) { // 6.5.2.5p3
5675     if (CheckForConstantInitializer(LiteralExpr, literalType))
5676       return ExprError();
5677   }
5678 
5679   // In C, compound literals are l-values for some reason.
5680   // For GCC compatibility, in C++, file-scope array compound literals with
5681   // constant initializers are also l-values, and compound literals are
5682   // otherwise prvalues.
5683   //
5684   // (GCC also treats C++ list-initialized file-scope array prvalues with
5685   // constant initializers as l-values, but that's non-conforming, so we don't
5686   // follow it there.)
5687   //
5688   // FIXME: It would be better to handle the lvalue cases as materializing and
5689   // lifetime-extending a temporary object, but our materialized temporaries
5690   // representation only supports lifetime extension from a variable, not "out
5691   // of thin air".
5692   // FIXME: For C++, we might want to instead lifetime-extend only if a pointer
5693   // is bound to the result of applying array-to-pointer decay to the compound
5694   // literal.
5695   // FIXME: GCC supports compound literals of reference type, which should
5696   // obviously have a value kind derived from the kind of reference involved.
5697   ExprValueKind VK =
5698       (getLangOpts().CPlusPlus && !(isFileScope && literalType->isArrayType()))
5699           ? VK_RValue
5700           : VK_LValue;
5701 
5702   return MaybeBindToTemporary(
5703       new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5704                                         VK, LiteralExpr, isFileScope));
5705 }
5706 
5707 ExprResult
5708 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5709                     SourceLocation RBraceLoc) {
5710   // Immediately handle non-overload placeholders.  Overloads can be
5711   // resolved contextually, but everything else here can't.
5712   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5713     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5714       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5715 
5716       // Ignore failures; dropping the entire initializer list because
5717       // of one failure would be terrible for indexing/etc.
5718       if (result.isInvalid()) continue;
5719 
5720       InitArgList[I] = result.get();
5721     }
5722   }
5723 
5724   // Semantic analysis for initializers is done by ActOnDeclarator() and
5725   // CheckInitializer() - it requires knowledge of the object being initialized.
5726 
5727   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5728                                                RBraceLoc);
5729   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5730   return E;
5731 }
5732 
5733 /// Do an explicit extend of the given block pointer if we're in ARC.
5734 void Sema::maybeExtendBlockObject(ExprResult &E) {
5735   assert(E.get()->getType()->isBlockPointerType());
5736   assert(E.get()->isRValue());
5737 
5738   // Only do this in an r-value context.
5739   if (!getLangOpts().ObjCAutoRefCount) return;
5740 
5741   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5742                                CK_ARCExtendBlockObject, E.get(),
5743                                /*base path*/ nullptr, VK_RValue);
5744   Cleanup.setExprNeedsCleanups(true);
5745 }
5746 
5747 /// Prepare a conversion of the given expression to an ObjC object
5748 /// pointer type.
5749 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5750   QualType type = E.get()->getType();
5751   if (type->isObjCObjectPointerType()) {
5752     return CK_BitCast;
5753   } else if (type->isBlockPointerType()) {
5754     maybeExtendBlockObject(E);
5755     return CK_BlockPointerToObjCPointerCast;
5756   } else {
5757     assert(type->isPointerType());
5758     return CK_CPointerToObjCPointerCast;
5759   }
5760 }
5761 
5762 /// Prepares for a scalar cast, performing all the necessary stages
5763 /// except the final cast and returning the kind required.
5764 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5765   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5766   // Also, callers should have filtered out the invalid cases with
5767   // pointers.  Everything else should be possible.
5768 
5769   QualType SrcTy = Src.get()->getType();
5770   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5771     return CK_NoOp;
5772 
5773   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5774   case Type::STK_MemberPointer:
5775     llvm_unreachable("member pointer type in C");
5776 
5777   case Type::STK_CPointer:
5778   case Type::STK_BlockPointer:
5779   case Type::STK_ObjCObjectPointer:
5780     switch (DestTy->getScalarTypeKind()) {
5781     case Type::STK_CPointer: {
5782       LangAS SrcAS = SrcTy->getPointeeType().getAddressSpace();
5783       LangAS DestAS = DestTy->getPointeeType().getAddressSpace();
5784       if (SrcAS != DestAS)
5785         return CK_AddressSpaceConversion;
5786       return CK_BitCast;
5787     }
5788     case Type::STK_BlockPointer:
5789       return (SrcKind == Type::STK_BlockPointer
5790                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5791     case Type::STK_ObjCObjectPointer:
5792       if (SrcKind == Type::STK_ObjCObjectPointer)
5793         return CK_BitCast;
5794       if (SrcKind == Type::STK_CPointer)
5795         return CK_CPointerToObjCPointerCast;
5796       maybeExtendBlockObject(Src);
5797       return CK_BlockPointerToObjCPointerCast;
5798     case Type::STK_Bool:
5799       return CK_PointerToBoolean;
5800     case Type::STK_Integral:
5801       return CK_PointerToIntegral;
5802     case Type::STK_Floating:
5803     case Type::STK_FloatingComplex:
5804     case Type::STK_IntegralComplex:
5805     case Type::STK_MemberPointer:
5806       llvm_unreachable("illegal cast from pointer");
5807     }
5808     llvm_unreachable("Should have returned before this");
5809 
5810   case Type::STK_Bool: // casting from bool is like casting from an integer
5811   case Type::STK_Integral:
5812     switch (DestTy->getScalarTypeKind()) {
5813     case Type::STK_CPointer:
5814     case Type::STK_ObjCObjectPointer:
5815     case Type::STK_BlockPointer:
5816       if (Src.get()->isNullPointerConstant(Context,
5817                                            Expr::NPC_ValueDependentIsNull))
5818         return CK_NullToPointer;
5819       return CK_IntegralToPointer;
5820     case Type::STK_Bool:
5821       return CK_IntegralToBoolean;
5822     case Type::STK_Integral:
5823       return CK_IntegralCast;
5824     case Type::STK_Floating:
5825       return CK_IntegralToFloating;
5826     case Type::STK_IntegralComplex:
5827       Src = ImpCastExprToType(Src.get(),
5828                       DestTy->castAs<ComplexType>()->getElementType(),
5829                       CK_IntegralCast);
5830       return CK_IntegralRealToComplex;
5831     case Type::STK_FloatingComplex:
5832       Src = ImpCastExprToType(Src.get(),
5833                       DestTy->castAs<ComplexType>()->getElementType(),
5834                       CK_IntegralToFloating);
5835       return CK_FloatingRealToComplex;
5836     case Type::STK_MemberPointer:
5837       llvm_unreachable("member pointer type in C");
5838     }
5839     llvm_unreachable("Should have returned before this");
5840 
5841   case Type::STK_Floating:
5842     switch (DestTy->getScalarTypeKind()) {
5843     case Type::STK_Floating:
5844       return CK_FloatingCast;
5845     case Type::STK_Bool:
5846       return CK_FloatingToBoolean;
5847     case Type::STK_Integral:
5848       return CK_FloatingToIntegral;
5849     case Type::STK_FloatingComplex:
5850       Src = ImpCastExprToType(Src.get(),
5851                               DestTy->castAs<ComplexType>()->getElementType(),
5852                               CK_FloatingCast);
5853       return CK_FloatingRealToComplex;
5854     case Type::STK_IntegralComplex:
5855       Src = ImpCastExprToType(Src.get(),
5856                               DestTy->castAs<ComplexType>()->getElementType(),
5857                               CK_FloatingToIntegral);
5858       return CK_IntegralRealToComplex;
5859     case Type::STK_CPointer:
5860     case Type::STK_ObjCObjectPointer:
5861     case Type::STK_BlockPointer:
5862       llvm_unreachable("valid float->pointer cast?");
5863     case Type::STK_MemberPointer:
5864       llvm_unreachable("member pointer type in C");
5865     }
5866     llvm_unreachable("Should have returned before this");
5867 
5868   case Type::STK_FloatingComplex:
5869     switch (DestTy->getScalarTypeKind()) {
5870     case Type::STK_FloatingComplex:
5871       return CK_FloatingComplexCast;
5872     case Type::STK_IntegralComplex:
5873       return CK_FloatingComplexToIntegralComplex;
5874     case Type::STK_Floating: {
5875       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5876       if (Context.hasSameType(ET, DestTy))
5877         return CK_FloatingComplexToReal;
5878       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5879       return CK_FloatingCast;
5880     }
5881     case Type::STK_Bool:
5882       return CK_FloatingComplexToBoolean;
5883     case Type::STK_Integral:
5884       Src = ImpCastExprToType(Src.get(),
5885                               SrcTy->castAs<ComplexType>()->getElementType(),
5886                               CK_FloatingComplexToReal);
5887       return CK_FloatingToIntegral;
5888     case Type::STK_CPointer:
5889     case Type::STK_ObjCObjectPointer:
5890     case Type::STK_BlockPointer:
5891       llvm_unreachable("valid complex float->pointer cast?");
5892     case Type::STK_MemberPointer:
5893       llvm_unreachable("member pointer type in C");
5894     }
5895     llvm_unreachable("Should have returned before this");
5896 
5897   case Type::STK_IntegralComplex:
5898     switch (DestTy->getScalarTypeKind()) {
5899     case Type::STK_FloatingComplex:
5900       return CK_IntegralComplexToFloatingComplex;
5901     case Type::STK_IntegralComplex:
5902       return CK_IntegralComplexCast;
5903     case Type::STK_Integral: {
5904       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5905       if (Context.hasSameType(ET, DestTy))
5906         return CK_IntegralComplexToReal;
5907       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5908       return CK_IntegralCast;
5909     }
5910     case Type::STK_Bool:
5911       return CK_IntegralComplexToBoolean;
5912     case Type::STK_Floating:
5913       Src = ImpCastExprToType(Src.get(),
5914                               SrcTy->castAs<ComplexType>()->getElementType(),
5915                               CK_IntegralComplexToReal);
5916       return CK_IntegralToFloating;
5917     case Type::STK_CPointer:
5918     case Type::STK_ObjCObjectPointer:
5919     case Type::STK_BlockPointer:
5920       llvm_unreachable("valid complex int->pointer cast?");
5921     case Type::STK_MemberPointer:
5922       llvm_unreachable("member pointer type in C");
5923     }
5924     llvm_unreachable("Should have returned before this");
5925   }
5926 
5927   llvm_unreachable("Unhandled scalar cast");
5928 }
5929 
5930 static bool breakDownVectorType(QualType type, uint64_t &len,
5931                                 QualType &eltType) {
5932   // Vectors are simple.
5933   if (const VectorType *vecType = type->getAs<VectorType>()) {
5934     len = vecType->getNumElements();
5935     eltType = vecType->getElementType();
5936     assert(eltType->isScalarType());
5937     return true;
5938   }
5939 
5940   // We allow lax conversion to and from non-vector types, but only if
5941   // they're real types (i.e. non-complex, non-pointer scalar types).
5942   if (!type->isRealType()) return false;
5943 
5944   len = 1;
5945   eltType = type;
5946   return true;
5947 }
5948 
5949 /// Are the two types lax-compatible vector types?  That is, given
5950 /// that one of them is a vector, do they have equal storage sizes,
5951 /// where the storage size is the number of elements times the element
5952 /// size?
5953 ///
5954 /// This will also return false if either of the types is neither a
5955 /// vector nor a real type.
5956 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5957   assert(destTy->isVectorType() || srcTy->isVectorType());
5958 
5959   // Disallow lax conversions between scalars and ExtVectors (these
5960   // conversions are allowed for other vector types because common headers
5961   // depend on them).  Most scalar OP ExtVector cases are handled by the
5962   // splat path anyway, which does what we want (convert, not bitcast).
5963   // What this rules out for ExtVectors is crazy things like char4*float.
5964   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5965   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5966 
5967   uint64_t srcLen, destLen;
5968   QualType srcEltTy, destEltTy;
5969   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5970   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5971 
5972   // ASTContext::getTypeSize will return the size rounded up to a
5973   // power of 2, so instead of using that, we need to use the raw
5974   // element size multiplied by the element count.
5975   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5976   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5977 
5978   return (srcLen * srcEltSize == destLen * destEltSize);
5979 }
5980 
5981 /// Is this a legal conversion between two types, one of which is
5982 /// known to be a vector type?
5983 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5984   assert(destTy->isVectorType() || srcTy->isVectorType());
5985 
5986   if (!Context.getLangOpts().LaxVectorConversions)
5987     return false;
5988   return areLaxCompatibleVectorTypes(srcTy, destTy);
5989 }
5990 
5991 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5992                            CastKind &Kind) {
5993   assert(VectorTy->isVectorType() && "Not a vector type!");
5994 
5995   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5996     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5997       return Diag(R.getBegin(),
5998                   Ty->isVectorType() ?
5999                   diag::err_invalid_conversion_between_vectors :
6000                   diag::err_invalid_conversion_between_vector_and_integer)
6001         << VectorTy << Ty << R;
6002   } else
6003     return Diag(R.getBegin(),
6004                 diag::err_invalid_conversion_between_vector_and_scalar)
6005       << VectorTy << Ty << R;
6006 
6007   Kind = CK_BitCast;
6008   return false;
6009 }
6010 
6011 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
6012   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
6013 
6014   if (DestElemTy == SplattedExpr->getType())
6015     return SplattedExpr;
6016 
6017   assert(DestElemTy->isFloatingType() ||
6018          DestElemTy->isIntegralOrEnumerationType());
6019 
6020   CastKind CK;
6021   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
6022     // OpenCL requires that we convert `true` boolean expressions to -1, but
6023     // only when splatting vectors.
6024     if (DestElemTy->isFloatingType()) {
6025       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
6026       // in two steps: boolean to signed integral, then to floating.
6027       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
6028                                                  CK_BooleanToSignedIntegral);
6029       SplattedExpr = CastExprRes.get();
6030       CK = CK_IntegralToFloating;
6031     } else {
6032       CK = CK_BooleanToSignedIntegral;
6033     }
6034   } else {
6035     ExprResult CastExprRes = SplattedExpr;
6036     CK = PrepareScalarCast(CastExprRes, DestElemTy);
6037     if (CastExprRes.isInvalid())
6038       return ExprError();
6039     SplattedExpr = CastExprRes.get();
6040   }
6041   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
6042 }
6043 
6044 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
6045                                     Expr *CastExpr, CastKind &Kind) {
6046   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
6047 
6048   QualType SrcTy = CastExpr->getType();
6049 
6050   // If SrcTy is a VectorType, the total size must match to explicitly cast to
6051   // an ExtVectorType.
6052   // In OpenCL, casts between vectors of different types are not allowed.
6053   // (See OpenCL 6.2).
6054   if (SrcTy->isVectorType()) {
6055     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy) ||
6056         (getLangOpts().OpenCL &&
6057          !Context.hasSameUnqualifiedType(DestTy, SrcTy))) {
6058       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
6059         << DestTy << SrcTy << R;
6060       return ExprError();
6061     }
6062     Kind = CK_BitCast;
6063     return CastExpr;
6064   }
6065 
6066   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
6067   // conversion will take place first from scalar to elt type, and then
6068   // splat from elt type to vector.
6069   if (SrcTy->isPointerType())
6070     return Diag(R.getBegin(),
6071                 diag::err_invalid_conversion_between_vector_and_scalar)
6072       << DestTy << SrcTy << R;
6073 
6074   Kind = CK_VectorSplat;
6075   return prepareVectorSplat(DestTy, CastExpr);
6076 }
6077 
6078 ExprResult
6079 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
6080                     Declarator &D, ParsedType &Ty,
6081                     SourceLocation RParenLoc, Expr *CastExpr) {
6082   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
6083          "ActOnCastExpr(): missing type or expr");
6084 
6085   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
6086   if (D.isInvalidType())
6087     return ExprError();
6088 
6089   if (getLangOpts().CPlusPlus) {
6090     // Check that there are no default arguments (C++ only).
6091     CheckExtraCXXDefaultArguments(D);
6092   } else {
6093     // Make sure any TypoExprs have been dealt with.
6094     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6095     if (!Res.isUsable())
6096       return ExprError();
6097     CastExpr = Res.get();
6098   }
6099 
6100   checkUnusedDeclAttributes(D);
6101 
6102   QualType castType = castTInfo->getType();
6103   Ty = CreateParsedType(castType, castTInfo);
6104 
6105   bool isVectorLiteral = false;
6106 
6107   // Check for an altivec or OpenCL literal,
6108   // i.e. all the elements are integer constants.
6109   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6110   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6111   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6112        && castType->isVectorType() && (PE || PLE)) {
6113     if (PLE && PLE->getNumExprs() == 0) {
6114       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6115       return ExprError();
6116     }
6117     if (PE || PLE->getNumExprs() == 1) {
6118       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6119       if (!E->getType()->isVectorType())
6120         isVectorLiteral = true;
6121     }
6122     else
6123       isVectorLiteral = true;
6124   }
6125 
6126   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6127   // then handle it as such.
6128   if (isVectorLiteral)
6129     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6130 
6131   // If the Expr being casted is a ParenListExpr, handle it specially.
6132   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6133   // sequence of BinOp comma operators.
6134   if (isa<ParenListExpr>(CastExpr)) {
6135     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6136     if (Result.isInvalid()) return ExprError();
6137     CastExpr = Result.get();
6138   }
6139 
6140   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6141       !getSourceManager().isInSystemMacro(LParenLoc))
6142     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6143 
6144   CheckTollFreeBridgeCast(castType, CastExpr);
6145 
6146   CheckObjCBridgeRelatedCast(castType, CastExpr);
6147 
6148   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6149 
6150   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6151 }
6152 
6153 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6154                                     SourceLocation RParenLoc, Expr *E,
6155                                     TypeSourceInfo *TInfo) {
6156   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6157          "Expected paren or paren list expression");
6158 
6159   Expr **exprs;
6160   unsigned numExprs;
6161   Expr *subExpr;
6162   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6163   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6164     LiteralLParenLoc = PE->getLParenLoc();
6165     LiteralRParenLoc = PE->getRParenLoc();
6166     exprs = PE->getExprs();
6167     numExprs = PE->getNumExprs();
6168   } else { // isa<ParenExpr> by assertion at function entrance
6169     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6170     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6171     subExpr = cast<ParenExpr>(E)->getSubExpr();
6172     exprs = &subExpr;
6173     numExprs = 1;
6174   }
6175 
6176   QualType Ty = TInfo->getType();
6177   assert(Ty->isVectorType() && "Expected vector type");
6178 
6179   SmallVector<Expr *, 8> initExprs;
6180   const VectorType *VTy = Ty->getAs<VectorType>();
6181   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6182 
6183   // '(...)' form of vector initialization in AltiVec: the number of
6184   // initializers must be one or must match the size of the vector.
6185   // If a single value is specified in the initializer then it will be
6186   // replicated to all the components of the vector
6187   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6188     // The number of initializers must be one or must match the size of the
6189     // vector. If a single value is specified in the initializer then it will
6190     // be replicated to all the components of the vector
6191     if (numExprs == 1) {
6192       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6193       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6194       if (Literal.isInvalid())
6195         return ExprError();
6196       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6197                                   PrepareScalarCast(Literal, ElemTy));
6198       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6199     }
6200     else if (numExprs < numElems) {
6201       Diag(E->getExprLoc(),
6202            diag::err_incorrect_number_of_vector_initializers);
6203       return ExprError();
6204     }
6205     else
6206       initExprs.append(exprs, exprs + numExprs);
6207   }
6208   else {
6209     // For OpenCL, when the number of initializers is a single value,
6210     // it will be replicated to all components of the vector.
6211     if (getLangOpts().OpenCL &&
6212         VTy->getVectorKind() == VectorType::GenericVector &&
6213         numExprs == 1) {
6214         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6215         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6216         if (Literal.isInvalid())
6217           return ExprError();
6218         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6219                                     PrepareScalarCast(Literal, ElemTy));
6220         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6221     }
6222 
6223     initExprs.append(exprs, exprs + numExprs);
6224   }
6225   // FIXME: This means that pretty-printing the final AST will produce curly
6226   // braces instead of the original commas.
6227   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6228                                                    initExprs, LiteralRParenLoc);
6229   initE->setType(Ty);
6230   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6231 }
6232 
6233 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6234 /// the ParenListExpr into a sequence of comma binary operators.
6235 ExprResult
6236 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6237   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6238   if (!E)
6239     return OrigExpr;
6240 
6241   ExprResult Result(E->getExpr(0));
6242 
6243   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6244     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6245                         E->getExpr(i));
6246 
6247   if (Result.isInvalid()) return ExprError();
6248 
6249   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6250 }
6251 
6252 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6253                                     SourceLocation R,
6254                                     MultiExprArg Val) {
6255   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6256   return expr;
6257 }
6258 
6259 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6260 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6261 /// emitted.
6262 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6263                                       SourceLocation QuestionLoc) {
6264   Expr *NullExpr = LHSExpr;
6265   Expr *NonPointerExpr = RHSExpr;
6266   Expr::NullPointerConstantKind NullKind =
6267       NullExpr->isNullPointerConstant(Context,
6268                                       Expr::NPC_ValueDependentIsNotNull);
6269 
6270   if (NullKind == Expr::NPCK_NotNull) {
6271     NullExpr = RHSExpr;
6272     NonPointerExpr = LHSExpr;
6273     NullKind =
6274         NullExpr->isNullPointerConstant(Context,
6275                                         Expr::NPC_ValueDependentIsNotNull);
6276   }
6277 
6278   if (NullKind == Expr::NPCK_NotNull)
6279     return false;
6280 
6281   if (NullKind == Expr::NPCK_ZeroExpression)
6282     return false;
6283 
6284   if (NullKind == Expr::NPCK_ZeroLiteral) {
6285     // In this case, check to make sure that we got here from a "NULL"
6286     // string in the source code.
6287     NullExpr = NullExpr->IgnoreParenImpCasts();
6288     SourceLocation loc = NullExpr->getExprLoc();
6289     if (!findMacroSpelling(loc, "NULL"))
6290       return false;
6291   }
6292 
6293   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6294   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6295       << NonPointerExpr->getType() << DiagType
6296       << NonPointerExpr->getSourceRange();
6297   return true;
6298 }
6299 
6300 /// \brief Return false if the condition expression is valid, true otherwise.
6301 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6302   QualType CondTy = Cond->getType();
6303 
6304   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6305   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6306     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6307       << CondTy << Cond->getSourceRange();
6308     return true;
6309   }
6310 
6311   // C99 6.5.15p2
6312   if (CondTy->isScalarType()) return false;
6313 
6314   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6315     << CondTy << Cond->getSourceRange();
6316   return true;
6317 }
6318 
6319 /// \brief Handle when one or both operands are void type.
6320 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6321                                          ExprResult &RHS) {
6322     Expr *LHSExpr = LHS.get();
6323     Expr *RHSExpr = RHS.get();
6324 
6325     if (!LHSExpr->getType()->isVoidType())
6326       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6327         << RHSExpr->getSourceRange();
6328     if (!RHSExpr->getType()->isVoidType())
6329       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6330         << LHSExpr->getSourceRange();
6331     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6332     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6333     return S.Context.VoidTy;
6334 }
6335 
6336 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6337 /// true otherwise.
6338 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6339                                         QualType PointerTy) {
6340   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6341       !NullExpr.get()->isNullPointerConstant(S.Context,
6342                                             Expr::NPC_ValueDependentIsNull))
6343     return true;
6344 
6345   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6346   return false;
6347 }
6348 
6349 /// \brief Checks compatibility between two pointers and return the resulting
6350 /// type.
6351 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6352                                                      ExprResult &RHS,
6353                                                      SourceLocation Loc) {
6354   QualType LHSTy = LHS.get()->getType();
6355   QualType RHSTy = RHS.get()->getType();
6356 
6357   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6358     // Two identical pointers types are always compatible.
6359     return LHSTy;
6360   }
6361 
6362   QualType lhptee, rhptee;
6363 
6364   // Get the pointee types.
6365   bool IsBlockPointer = false;
6366   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6367     lhptee = LHSBTy->getPointeeType();
6368     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6369     IsBlockPointer = true;
6370   } else {
6371     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6372     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6373   }
6374 
6375   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6376   // differently qualified versions of compatible types, the result type is
6377   // a pointer to an appropriately qualified version of the composite
6378   // type.
6379 
6380   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6381   // clause doesn't make sense for our extensions. E.g. address space 2 should
6382   // be incompatible with address space 3: they may live on different devices or
6383   // anything.
6384   Qualifiers lhQual = lhptee.getQualifiers();
6385   Qualifiers rhQual = rhptee.getQualifiers();
6386 
6387   LangAS ResultAddrSpace = LangAS::Default;
6388   LangAS LAddrSpace = lhQual.getAddressSpace();
6389   LangAS RAddrSpace = rhQual.getAddressSpace();
6390   if (S.getLangOpts().OpenCL) {
6391     // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6392     // spaces is disallowed.
6393     if (lhQual.isAddressSpaceSupersetOf(rhQual))
6394       ResultAddrSpace = LAddrSpace;
6395     else if (rhQual.isAddressSpaceSupersetOf(lhQual))
6396       ResultAddrSpace = RAddrSpace;
6397     else {
6398       S.Diag(Loc,
6399              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6400           << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6401           << RHS.get()->getSourceRange();
6402       return QualType();
6403     }
6404   }
6405 
6406   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6407   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6408   lhQual.removeCVRQualifiers();
6409   rhQual.removeCVRQualifiers();
6410 
6411   // OpenCL v2.0 specification doesn't extend compatibility of type qualifiers
6412   // (C99 6.7.3) for address spaces. We assume that the check should behave in
6413   // the same manner as it's defined for CVR qualifiers, so for OpenCL two
6414   // qual types are compatible iff
6415   //  * corresponded types are compatible
6416   //  * CVR qualifiers are equal
6417   //  * address spaces are equal
6418   // Thus for conditional operator we merge CVR and address space unqualified
6419   // pointees and if there is a composite type we return a pointer to it with
6420   // merged qualifiers.
6421   if (S.getLangOpts().OpenCL) {
6422     LHSCastKind = LAddrSpace == ResultAddrSpace
6423                       ? CK_BitCast
6424                       : CK_AddressSpaceConversion;
6425     RHSCastKind = RAddrSpace == ResultAddrSpace
6426                       ? CK_BitCast
6427                       : CK_AddressSpaceConversion;
6428     lhQual.removeAddressSpace();
6429     rhQual.removeAddressSpace();
6430   }
6431 
6432   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6433   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6434 
6435   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6436 
6437   if (CompositeTy.isNull()) {
6438     // In this situation, we assume void* type. No especially good
6439     // reason, but this is what gcc does, and we do have to pick
6440     // to get a consistent AST.
6441     QualType incompatTy;
6442     incompatTy = S.Context.getPointerType(
6443         S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6444     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, LHSCastKind);
6445     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, RHSCastKind);
6446     // FIXME: For OpenCL the warning emission and cast to void* leaves a room
6447     // for casts between types with incompatible address space qualifiers.
6448     // For the following code the compiler produces casts between global and
6449     // local address spaces of the corresponded innermost pointees:
6450     // local int *global *a;
6451     // global int *global *b;
6452     // a = (0 ? a : b); // see C99 6.5.16.1.p1.
6453     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6454         << LHSTy << RHSTy << LHS.get()->getSourceRange()
6455         << RHS.get()->getSourceRange();
6456     return incompatTy;
6457   }
6458 
6459   // The pointer types are compatible.
6460   // In case of OpenCL ResultTy should have the address space qualifier
6461   // which is a superset of address spaces of both the 2nd and the 3rd
6462   // operands of the conditional operator.
6463   QualType ResultTy = [&, ResultAddrSpace]() {
6464     if (S.getLangOpts().OpenCL) {
6465       Qualifiers CompositeQuals = CompositeTy.getQualifiers();
6466       CompositeQuals.setAddressSpace(ResultAddrSpace);
6467       return S.Context
6468           .getQualifiedType(CompositeTy.getUnqualifiedType(), CompositeQuals)
6469           .withCVRQualifiers(MergedCVRQual);
6470     }
6471     return CompositeTy.withCVRQualifiers(MergedCVRQual);
6472   }();
6473   if (IsBlockPointer)
6474     ResultTy = S.Context.getBlockPointerType(ResultTy);
6475   else
6476     ResultTy = S.Context.getPointerType(ResultTy);
6477 
6478   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6479   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6480   return ResultTy;
6481 }
6482 
6483 /// \brief Return the resulting type when the operands are both block pointers.
6484 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6485                                                           ExprResult &LHS,
6486                                                           ExprResult &RHS,
6487                                                           SourceLocation Loc) {
6488   QualType LHSTy = LHS.get()->getType();
6489   QualType RHSTy = RHS.get()->getType();
6490 
6491   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6492     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6493       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6494       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6495       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6496       return destType;
6497     }
6498     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6499       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6500       << RHS.get()->getSourceRange();
6501     return QualType();
6502   }
6503 
6504   // We have 2 block pointer types.
6505   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6506 }
6507 
6508 /// \brief Return the resulting type when the operands are both pointers.
6509 static QualType
6510 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6511                                             ExprResult &RHS,
6512                                             SourceLocation Loc) {
6513   // get the pointer types
6514   QualType LHSTy = LHS.get()->getType();
6515   QualType RHSTy = RHS.get()->getType();
6516 
6517   // get the "pointed to" types
6518   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6519   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6520 
6521   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6522   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6523     // Figure out necessary qualifiers (C99 6.5.15p6)
6524     QualType destPointee
6525       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6526     QualType destType = S.Context.getPointerType(destPointee);
6527     // Add qualifiers if necessary.
6528     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6529     // Promote to void*.
6530     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6531     return destType;
6532   }
6533   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6534     QualType destPointee
6535       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6536     QualType destType = S.Context.getPointerType(destPointee);
6537     // Add qualifiers if necessary.
6538     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6539     // Promote to void*.
6540     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6541     return destType;
6542   }
6543 
6544   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6545 }
6546 
6547 /// \brief Return false if the first expression is not an integer and the second
6548 /// expression is not a pointer, true otherwise.
6549 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6550                                         Expr* PointerExpr, SourceLocation Loc,
6551                                         bool IsIntFirstExpr) {
6552   if (!PointerExpr->getType()->isPointerType() ||
6553       !Int.get()->getType()->isIntegerType())
6554     return false;
6555 
6556   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6557   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6558 
6559   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6560     << Expr1->getType() << Expr2->getType()
6561     << Expr1->getSourceRange() << Expr2->getSourceRange();
6562   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6563                             CK_IntegralToPointer);
6564   return true;
6565 }
6566 
6567 /// \brief Simple conversion between integer and floating point types.
6568 ///
6569 /// Used when handling the OpenCL conditional operator where the
6570 /// condition is a vector while the other operands are scalar.
6571 ///
6572 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6573 /// types are either integer or floating type. Between the two
6574 /// operands, the type with the higher rank is defined as the "result
6575 /// type". The other operand needs to be promoted to the same type. No
6576 /// other type promotion is allowed. We cannot use
6577 /// UsualArithmeticConversions() for this purpose, since it always
6578 /// promotes promotable types.
6579 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6580                                             ExprResult &RHS,
6581                                             SourceLocation QuestionLoc) {
6582   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6583   if (LHS.isInvalid())
6584     return QualType();
6585   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6586   if (RHS.isInvalid())
6587     return QualType();
6588 
6589   // For conversion purposes, we ignore any qualifiers.
6590   // For example, "const float" and "float" are equivalent.
6591   QualType LHSType =
6592     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6593   QualType RHSType =
6594     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6595 
6596   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6597     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6598       << LHSType << LHS.get()->getSourceRange();
6599     return QualType();
6600   }
6601 
6602   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6603     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6604       << RHSType << RHS.get()->getSourceRange();
6605     return QualType();
6606   }
6607 
6608   // If both types are identical, no conversion is needed.
6609   if (LHSType == RHSType)
6610     return LHSType;
6611 
6612   // Now handle "real" floating types (i.e. float, double, long double).
6613   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6614     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6615                                  /*IsCompAssign = */ false);
6616 
6617   // Finally, we have two differing integer types.
6618   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6619   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6620 }
6621 
6622 /// \brief Convert scalar operands to a vector that matches the
6623 ///        condition in length.
6624 ///
6625 /// Used when handling the OpenCL conditional operator where the
6626 /// condition is a vector while the other operands are scalar.
6627 ///
6628 /// We first compute the "result type" for the scalar operands
6629 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6630 /// into a vector of that type where the length matches the condition
6631 /// vector type. s6.11.6 requires that the element types of the result
6632 /// and the condition must have the same number of bits.
6633 static QualType
6634 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6635                               QualType CondTy, SourceLocation QuestionLoc) {
6636   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6637   if (ResTy.isNull()) return QualType();
6638 
6639   const VectorType *CV = CondTy->getAs<VectorType>();
6640   assert(CV);
6641 
6642   // Determine the vector result type
6643   unsigned NumElements = CV->getNumElements();
6644   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6645 
6646   // Ensure that all types have the same number of bits
6647   if (S.Context.getTypeSize(CV->getElementType())
6648       != S.Context.getTypeSize(ResTy)) {
6649     // Since VectorTy is created internally, it does not pretty print
6650     // with an OpenCL name. Instead, we just print a description.
6651     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6652     SmallString<64> Str;
6653     llvm::raw_svector_ostream OS(Str);
6654     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6655     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6656       << CondTy << OS.str();
6657     return QualType();
6658   }
6659 
6660   // Convert operands to the vector result type
6661   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6662   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6663 
6664   return VectorTy;
6665 }
6666 
6667 /// \brief Return false if this is a valid OpenCL condition vector
6668 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6669                                        SourceLocation QuestionLoc) {
6670   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6671   // integral type.
6672   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6673   assert(CondTy);
6674   QualType EleTy = CondTy->getElementType();
6675   if (EleTy->isIntegerType()) return false;
6676 
6677   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6678     << Cond->getType() << Cond->getSourceRange();
6679   return true;
6680 }
6681 
6682 /// \brief Return false if the vector condition type and the vector
6683 ///        result type are compatible.
6684 ///
6685 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6686 /// number of elements, and their element types have the same number
6687 /// of bits.
6688 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6689                               SourceLocation QuestionLoc) {
6690   const VectorType *CV = CondTy->getAs<VectorType>();
6691   const VectorType *RV = VecResTy->getAs<VectorType>();
6692   assert(CV && RV);
6693 
6694   if (CV->getNumElements() != RV->getNumElements()) {
6695     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6696       << CondTy << VecResTy;
6697     return true;
6698   }
6699 
6700   QualType CVE = CV->getElementType();
6701   QualType RVE = RV->getElementType();
6702 
6703   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6704     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6705       << CondTy << VecResTy;
6706     return true;
6707   }
6708 
6709   return false;
6710 }
6711 
6712 /// \brief Return the resulting type for the conditional operator in
6713 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6714 ///        s6.3.i) when the condition is a vector type.
6715 static QualType
6716 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6717                              ExprResult &LHS, ExprResult &RHS,
6718                              SourceLocation QuestionLoc) {
6719   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6720   if (Cond.isInvalid())
6721     return QualType();
6722   QualType CondTy = Cond.get()->getType();
6723 
6724   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6725     return QualType();
6726 
6727   // If either operand is a vector then find the vector type of the
6728   // result as specified in OpenCL v1.1 s6.3.i.
6729   if (LHS.get()->getType()->isVectorType() ||
6730       RHS.get()->getType()->isVectorType()) {
6731     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6732                                               /*isCompAssign*/false,
6733                                               /*AllowBothBool*/true,
6734                                               /*AllowBoolConversions*/false);
6735     if (VecResTy.isNull()) return QualType();
6736     // The result type must match the condition type as specified in
6737     // OpenCL v1.1 s6.11.6.
6738     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6739       return QualType();
6740     return VecResTy;
6741   }
6742 
6743   // Both operands are scalar.
6744   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6745 }
6746 
6747 /// \brief Return true if the Expr is block type
6748 static bool checkBlockType(Sema &S, const Expr *E) {
6749   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6750     QualType Ty = CE->getCallee()->getType();
6751     if (Ty->isBlockPointerType()) {
6752       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6753       return true;
6754     }
6755   }
6756   return false;
6757 }
6758 
6759 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6760 /// In that case, LHS = cond.
6761 /// C99 6.5.15
6762 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6763                                         ExprResult &RHS, ExprValueKind &VK,
6764                                         ExprObjectKind &OK,
6765                                         SourceLocation QuestionLoc) {
6766 
6767   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6768   if (!LHSResult.isUsable()) return QualType();
6769   LHS = LHSResult;
6770 
6771   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6772   if (!RHSResult.isUsable()) return QualType();
6773   RHS = RHSResult;
6774 
6775   // C++ is sufficiently different to merit its own checker.
6776   if (getLangOpts().CPlusPlus)
6777     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6778 
6779   VK = VK_RValue;
6780   OK = OK_Ordinary;
6781 
6782   // The OpenCL operator with a vector condition is sufficiently
6783   // different to merit its own checker.
6784   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6785     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6786 
6787   // First, check the condition.
6788   Cond = UsualUnaryConversions(Cond.get());
6789   if (Cond.isInvalid())
6790     return QualType();
6791   if (checkCondition(*this, Cond.get(), QuestionLoc))
6792     return QualType();
6793 
6794   // Now check the two expressions.
6795   if (LHS.get()->getType()->isVectorType() ||
6796       RHS.get()->getType()->isVectorType())
6797     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6798                                /*AllowBothBool*/true,
6799                                /*AllowBoolConversions*/false);
6800 
6801   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6802   if (LHS.isInvalid() || RHS.isInvalid())
6803     return QualType();
6804 
6805   QualType LHSTy = LHS.get()->getType();
6806   QualType RHSTy = RHS.get()->getType();
6807 
6808   // Diagnose attempts to convert between __float128 and long double where
6809   // such conversions currently can't be handled.
6810   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6811     Diag(QuestionLoc,
6812          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6813       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6814     return QualType();
6815   }
6816 
6817   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6818   // selection operator (?:).
6819   if (getLangOpts().OpenCL &&
6820       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6821     return QualType();
6822   }
6823 
6824   // If both operands have arithmetic type, do the usual arithmetic conversions
6825   // to find a common type: C99 6.5.15p3,5.
6826   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6827     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6828     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6829 
6830     return ResTy;
6831   }
6832 
6833   // If both operands are the same structure or union type, the result is that
6834   // type.
6835   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6836     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6837       if (LHSRT->getDecl() == RHSRT->getDecl())
6838         // "If both the operands have structure or union type, the result has
6839         // that type."  This implies that CV qualifiers are dropped.
6840         return LHSTy.getUnqualifiedType();
6841     // FIXME: Type of conditional expression must be complete in C mode.
6842   }
6843 
6844   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6845   // The following || allows only one side to be void (a GCC-ism).
6846   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6847     return checkConditionalVoidType(*this, LHS, RHS);
6848   }
6849 
6850   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6851   // the type of the other operand."
6852   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6853   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6854 
6855   // All objective-c pointer type analysis is done here.
6856   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6857                                                         QuestionLoc);
6858   if (LHS.isInvalid() || RHS.isInvalid())
6859     return QualType();
6860   if (!compositeType.isNull())
6861     return compositeType;
6862 
6863 
6864   // Handle block pointer types.
6865   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6866     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6867                                                      QuestionLoc);
6868 
6869   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6870   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6871     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6872                                                        QuestionLoc);
6873 
6874   // GCC compatibility: soften pointer/integer mismatch.  Note that
6875   // null pointers have been filtered out by this point.
6876   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6877       /*isIntFirstExpr=*/true))
6878     return RHSTy;
6879   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6880       /*isIntFirstExpr=*/false))
6881     return LHSTy;
6882 
6883   // Emit a better diagnostic if one of the expressions is a null pointer
6884   // constant and the other is not a pointer type. In this case, the user most
6885   // likely forgot to take the address of the other expression.
6886   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6887     return QualType();
6888 
6889   // Otherwise, the operands are not compatible.
6890   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6891     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6892     << RHS.get()->getSourceRange();
6893   return QualType();
6894 }
6895 
6896 /// FindCompositeObjCPointerType - Helper method to find composite type of
6897 /// two objective-c pointer types of the two input expressions.
6898 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6899                                             SourceLocation QuestionLoc) {
6900   QualType LHSTy = LHS.get()->getType();
6901   QualType RHSTy = RHS.get()->getType();
6902 
6903   // Handle things like Class and struct objc_class*.  Here we case the result
6904   // to the pseudo-builtin, because that will be implicitly cast back to the
6905   // redefinition type if an attempt is made to access its fields.
6906   if (LHSTy->isObjCClassType() &&
6907       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6908     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6909     return LHSTy;
6910   }
6911   if (RHSTy->isObjCClassType() &&
6912       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6913     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6914     return RHSTy;
6915   }
6916   // And the same for struct objc_object* / id
6917   if (LHSTy->isObjCIdType() &&
6918       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6919     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6920     return LHSTy;
6921   }
6922   if (RHSTy->isObjCIdType() &&
6923       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6924     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6925     return RHSTy;
6926   }
6927   // And the same for struct objc_selector* / SEL
6928   if (Context.isObjCSelType(LHSTy) &&
6929       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6930     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6931     return LHSTy;
6932   }
6933   if (Context.isObjCSelType(RHSTy) &&
6934       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6935     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6936     return RHSTy;
6937   }
6938   // Check constraints for Objective-C object pointers types.
6939   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6940 
6941     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6942       // Two identical object pointer types are always compatible.
6943       return LHSTy;
6944     }
6945     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6946     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6947     QualType compositeType = LHSTy;
6948 
6949     // If both operands are interfaces and either operand can be
6950     // assigned to the other, use that type as the composite
6951     // type. This allows
6952     //   xxx ? (A*) a : (B*) b
6953     // where B is a subclass of A.
6954     //
6955     // Additionally, as for assignment, if either type is 'id'
6956     // allow silent coercion. Finally, if the types are
6957     // incompatible then make sure to use 'id' as the composite
6958     // type so the result is acceptable for sending messages to.
6959 
6960     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6961     // It could return the composite type.
6962     if (!(compositeType =
6963           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6964       // Nothing more to do.
6965     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6966       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6967     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6968       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6969     } else if ((LHSTy->isObjCQualifiedIdType() ||
6970                 RHSTy->isObjCQualifiedIdType()) &&
6971                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6972       // Need to handle "id<xx>" explicitly.
6973       // GCC allows qualified id and any Objective-C type to devolve to
6974       // id. Currently localizing to here until clear this should be
6975       // part of ObjCQualifiedIdTypesAreCompatible.
6976       compositeType = Context.getObjCIdType();
6977     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6978       compositeType = Context.getObjCIdType();
6979     } else {
6980       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6981       << LHSTy << RHSTy
6982       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6983       QualType incompatTy = Context.getObjCIdType();
6984       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6985       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6986       return incompatTy;
6987     }
6988     // The object pointer types are compatible.
6989     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6990     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6991     return compositeType;
6992   }
6993   // Check Objective-C object pointer types and 'void *'
6994   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6995     if (getLangOpts().ObjCAutoRefCount) {
6996       // ARC forbids the implicit conversion of object pointers to 'void *',
6997       // so these types are not compatible.
6998       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6999           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7000       LHS = RHS = true;
7001       return QualType();
7002     }
7003     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
7004     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7005     QualType destPointee
7006     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
7007     QualType destType = Context.getPointerType(destPointee);
7008     // Add qualifiers if necessary.
7009     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
7010     // Promote to void*.
7011     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
7012     return destType;
7013   }
7014   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
7015     if (getLangOpts().ObjCAutoRefCount) {
7016       // ARC forbids the implicit conversion of object pointers to 'void *',
7017       // so these types are not compatible.
7018       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
7019           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7020       LHS = RHS = true;
7021       return QualType();
7022     }
7023     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
7024     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
7025     QualType destPointee
7026     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
7027     QualType destType = Context.getPointerType(destPointee);
7028     // Add qualifiers if necessary.
7029     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
7030     // Promote to void*.
7031     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
7032     return destType;
7033   }
7034   return QualType();
7035 }
7036 
7037 /// SuggestParentheses - Emit a note with a fixit hint that wraps
7038 /// ParenRange in parentheses.
7039 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
7040                                const PartialDiagnostic &Note,
7041                                SourceRange ParenRange) {
7042   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
7043   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
7044       EndLoc.isValid()) {
7045     Self.Diag(Loc, Note)
7046       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
7047       << FixItHint::CreateInsertion(EndLoc, ")");
7048   } else {
7049     // We can't display the parentheses, so just show the bare note.
7050     Self.Diag(Loc, Note) << ParenRange;
7051   }
7052 }
7053 
7054 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
7055   return BinaryOperator::isAdditiveOp(Opc) ||
7056          BinaryOperator::isMultiplicativeOp(Opc) ||
7057          BinaryOperator::isShiftOp(Opc);
7058 }
7059 
7060 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
7061 /// expression, either using a built-in or overloaded operator,
7062 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
7063 /// expression.
7064 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
7065                                    Expr **RHSExprs) {
7066   // Don't strip parenthesis: we should not warn if E is in parenthesis.
7067   E = E->IgnoreImpCasts();
7068   E = E->IgnoreConversionOperator();
7069   E = E->IgnoreImpCasts();
7070 
7071   // Built-in binary operator.
7072   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
7073     if (IsArithmeticOp(OP->getOpcode())) {
7074       *Opcode = OP->getOpcode();
7075       *RHSExprs = OP->getRHS();
7076       return true;
7077     }
7078   }
7079 
7080   // Overloaded operator.
7081   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
7082     if (Call->getNumArgs() != 2)
7083       return false;
7084 
7085     // Make sure this is really a binary operator that is safe to pass into
7086     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
7087     OverloadedOperatorKind OO = Call->getOperator();
7088     if (OO < OO_Plus || OO > OO_Arrow ||
7089         OO == OO_PlusPlus || OO == OO_MinusMinus)
7090       return false;
7091 
7092     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
7093     if (IsArithmeticOp(OpKind)) {
7094       *Opcode = OpKind;
7095       *RHSExprs = Call->getArg(1);
7096       return true;
7097     }
7098   }
7099 
7100   return false;
7101 }
7102 
7103 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7104 /// or is a logical expression such as (x==y) which has int type, but is
7105 /// commonly interpreted as boolean.
7106 static bool ExprLooksBoolean(Expr *E) {
7107   E = E->IgnoreParenImpCasts();
7108 
7109   if (E->getType()->isBooleanType())
7110     return true;
7111   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7112     return OP->isComparisonOp() || OP->isLogicalOp();
7113   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7114     return OP->getOpcode() == UO_LNot;
7115   if (E->getType()->isPointerType())
7116     return true;
7117 
7118   return false;
7119 }
7120 
7121 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7122 /// and binary operator are mixed in a way that suggests the programmer assumed
7123 /// the conditional operator has higher precedence, for example:
7124 /// "int x = a + someBinaryCondition ? 1 : 2".
7125 static void DiagnoseConditionalPrecedence(Sema &Self,
7126                                           SourceLocation OpLoc,
7127                                           Expr *Condition,
7128                                           Expr *LHSExpr,
7129                                           Expr *RHSExpr) {
7130   BinaryOperatorKind CondOpcode;
7131   Expr *CondRHS;
7132 
7133   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7134     return;
7135   if (!ExprLooksBoolean(CondRHS))
7136     return;
7137 
7138   // The condition is an arithmetic binary expression, with a right-
7139   // hand side that looks boolean, so warn.
7140 
7141   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7142       << Condition->getSourceRange()
7143       << BinaryOperator::getOpcodeStr(CondOpcode);
7144 
7145   SuggestParentheses(Self, OpLoc,
7146     Self.PDiag(diag::note_precedence_silence)
7147       << BinaryOperator::getOpcodeStr(CondOpcode),
7148     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7149 
7150   SuggestParentheses(Self, OpLoc,
7151     Self.PDiag(diag::note_precedence_conditional_first),
7152     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7153 }
7154 
7155 /// Compute the nullability of a conditional expression.
7156 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7157                                               QualType LHSTy, QualType RHSTy,
7158                                               ASTContext &Ctx) {
7159   if (!ResTy->isAnyPointerType())
7160     return ResTy;
7161 
7162   auto GetNullability = [&Ctx](QualType Ty) {
7163     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7164     if (Kind)
7165       return *Kind;
7166     return NullabilityKind::Unspecified;
7167   };
7168 
7169   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7170   NullabilityKind MergedKind;
7171 
7172   // Compute nullability of a binary conditional expression.
7173   if (IsBin) {
7174     if (LHSKind == NullabilityKind::NonNull)
7175       MergedKind = NullabilityKind::NonNull;
7176     else
7177       MergedKind = RHSKind;
7178   // Compute nullability of a normal conditional expression.
7179   } else {
7180     if (LHSKind == NullabilityKind::Nullable ||
7181         RHSKind == NullabilityKind::Nullable)
7182       MergedKind = NullabilityKind::Nullable;
7183     else if (LHSKind == NullabilityKind::NonNull)
7184       MergedKind = RHSKind;
7185     else if (RHSKind == NullabilityKind::NonNull)
7186       MergedKind = LHSKind;
7187     else
7188       MergedKind = NullabilityKind::Unspecified;
7189   }
7190 
7191   // Return if ResTy already has the correct nullability.
7192   if (GetNullability(ResTy) == MergedKind)
7193     return ResTy;
7194 
7195   // Strip all nullability from ResTy.
7196   while (ResTy->getNullability(Ctx))
7197     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7198 
7199   // Create a new AttributedType with the new nullability kind.
7200   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7201   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7202 }
7203 
7204 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7205 /// in the case of a the GNU conditional expr extension.
7206 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7207                                     SourceLocation ColonLoc,
7208                                     Expr *CondExpr, Expr *LHSExpr,
7209                                     Expr *RHSExpr) {
7210   if (!getLangOpts().CPlusPlus) {
7211     // C cannot handle TypoExpr nodes in the condition because it
7212     // doesn't handle dependent types properly, so make sure any TypoExprs have
7213     // been dealt with before checking the operands.
7214     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7215     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7216     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7217 
7218     if (!CondResult.isUsable())
7219       return ExprError();
7220 
7221     if (LHSExpr) {
7222       if (!LHSResult.isUsable())
7223         return ExprError();
7224     }
7225 
7226     if (!RHSResult.isUsable())
7227       return ExprError();
7228 
7229     CondExpr = CondResult.get();
7230     LHSExpr = LHSResult.get();
7231     RHSExpr = RHSResult.get();
7232   }
7233 
7234   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7235   // was the condition.
7236   OpaqueValueExpr *opaqueValue = nullptr;
7237   Expr *commonExpr = nullptr;
7238   if (!LHSExpr) {
7239     commonExpr = CondExpr;
7240     // Lower out placeholder types first.  This is important so that we don't
7241     // try to capture a placeholder. This happens in few cases in C++; such
7242     // as Objective-C++'s dictionary subscripting syntax.
7243     if (commonExpr->hasPlaceholderType()) {
7244       ExprResult result = CheckPlaceholderExpr(commonExpr);
7245       if (!result.isUsable()) return ExprError();
7246       commonExpr = result.get();
7247     }
7248     // We usually want to apply unary conversions *before* saving, except
7249     // in the special case of a C++ l-value conditional.
7250     if (!(getLangOpts().CPlusPlus
7251           && !commonExpr->isTypeDependent()
7252           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7253           && commonExpr->isGLValue()
7254           && commonExpr->isOrdinaryOrBitFieldObject()
7255           && RHSExpr->isOrdinaryOrBitFieldObject()
7256           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7257       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7258       if (commonRes.isInvalid())
7259         return ExprError();
7260       commonExpr = commonRes.get();
7261     }
7262 
7263     // If the common expression is a class or array prvalue, materialize it
7264     // so that we can safely refer to it multiple times.
7265     if (commonExpr->isRValue() && (commonExpr->getType()->isRecordType() ||
7266                                    commonExpr->getType()->isArrayType())) {
7267       ExprResult MatExpr = TemporaryMaterializationConversion(commonExpr);
7268       if (MatExpr.isInvalid())
7269         return ExprError();
7270       commonExpr = MatExpr.get();
7271     }
7272 
7273     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7274                                                 commonExpr->getType(),
7275                                                 commonExpr->getValueKind(),
7276                                                 commonExpr->getObjectKind(),
7277                                                 commonExpr);
7278     LHSExpr = CondExpr = opaqueValue;
7279   }
7280 
7281   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7282   ExprValueKind VK = VK_RValue;
7283   ExprObjectKind OK = OK_Ordinary;
7284   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7285   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7286                                              VK, OK, QuestionLoc);
7287   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7288       RHS.isInvalid())
7289     return ExprError();
7290 
7291   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7292                                 RHS.get());
7293 
7294   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7295 
7296   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7297                                          Context);
7298 
7299   if (!commonExpr)
7300     return new (Context)
7301         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7302                             RHS.get(), result, VK, OK);
7303 
7304   return new (Context) BinaryConditionalOperator(
7305       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7306       ColonLoc, result, VK, OK);
7307 }
7308 
7309 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7310 // being closely modeled after the C99 spec:-). The odd characteristic of this
7311 // routine is it effectively iqnores the qualifiers on the top level pointee.
7312 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7313 // FIXME: add a couple examples in this comment.
7314 static Sema::AssignConvertType
7315 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7316   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7317   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7318 
7319   // get the "pointed to" type (ignoring qualifiers at the top level)
7320   const Type *lhptee, *rhptee;
7321   Qualifiers lhq, rhq;
7322   std::tie(lhptee, lhq) =
7323       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7324   std::tie(rhptee, rhq) =
7325       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7326 
7327   Sema::AssignConvertType ConvTy = Sema::Compatible;
7328 
7329   // C99 6.5.16.1p1: This following citation is common to constraints
7330   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7331   // qualifiers of the type *pointed to* by the right;
7332 
7333   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7334   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7335       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7336     // Ignore lifetime for further calculation.
7337     lhq.removeObjCLifetime();
7338     rhq.removeObjCLifetime();
7339   }
7340 
7341   if (!lhq.compatiblyIncludes(rhq)) {
7342     // Treat address-space mismatches as fatal.  TODO: address subspaces
7343     if (!lhq.isAddressSpaceSupersetOf(rhq))
7344       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7345 
7346     // It's okay to add or remove GC or lifetime qualifiers when converting to
7347     // and from void*.
7348     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7349                         .compatiblyIncludes(
7350                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7351              && (lhptee->isVoidType() || rhptee->isVoidType()))
7352       ; // keep old
7353 
7354     // Treat lifetime mismatches as fatal.
7355     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7356       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7357 
7358     // For GCC/MS compatibility, other qualifier mismatches are treated
7359     // as still compatible in C.
7360     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7361   }
7362 
7363   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7364   // incomplete type and the other is a pointer to a qualified or unqualified
7365   // version of void...
7366   if (lhptee->isVoidType()) {
7367     if (rhptee->isIncompleteOrObjectType())
7368       return ConvTy;
7369 
7370     // As an extension, we allow cast to/from void* to function pointer.
7371     assert(rhptee->isFunctionType());
7372     return Sema::FunctionVoidPointer;
7373   }
7374 
7375   if (rhptee->isVoidType()) {
7376     if (lhptee->isIncompleteOrObjectType())
7377       return ConvTy;
7378 
7379     // As an extension, we allow cast to/from void* to function pointer.
7380     assert(lhptee->isFunctionType());
7381     return Sema::FunctionVoidPointer;
7382   }
7383 
7384   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7385   // unqualified versions of compatible types, ...
7386   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7387   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7388     // Check if the pointee types are compatible ignoring the sign.
7389     // We explicitly check for char so that we catch "char" vs
7390     // "unsigned char" on systems where "char" is unsigned.
7391     if (lhptee->isCharType())
7392       ltrans = S.Context.UnsignedCharTy;
7393     else if (lhptee->hasSignedIntegerRepresentation())
7394       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7395 
7396     if (rhptee->isCharType())
7397       rtrans = S.Context.UnsignedCharTy;
7398     else if (rhptee->hasSignedIntegerRepresentation())
7399       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7400 
7401     if (ltrans == rtrans) {
7402       // Types are compatible ignoring the sign. Qualifier incompatibility
7403       // takes priority over sign incompatibility because the sign
7404       // warning can be disabled.
7405       if (ConvTy != Sema::Compatible)
7406         return ConvTy;
7407 
7408       return Sema::IncompatiblePointerSign;
7409     }
7410 
7411     // If we are a multi-level pointer, it's possible that our issue is simply
7412     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7413     // the eventual target type is the same and the pointers have the same
7414     // level of indirection, this must be the issue.
7415     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7416       do {
7417         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7418         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7419       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7420 
7421       if (lhptee == rhptee)
7422         return Sema::IncompatibleNestedPointerQualifiers;
7423     }
7424 
7425     // General pointer incompatibility takes priority over qualifiers.
7426     return Sema::IncompatiblePointer;
7427   }
7428   if (!S.getLangOpts().CPlusPlus &&
7429       S.IsFunctionConversion(ltrans, rtrans, ltrans))
7430     return Sema::IncompatiblePointer;
7431   return ConvTy;
7432 }
7433 
7434 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7435 /// block pointer types are compatible or whether a block and normal pointer
7436 /// are compatible. It is more restrict than comparing two function pointer
7437 // types.
7438 static Sema::AssignConvertType
7439 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7440                                     QualType RHSType) {
7441   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7442   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7443 
7444   QualType lhptee, rhptee;
7445 
7446   // get the "pointed to" type (ignoring qualifiers at the top level)
7447   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7448   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7449 
7450   // In C++, the types have to match exactly.
7451   if (S.getLangOpts().CPlusPlus)
7452     return Sema::IncompatibleBlockPointer;
7453 
7454   Sema::AssignConvertType ConvTy = Sema::Compatible;
7455 
7456   // For blocks we enforce that qualifiers are identical.
7457   Qualifiers LQuals = lhptee.getLocalQualifiers();
7458   Qualifiers RQuals = rhptee.getLocalQualifiers();
7459   if (S.getLangOpts().OpenCL) {
7460     LQuals.removeAddressSpace();
7461     RQuals.removeAddressSpace();
7462   }
7463   if (LQuals != RQuals)
7464     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7465 
7466   // FIXME: OpenCL doesn't define the exact compile time semantics for a block
7467   // assignment.
7468   // The current behavior is similar to C++ lambdas. A block might be
7469   // assigned to a variable iff its return type and parameters are compatible
7470   // (C99 6.2.7) with the corresponding return type and parameters of the LHS of
7471   // an assignment. Presumably it should behave in way that a function pointer
7472   // assignment does in C, so for each parameter and return type:
7473   //  * CVR and address space of LHS should be a superset of CVR and address
7474   //  space of RHS.
7475   //  * unqualified types should be compatible.
7476   if (S.getLangOpts().OpenCL) {
7477     if (!S.Context.typesAreBlockPointerCompatible(
7478             S.Context.getQualifiedType(LHSType.getUnqualifiedType(), LQuals),
7479             S.Context.getQualifiedType(RHSType.getUnqualifiedType(), RQuals)))
7480       return Sema::IncompatibleBlockPointer;
7481   } else if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7482     return Sema::IncompatibleBlockPointer;
7483 
7484   return ConvTy;
7485 }
7486 
7487 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7488 /// for assignment compatibility.
7489 static Sema::AssignConvertType
7490 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7491                                    QualType RHSType) {
7492   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7493   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7494 
7495   if (LHSType->isObjCBuiltinType()) {
7496     // Class is not compatible with ObjC object pointers.
7497     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7498         !RHSType->isObjCQualifiedClassType())
7499       return Sema::IncompatiblePointer;
7500     return Sema::Compatible;
7501   }
7502   if (RHSType->isObjCBuiltinType()) {
7503     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7504         !LHSType->isObjCQualifiedClassType())
7505       return Sema::IncompatiblePointer;
7506     return Sema::Compatible;
7507   }
7508   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7509   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7510 
7511   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7512       // make an exception for id<P>
7513       !LHSType->isObjCQualifiedIdType())
7514     return Sema::CompatiblePointerDiscardsQualifiers;
7515 
7516   if (S.Context.typesAreCompatible(LHSType, RHSType))
7517     return Sema::Compatible;
7518   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7519     return Sema::IncompatibleObjCQualifiedId;
7520   return Sema::IncompatiblePointer;
7521 }
7522 
7523 Sema::AssignConvertType
7524 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7525                                  QualType LHSType, QualType RHSType) {
7526   // Fake up an opaque expression.  We don't actually care about what
7527   // cast operations are required, so if CheckAssignmentConstraints
7528   // adds casts to this they'll be wasted, but fortunately that doesn't
7529   // usually happen on valid code.
7530   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7531   ExprResult RHSPtr = &RHSExpr;
7532   CastKind K;
7533 
7534   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7535 }
7536 
7537 /// This helper function returns true if QT is a vector type that has element
7538 /// type ElementType.
7539 static bool isVector(QualType QT, QualType ElementType) {
7540   if (const VectorType *VT = QT->getAs<VectorType>())
7541     return VT->getElementType() == ElementType;
7542   return false;
7543 }
7544 
7545 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7546 /// has code to accommodate several GCC extensions when type checking
7547 /// pointers. Here are some objectionable examples that GCC considers warnings:
7548 ///
7549 ///  int a, *pint;
7550 ///  short *pshort;
7551 ///  struct foo *pfoo;
7552 ///
7553 ///  pint = pshort; // warning: assignment from incompatible pointer type
7554 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7555 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7556 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7557 ///
7558 /// As a result, the code for dealing with pointers is more complex than the
7559 /// C99 spec dictates.
7560 ///
7561 /// Sets 'Kind' for any result kind except Incompatible.
7562 Sema::AssignConvertType
7563 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7564                                  CastKind &Kind, bool ConvertRHS) {
7565   QualType RHSType = RHS.get()->getType();
7566   QualType OrigLHSType = LHSType;
7567 
7568   // Get canonical types.  We're not formatting these types, just comparing
7569   // them.
7570   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7571   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7572 
7573   // Common case: no conversion required.
7574   if (LHSType == RHSType) {
7575     Kind = CK_NoOp;
7576     return Compatible;
7577   }
7578 
7579   // If we have an atomic type, try a non-atomic assignment, then just add an
7580   // atomic qualification step.
7581   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7582     Sema::AssignConvertType result =
7583       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7584     if (result != Compatible)
7585       return result;
7586     if (Kind != CK_NoOp && ConvertRHS)
7587       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7588     Kind = CK_NonAtomicToAtomic;
7589     return Compatible;
7590   }
7591 
7592   // If the left-hand side is a reference type, then we are in a
7593   // (rare!) case where we've allowed the use of references in C,
7594   // e.g., as a parameter type in a built-in function. In this case,
7595   // just make sure that the type referenced is compatible with the
7596   // right-hand side type. The caller is responsible for adjusting
7597   // LHSType so that the resulting expression does not have reference
7598   // type.
7599   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7600     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7601       Kind = CK_LValueBitCast;
7602       return Compatible;
7603     }
7604     return Incompatible;
7605   }
7606 
7607   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7608   // to the same ExtVector type.
7609   if (LHSType->isExtVectorType()) {
7610     if (RHSType->isExtVectorType())
7611       return Incompatible;
7612     if (RHSType->isArithmeticType()) {
7613       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7614       if (ConvertRHS)
7615         RHS = prepareVectorSplat(LHSType, RHS.get());
7616       Kind = CK_VectorSplat;
7617       return Compatible;
7618     }
7619   }
7620 
7621   // Conversions to or from vector type.
7622   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7623     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7624       // Allow assignments of an AltiVec vector type to an equivalent GCC
7625       // vector type and vice versa
7626       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7627         Kind = CK_BitCast;
7628         return Compatible;
7629       }
7630 
7631       // If we are allowing lax vector conversions, and LHS and RHS are both
7632       // vectors, the total size only needs to be the same. This is a bitcast;
7633       // no bits are changed but the result type is different.
7634       if (isLaxVectorConversion(RHSType, LHSType)) {
7635         Kind = CK_BitCast;
7636         return IncompatibleVectors;
7637       }
7638     }
7639 
7640     // When the RHS comes from another lax conversion (e.g. binops between
7641     // scalars and vectors) the result is canonicalized as a vector. When the
7642     // LHS is also a vector, the lax is allowed by the condition above. Handle
7643     // the case where LHS is a scalar.
7644     if (LHSType->isScalarType()) {
7645       const VectorType *VecType = RHSType->getAs<VectorType>();
7646       if (VecType && VecType->getNumElements() == 1 &&
7647           isLaxVectorConversion(RHSType, LHSType)) {
7648         ExprResult *VecExpr = &RHS;
7649         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7650         Kind = CK_BitCast;
7651         return Compatible;
7652       }
7653     }
7654 
7655     return Incompatible;
7656   }
7657 
7658   // Diagnose attempts to convert between __float128 and long double where
7659   // such conversions currently can't be handled.
7660   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7661     return Incompatible;
7662 
7663   // Disallow assigning a _Complex to a real type in C++ mode since it simply
7664   // discards the imaginary part.
7665   if (getLangOpts().CPlusPlus && RHSType->getAs<ComplexType>() &&
7666       !LHSType->getAs<ComplexType>())
7667     return Incompatible;
7668 
7669   // Arithmetic conversions.
7670   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7671       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7672     if (ConvertRHS)
7673       Kind = PrepareScalarCast(RHS, LHSType);
7674     return Compatible;
7675   }
7676 
7677   // Conversions to normal pointers.
7678   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7679     // U* -> T*
7680     if (isa<PointerType>(RHSType)) {
7681       LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7682       LangAS AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7683       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7684       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7685     }
7686 
7687     // int -> T*
7688     if (RHSType->isIntegerType()) {
7689       Kind = CK_IntegralToPointer; // FIXME: null?
7690       return IntToPointer;
7691     }
7692 
7693     // C pointers are not compatible with ObjC object pointers,
7694     // with two exceptions:
7695     if (isa<ObjCObjectPointerType>(RHSType)) {
7696       //  - conversions to void*
7697       if (LHSPointer->getPointeeType()->isVoidType()) {
7698         Kind = CK_BitCast;
7699         return Compatible;
7700       }
7701 
7702       //  - conversions from 'Class' to the redefinition type
7703       if (RHSType->isObjCClassType() &&
7704           Context.hasSameType(LHSType,
7705                               Context.getObjCClassRedefinitionType())) {
7706         Kind = CK_BitCast;
7707         return Compatible;
7708       }
7709 
7710       Kind = CK_BitCast;
7711       return IncompatiblePointer;
7712     }
7713 
7714     // U^ -> void*
7715     if (RHSType->getAs<BlockPointerType>()) {
7716       if (LHSPointer->getPointeeType()->isVoidType()) {
7717         LangAS AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7718         LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7719                                 ->getPointeeType()
7720                                 .getAddressSpace();
7721         Kind =
7722             AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7723         return Compatible;
7724       }
7725     }
7726 
7727     return Incompatible;
7728   }
7729 
7730   // Conversions to block pointers.
7731   if (isa<BlockPointerType>(LHSType)) {
7732     // U^ -> T^
7733     if (RHSType->isBlockPointerType()) {
7734       LangAS AddrSpaceL = LHSType->getAs<BlockPointerType>()
7735                               ->getPointeeType()
7736                               .getAddressSpace();
7737       LangAS AddrSpaceR = RHSType->getAs<BlockPointerType>()
7738                               ->getPointeeType()
7739                               .getAddressSpace();
7740       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7741       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7742     }
7743 
7744     // int or null -> T^
7745     if (RHSType->isIntegerType()) {
7746       Kind = CK_IntegralToPointer; // FIXME: null
7747       return IntToBlockPointer;
7748     }
7749 
7750     // id -> T^
7751     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7752       Kind = CK_AnyPointerToBlockPointerCast;
7753       return Compatible;
7754     }
7755 
7756     // void* -> T^
7757     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7758       if (RHSPT->getPointeeType()->isVoidType()) {
7759         Kind = CK_AnyPointerToBlockPointerCast;
7760         return Compatible;
7761       }
7762 
7763     return Incompatible;
7764   }
7765 
7766   // Conversions to Objective-C pointers.
7767   if (isa<ObjCObjectPointerType>(LHSType)) {
7768     // A* -> B*
7769     if (RHSType->isObjCObjectPointerType()) {
7770       Kind = CK_BitCast;
7771       Sema::AssignConvertType result =
7772         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7773       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7774           result == Compatible &&
7775           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7776         result = IncompatibleObjCWeakRef;
7777       return result;
7778     }
7779 
7780     // int or null -> A*
7781     if (RHSType->isIntegerType()) {
7782       Kind = CK_IntegralToPointer; // FIXME: null
7783       return IntToPointer;
7784     }
7785 
7786     // In general, C pointers are not compatible with ObjC object pointers,
7787     // with two exceptions:
7788     if (isa<PointerType>(RHSType)) {
7789       Kind = CK_CPointerToObjCPointerCast;
7790 
7791       //  - conversions from 'void*'
7792       if (RHSType->isVoidPointerType()) {
7793         return Compatible;
7794       }
7795 
7796       //  - conversions to 'Class' from its redefinition type
7797       if (LHSType->isObjCClassType() &&
7798           Context.hasSameType(RHSType,
7799                               Context.getObjCClassRedefinitionType())) {
7800         return Compatible;
7801       }
7802 
7803       return IncompatiblePointer;
7804     }
7805 
7806     // Only under strict condition T^ is compatible with an Objective-C pointer.
7807     if (RHSType->isBlockPointerType() &&
7808         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7809       if (ConvertRHS)
7810         maybeExtendBlockObject(RHS);
7811       Kind = CK_BlockPointerToObjCPointerCast;
7812       return Compatible;
7813     }
7814 
7815     return Incompatible;
7816   }
7817 
7818   // Conversions from pointers that are not covered by the above.
7819   if (isa<PointerType>(RHSType)) {
7820     // T* -> _Bool
7821     if (LHSType == Context.BoolTy) {
7822       Kind = CK_PointerToBoolean;
7823       return Compatible;
7824     }
7825 
7826     // T* -> int
7827     if (LHSType->isIntegerType()) {
7828       Kind = CK_PointerToIntegral;
7829       return PointerToInt;
7830     }
7831 
7832     return Incompatible;
7833   }
7834 
7835   // Conversions from Objective-C pointers that are not covered by the above.
7836   if (isa<ObjCObjectPointerType>(RHSType)) {
7837     // T* -> _Bool
7838     if (LHSType == Context.BoolTy) {
7839       Kind = CK_PointerToBoolean;
7840       return Compatible;
7841     }
7842 
7843     // T* -> int
7844     if (LHSType->isIntegerType()) {
7845       Kind = CK_PointerToIntegral;
7846       return PointerToInt;
7847     }
7848 
7849     return Incompatible;
7850   }
7851 
7852   // struct A -> struct B
7853   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7854     if (Context.typesAreCompatible(LHSType, RHSType)) {
7855       Kind = CK_NoOp;
7856       return Compatible;
7857     }
7858   }
7859 
7860   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7861     Kind = CK_IntToOCLSampler;
7862     return Compatible;
7863   }
7864 
7865   return Incompatible;
7866 }
7867 
7868 /// \brief Constructs a transparent union from an expression that is
7869 /// used to initialize the transparent union.
7870 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7871                                       ExprResult &EResult, QualType UnionType,
7872                                       FieldDecl *Field) {
7873   // Build an initializer list that designates the appropriate member
7874   // of the transparent union.
7875   Expr *E = EResult.get();
7876   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7877                                                    E, SourceLocation());
7878   Initializer->setType(UnionType);
7879   Initializer->setInitializedFieldInUnion(Field);
7880 
7881   // Build a compound literal constructing a value of the transparent
7882   // union type from this initializer list.
7883   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7884   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7885                                         VK_RValue, Initializer, false);
7886 }
7887 
7888 Sema::AssignConvertType
7889 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7890                                                ExprResult &RHS) {
7891   QualType RHSType = RHS.get()->getType();
7892 
7893   // If the ArgType is a Union type, we want to handle a potential
7894   // transparent_union GCC extension.
7895   const RecordType *UT = ArgType->getAsUnionType();
7896   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7897     return Incompatible;
7898 
7899   // The field to initialize within the transparent union.
7900   RecordDecl *UD = UT->getDecl();
7901   FieldDecl *InitField = nullptr;
7902   // It's compatible if the expression matches any of the fields.
7903   for (auto *it : UD->fields()) {
7904     if (it->getType()->isPointerType()) {
7905       // If the transparent union contains a pointer type, we allow:
7906       // 1) void pointer
7907       // 2) null pointer constant
7908       if (RHSType->isPointerType())
7909         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7910           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7911           InitField = it;
7912           break;
7913         }
7914 
7915       if (RHS.get()->isNullPointerConstant(Context,
7916                                            Expr::NPC_ValueDependentIsNull)) {
7917         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7918                                 CK_NullToPointer);
7919         InitField = it;
7920         break;
7921       }
7922     }
7923 
7924     CastKind Kind;
7925     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7926           == Compatible) {
7927       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7928       InitField = it;
7929       break;
7930     }
7931   }
7932 
7933   if (!InitField)
7934     return Incompatible;
7935 
7936   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7937   return Compatible;
7938 }
7939 
7940 Sema::AssignConvertType
7941 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7942                                        bool Diagnose,
7943                                        bool DiagnoseCFAudited,
7944                                        bool ConvertRHS) {
7945   // We need to be able to tell the caller whether we diagnosed a problem, if
7946   // they ask us to issue diagnostics.
7947   assert((ConvertRHS || !Diagnose) && "can't indicate whether we diagnosed");
7948 
7949   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7950   // we can't avoid *all* modifications at the moment, so we need some somewhere
7951   // to put the updated value.
7952   ExprResult LocalRHS = CallerRHS;
7953   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7954 
7955   if (getLangOpts().CPlusPlus) {
7956     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7957       // C++ 5.17p3: If the left operand is not of class type, the
7958       // expression is implicitly converted (C++ 4) to the
7959       // cv-unqualified type of the left operand.
7960       QualType RHSType = RHS.get()->getType();
7961       if (Diagnose) {
7962         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7963                                         AA_Assigning);
7964       } else {
7965         ImplicitConversionSequence ICS =
7966             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7967                                   /*SuppressUserConversions=*/false,
7968                                   /*AllowExplicit=*/false,
7969                                   /*InOverloadResolution=*/false,
7970                                   /*CStyle=*/false,
7971                                   /*AllowObjCWritebackConversion=*/false);
7972         if (ICS.isFailure())
7973           return Incompatible;
7974         RHS = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7975                                         ICS, AA_Assigning);
7976       }
7977       if (RHS.isInvalid())
7978         return Incompatible;
7979       Sema::AssignConvertType result = Compatible;
7980       if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
7981           !CheckObjCARCUnavailableWeakConversion(LHSType, RHSType))
7982         result = IncompatibleObjCWeakRef;
7983       return result;
7984     }
7985 
7986     // FIXME: Currently, we fall through and treat C++ classes like C
7987     // structures.
7988     // FIXME: We also fall through for atomics; not sure what should
7989     // happen there, though.
7990   } else if (RHS.get()->getType() == Context.OverloadTy) {
7991     // As a set of extensions to C, we support overloading on functions. These
7992     // functions need to be resolved here.
7993     DeclAccessPair DAP;
7994     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7995             RHS.get(), LHSType, /*Complain=*/false, DAP))
7996       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7997     else
7998       return Incompatible;
7999   }
8000 
8001   // C99 6.5.16.1p1: the left operand is a pointer and the right is
8002   // a null pointer constant.
8003   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
8004        LHSType->isBlockPointerType()) &&
8005       RHS.get()->isNullPointerConstant(Context,
8006                                        Expr::NPC_ValueDependentIsNull)) {
8007     if (Diagnose || ConvertRHS) {
8008       CastKind Kind;
8009       CXXCastPath Path;
8010       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
8011                              /*IgnoreBaseAccess=*/false, Diagnose);
8012       if (ConvertRHS)
8013         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
8014     }
8015     return Compatible;
8016   }
8017 
8018   // This check seems unnatural, however it is necessary to ensure the proper
8019   // conversion of functions/arrays. If the conversion were done for all
8020   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
8021   // expressions that suppress this implicit conversion (&, sizeof).
8022   //
8023   // Suppress this for references: C++ 8.5.3p5.
8024   if (!LHSType->isReferenceType()) {
8025     // FIXME: We potentially allocate here even if ConvertRHS is false.
8026     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
8027     if (RHS.isInvalid())
8028       return Incompatible;
8029   }
8030 
8031   Expr *PRE = RHS.get()->IgnoreParenCasts();
8032   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
8033     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
8034     if (PDecl && !PDecl->hasDefinition()) {
8035       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl;
8036       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
8037     }
8038   }
8039 
8040   CastKind Kind;
8041   Sema::AssignConvertType result =
8042     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
8043 
8044   // C99 6.5.16.1p2: The value of the right operand is converted to the
8045   // type of the assignment expression.
8046   // CheckAssignmentConstraints allows the left-hand side to be a reference,
8047   // so that we can use references in built-in functions even in C.
8048   // The getNonReferenceType() call makes sure that the resulting expression
8049   // does not have reference type.
8050   if (result != Incompatible && RHS.get()->getType() != LHSType) {
8051     QualType Ty = LHSType.getNonLValueExprType(Context);
8052     Expr *E = RHS.get();
8053 
8054     // Check for various Objective-C errors. If we are not reporting
8055     // diagnostics and just checking for errors, e.g., during overload
8056     // resolution, return Incompatible to indicate the failure.
8057     if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
8058         CheckObjCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
8059                             Diagnose, DiagnoseCFAudited) != ACR_okay) {
8060       if (!Diagnose)
8061         return Incompatible;
8062     }
8063     if (getLangOpts().ObjC1 &&
8064         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
8065                                            E->getType(), E, Diagnose) ||
8066          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
8067       if (!Diagnose)
8068         return Incompatible;
8069       // Replace the expression with a corrected version and continue so we
8070       // can find further errors.
8071       RHS = E;
8072       return Compatible;
8073     }
8074 
8075     if (ConvertRHS)
8076       RHS = ImpCastExprToType(E, Ty, Kind);
8077   }
8078   return result;
8079 }
8080 
8081 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
8082                                ExprResult &RHS) {
8083   Diag(Loc, diag::err_typecheck_invalid_operands)
8084     << LHS.get()->getType() << RHS.get()->getType()
8085     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8086   return QualType();
8087 }
8088 
8089 // Diagnose cases where a scalar was implicitly converted to a vector and
8090 // diagnose the underlying types. Otherwise, diagnose the error
8091 // as invalid vector logical operands for non-C++ cases.
8092 QualType Sema::InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS,
8093                                             ExprResult &RHS) {
8094   QualType LHSType = LHS.get()->IgnoreImpCasts()->getType();
8095   QualType RHSType = RHS.get()->IgnoreImpCasts()->getType();
8096 
8097   bool LHSNatVec = LHSType->isVectorType();
8098   bool RHSNatVec = RHSType->isVectorType();
8099 
8100   if (!(LHSNatVec && RHSNatVec)) {
8101     Expr *Vector = LHSNatVec ? LHS.get() : RHS.get();
8102     Expr *NonVector = !LHSNatVec ? LHS.get() : RHS.get();
8103     Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8104         << 0 << Vector->getType() << NonVector->IgnoreImpCasts()->getType()
8105         << Vector->getSourceRange();
8106     return QualType();
8107   }
8108 
8109   Diag(Loc, diag::err_typecheck_logical_vector_expr_gnu_cpp_restrict)
8110       << 1 << LHSType << RHSType << LHS.get()->getSourceRange()
8111       << RHS.get()->getSourceRange();
8112 
8113   return QualType();
8114 }
8115 
8116 /// Try to convert a value of non-vector type to a vector type by converting
8117 /// the type to the element type of the vector and then performing a splat.
8118 /// If the language is OpenCL, we only use conversions that promote scalar
8119 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
8120 /// for float->int.
8121 ///
8122 /// OpenCL V2.0 6.2.6.p2:
8123 /// An error shall occur if any scalar operand type has greater rank
8124 /// than the type of the vector element.
8125 ///
8126 /// \param scalar - if non-null, actually perform the conversions
8127 /// \return true if the operation fails (but without diagnosing the failure)
8128 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
8129                                      QualType scalarTy,
8130                                      QualType vectorEltTy,
8131                                      QualType vectorTy,
8132                                      unsigned &DiagID) {
8133   // The conversion to apply to the scalar before splatting it,
8134   // if necessary.
8135   CastKind scalarCast = CK_NoOp;
8136 
8137   if (vectorEltTy->isIntegralType(S.Context)) {
8138     if (S.getLangOpts().OpenCL && (scalarTy->isRealFloatingType() ||
8139         (scalarTy->isIntegerType() &&
8140          S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0))) {
8141       DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8142       return true;
8143     }
8144     if (!scalarTy->isIntegralType(S.Context))
8145       return true;
8146     scalarCast = CK_IntegralCast;
8147   } else if (vectorEltTy->isRealFloatingType()) {
8148     if (scalarTy->isRealFloatingType()) {
8149       if (S.getLangOpts().OpenCL &&
8150           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0) {
8151         DiagID = diag::err_opencl_scalar_type_rank_greater_than_vector_type;
8152         return true;
8153       }
8154       scalarCast = CK_FloatingCast;
8155     }
8156     else if (scalarTy->isIntegralType(S.Context))
8157       scalarCast = CK_IntegralToFloating;
8158     else
8159       return true;
8160   } else {
8161     return true;
8162   }
8163 
8164   // Adjust scalar if desired.
8165   if (scalar) {
8166     if (scalarCast != CK_NoOp)
8167       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
8168     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
8169   }
8170   return false;
8171 }
8172 
8173 /// Convert vector E to a vector with the same number of elements but different
8174 /// element type.
8175 static ExprResult convertVector(Expr *E, QualType ElementType, Sema &S) {
8176   const auto *VecTy = E->getType()->getAs<VectorType>();
8177   assert(VecTy && "Expression E must be a vector");
8178   QualType NewVecTy = S.Context.getVectorType(ElementType,
8179                                               VecTy->getNumElements(),
8180                                               VecTy->getVectorKind());
8181 
8182   // Look through the implicit cast. Return the subexpression if its type is
8183   // NewVecTy.
8184   if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
8185     if (ICE->getSubExpr()->getType() == NewVecTy)
8186       return ICE->getSubExpr();
8187 
8188   auto Cast = ElementType->isIntegerType() ? CK_IntegralCast : CK_FloatingCast;
8189   return S.ImpCastExprToType(E, NewVecTy, Cast);
8190 }
8191 
8192 /// Test if a (constant) integer Int can be casted to another integer type
8193 /// IntTy without losing precision.
8194 static bool canConvertIntToOtherIntTy(Sema &S, ExprResult *Int,
8195                                       QualType OtherIntTy) {
8196   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8197 
8198   // Reject cases where the value of the Int is unknown as that would
8199   // possibly cause truncation, but accept cases where the scalar can be
8200   // demoted without loss of precision.
8201   llvm::APSInt Result;
8202   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8203   int Order = S.Context.getIntegerTypeOrder(OtherIntTy, IntTy);
8204   bool IntSigned = IntTy->hasSignedIntegerRepresentation();
8205   bool OtherIntSigned = OtherIntTy->hasSignedIntegerRepresentation();
8206 
8207   if (CstInt) {
8208     // If the scalar is constant and is of a higher order and has more active
8209     // bits that the vector element type, reject it.
8210     unsigned NumBits = IntSigned
8211                            ? (Result.isNegative() ? Result.getMinSignedBits()
8212                                                   : Result.getActiveBits())
8213                            : Result.getActiveBits();
8214     if (Order < 0 && S.Context.getIntWidth(OtherIntTy) < NumBits)
8215       return true;
8216 
8217     // If the signedness of the scalar type and the vector element type
8218     // differs and the number of bits is greater than that of the vector
8219     // element reject it.
8220     return (IntSigned != OtherIntSigned &&
8221             NumBits > S.Context.getIntWidth(OtherIntTy));
8222   }
8223 
8224   // Reject cases where the value of the scalar is not constant and it's
8225   // order is greater than that of the vector element type.
8226   return (Order < 0);
8227 }
8228 
8229 /// Test if a (constant) integer Int can be casted to floating point type
8230 /// FloatTy without losing precision.
8231 static bool canConvertIntTyToFloatTy(Sema &S, ExprResult *Int,
8232                                      QualType FloatTy) {
8233   QualType IntTy = Int->get()->getType().getUnqualifiedType();
8234 
8235   // Determine if the integer constant can be expressed as a floating point
8236   // number of the appropriate type.
8237   llvm::APSInt Result;
8238   bool CstInt = Int->get()->EvaluateAsInt(Result, S.Context);
8239   uint64_t Bits = 0;
8240   if (CstInt) {
8241     // Reject constants that would be truncated if they were converted to
8242     // the floating point type. Test by simple to/from conversion.
8243     // FIXME: Ideally the conversion to an APFloat and from an APFloat
8244     //        could be avoided if there was a convertFromAPInt method
8245     //        which could signal back if implicit truncation occurred.
8246     llvm::APFloat Float(S.Context.getFloatTypeSemantics(FloatTy));
8247     Float.convertFromAPInt(Result, IntTy->hasSignedIntegerRepresentation(),
8248                            llvm::APFloat::rmTowardZero);
8249     llvm::APSInt ConvertBack(S.Context.getIntWidth(IntTy),
8250                              !IntTy->hasSignedIntegerRepresentation());
8251     bool Ignored = false;
8252     Float.convertToInteger(ConvertBack, llvm::APFloat::rmNearestTiesToEven,
8253                            &Ignored);
8254     if (Result != ConvertBack)
8255       return true;
8256   } else {
8257     // Reject types that cannot be fully encoded into the mantissa of
8258     // the float.
8259     Bits = S.Context.getTypeSize(IntTy);
8260     unsigned FloatPrec = llvm::APFloat::semanticsPrecision(
8261         S.Context.getFloatTypeSemantics(FloatTy));
8262     if (Bits > FloatPrec)
8263       return true;
8264   }
8265 
8266   return false;
8267 }
8268 
8269 /// Attempt to convert and splat Scalar into a vector whose types matches
8270 /// Vector following GCC conversion rules. The rule is that implicit
8271 /// conversion can occur when Scalar can be casted to match Vector's element
8272 /// type without causing truncation of Scalar.
8273 static bool tryGCCVectorConvertAndSplat(Sema &S, ExprResult *Scalar,
8274                                         ExprResult *Vector) {
8275   QualType ScalarTy = Scalar->get()->getType().getUnqualifiedType();
8276   QualType VectorTy = Vector->get()->getType().getUnqualifiedType();
8277   const VectorType *VT = VectorTy->getAs<VectorType>();
8278 
8279   assert(!isa<ExtVectorType>(VT) &&
8280          "ExtVectorTypes should not be handled here!");
8281 
8282   QualType VectorEltTy = VT->getElementType();
8283 
8284   // Reject cases where the vector element type or the scalar element type are
8285   // not integral or floating point types.
8286   if (!VectorEltTy->isArithmeticType() || !ScalarTy->isArithmeticType())
8287     return true;
8288 
8289   // The conversion to apply to the scalar before splatting it,
8290   // if necessary.
8291   CastKind ScalarCast = CK_NoOp;
8292 
8293   // Accept cases where the vector elements are integers and the scalar is
8294   // an integer.
8295   // FIXME: Notionally if the scalar was a floating point value with a precise
8296   //        integral representation, we could cast it to an appropriate integer
8297   //        type and then perform the rest of the checks here. GCC will perform
8298   //        this conversion in some cases as determined by the input language.
8299   //        We should accept it on a language independent basis.
8300   if (VectorEltTy->isIntegralType(S.Context) &&
8301       ScalarTy->isIntegralType(S.Context) &&
8302       S.Context.getIntegerTypeOrder(VectorEltTy, ScalarTy)) {
8303 
8304     if (canConvertIntToOtherIntTy(S, Scalar, VectorEltTy))
8305       return true;
8306 
8307     ScalarCast = CK_IntegralCast;
8308   } else if (VectorEltTy->isRealFloatingType()) {
8309     if (ScalarTy->isRealFloatingType()) {
8310 
8311       // Reject cases where the scalar type is not a constant and has a higher
8312       // Order than the vector element type.
8313       llvm::APFloat Result(0.0);
8314       bool CstScalar = Scalar->get()->EvaluateAsFloat(Result, S.Context);
8315       int Order = S.Context.getFloatingTypeOrder(VectorEltTy, ScalarTy);
8316       if (!CstScalar && Order < 0)
8317         return true;
8318 
8319       // If the scalar cannot be safely casted to the vector element type,
8320       // reject it.
8321       if (CstScalar) {
8322         bool Truncated = false;
8323         Result.convert(S.Context.getFloatTypeSemantics(VectorEltTy),
8324                        llvm::APFloat::rmNearestTiesToEven, &Truncated);
8325         if (Truncated)
8326           return true;
8327       }
8328 
8329       ScalarCast = CK_FloatingCast;
8330     } else if (ScalarTy->isIntegralType(S.Context)) {
8331       if (canConvertIntTyToFloatTy(S, Scalar, VectorEltTy))
8332         return true;
8333 
8334       ScalarCast = CK_IntegralToFloating;
8335     } else
8336       return true;
8337   }
8338 
8339   // Adjust scalar if desired.
8340   if (Scalar) {
8341     if (ScalarCast != CK_NoOp)
8342       *Scalar = S.ImpCastExprToType(Scalar->get(), VectorEltTy, ScalarCast);
8343     *Scalar = S.ImpCastExprToType(Scalar->get(), VectorTy, CK_VectorSplat);
8344   }
8345   return false;
8346 }
8347 
8348 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
8349                                    SourceLocation Loc, bool IsCompAssign,
8350                                    bool AllowBothBool,
8351                                    bool AllowBoolConversions) {
8352   if (!IsCompAssign) {
8353     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
8354     if (LHS.isInvalid())
8355       return QualType();
8356   }
8357   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
8358   if (RHS.isInvalid())
8359     return QualType();
8360 
8361   // For conversion purposes, we ignore any qualifiers.
8362   // For example, "const float" and "float" are equivalent.
8363   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
8364   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8365 
8366   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8367   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8368   assert(LHSVecType || RHSVecType);
8369 
8370   // AltiVec-style "vector bool op vector bool" combinations are allowed
8371   // for some operators but not others.
8372   if (!AllowBothBool &&
8373       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8374       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8375     return InvalidOperands(Loc, LHS, RHS);
8376 
8377   // If the vector types are identical, return.
8378   if (Context.hasSameType(LHSType, RHSType))
8379     return LHSType;
8380 
8381   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8382   if (LHSVecType && RHSVecType &&
8383       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8384     if (isa<ExtVectorType>(LHSVecType)) {
8385       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8386       return LHSType;
8387     }
8388 
8389     if (!IsCompAssign)
8390       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8391     return RHSType;
8392   }
8393 
8394   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8395   // can be mixed, with the result being the non-bool type.  The non-bool
8396   // operand must have integer element type.
8397   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8398       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8399       (Context.getTypeSize(LHSVecType->getElementType()) ==
8400        Context.getTypeSize(RHSVecType->getElementType()))) {
8401     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8402         LHSVecType->getElementType()->isIntegerType() &&
8403         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8404       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8405       return LHSType;
8406     }
8407     if (!IsCompAssign &&
8408         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8409         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8410         RHSVecType->getElementType()->isIntegerType()) {
8411       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8412       return RHSType;
8413     }
8414   }
8415 
8416   // If there's a vector type and a scalar, try to convert the scalar to
8417   // the vector element type and splat.
8418   unsigned DiagID = diag::err_typecheck_vector_not_convertable;
8419   if (!RHSVecType) {
8420     if (isa<ExtVectorType>(LHSVecType)) {
8421       if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8422                                     LHSVecType->getElementType(), LHSType,
8423                                     DiagID))
8424         return LHSType;
8425     } else {
8426       if (!tryGCCVectorConvertAndSplat(*this, &RHS, &LHS))
8427         return LHSType;
8428     }
8429   }
8430   if (!LHSVecType) {
8431     if (isa<ExtVectorType>(RHSVecType)) {
8432       if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8433                                     LHSType, RHSVecType->getElementType(),
8434                                     RHSType, DiagID))
8435         return RHSType;
8436     } else {
8437       if (LHS.get()->getValueKind() == VK_LValue ||
8438           !tryGCCVectorConvertAndSplat(*this, &LHS, &RHS))
8439         return RHSType;
8440     }
8441   }
8442 
8443   // FIXME: The code below also handles conversion between vectors and
8444   // non-scalars, we should break this down into fine grained specific checks
8445   // and emit proper diagnostics.
8446   QualType VecType = LHSVecType ? LHSType : RHSType;
8447   const VectorType *VT = LHSVecType ? LHSVecType : RHSVecType;
8448   QualType OtherType = LHSVecType ? RHSType : LHSType;
8449   ExprResult *OtherExpr = LHSVecType ? &RHS : &LHS;
8450   if (isLaxVectorConversion(OtherType, VecType)) {
8451     // If we're allowing lax vector conversions, only the total (data) size
8452     // needs to be the same. For non compound assignment, if one of the types is
8453     // scalar, the result is always the vector type.
8454     if (!IsCompAssign) {
8455       *OtherExpr = ImpCastExprToType(OtherExpr->get(), VecType, CK_BitCast);
8456       return VecType;
8457     // In a compound assignment, lhs += rhs, 'lhs' is a lvalue src, forbidding
8458     // any implicit cast. Here, the 'rhs' should be implicit casted to 'lhs'
8459     // type. Note that this is already done by non-compound assignments in
8460     // CheckAssignmentConstraints. If it's a scalar type, only bitcast for
8461     // <1 x T> -> T. The result is also a vector type.
8462     } else if (OtherType->isExtVectorType() || OtherType->isVectorType() ||
8463                (OtherType->isScalarType() && VT->getNumElements() == 1)) {
8464       ExprResult *RHSExpr = &RHS;
8465       *RHSExpr = ImpCastExprToType(RHSExpr->get(), LHSType, CK_BitCast);
8466       return VecType;
8467     }
8468   }
8469 
8470   // Okay, the expression is invalid.
8471 
8472   // If there's a non-vector, non-real operand, diagnose that.
8473   if ((!RHSVecType && !RHSType->isRealType()) ||
8474       (!LHSVecType && !LHSType->isRealType())) {
8475     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8476       << LHSType << RHSType
8477       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8478     return QualType();
8479   }
8480 
8481   // OpenCL V1.1 6.2.6.p1:
8482   // If the operands are of more than one vector type, then an error shall
8483   // occur. Implicit conversions between vector types are not permitted, per
8484   // section 6.2.1.
8485   if (getLangOpts().OpenCL &&
8486       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8487       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8488     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8489                                                            << RHSType;
8490     return QualType();
8491   }
8492 
8493 
8494   // If there is a vector type that is not a ExtVector and a scalar, we reach
8495   // this point if scalar could not be converted to the vector's element type
8496   // without truncation.
8497   if ((RHSVecType && !isa<ExtVectorType>(RHSVecType)) ||
8498       (LHSVecType && !isa<ExtVectorType>(LHSVecType))) {
8499     QualType Scalar = LHSVecType ? RHSType : LHSType;
8500     QualType Vector = LHSVecType ? LHSType : RHSType;
8501     unsigned ScalarOrVector = LHSVecType && RHSVecType ? 1 : 0;
8502     Diag(Loc,
8503          diag::err_typecheck_vector_not_convertable_implict_truncation)
8504         << ScalarOrVector << Scalar << Vector;
8505 
8506     return QualType();
8507   }
8508 
8509   // Otherwise, use the generic diagnostic.
8510   Diag(Loc, DiagID)
8511     << LHSType << RHSType
8512     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8513   return QualType();
8514 }
8515 
8516 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8517 // expression.  These are mainly cases where the null pointer is used as an
8518 // integer instead of a pointer.
8519 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8520                                 SourceLocation Loc, bool IsCompare) {
8521   // The canonical way to check for a GNU null is with isNullPointerConstant,
8522   // but we use a bit of a hack here for speed; this is a relatively
8523   // hot path, and isNullPointerConstant is slow.
8524   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8525   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8526 
8527   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8528 
8529   // Avoid analyzing cases where the result will either be invalid (and
8530   // diagnosed as such) or entirely valid and not something to warn about.
8531   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8532       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8533     return;
8534 
8535   // Comparison operations would not make sense with a null pointer no matter
8536   // what the other expression is.
8537   if (!IsCompare) {
8538     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8539         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8540         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8541     return;
8542   }
8543 
8544   // The rest of the operations only make sense with a null pointer
8545   // if the other expression is a pointer.
8546   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8547       NonNullType->canDecayToPointerType())
8548     return;
8549 
8550   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8551       << LHSNull /* LHS is NULL */ << NonNullType
8552       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8553 }
8554 
8555 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8556                                                ExprResult &RHS,
8557                                                SourceLocation Loc, bool IsDiv) {
8558   // Check for division/remainder by zero.
8559   llvm::APSInt RHSValue;
8560   if (!RHS.get()->isValueDependent() &&
8561       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8562     S.DiagRuntimeBehavior(Loc, RHS.get(),
8563                           S.PDiag(diag::warn_remainder_division_by_zero)
8564                             << IsDiv << RHS.get()->getSourceRange());
8565 }
8566 
8567 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8568                                            SourceLocation Loc,
8569                                            bool IsCompAssign, bool IsDiv) {
8570   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8571 
8572   if (LHS.get()->getType()->isVectorType() ||
8573       RHS.get()->getType()->isVectorType())
8574     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8575                                /*AllowBothBool*/getLangOpts().AltiVec,
8576                                /*AllowBoolConversions*/false);
8577 
8578   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8579   if (LHS.isInvalid() || RHS.isInvalid())
8580     return QualType();
8581 
8582 
8583   if (compType.isNull() || !compType->isArithmeticType())
8584     return InvalidOperands(Loc, LHS, RHS);
8585   if (IsDiv)
8586     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8587   return compType;
8588 }
8589 
8590 QualType Sema::CheckRemainderOperands(
8591   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8592   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8593 
8594   if (LHS.get()->getType()->isVectorType() ||
8595       RHS.get()->getType()->isVectorType()) {
8596     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8597         RHS.get()->getType()->hasIntegerRepresentation())
8598       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8599                                  /*AllowBothBool*/getLangOpts().AltiVec,
8600                                  /*AllowBoolConversions*/false);
8601     return InvalidOperands(Loc, LHS, RHS);
8602   }
8603 
8604   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8605   if (LHS.isInvalid() || RHS.isInvalid())
8606     return QualType();
8607 
8608   if (compType.isNull() || !compType->isIntegerType())
8609     return InvalidOperands(Loc, LHS, RHS);
8610   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8611   return compType;
8612 }
8613 
8614 /// \brief Diagnose invalid arithmetic on two void pointers.
8615 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8616                                                 Expr *LHSExpr, Expr *RHSExpr) {
8617   S.Diag(Loc, S.getLangOpts().CPlusPlus
8618                 ? diag::err_typecheck_pointer_arith_void_type
8619                 : diag::ext_gnu_void_ptr)
8620     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8621                             << RHSExpr->getSourceRange();
8622 }
8623 
8624 /// \brief Diagnose invalid arithmetic on a void pointer.
8625 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8626                                             Expr *Pointer) {
8627   S.Diag(Loc, S.getLangOpts().CPlusPlus
8628                 ? diag::err_typecheck_pointer_arith_void_type
8629                 : diag::ext_gnu_void_ptr)
8630     << 0 /* one pointer */ << Pointer->getSourceRange();
8631 }
8632 
8633 /// \brief Diagnose invalid arithmetic on a null pointer.
8634 ///
8635 /// If \p IsGNUIdiom is true, the operation is using the 'p = (i8*)nullptr + n'
8636 /// idiom, which we recognize as a GNU extension.
8637 ///
8638 static void diagnoseArithmeticOnNullPointer(Sema &S, SourceLocation Loc,
8639                                             Expr *Pointer, bool IsGNUIdiom) {
8640   if (IsGNUIdiom)
8641     S.Diag(Loc, diag::warn_gnu_null_ptr_arith)
8642       << Pointer->getSourceRange();
8643   else
8644     S.Diag(Loc, diag::warn_pointer_arith_null_ptr)
8645       << S.getLangOpts().CPlusPlus << Pointer->getSourceRange();
8646 }
8647 
8648 /// \brief Diagnose invalid arithmetic on two function pointers.
8649 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8650                                                     Expr *LHS, Expr *RHS) {
8651   assert(LHS->getType()->isAnyPointerType());
8652   assert(RHS->getType()->isAnyPointerType());
8653   S.Diag(Loc, S.getLangOpts().CPlusPlus
8654                 ? diag::err_typecheck_pointer_arith_function_type
8655                 : diag::ext_gnu_ptr_func_arith)
8656     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8657     // We only show the second type if it differs from the first.
8658     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8659                                                    RHS->getType())
8660     << RHS->getType()->getPointeeType()
8661     << LHS->getSourceRange() << RHS->getSourceRange();
8662 }
8663 
8664 /// \brief Diagnose invalid arithmetic on a function pointer.
8665 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8666                                                 Expr *Pointer) {
8667   assert(Pointer->getType()->isAnyPointerType());
8668   S.Diag(Loc, S.getLangOpts().CPlusPlus
8669                 ? diag::err_typecheck_pointer_arith_function_type
8670                 : diag::ext_gnu_ptr_func_arith)
8671     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8672     << 0 /* one pointer, so only one type */
8673     << Pointer->getSourceRange();
8674 }
8675 
8676 /// \brief Emit error if Operand is incomplete pointer type
8677 ///
8678 /// \returns True if pointer has incomplete type
8679 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8680                                                  Expr *Operand) {
8681   QualType ResType = Operand->getType();
8682   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8683     ResType = ResAtomicType->getValueType();
8684 
8685   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8686   QualType PointeeTy = ResType->getPointeeType();
8687   return S.RequireCompleteType(Loc, PointeeTy,
8688                                diag::err_typecheck_arithmetic_incomplete_type,
8689                                PointeeTy, Operand->getSourceRange());
8690 }
8691 
8692 /// \brief Check the validity of an arithmetic pointer operand.
8693 ///
8694 /// If the operand has pointer type, this code will check for pointer types
8695 /// which are invalid in arithmetic operations. These will be diagnosed
8696 /// appropriately, including whether or not the use is supported as an
8697 /// extension.
8698 ///
8699 /// \returns True when the operand is valid to use (even if as an extension).
8700 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8701                                             Expr *Operand) {
8702   QualType ResType = Operand->getType();
8703   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8704     ResType = ResAtomicType->getValueType();
8705 
8706   if (!ResType->isAnyPointerType()) return true;
8707 
8708   QualType PointeeTy = ResType->getPointeeType();
8709   if (PointeeTy->isVoidType()) {
8710     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8711     return !S.getLangOpts().CPlusPlus;
8712   }
8713   if (PointeeTy->isFunctionType()) {
8714     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8715     return !S.getLangOpts().CPlusPlus;
8716   }
8717 
8718   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8719 
8720   return true;
8721 }
8722 
8723 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8724 /// operands.
8725 ///
8726 /// This routine will diagnose any invalid arithmetic on pointer operands much
8727 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8728 /// for emitting a single diagnostic even for operations where both LHS and RHS
8729 /// are (potentially problematic) pointers.
8730 ///
8731 /// \returns True when the operand is valid to use (even if as an extension).
8732 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8733                                                 Expr *LHSExpr, Expr *RHSExpr) {
8734   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8735   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8736   if (!isLHSPointer && !isRHSPointer) return true;
8737 
8738   QualType LHSPointeeTy, RHSPointeeTy;
8739   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8740   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8741 
8742   // if both are pointers check if operation is valid wrt address spaces
8743   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8744     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8745     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8746     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8747       S.Diag(Loc,
8748              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8749           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8750           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8751       return false;
8752     }
8753   }
8754 
8755   // Check for arithmetic on pointers to incomplete types.
8756   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8757   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8758   if (isLHSVoidPtr || isRHSVoidPtr) {
8759     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8760     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8761     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8762 
8763     return !S.getLangOpts().CPlusPlus;
8764   }
8765 
8766   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8767   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8768   if (isLHSFuncPtr || isRHSFuncPtr) {
8769     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8770     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8771                                                                 RHSExpr);
8772     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8773 
8774     return !S.getLangOpts().CPlusPlus;
8775   }
8776 
8777   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8778     return false;
8779   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8780     return false;
8781 
8782   return true;
8783 }
8784 
8785 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8786 /// literal.
8787 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8788                                   Expr *LHSExpr, Expr *RHSExpr) {
8789   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8790   Expr* IndexExpr = RHSExpr;
8791   if (!StrExpr) {
8792     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8793     IndexExpr = LHSExpr;
8794   }
8795 
8796   bool IsStringPlusInt = StrExpr &&
8797       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8798   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8799     return;
8800 
8801   llvm::APSInt index;
8802   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8803     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8804     if (index.isNonNegative() &&
8805         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8806                               index.isUnsigned()))
8807       return;
8808   }
8809 
8810   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8811   Self.Diag(OpLoc, diag::warn_string_plus_int)
8812       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8813 
8814   // Only print a fixit for "str" + int, not for int + "str".
8815   if (IndexExpr == RHSExpr) {
8816     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8817     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8818         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8819         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8820         << FixItHint::CreateInsertion(EndLoc, "]");
8821   } else
8822     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8823 }
8824 
8825 /// \brief Emit a warning when adding a char literal to a string.
8826 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8827                                    Expr *LHSExpr, Expr *RHSExpr) {
8828   const Expr *StringRefExpr = LHSExpr;
8829   const CharacterLiteral *CharExpr =
8830       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8831 
8832   if (!CharExpr) {
8833     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8834     StringRefExpr = RHSExpr;
8835   }
8836 
8837   if (!CharExpr || !StringRefExpr)
8838     return;
8839 
8840   const QualType StringType = StringRefExpr->getType();
8841 
8842   // Return if not a PointerType.
8843   if (!StringType->isAnyPointerType())
8844     return;
8845 
8846   // Return if not a CharacterType.
8847   if (!StringType->getPointeeType()->isAnyCharacterType())
8848     return;
8849 
8850   ASTContext &Ctx = Self.getASTContext();
8851   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8852 
8853   const QualType CharType = CharExpr->getType();
8854   if (!CharType->isAnyCharacterType() &&
8855       CharType->isIntegerType() &&
8856       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8857     Self.Diag(OpLoc, diag::warn_string_plus_char)
8858         << DiagRange << Ctx.CharTy;
8859   } else {
8860     Self.Diag(OpLoc, diag::warn_string_plus_char)
8861         << DiagRange << CharExpr->getType();
8862   }
8863 
8864   // Only print a fixit for str + char, not for char + str.
8865   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8866     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8867     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8868         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8869         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8870         << FixItHint::CreateInsertion(EndLoc, "]");
8871   } else {
8872     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8873   }
8874 }
8875 
8876 /// \brief Emit error when two pointers are incompatible.
8877 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8878                                            Expr *LHSExpr, Expr *RHSExpr) {
8879   assert(LHSExpr->getType()->isAnyPointerType());
8880   assert(RHSExpr->getType()->isAnyPointerType());
8881   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8882     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8883     << RHSExpr->getSourceRange();
8884 }
8885 
8886 // C99 6.5.6
8887 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8888                                      SourceLocation Loc, BinaryOperatorKind Opc,
8889                                      QualType* CompLHSTy) {
8890   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8891 
8892   if (LHS.get()->getType()->isVectorType() ||
8893       RHS.get()->getType()->isVectorType()) {
8894     QualType compType = CheckVectorOperands(
8895         LHS, RHS, Loc, CompLHSTy,
8896         /*AllowBothBool*/getLangOpts().AltiVec,
8897         /*AllowBoolConversions*/getLangOpts().ZVector);
8898     if (CompLHSTy) *CompLHSTy = compType;
8899     return compType;
8900   }
8901 
8902   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8903   if (LHS.isInvalid() || RHS.isInvalid())
8904     return QualType();
8905 
8906   // Diagnose "string literal" '+' int and string '+' "char literal".
8907   if (Opc == BO_Add) {
8908     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8909     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8910   }
8911 
8912   // handle the common case first (both operands are arithmetic).
8913   if (!compType.isNull() && compType->isArithmeticType()) {
8914     if (CompLHSTy) *CompLHSTy = compType;
8915     return compType;
8916   }
8917 
8918   // Type-checking.  Ultimately the pointer's going to be in PExp;
8919   // note that we bias towards the LHS being the pointer.
8920   Expr *PExp = LHS.get(), *IExp = RHS.get();
8921 
8922   bool isObjCPointer;
8923   if (PExp->getType()->isPointerType()) {
8924     isObjCPointer = false;
8925   } else if (PExp->getType()->isObjCObjectPointerType()) {
8926     isObjCPointer = true;
8927   } else {
8928     std::swap(PExp, IExp);
8929     if (PExp->getType()->isPointerType()) {
8930       isObjCPointer = false;
8931     } else if (PExp->getType()->isObjCObjectPointerType()) {
8932       isObjCPointer = true;
8933     } else {
8934       return InvalidOperands(Loc, LHS, RHS);
8935     }
8936   }
8937   assert(PExp->getType()->isAnyPointerType());
8938 
8939   if (!IExp->getType()->isIntegerType())
8940     return InvalidOperands(Loc, LHS, RHS);
8941 
8942   // Adding to a null pointer results in undefined behavior.
8943   if (PExp->IgnoreParenCasts()->isNullPointerConstant(
8944           Context, Expr::NPC_ValueDependentIsNotNull)) {
8945     // In C++ adding zero to a null pointer is defined.
8946     llvm::APSInt KnownVal;
8947     if (!getLangOpts().CPlusPlus ||
8948         (!IExp->isValueDependent() &&
8949          (!IExp->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
8950       // Check the conditions to see if this is the 'p = nullptr + n' idiom.
8951       bool IsGNUIdiom = BinaryOperator::isNullPointerArithmeticExtension(
8952           Context, BO_Add, PExp, IExp);
8953       diagnoseArithmeticOnNullPointer(*this, Loc, PExp, IsGNUIdiom);
8954     }
8955   }
8956 
8957   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8958     return QualType();
8959 
8960   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8961     return QualType();
8962 
8963   // Check array bounds for pointer arithemtic
8964   CheckArrayAccess(PExp, IExp);
8965 
8966   if (CompLHSTy) {
8967     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8968     if (LHSTy.isNull()) {
8969       LHSTy = LHS.get()->getType();
8970       if (LHSTy->isPromotableIntegerType())
8971         LHSTy = Context.getPromotedIntegerType(LHSTy);
8972     }
8973     *CompLHSTy = LHSTy;
8974   }
8975 
8976   return PExp->getType();
8977 }
8978 
8979 // C99 6.5.6
8980 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8981                                         SourceLocation Loc,
8982                                         QualType* CompLHSTy) {
8983   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8984 
8985   if (LHS.get()->getType()->isVectorType() ||
8986       RHS.get()->getType()->isVectorType()) {
8987     QualType compType = CheckVectorOperands(
8988         LHS, RHS, Loc, CompLHSTy,
8989         /*AllowBothBool*/getLangOpts().AltiVec,
8990         /*AllowBoolConversions*/getLangOpts().ZVector);
8991     if (CompLHSTy) *CompLHSTy = compType;
8992     return compType;
8993   }
8994 
8995   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8996   if (LHS.isInvalid() || RHS.isInvalid())
8997     return QualType();
8998 
8999   // Enforce type constraints: C99 6.5.6p3.
9000 
9001   // Handle the common case first (both operands are arithmetic).
9002   if (!compType.isNull() && compType->isArithmeticType()) {
9003     if (CompLHSTy) *CompLHSTy = compType;
9004     return compType;
9005   }
9006 
9007   // Either ptr - int   or   ptr - ptr.
9008   if (LHS.get()->getType()->isAnyPointerType()) {
9009     QualType lpointee = LHS.get()->getType()->getPointeeType();
9010 
9011     // Diagnose bad cases where we step over interface counts.
9012     if (LHS.get()->getType()->isObjCObjectPointerType() &&
9013         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
9014       return QualType();
9015 
9016     // The result type of a pointer-int computation is the pointer type.
9017     if (RHS.get()->getType()->isIntegerType()) {
9018       // Subtracting from a null pointer should produce a warning.
9019       // The last argument to the diagnose call says this doesn't match the
9020       // GNU int-to-pointer idiom.
9021       if (LHS.get()->IgnoreParenCasts()->isNullPointerConstant(Context,
9022                                            Expr::NPC_ValueDependentIsNotNull)) {
9023         // In C++ adding zero to a null pointer is defined.
9024         llvm::APSInt KnownVal;
9025         if (!getLangOpts().CPlusPlus ||
9026             (!RHS.get()->isValueDependent() &&
9027              (!RHS.get()->EvaluateAsInt(KnownVal, Context) || KnownVal != 0))) {
9028           diagnoseArithmeticOnNullPointer(*this, Loc, LHS.get(), false);
9029         }
9030       }
9031 
9032       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
9033         return QualType();
9034 
9035       // Check array bounds for pointer arithemtic
9036       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
9037                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
9038 
9039       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9040       return LHS.get()->getType();
9041     }
9042 
9043     // Handle pointer-pointer subtractions.
9044     if (const PointerType *RHSPTy
9045           = RHS.get()->getType()->getAs<PointerType>()) {
9046       QualType rpointee = RHSPTy->getPointeeType();
9047 
9048       if (getLangOpts().CPlusPlus) {
9049         // Pointee types must be the same: C++ [expr.add]
9050         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
9051           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9052         }
9053       } else {
9054         // Pointee types must be compatible C99 6.5.6p3
9055         if (!Context.typesAreCompatible(
9056                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
9057                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
9058           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
9059           return QualType();
9060         }
9061       }
9062 
9063       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
9064                                                LHS.get(), RHS.get()))
9065         return QualType();
9066 
9067       // FIXME: Add warnings for nullptr - ptr.
9068 
9069       // The pointee type may have zero size.  As an extension, a structure or
9070       // union may have zero size or an array may have zero length.  In this
9071       // case subtraction does not make sense.
9072       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
9073         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
9074         if (ElementSize.isZero()) {
9075           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
9076             << rpointee.getUnqualifiedType()
9077             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9078         }
9079       }
9080 
9081       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
9082       return Context.getPointerDiffType();
9083     }
9084   }
9085 
9086   return InvalidOperands(Loc, LHS, RHS);
9087 }
9088 
9089 static bool isScopedEnumerationType(QualType T) {
9090   if (const EnumType *ET = T->getAs<EnumType>())
9091     return ET->getDecl()->isScoped();
9092   return false;
9093 }
9094 
9095 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
9096                                    SourceLocation Loc, BinaryOperatorKind Opc,
9097                                    QualType LHSType) {
9098   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
9099   // so skip remaining warnings as we don't want to modify values within Sema.
9100   if (S.getLangOpts().OpenCL)
9101     return;
9102 
9103   llvm::APSInt Right;
9104   // Check right/shifter operand
9105   if (RHS.get()->isValueDependent() ||
9106       !RHS.get()->EvaluateAsInt(Right, S.Context))
9107     return;
9108 
9109   if (Right.isNegative()) {
9110     S.DiagRuntimeBehavior(Loc, RHS.get(),
9111                           S.PDiag(diag::warn_shift_negative)
9112                             << RHS.get()->getSourceRange());
9113     return;
9114   }
9115   llvm::APInt LeftBits(Right.getBitWidth(),
9116                        S.Context.getTypeSize(LHS.get()->getType()));
9117   if (Right.uge(LeftBits)) {
9118     S.DiagRuntimeBehavior(Loc, RHS.get(),
9119                           S.PDiag(diag::warn_shift_gt_typewidth)
9120                             << RHS.get()->getSourceRange());
9121     return;
9122   }
9123   if (Opc != BO_Shl)
9124     return;
9125 
9126   // When left shifting an ICE which is signed, we can check for overflow which
9127   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
9128   // integers have defined behavior modulo one more than the maximum value
9129   // representable in the result type, so never warn for those.
9130   llvm::APSInt Left;
9131   if (LHS.get()->isValueDependent() ||
9132       LHSType->hasUnsignedIntegerRepresentation() ||
9133       !LHS.get()->EvaluateAsInt(Left, S.Context))
9134     return;
9135 
9136   // If LHS does not have a signed type and non-negative value
9137   // then, the behavior is undefined. Warn about it.
9138   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
9139     S.DiagRuntimeBehavior(Loc, LHS.get(),
9140                           S.PDiag(diag::warn_shift_lhs_negative)
9141                             << LHS.get()->getSourceRange());
9142     return;
9143   }
9144 
9145   llvm::APInt ResultBits =
9146       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
9147   if (LeftBits.uge(ResultBits))
9148     return;
9149   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
9150   Result = Result.shl(Right);
9151 
9152   // Print the bit representation of the signed integer as an unsigned
9153   // hexadecimal number.
9154   SmallString<40> HexResult;
9155   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
9156 
9157   // If we are only missing a sign bit, this is less likely to result in actual
9158   // bugs -- if the result is cast back to an unsigned type, it will have the
9159   // expected value. Thus we place this behind a different warning that can be
9160   // turned off separately if needed.
9161   if (LeftBits == ResultBits - 1) {
9162     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
9163         << HexResult << LHSType
9164         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9165     return;
9166   }
9167 
9168   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
9169     << HexResult.str() << Result.getMinSignedBits() << LHSType
9170     << Left.getBitWidth() << LHS.get()->getSourceRange()
9171     << RHS.get()->getSourceRange();
9172 }
9173 
9174 /// \brief Return the resulting type when a vector is shifted
9175 ///        by a scalar or vector shift amount.
9176 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
9177                                  SourceLocation Loc, bool IsCompAssign) {
9178   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
9179   if ((S.LangOpts.OpenCL || S.LangOpts.ZVector) &&
9180       !LHS.get()->getType()->isVectorType()) {
9181     S.Diag(Loc, diag::err_shift_rhs_only_vector)
9182       << RHS.get()->getType() << LHS.get()->getType()
9183       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9184     return QualType();
9185   }
9186 
9187   if (!IsCompAssign) {
9188     LHS = S.UsualUnaryConversions(LHS.get());
9189     if (LHS.isInvalid()) return QualType();
9190   }
9191 
9192   RHS = S.UsualUnaryConversions(RHS.get());
9193   if (RHS.isInvalid()) return QualType();
9194 
9195   QualType LHSType = LHS.get()->getType();
9196   // Note that LHS might be a scalar because the routine calls not only in
9197   // OpenCL case.
9198   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
9199   QualType LHSEleType = LHSVecTy ? LHSVecTy->getElementType() : LHSType;
9200 
9201   // Note that RHS might not be a vector.
9202   QualType RHSType = RHS.get()->getType();
9203   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
9204   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
9205 
9206   // The operands need to be integers.
9207   if (!LHSEleType->isIntegerType()) {
9208     S.Diag(Loc, diag::err_typecheck_expect_int)
9209       << LHS.get()->getType() << LHS.get()->getSourceRange();
9210     return QualType();
9211   }
9212 
9213   if (!RHSEleType->isIntegerType()) {
9214     S.Diag(Loc, diag::err_typecheck_expect_int)
9215       << RHS.get()->getType() << RHS.get()->getSourceRange();
9216     return QualType();
9217   }
9218 
9219   if (!LHSVecTy) {
9220     assert(RHSVecTy);
9221     if (IsCompAssign)
9222       return RHSType;
9223     if (LHSEleType != RHSEleType) {
9224       LHS = S.ImpCastExprToType(LHS.get(),RHSEleType, CK_IntegralCast);
9225       LHSEleType = RHSEleType;
9226     }
9227     QualType VecTy =
9228         S.Context.getExtVectorType(LHSEleType, RHSVecTy->getNumElements());
9229     LHS = S.ImpCastExprToType(LHS.get(), VecTy, CK_VectorSplat);
9230     LHSType = VecTy;
9231   } else if (RHSVecTy) {
9232     // OpenCL v1.1 s6.3.j says that for vector types, the operators
9233     // are applied component-wise. So if RHS is a vector, then ensure
9234     // that the number of elements is the same as LHS...
9235     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
9236       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
9237         << LHS.get()->getType() << RHS.get()->getType()
9238         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9239       return QualType();
9240     }
9241     if (!S.LangOpts.OpenCL && !S.LangOpts.ZVector) {
9242       const BuiltinType *LHSBT = LHSEleType->getAs<clang::BuiltinType>();
9243       const BuiltinType *RHSBT = RHSEleType->getAs<clang::BuiltinType>();
9244       if (LHSBT != RHSBT &&
9245           S.Context.getTypeSize(LHSBT) != S.Context.getTypeSize(RHSBT)) {
9246         S.Diag(Loc, diag::warn_typecheck_vector_element_sizes_not_equal)
9247             << LHS.get()->getType() << RHS.get()->getType()
9248             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9249       }
9250     }
9251   } else {
9252     // ...else expand RHS to match the number of elements in LHS.
9253     QualType VecTy =
9254       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
9255     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
9256   }
9257 
9258   return LHSType;
9259 }
9260 
9261 // C99 6.5.7
9262 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
9263                                   SourceLocation Loc, BinaryOperatorKind Opc,
9264                                   bool IsCompAssign) {
9265   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9266 
9267   // Vector shifts promote their scalar inputs to vector type.
9268   if (LHS.get()->getType()->isVectorType() ||
9269       RHS.get()->getType()->isVectorType()) {
9270     if (LangOpts.ZVector) {
9271       // The shift operators for the z vector extensions work basically
9272       // like general shifts, except that neither the LHS nor the RHS is
9273       // allowed to be a "vector bool".
9274       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
9275         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
9276           return InvalidOperands(Loc, LHS, RHS);
9277       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
9278         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
9279           return InvalidOperands(Loc, LHS, RHS);
9280     }
9281     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
9282   }
9283 
9284   // Shifts don't perform usual arithmetic conversions, they just do integer
9285   // promotions on each operand. C99 6.5.7p3
9286 
9287   // For the LHS, do usual unary conversions, but then reset them away
9288   // if this is a compound assignment.
9289   ExprResult OldLHS = LHS;
9290   LHS = UsualUnaryConversions(LHS.get());
9291   if (LHS.isInvalid())
9292     return QualType();
9293   QualType LHSType = LHS.get()->getType();
9294   if (IsCompAssign) LHS = OldLHS;
9295 
9296   // The RHS is simpler.
9297   RHS = UsualUnaryConversions(RHS.get());
9298   if (RHS.isInvalid())
9299     return QualType();
9300   QualType RHSType = RHS.get()->getType();
9301 
9302   // C99 6.5.7p2: Each of the operands shall have integer type.
9303   if (!LHSType->hasIntegerRepresentation() ||
9304       !RHSType->hasIntegerRepresentation())
9305     return InvalidOperands(Loc, LHS, RHS);
9306 
9307   // C++0x: Don't allow scoped enums. FIXME: Use something better than
9308   // hasIntegerRepresentation() above instead of this.
9309   if (isScopedEnumerationType(LHSType) ||
9310       isScopedEnumerationType(RHSType)) {
9311     return InvalidOperands(Loc, LHS, RHS);
9312   }
9313   // Sanity-check shift operands
9314   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
9315 
9316   // "The type of the result is that of the promoted left operand."
9317   return LHSType;
9318 }
9319 
9320 /// If two different enums are compared, raise a warning.
9321 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
9322                                 Expr *RHS) {
9323   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
9324   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
9325 
9326   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
9327   if (!LHSEnumType)
9328     return;
9329   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
9330   if (!RHSEnumType)
9331     return;
9332 
9333   // Ignore anonymous enums.
9334   if (!LHSEnumType->getDecl()->getIdentifier() &&
9335       !LHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9336     return;
9337   if (!RHSEnumType->getDecl()->getIdentifier() &&
9338       !RHSEnumType->getDecl()->getTypedefNameForAnonDecl())
9339     return;
9340 
9341   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
9342     return;
9343 
9344   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
9345       << LHSStrippedType << RHSStrippedType
9346       << LHS->getSourceRange() << RHS->getSourceRange();
9347 }
9348 
9349 /// \brief Diagnose bad pointer comparisons.
9350 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
9351                                               ExprResult &LHS, ExprResult &RHS,
9352                                               bool IsError) {
9353   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
9354                       : diag::ext_typecheck_comparison_of_distinct_pointers)
9355     << LHS.get()->getType() << RHS.get()->getType()
9356     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9357 }
9358 
9359 /// \brief Returns false if the pointers are converted to a composite type,
9360 /// true otherwise.
9361 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
9362                                            ExprResult &LHS, ExprResult &RHS) {
9363   // C++ [expr.rel]p2:
9364   //   [...] Pointer conversions (4.10) and qualification
9365   //   conversions (4.4) are performed on pointer operands (or on
9366   //   a pointer operand and a null pointer constant) to bring
9367   //   them to their composite pointer type. [...]
9368   //
9369   // C++ [expr.eq]p1 uses the same notion for (in)equality
9370   // comparisons of pointers.
9371 
9372   QualType LHSType = LHS.get()->getType();
9373   QualType RHSType = RHS.get()->getType();
9374   assert(LHSType->isPointerType() || RHSType->isPointerType() ||
9375          LHSType->isMemberPointerType() || RHSType->isMemberPointerType());
9376 
9377   QualType T = S.FindCompositePointerType(Loc, LHS, RHS);
9378   if (T.isNull()) {
9379     if ((LHSType->isPointerType() || LHSType->isMemberPointerType()) &&
9380         (RHSType->isPointerType() || RHSType->isMemberPointerType()))
9381       diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
9382     else
9383       S.InvalidOperands(Loc, LHS, RHS);
9384     return true;
9385   }
9386 
9387   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
9388   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
9389   return false;
9390 }
9391 
9392 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
9393                                                     ExprResult &LHS,
9394                                                     ExprResult &RHS,
9395                                                     bool IsError) {
9396   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
9397                       : diag::ext_typecheck_comparison_of_fptr_to_void)
9398     << LHS.get()->getType() << RHS.get()->getType()
9399     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9400 }
9401 
9402 static bool isObjCObjectLiteral(ExprResult &E) {
9403   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
9404   case Stmt::ObjCArrayLiteralClass:
9405   case Stmt::ObjCDictionaryLiteralClass:
9406   case Stmt::ObjCStringLiteralClass:
9407   case Stmt::ObjCBoxedExprClass:
9408     return true;
9409   default:
9410     // Note that ObjCBoolLiteral is NOT an object literal!
9411     return false;
9412   }
9413 }
9414 
9415 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
9416   const ObjCObjectPointerType *Type =
9417     LHS->getType()->getAs<ObjCObjectPointerType>();
9418 
9419   // If this is not actually an Objective-C object, bail out.
9420   if (!Type)
9421     return false;
9422 
9423   // Get the LHS object's interface type.
9424   QualType InterfaceType = Type->getPointeeType();
9425 
9426   // If the RHS isn't an Objective-C object, bail out.
9427   if (!RHS->getType()->isObjCObjectPointerType())
9428     return false;
9429 
9430   // Try to find the -isEqual: method.
9431   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
9432   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
9433                                                       InterfaceType,
9434                                                       /*instance=*/true);
9435   if (!Method) {
9436     if (Type->isObjCIdType()) {
9437       // For 'id', just check the global pool.
9438       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
9439                                                   /*receiverId=*/true);
9440     } else {
9441       // Check protocols.
9442       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
9443                                              /*instance=*/true);
9444     }
9445   }
9446 
9447   if (!Method)
9448     return false;
9449 
9450   QualType T = Method->parameters()[0]->getType();
9451   if (!T->isObjCObjectPointerType())
9452     return false;
9453 
9454   QualType R = Method->getReturnType();
9455   if (!R->isScalarType())
9456     return false;
9457 
9458   return true;
9459 }
9460 
9461 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9462   FromE = FromE->IgnoreParenImpCasts();
9463   switch (FromE->getStmtClass()) {
9464     default:
9465       break;
9466     case Stmt::ObjCStringLiteralClass:
9467       // "string literal"
9468       return LK_String;
9469     case Stmt::ObjCArrayLiteralClass:
9470       // "array literal"
9471       return LK_Array;
9472     case Stmt::ObjCDictionaryLiteralClass:
9473       // "dictionary literal"
9474       return LK_Dictionary;
9475     case Stmt::BlockExprClass:
9476       return LK_Block;
9477     case Stmt::ObjCBoxedExprClass: {
9478       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9479       switch (Inner->getStmtClass()) {
9480         case Stmt::IntegerLiteralClass:
9481         case Stmt::FloatingLiteralClass:
9482         case Stmt::CharacterLiteralClass:
9483         case Stmt::ObjCBoolLiteralExprClass:
9484         case Stmt::CXXBoolLiteralExprClass:
9485           // "numeric literal"
9486           return LK_Numeric;
9487         case Stmt::ImplicitCastExprClass: {
9488           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9489           // Boolean literals can be represented by implicit casts.
9490           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9491             return LK_Numeric;
9492           break;
9493         }
9494         default:
9495           break;
9496       }
9497       return LK_Boxed;
9498     }
9499   }
9500   return LK_None;
9501 }
9502 
9503 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9504                                           ExprResult &LHS, ExprResult &RHS,
9505                                           BinaryOperator::Opcode Opc){
9506   Expr *Literal;
9507   Expr *Other;
9508   if (isObjCObjectLiteral(LHS)) {
9509     Literal = LHS.get();
9510     Other = RHS.get();
9511   } else {
9512     Literal = RHS.get();
9513     Other = LHS.get();
9514   }
9515 
9516   // Don't warn on comparisons against nil.
9517   Other = Other->IgnoreParenCasts();
9518   if (Other->isNullPointerConstant(S.getASTContext(),
9519                                    Expr::NPC_ValueDependentIsNotNull))
9520     return;
9521 
9522   // This should be kept in sync with warn_objc_literal_comparison.
9523   // LK_String should always be after the other literals, since it has its own
9524   // warning flag.
9525   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9526   assert(LiteralKind != Sema::LK_Block);
9527   if (LiteralKind == Sema::LK_None) {
9528     llvm_unreachable("Unknown Objective-C object literal kind");
9529   }
9530 
9531   if (LiteralKind == Sema::LK_String)
9532     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9533       << Literal->getSourceRange();
9534   else
9535     S.Diag(Loc, diag::warn_objc_literal_comparison)
9536       << LiteralKind << Literal->getSourceRange();
9537 
9538   if (BinaryOperator::isEqualityOp(Opc) &&
9539       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9540     SourceLocation Start = LHS.get()->getLocStart();
9541     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9542     CharSourceRange OpRange =
9543       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9544 
9545     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9546       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9547       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9548       << FixItHint::CreateInsertion(End, "]");
9549   }
9550 }
9551 
9552 /// Warns on !x < y, !x & y where !(x < y), !(x & y) was probably intended.
9553 static void diagnoseLogicalNotOnLHSofCheck(Sema &S, ExprResult &LHS,
9554                                            ExprResult &RHS, SourceLocation Loc,
9555                                            BinaryOperatorKind Opc) {
9556   // Check that left hand side is !something.
9557   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9558   if (!UO || UO->getOpcode() != UO_LNot) return;
9559 
9560   // Only check if the right hand side is non-bool arithmetic type.
9561   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9562 
9563   // Make sure that the something in !something is not bool.
9564   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9565   if (SubExpr->isKnownToHaveBooleanValue()) return;
9566 
9567   // Emit warning.
9568   bool IsBitwiseOp = Opc == BO_And || Opc == BO_Or || Opc == BO_Xor;
9569   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_check)
9570       << Loc << IsBitwiseOp;
9571 
9572   // First note suggest !(x < y)
9573   SourceLocation FirstOpen = SubExpr->getLocStart();
9574   SourceLocation FirstClose = RHS.get()->getLocEnd();
9575   FirstClose = S.getLocForEndOfToken(FirstClose);
9576   if (FirstClose.isInvalid())
9577     FirstOpen = SourceLocation();
9578   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9579       << IsBitwiseOp
9580       << FixItHint::CreateInsertion(FirstOpen, "(")
9581       << FixItHint::CreateInsertion(FirstClose, ")");
9582 
9583   // Second note suggests (!x) < y
9584   SourceLocation SecondOpen = LHS.get()->getLocStart();
9585   SourceLocation SecondClose = LHS.get()->getLocEnd();
9586   SecondClose = S.getLocForEndOfToken(SecondClose);
9587   if (SecondClose.isInvalid())
9588     SecondOpen = SourceLocation();
9589   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9590       << FixItHint::CreateInsertion(SecondOpen, "(")
9591       << FixItHint::CreateInsertion(SecondClose, ")");
9592 }
9593 
9594 // Get the decl for a simple expression: a reference to a variable,
9595 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9596 static ValueDecl *getCompareDecl(Expr *E) {
9597   if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E))
9598     return DR->getDecl();
9599   if (ObjCIvarRefExpr *Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9600     if (Ivar->isFreeIvar())
9601       return Ivar->getDecl();
9602   }
9603   if (MemberExpr *Mem = dyn_cast<MemberExpr>(E)) {
9604     if (Mem->isImplicitAccess())
9605       return Mem->getMemberDecl();
9606   }
9607   return nullptr;
9608 }
9609 
9610 /// Diagnose some forms of syntactically-obvious tautological comparison.
9611 static void diagnoseTautologicalComparison(Sema &S, SourceLocation Loc,
9612                                            Expr *LHS, Expr *RHS,
9613                                            BinaryOperatorKind Opc) {
9614   Expr *LHSStripped = LHS->IgnoreParenImpCasts();
9615   Expr *RHSStripped = RHS->IgnoreParenImpCasts();
9616 
9617   QualType LHSType = LHS->getType();
9618   if (LHSType->hasFloatingRepresentation() ||
9619       (LHSType->isBlockPointerType() && !BinaryOperator::isEqualityOp(Opc)) ||
9620       LHS->getLocStart().isMacroID() || RHS->getLocStart().isMacroID() ||
9621       S.inTemplateInstantiation())
9622     return;
9623 
9624   // For non-floating point types, check for self-comparisons of the form
9625   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9626   // often indicate logic errors in the program.
9627   //
9628   // NOTE: Don't warn about comparison expressions resulting from macro
9629   // expansion. Also don't warn about comparisons which are only self
9630   // comparisons within a template instantiation. The warnings should catch
9631   // obvious cases in the definition of the template anyways. The idea is to
9632   // warn when the typed comparison operator will always evaluate to the same
9633   // result.
9634   ValueDecl *DL = getCompareDecl(LHSStripped);
9635   ValueDecl *DR = getCompareDecl(RHSStripped);
9636   if (DL && DR && declaresSameEntity(DL, DR)) {
9637     StringRef Result;
9638     switch (Opc) {
9639     case BO_EQ: case BO_LE: case BO_GE:
9640       Result = "true";
9641       break;
9642     case BO_NE: case BO_LT: case BO_GT:
9643       Result = "false";
9644       break;
9645     case BO_Cmp:
9646       Result = "'std::strong_ordering::equal'";
9647       break;
9648     default:
9649       break;
9650     }
9651     S.DiagRuntimeBehavior(Loc, nullptr,
9652                           S.PDiag(diag::warn_comparison_always)
9653                               << 0 /*self-comparison*/ << !Result.empty()
9654                               << Result);
9655   } else if (DL && DR &&
9656              DL->getType()->isArrayType() && DR->getType()->isArrayType() &&
9657              !DL->isWeak() && !DR->isWeak()) {
9658     // What is it always going to evaluate to?
9659     StringRef Result;
9660     switch(Opc) {
9661     case BO_EQ: // e.g. array1 == array2
9662       Result = "false";
9663       break;
9664     case BO_NE: // e.g. array1 != array2
9665       Result = "true";
9666       break;
9667     default: // e.g. array1 <= array2
9668       // The best we can say is 'a constant'
9669       break;
9670     }
9671     S.DiagRuntimeBehavior(Loc, nullptr,
9672                           S.PDiag(diag::warn_comparison_always)
9673                               << 1 /*array comparison*/
9674                               << !Result.empty() << Result);
9675   }
9676 
9677   if (isa<CastExpr>(LHSStripped))
9678     LHSStripped = LHSStripped->IgnoreParenCasts();
9679   if (isa<CastExpr>(RHSStripped))
9680     RHSStripped = RHSStripped->IgnoreParenCasts();
9681 
9682   // Warn about comparisons against a string constant (unless the other
9683   // operand is null); the user probably wants strcmp.
9684   Expr *LiteralString = nullptr;
9685   Expr *LiteralStringStripped = nullptr;
9686   if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9687       !RHSStripped->isNullPointerConstant(S.Context,
9688                                           Expr::NPC_ValueDependentIsNull)) {
9689     LiteralString = LHS;
9690     LiteralStringStripped = LHSStripped;
9691   } else if ((isa<StringLiteral>(RHSStripped) ||
9692               isa<ObjCEncodeExpr>(RHSStripped)) &&
9693              !LHSStripped->isNullPointerConstant(S.Context,
9694                                           Expr::NPC_ValueDependentIsNull)) {
9695     LiteralString = RHS;
9696     LiteralStringStripped = RHSStripped;
9697   }
9698 
9699   if (LiteralString) {
9700     S.DiagRuntimeBehavior(Loc, nullptr,
9701                           S.PDiag(diag::warn_stringcompare)
9702                               << isa<ObjCEncodeExpr>(LiteralStringStripped)
9703                               << LiteralString->getSourceRange());
9704   }
9705 }
9706 
9707 static QualType checkArithmeticOrEnumeralCompare(Sema &S, ExprResult &LHS,
9708                                                  ExprResult &RHS,
9709                                                  SourceLocation Loc,
9710                                                  BinaryOperatorKind Opc) {
9711   // C99 6.5.8p3 / C99 6.5.9p4
9712   QualType Type = S.UsualArithmeticConversions(LHS, RHS);
9713   if (LHS.isInvalid() || RHS.isInvalid())
9714     return QualType();
9715   if (Type.isNull())
9716     return S.InvalidOperands(Loc, LHS, RHS);
9717   assert(Type->isArithmeticType() || Type->isEnumeralType());
9718 
9719   checkEnumComparison(S, Loc, LHS.get(), RHS.get());
9720 
9721   enum { StrongEquality, PartialOrdering, StrongOrdering } Ordering;
9722   if (Type->isAnyComplexType())
9723     Ordering = StrongEquality;
9724   else if (Type->isFloatingType())
9725     Ordering = PartialOrdering;
9726   else
9727     Ordering = StrongOrdering;
9728 
9729   if (Ordering == StrongEquality && BinaryOperator::isRelationalOp(Opc))
9730     return S.InvalidOperands(Loc, LHS, RHS);
9731 
9732   // Check for comparisons of floating point operands using != and ==.
9733   if (Type->hasFloatingRepresentation() && BinaryOperator::isEqualityOp(Opc))
9734     S.CheckFloatComparison(Loc, LHS.get(), RHS.get());
9735 
9736   // The result of comparisons is 'bool' in C++, 'int' in C.
9737   // FIXME: For BO_Cmp, return the relevant comparison category type.
9738   return S.Context.getLogicalOperationType();
9739 }
9740 
9741 // C99 6.5.8, C++ [expr.rel]
9742 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9743                                     SourceLocation Loc, BinaryOperatorKind Opc,
9744                                     bool IsRelational) {
9745   // Comparisons expect an rvalue, so convert to rvalue before any
9746   // type-related checks.
9747   LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
9748   if (LHS.isInvalid())
9749     return QualType();
9750   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
9751   if (RHS.isInvalid())
9752     return QualType();
9753 
9754   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9755 
9756   // Handle vector comparisons separately.
9757   if (LHS.get()->getType()->isVectorType() ||
9758       RHS.get()->getType()->isVectorType())
9759     return CheckVectorCompareOperands(LHS, RHS, Loc, Opc);
9760 
9761   diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
9762   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
9763 
9764   QualType LHSType = LHS.get()->getType();
9765   QualType RHSType = RHS.get()->getType();
9766   if ((LHSType->isArithmeticType() || LHSType->isEnumeralType()) &&
9767       (RHSType->isArithmeticType() || RHSType->isEnumeralType()))
9768     return checkArithmeticOrEnumeralCompare(*this, LHS, RHS, Loc, Opc);
9769 
9770   QualType ResultTy = Context.getLogicalOperationType();
9771 
9772   const Expr::NullPointerConstantKind LHSNullKind =
9773       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9774   const Expr::NullPointerConstantKind RHSNullKind =
9775       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9776   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9777   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9778 
9779   if (!IsRelational && LHSIsNull != RHSIsNull) {
9780     bool IsEquality = Opc == BO_EQ;
9781     if (RHSIsNull)
9782       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9783                                    RHS.get()->getSourceRange());
9784     else
9785       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9786                                    LHS.get()->getSourceRange());
9787   }
9788 
9789   if ((LHSType->isIntegerType() && !LHSIsNull) ||
9790       (RHSType->isIntegerType() && !RHSIsNull)) {
9791     // Skip normal pointer conversion checks in this case; we have better
9792     // diagnostics for this below.
9793   } else if (getLangOpts().CPlusPlus) {
9794     // Equality comparison of a function pointer to a void pointer is invalid,
9795     // but we allow it as an extension.
9796     // FIXME: If we really want to allow this, should it be part of composite
9797     // pointer type computation so it works in conditionals too?
9798     if (!IsRelational &&
9799         ((LHSType->isFunctionPointerType() && RHSType->isVoidPointerType()) ||
9800          (RHSType->isFunctionPointerType() && LHSType->isVoidPointerType()))) {
9801       // This is a gcc extension compatibility comparison.
9802       // In a SFINAE context, we treat this as a hard error to maintain
9803       // conformance with the C++ standard.
9804       diagnoseFunctionPointerToVoidComparison(
9805           *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9806 
9807       if (isSFINAEContext())
9808         return QualType();
9809 
9810       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9811       return ResultTy;
9812     }
9813 
9814     // C++ [expr.eq]p2:
9815     //   If at least one operand is a pointer [...] bring them to their
9816     //   composite pointer type.
9817     // C++ [expr.rel]p2:
9818     //   If both operands are pointers, [...] bring them to their composite
9819     //   pointer type.
9820     if ((int)LHSType->isPointerType() + (int)RHSType->isPointerType() >=
9821             (IsRelational ? 2 : 1) &&
9822         (!LangOpts.ObjCAutoRefCount ||
9823          !(LHSType->isObjCObjectPointerType() ||
9824            RHSType->isObjCObjectPointerType()))) {
9825       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9826         return QualType();
9827       else
9828         return ResultTy;
9829     }
9830   } else if (LHSType->isPointerType() &&
9831              RHSType->isPointerType()) { // C99 6.5.8p2
9832     // All of the following pointer-related warnings are GCC extensions, except
9833     // when handling null pointer constants.
9834     QualType LCanPointeeTy =
9835       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9836     QualType RCanPointeeTy =
9837       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9838 
9839     // C99 6.5.9p2 and C99 6.5.8p2
9840     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9841                                    RCanPointeeTy.getUnqualifiedType())) {
9842       // Valid unless a relational comparison of function pointers
9843       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9844         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9845           << LHSType << RHSType << LHS.get()->getSourceRange()
9846           << RHS.get()->getSourceRange();
9847       }
9848     } else if (!IsRelational &&
9849                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9850       // Valid unless comparison between non-null pointer and function pointer
9851       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9852           && !LHSIsNull && !RHSIsNull)
9853         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9854                                                 /*isError*/false);
9855     } else {
9856       // Invalid
9857       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9858     }
9859     if (LCanPointeeTy != RCanPointeeTy) {
9860       // Treat NULL constant as a special case in OpenCL.
9861       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9862         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9863         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9864           Diag(Loc,
9865                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9866               << LHSType << RHSType << 0 /* comparison */
9867               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9868         }
9869       }
9870       LangAS AddrSpaceL = LCanPointeeTy.getAddressSpace();
9871       LangAS AddrSpaceR = RCanPointeeTy.getAddressSpace();
9872       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9873                                                : CK_BitCast;
9874       if (LHSIsNull && !RHSIsNull)
9875         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9876       else
9877         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9878     }
9879     return ResultTy;
9880   }
9881 
9882   if (getLangOpts().CPlusPlus) {
9883     // C++ [expr.eq]p4:
9884     //   Two operands of type std::nullptr_t or one operand of type
9885     //   std::nullptr_t and the other a null pointer constant compare equal.
9886     if (!IsRelational && LHSIsNull && RHSIsNull) {
9887       if (LHSType->isNullPtrType()) {
9888         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9889         return ResultTy;
9890       }
9891       if (RHSType->isNullPtrType()) {
9892         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9893         return ResultTy;
9894       }
9895     }
9896 
9897     // Comparison of Objective-C pointers and block pointers against nullptr_t.
9898     // These aren't covered by the composite pointer type rules.
9899     if (!IsRelational && RHSType->isNullPtrType() &&
9900         (LHSType->isObjCObjectPointerType() || LHSType->isBlockPointerType())) {
9901       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9902       return ResultTy;
9903     }
9904     if (!IsRelational && LHSType->isNullPtrType() &&
9905         (RHSType->isObjCObjectPointerType() || RHSType->isBlockPointerType())) {
9906       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9907       return ResultTy;
9908     }
9909 
9910     if (IsRelational &&
9911         ((LHSType->isNullPtrType() && RHSType->isPointerType()) ||
9912          (RHSType->isNullPtrType() && LHSType->isPointerType()))) {
9913       // HACK: Relational comparison of nullptr_t against a pointer type is
9914       // invalid per DR583, but we allow it within std::less<> and friends,
9915       // since otherwise common uses of it break.
9916       // FIXME: Consider removing this hack once LWG fixes std::less<> and
9917       // friends to have std::nullptr_t overload candidates.
9918       DeclContext *DC = CurContext;
9919       if (isa<FunctionDecl>(DC))
9920         DC = DC->getParent();
9921       if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
9922         if (CTSD->isInStdNamespace() &&
9923             llvm::StringSwitch<bool>(CTSD->getName())
9924                 .Cases("less", "less_equal", "greater", "greater_equal", true)
9925                 .Default(false)) {
9926           if (RHSType->isNullPtrType())
9927             RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9928           else
9929             LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9930           return ResultTy;
9931         }
9932       }
9933     }
9934 
9935     // C++ [expr.eq]p2:
9936     //   If at least one operand is a pointer to member, [...] bring them to
9937     //   their composite pointer type.
9938     if (!IsRelational &&
9939         (LHSType->isMemberPointerType() || RHSType->isMemberPointerType())) {
9940       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9941         return QualType();
9942       else
9943         return ResultTy;
9944     }
9945   }
9946 
9947   // Handle block pointer types.
9948   if (!IsRelational && LHSType->isBlockPointerType() &&
9949       RHSType->isBlockPointerType()) {
9950     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9951     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9952 
9953     if (!LHSIsNull && !RHSIsNull &&
9954         !Context.typesAreCompatible(lpointee, rpointee)) {
9955       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9956         << LHSType << RHSType << LHS.get()->getSourceRange()
9957         << RHS.get()->getSourceRange();
9958     }
9959     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9960     return ResultTy;
9961   }
9962 
9963   // Allow block pointers to be compared with null pointer constants.
9964   if (!IsRelational
9965       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9966           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9967     if (!LHSIsNull && !RHSIsNull) {
9968       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9969              ->getPointeeType()->isVoidType())
9970             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9971                 ->getPointeeType()->isVoidType())))
9972         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9973           << LHSType << RHSType << LHS.get()->getSourceRange()
9974           << RHS.get()->getSourceRange();
9975     }
9976     if (LHSIsNull && !RHSIsNull)
9977       LHS = ImpCastExprToType(LHS.get(), RHSType,
9978                               RHSType->isPointerType() ? CK_BitCast
9979                                 : CK_AnyPointerToBlockPointerCast);
9980     else
9981       RHS = ImpCastExprToType(RHS.get(), LHSType,
9982                               LHSType->isPointerType() ? CK_BitCast
9983                                 : CK_AnyPointerToBlockPointerCast);
9984     return ResultTy;
9985   }
9986 
9987   if (LHSType->isObjCObjectPointerType() ||
9988       RHSType->isObjCObjectPointerType()) {
9989     const PointerType *LPT = LHSType->getAs<PointerType>();
9990     const PointerType *RPT = RHSType->getAs<PointerType>();
9991     if (LPT || RPT) {
9992       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9993       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9994 
9995       if (!LPtrToVoid && !RPtrToVoid &&
9996           !Context.typesAreCompatible(LHSType, RHSType)) {
9997         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9998                                           /*isError*/false);
9999       }
10000       if (LHSIsNull && !RHSIsNull) {
10001         Expr *E = LHS.get();
10002         if (getLangOpts().ObjCAutoRefCount)
10003           CheckObjCConversion(SourceRange(), RHSType, E,
10004                               CCK_ImplicitConversion);
10005         LHS = ImpCastExprToType(E, RHSType,
10006                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10007       }
10008       else {
10009         Expr *E = RHS.get();
10010         if (getLangOpts().ObjCAutoRefCount)
10011           CheckObjCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion,
10012                               /*Diagnose=*/true,
10013                               /*DiagnoseCFAudited=*/false, Opc);
10014         RHS = ImpCastExprToType(E, LHSType,
10015                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
10016       }
10017       return ResultTy;
10018     }
10019     if (LHSType->isObjCObjectPointerType() &&
10020         RHSType->isObjCObjectPointerType()) {
10021       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
10022         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
10023                                           /*isError*/false);
10024       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
10025         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
10026 
10027       if (LHSIsNull && !RHSIsNull)
10028         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
10029       else
10030         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
10031       return ResultTy;
10032     }
10033 
10034     if (!IsRelational && LHSType->isBlockPointerType() &&
10035         RHSType->isBlockCompatibleObjCPointerType(Context)) {
10036       LHS = ImpCastExprToType(LHS.get(), RHSType,
10037                               CK_BlockPointerToObjCPointerCast);
10038       return ResultTy;
10039     } else if (!IsRelational &&
10040                LHSType->isBlockCompatibleObjCPointerType(Context) &&
10041                RHSType->isBlockPointerType()) {
10042       RHS = ImpCastExprToType(RHS.get(), LHSType,
10043                               CK_BlockPointerToObjCPointerCast);
10044       return ResultTy;
10045     }
10046   }
10047   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
10048       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
10049     unsigned DiagID = 0;
10050     bool isError = false;
10051     if (LangOpts.DebuggerSupport) {
10052       // Under a debugger, allow the comparison of pointers to integers,
10053       // since users tend to want to compare addresses.
10054     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
10055                (RHSIsNull && RHSType->isIntegerType())) {
10056       if (IsRelational) {
10057         isError = getLangOpts().CPlusPlus;
10058         DiagID =
10059           isError ? diag::err_typecheck_ordered_comparison_of_pointer_and_zero
10060                   : diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
10061       }
10062     } else if (getLangOpts().CPlusPlus) {
10063       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
10064       isError = true;
10065     } else if (IsRelational)
10066       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
10067     else
10068       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
10069 
10070     if (DiagID) {
10071       Diag(Loc, DiagID)
10072         << LHSType << RHSType << LHS.get()->getSourceRange()
10073         << RHS.get()->getSourceRange();
10074       if (isError)
10075         return QualType();
10076     }
10077 
10078     if (LHSType->isIntegerType())
10079       LHS = ImpCastExprToType(LHS.get(), RHSType,
10080                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10081     else
10082       RHS = ImpCastExprToType(RHS.get(), LHSType,
10083                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
10084     return ResultTy;
10085   }
10086 
10087   // Handle block pointers.
10088   if (!IsRelational && RHSIsNull
10089       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
10090     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10091     return ResultTy;
10092   }
10093   if (!IsRelational && LHSIsNull
10094       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
10095     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10096     return ResultTy;
10097   }
10098 
10099   if (getLangOpts().OpenCLVersion >= 200) {
10100     if (LHSIsNull && RHSType->isQueueT()) {
10101       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
10102       return ResultTy;
10103     }
10104 
10105     if (LHSType->isQueueT() && RHSIsNull) {
10106       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
10107       return ResultTy;
10108     }
10109   }
10110 
10111   return InvalidOperands(Loc, LHS, RHS);
10112 }
10113 
10114 // Return a signed ext_vector_type that is of identical size and number of
10115 // elements. For floating point vectors, return an integer type of identical
10116 // size and number of elements. In the non ext_vector_type case, search from
10117 // the largest type to the smallest type to avoid cases where long long == long,
10118 // where long gets picked over long long.
10119 QualType Sema::GetSignedVectorType(QualType V) {
10120   const VectorType *VTy = V->getAs<VectorType>();
10121   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
10122 
10123   if (isa<ExtVectorType>(VTy)) {
10124     if (TypeSize == Context.getTypeSize(Context.CharTy))
10125       return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
10126     else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10127       return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
10128     else if (TypeSize == Context.getTypeSize(Context.IntTy))
10129       return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
10130     else if (TypeSize == Context.getTypeSize(Context.LongTy))
10131       return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
10132     assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
10133            "Unhandled vector element size in vector compare");
10134     return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
10135   }
10136 
10137   if (TypeSize == Context.getTypeSize(Context.LongLongTy))
10138     return Context.getVectorType(Context.LongLongTy, VTy->getNumElements(),
10139                                  VectorType::GenericVector);
10140   else if (TypeSize == Context.getTypeSize(Context.LongTy))
10141     return Context.getVectorType(Context.LongTy, VTy->getNumElements(),
10142                                  VectorType::GenericVector);
10143   else if (TypeSize == Context.getTypeSize(Context.IntTy))
10144     return Context.getVectorType(Context.IntTy, VTy->getNumElements(),
10145                                  VectorType::GenericVector);
10146   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
10147     return Context.getVectorType(Context.ShortTy, VTy->getNumElements(),
10148                                  VectorType::GenericVector);
10149   assert(TypeSize == Context.getTypeSize(Context.CharTy) &&
10150          "Unhandled vector element size in vector compare");
10151   return Context.getVectorType(Context.CharTy, VTy->getNumElements(),
10152                                VectorType::GenericVector);
10153 }
10154 
10155 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
10156 /// operates on extended vector types.  Instead of producing an IntTy result,
10157 /// like a scalar comparison, a vector comparison produces a vector of integer
10158 /// types.
10159 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
10160                                           SourceLocation Loc,
10161                                           BinaryOperatorKind Opc) {
10162   // Check to make sure we're operating on vectors of the same type and width,
10163   // Allowing one side to be a scalar of element type.
10164   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
10165                               /*AllowBothBool*/true,
10166                               /*AllowBoolConversions*/getLangOpts().ZVector);
10167   if (vType.isNull())
10168     return vType;
10169 
10170   QualType LHSType = LHS.get()->getType();
10171 
10172   // If AltiVec, the comparison results in a numeric type, i.e.
10173   // bool for C++, int for C
10174   if (getLangOpts().AltiVec &&
10175       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
10176     return Context.getLogicalOperationType();
10177 
10178   // For non-floating point types, check for self-comparisons of the form
10179   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
10180   // often indicate logic errors in the program.
10181   diagnoseTautologicalComparison(*this, Loc, LHS.get(), RHS.get(), Opc);
10182 
10183   // Check for comparisons of floating point operands using != and ==.
10184   if (BinaryOperator::isEqualityOp(Opc) &&
10185       LHSType->hasFloatingRepresentation()) {
10186     assert(RHS.get()->getType()->hasFloatingRepresentation());
10187     CheckFloatComparison(Loc, LHS.get(), RHS.get());
10188   }
10189 
10190   // Return a signed type for the vector.
10191   return GetSignedVectorType(vType);
10192 }
10193 
10194 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10195                                           SourceLocation Loc) {
10196   // Ensure that either both operands are of the same vector type, or
10197   // one operand is of a vector type and the other is of its element type.
10198   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
10199                                        /*AllowBothBool*/true,
10200                                        /*AllowBoolConversions*/false);
10201   if (vType.isNull())
10202     return InvalidOperands(Loc, LHS, RHS);
10203   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
10204       vType->hasFloatingRepresentation())
10205     return InvalidOperands(Loc, LHS, RHS);
10206   // FIXME: The check for C++ here is for GCC compatibility. GCC rejects the
10207   //        usage of the logical operators && and || with vectors in C. This
10208   //        check could be notionally dropped.
10209   if (!getLangOpts().CPlusPlus &&
10210       !(isa<ExtVectorType>(vType->getAs<VectorType>())))
10211     return InvalidLogicalVectorOperands(Loc, LHS, RHS);
10212 
10213   return GetSignedVectorType(LHS.get()->getType());
10214 }
10215 
10216 inline QualType Sema::CheckBitwiseOperands(ExprResult &LHS, ExprResult &RHS,
10217                                            SourceLocation Loc,
10218                                            BinaryOperatorKind Opc) {
10219   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
10220 
10221   bool IsCompAssign =
10222       Opc == BO_AndAssign || Opc == BO_OrAssign || Opc == BO_XorAssign;
10223 
10224   if (LHS.get()->getType()->isVectorType() ||
10225       RHS.get()->getType()->isVectorType()) {
10226     if (LHS.get()->getType()->hasIntegerRepresentation() &&
10227         RHS.get()->getType()->hasIntegerRepresentation())
10228       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
10229                         /*AllowBothBool*/true,
10230                         /*AllowBoolConversions*/getLangOpts().ZVector);
10231     return InvalidOperands(Loc, LHS, RHS);
10232   }
10233 
10234   if (Opc == BO_And)
10235     diagnoseLogicalNotOnLHSofCheck(*this, LHS, RHS, Loc, Opc);
10236 
10237   ExprResult LHSResult = LHS, RHSResult = RHS;
10238   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
10239                                                  IsCompAssign);
10240   if (LHSResult.isInvalid() || RHSResult.isInvalid())
10241     return QualType();
10242   LHS = LHSResult.get();
10243   RHS = RHSResult.get();
10244 
10245   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
10246     return compType;
10247   return InvalidOperands(Loc, LHS, RHS);
10248 }
10249 
10250 // C99 6.5.[13,14]
10251 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
10252                                            SourceLocation Loc,
10253                                            BinaryOperatorKind Opc) {
10254   // Check vector operands differently.
10255   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
10256     return CheckVectorLogicalOperands(LHS, RHS, Loc);
10257 
10258   // Diagnose cases where the user write a logical and/or but probably meant a
10259   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
10260   // is a constant.
10261   if (LHS.get()->getType()->isIntegerType() &&
10262       !LHS.get()->getType()->isBooleanType() &&
10263       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
10264       // Don't warn in macros or template instantiations.
10265       !Loc.isMacroID() && !inTemplateInstantiation()) {
10266     // If the RHS can be constant folded, and if it constant folds to something
10267     // that isn't 0 or 1 (which indicate a potential logical operation that
10268     // happened to fold to true/false) then warn.
10269     // Parens on the RHS are ignored.
10270     llvm::APSInt Result;
10271     if (RHS.get()->EvaluateAsInt(Result, Context))
10272       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
10273            !RHS.get()->getExprLoc().isMacroID()) ||
10274           (Result != 0 && Result != 1)) {
10275         Diag(Loc, diag::warn_logical_instead_of_bitwise)
10276           << RHS.get()->getSourceRange()
10277           << (Opc == BO_LAnd ? "&&" : "||");
10278         // Suggest replacing the logical operator with the bitwise version
10279         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
10280             << (Opc == BO_LAnd ? "&" : "|")
10281             << FixItHint::CreateReplacement(SourceRange(
10282                                                  Loc, getLocForEndOfToken(Loc)),
10283                                             Opc == BO_LAnd ? "&" : "|");
10284         if (Opc == BO_LAnd)
10285           // Suggest replacing "Foo() && kNonZero" with "Foo()"
10286           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
10287               << FixItHint::CreateRemoval(
10288                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
10289                               RHS.get()->getLocEnd()));
10290       }
10291   }
10292 
10293   if (!Context.getLangOpts().CPlusPlus) {
10294     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
10295     // not operate on the built-in scalar and vector float types.
10296     if (Context.getLangOpts().OpenCL &&
10297         Context.getLangOpts().OpenCLVersion < 120) {
10298       if (LHS.get()->getType()->isFloatingType() ||
10299           RHS.get()->getType()->isFloatingType())
10300         return InvalidOperands(Loc, LHS, RHS);
10301     }
10302 
10303     LHS = UsualUnaryConversions(LHS.get());
10304     if (LHS.isInvalid())
10305       return QualType();
10306 
10307     RHS = UsualUnaryConversions(RHS.get());
10308     if (RHS.isInvalid())
10309       return QualType();
10310 
10311     if (!LHS.get()->getType()->isScalarType() ||
10312         !RHS.get()->getType()->isScalarType())
10313       return InvalidOperands(Loc, LHS, RHS);
10314 
10315     return Context.IntTy;
10316   }
10317 
10318   // The following is safe because we only use this method for
10319   // non-overloadable operands.
10320 
10321   // C++ [expr.log.and]p1
10322   // C++ [expr.log.or]p1
10323   // The operands are both contextually converted to type bool.
10324   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
10325   if (LHSRes.isInvalid())
10326     return InvalidOperands(Loc, LHS, RHS);
10327   LHS = LHSRes;
10328 
10329   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
10330   if (RHSRes.isInvalid())
10331     return InvalidOperands(Loc, LHS, RHS);
10332   RHS = RHSRes;
10333 
10334   // C++ [expr.log.and]p2
10335   // C++ [expr.log.or]p2
10336   // The result is a bool.
10337   return Context.BoolTy;
10338 }
10339 
10340 static bool IsReadonlyMessage(Expr *E, Sema &S) {
10341   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
10342   if (!ME) return false;
10343   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
10344   ObjCMessageExpr *Base = dyn_cast<ObjCMessageExpr>(
10345       ME->getBase()->IgnoreImplicit()->IgnoreParenImpCasts());
10346   if (!Base) return false;
10347   return Base->getMethodDecl() != nullptr;
10348 }
10349 
10350 /// Is the given expression (which must be 'const') a reference to a
10351 /// variable which was originally non-const, but which has become
10352 /// 'const' due to being captured within a block?
10353 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
10354 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
10355   assert(E->isLValue() && E->getType().isConstQualified());
10356   E = E->IgnoreParens();
10357 
10358   // Must be a reference to a declaration from an enclosing scope.
10359   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
10360   if (!DRE) return NCCK_None;
10361   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
10362 
10363   // The declaration must be a variable which is not declared 'const'.
10364   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
10365   if (!var) return NCCK_None;
10366   if (var->getType().isConstQualified()) return NCCK_None;
10367   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
10368 
10369   // Decide whether the first capture was for a block or a lambda.
10370   DeclContext *DC = S.CurContext, *Prev = nullptr;
10371   // Decide whether the first capture was for a block or a lambda.
10372   while (DC) {
10373     // For init-capture, it is possible that the variable belongs to the
10374     // template pattern of the current context.
10375     if (auto *FD = dyn_cast<FunctionDecl>(DC))
10376       if (var->isInitCapture() &&
10377           FD->getTemplateInstantiationPattern() == var->getDeclContext())
10378         break;
10379     if (DC == var->getDeclContext())
10380       break;
10381     Prev = DC;
10382     DC = DC->getParent();
10383   }
10384   // Unless we have an init-capture, we've gone one step too far.
10385   if (!var->isInitCapture())
10386     DC = Prev;
10387   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
10388 }
10389 
10390 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
10391   Ty = Ty.getNonReferenceType();
10392   if (IsDereference && Ty->isPointerType())
10393     Ty = Ty->getPointeeType();
10394   return !Ty.isConstQualified();
10395 }
10396 
10397 // Update err_typecheck_assign_const and note_typecheck_assign_const
10398 // when this enum is changed.
10399 enum {
10400   ConstFunction,
10401   ConstVariable,
10402   ConstMember,
10403   ConstMethod,
10404   NestedConstMember,
10405   ConstUnknown,  // Keep as last element
10406 };
10407 
10408 /// Emit the "read-only variable not assignable" error and print notes to give
10409 /// more information about why the variable is not assignable, such as pointing
10410 /// to the declaration of a const variable, showing that a method is const, or
10411 /// that the function is returning a const reference.
10412 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
10413                                     SourceLocation Loc) {
10414   SourceRange ExprRange = E->getSourceRange();
10415 
10416   // Only emit one error on the first const found.  All other consts will emit
10417   // a note to the error.
10418   bool DiagnosticEmitted = false;
10419 
10420   // Track if the current expression is the result of a dereference, and if the
10421   // next checked expression is the result of a dereference.
10422   bool IsDereference = false;
10423   bool NextIsDereference = false;
10424 
10425   // Loop to process MemberExpr chains.
10426   while (true) {
10427     IsDereference = NextIsDereference;
10428 
10429     E = E->IgnoreImplicit()->IgnoreParenImpCasts();
10430     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10431       NextIsDereference = ME->isArrow();
10432       const ValueDecl *VD = ME->getMemberDecl();
10433       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
10434         // Mutable fields can be modified even if the class is const.
10435         if (Field->isMutable()) {
10436           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
10437           break;
10438         }
10439 
10440         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
10441           if (!DiagnosticEmitted) {
10442             S.Diag(Loc, diag::err_typecheck_assign_const)
10443                 << ExprRange << ConstMember << false /*static*/ << Field
10444                 << Field->getType();
10445             DiagnosticEmitted = true;
10446           }
10447           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10448               << ConstMember << false /*static*/ << Field << Field->getType()
10449               << Field->getSourceRange();
10450         }
10451         E = ME->getBase();
10452         continue;
10453       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
10454         if (VDecl->getType().isConstQualified()) {
10455           if (!DiagnosticEmitted) {
10456             S.Diag(Loc, diag::err_typecheck_assign_const)
10457                 << ExprRange << ConstMember << true /*static*/ << VDecl
10458                 << VDecl->getType();
10459             DiagnosticEmitted = true;
10460           }
10461           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10462               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
10463               << VDecl->getSourceRange();
10464         }
10465         // Static fields do not inherit constness from parents.
10466         break;
10467       }
10468       break; // End MemberExpr
10469     } else if (const ArraySubscriptExpr *ASE =
10470                    dyn_cast<ArraySubscriptExpr>(E)) {
10471       E = ASE->getBase()->IgnoreParenImpCasts();
10472       continue;
10473     } else if (const ExtVectorElementExpr *EVE =
10474                    dyn_cast<ExtVectorElementExpr>(E)) {
10475       E = EVE->getBase()->IgnoreParenImpCasts();
10476       continue;
10477     }
10478     break;
10479   }
10480 
10481   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10482     // Function calls
10483     const FunctionDecl *FD = CE->getDirectCallee();
10484     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
10485       if (!DiagnosticEmitted) {
10486         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10487                                                       << ConstFunction << FD;
10488         DiagnosticEmitted = true;
10489       }
10490       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
10491              diag::note_typecheck_assign_const)
10492           << ConstFunction << FD << FD->getReturnType()
10493           << FD->getReturnTypeSourceRange();
10494     }
10495   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10496     // Point to variable declaration.
10497     if (const ValueDecl *VD = DRE->getDecl()) {
10498       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
10499         if (!DiagnosticEmitted) {
10500           S.Diag(Loc, diag::err_typecheck_assign_const)
10501               << ExprRange << ConstVariable << VD << VD->getType();
10502           DiagnosticEmitted = true;
10503         }
10504         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
10505             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
10506       }
10507     }
10508   } else if (isa<CXXThisExpr>(E)) {
10509     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
10510       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
10511         if (MD->isConst()) {
10512           if (!DiagnosticEmitted) {
10513             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
10514                                                           << ConstMethod << MD;
10515             DiagnosticEmitted = true;
10516           }
10517           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
10518               << ConstMethod << MD << MD->getSourceRange();
10519         }
10520       }
10521     }
10522   }
10523 
10524   if (DiagnosticEmitted)
10525     return;
10526 
10527   // Can't determine a more specific message, so display the generic error.
10528   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
10529 }
10530 
10531 enum OriginalExprKind {
10532   OEK_Variable,
10533   OEK_Member,
10534   OEK_LValue
10535 };
10536 
10537 static void DiagnoseRecursiveConstFields(Sema &S, const ValueDecl *VD,
10538                                          const RecordType *Ty,
10539                                          SourceLocation Loc, SourceRange Range,
10540                                          OriginalExprKind OEK,
10541                                          bool &DiagnosticEmitted,
10542                                          bool IsNested = false) {
10543   // We walk the record hierarchy breadth-first to ensure that we print
10544   // diagnostics in field nesting order.
10545   // First, check every field for constness.
10546   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10547     if (Field->getType().isConstQualified()) {
10548       if (!DiagnosticEmitted) {
10549         S.Diag(Loc, diag::err_typecheck_assign_const)
10550             << Range << NestedConstMember << OEK << VD
10551             << IsNested << Field;
10552         DiagnosticEmitted = true;
10553       }
10554       S.Diag(Field->getLocation(), diag::note_typecheck_assign_const)
10555           << NestedConstMember << IsNested << Field
10556           << Field->getType() << Field->getSourceRange();
10557     }
10558   }
10559   // Then, recurse.
10560   for (const FieldDecl *Field : Ty->getDecl()->fields()) {
10561     QualType FTy = Field->getType();
10562     if (const RecordType *FieldRecTy = FTy->getAs<RecordType>())
10563       DiagnoseRecursiveConstFields(S, VD, FieldRecTy, Loc, Range,
10564                                    OEK, DiagnosticEmitted, true);
10565   }
10566 }
10567 
10568 /// Emit an error for the case where a record we are trying to assign to has a
10569 /// const-qualified field somewhere in its hierarchy.
10570 static void DiagnoseRecursiveConstFields(Sema &S, const Expr *E,
10571                                          SourceLocation Loc) {
10572   QualType Ty = E->getType();
10573   assert(Ty->isRecordType() && "lvalue was not record?");
10574   SourceRange Range = E->getSourceRange();
10575   const RecordType *RTy = Ty.getCanonicalType()->getAs<RecordType>();
10576   bool DiagEmitted = false;
10577 
10578   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
10579     DiagnoseRecursiveConstFields(S, ME->getMemberDecl(), RTy, Loc,
10580             Range, OEK_Member, DiagEmitted);
10581   else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10582     DiagnoseRecursiveConstFields(S, DRE->getDecl(), RTy, Loc,
10583             Range, OEK_Variable, DiagEmitted);
10584   else
10585     DiagnoseRecursiveConstFields(S, nullptr, RTy, Loc,
10586             Range, OEK_LValue, DiagEmitted);
10587   if (!DiagEmitted)
10588     DiagnoseConstAssignment(S, E, Loc);
10589 }
10590 
10591 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
10592 /// emit an error and return true.  If so, return false.
10593 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
10594   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
10595 
10596   S.CheckShadowingDeclModification(E, Loc);
10597 
10598   SourceLocation OrigLoc = Loc;
10599   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
10600                                                               &Loc);
10601   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
10602     IsLV = Expr::MLV_InvalidMessageExpression;
10603   if (IsLV == Expr::MLV_Valid)
10604     return false;
10605 
10606   unsigned DiagID = 0;
10607   bool NeedType = false;
10608   switch (IsLV) { // C99 6.5.16p2
10609   case Expr::MLV_ConstQualified:
10610     // Use a specialized diagnostic when we're assigning to an object
10611     // from an enclosing function or block.
10612     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
10613       if (NCCK == NCCK_Block)
10614         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
10615       else
10616         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
10617       break;
10618     }
10619 
10620     // In ARC, use some specialized diagnostics for occasions where we
10621     // infer 'const'.  These are always pseudo-strong variables.
10622     if (S.getLangOpts().ObjCAutoRefCount) {
10623       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
10624       if (declRef && isa<VarDecl>(declRef->getDecl())) {
10625         VarDecl *var = cast<VarDecl>(declRef->getDecl());
10626 
10627         // Use the normal diagnostic if it's pseudo-__strong but the
10628         // user actually wrote 'const'.
10629         if (var->isARCPseudoStrong() &&
10630             (!var->getTypeSourceInfo() ||
10631              !var->getTypeSourceInfo()->getType().isConstQualified())) {
10632           // There are two pseudo-strong cases:
10633           //  - self
10634           ObjCMethodDecl *method = S.getCurMethodDecl();
10635           if (method && var == method->getSelfDecl())
10636             DiagID = method->isClassMethod()
10637               ? diag::err_typecheck_arc_assign_self_class_method
10638               : diag::err_typecheck_arc_assign_self;
10639 
10640           //  - fast enumeration variables
10641           else
10642             DiagID = diag::err_typecheck_arr_assign_enumeration;
10643 
10644           SourceRange Assign;
10645           if (Loc != OrigLoc)
10646             Assign = SourceRange(OrigLoc, OrigLoc);
10647           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10648           // We need to preserve the AST regardless, so migration tool
10649           // can do its job.
10650           return false;
10651         }
10652       }
10653     }
10654 
10655     // If none of the special cases above are triggered, then this is a
10656     // simple const assignment.
10657     if (DiagID == 0) {
10658       DiagnoseConstAssignment(S, E, Loc);
10659       return true;
10660     }
10661 
10662     break;
10663   case Expr::MLV_ConstAddrSpace:
10664     DiagnoseConstAssignment(S, E, Loc);
10665     return true;
10666   case Expr::MLV_ConstQualifiedField:
10667     DiagnoseRecursiveConstFields(S, E, Loc);
10668     return true;
10669   case Expr::MLV_ArrayType:
10670   case Expr::MLV_ArrayTemporary:
10671     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10672     NeedType = true;
10673     break;
10674   case Expr::MLV_NotObjectType:
10675     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10676     NeedType = true;
10677     break;
10678   case Expr::MLV_LValueCast:
10679     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10680     break;
10681   case Expr::MLV_Valid:
10682     llvm_unreachable("did not take early return for MLV_Valid");
10683   case Expr::MLV_InvalidExpression:
10684   case Expr::MLV_MemberFunction:
10685   case Expr::MLV_ClassTemporary:
10686     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10687     break;
10688   case Expr::MLV_IncompleteType:
10689   case Expr::MLV_IncompleteVoidType:
10690     return S.RequireCompleteType(Loc, E->getType(),
10691              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10692   case Expr::MLV_DuplicateVectorComponents:
10693     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10694     break;
10695   case Expr::MLV_NoSetterProperty:
10696     llvm_unreachable("readonly properties should be processed differently");
10697   case Expr::MLV_InvalidMessageExpression:
10698     DiagID = diag::err_readonly_message_assignment;
10699     break;
10700   case Expr::MLV_SubObjCPropertySetting:
10701     DiagID = diag::err_no_subobject_property_setting;
10702     break;
10703   }
10704 
10705   SourceRange Assign;
10706   if (Loc != OrigLoc)
10707     Assign = SourceRange(OrigLoc, OrigLoc);
10708   if (NeedType)
10709     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10710   else
10711     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10712   return true;
10713 }
10714 
10715 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10716                                          SourceLocation Loc,
10717                                          Sema &Sema) {
10718   if (Sema.inTemplateInstantiation())
10719     return;
10720   if (Sema.isUnevaluatedContext())
10721     return;
10722   if (Loc.isInvalid() || Loc.isMacroID())
10723     return;
10724   if (LHSExpr->getExprLoc().isMacroID() || RHSExpr->getExprLoc().isMacroID())
10725     return;
10726 
10727   // C / C++ fields
10728   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10729   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10730   if (ML && MR) {
10731     if (!(isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase())))
10732       return;
10733     const ValueDecl *LHSDecl =
10734         cast<ValueDecl>(ML->getMemberDecl()->getCanonicalDecl());
10735     const ValueDecl *RHSDecl =
10736         cast<ValueDecl>(MR->getMemberDecl()->getCanonicalDecl());
10737     if (LHSDecl != RHSDecl)
10738       return;
10739     if (LHSDecl->getType().isVolatileQualified())
10740       return;
10741     if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10742       if (RefTy->getPointeeType().isVolatileQualified())
10743         return;
10744 
10745     Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10746   }
10747 
10748   // Objective-C instance variables
10749   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10750   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10751   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10752     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10753     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10754     if (RL && RR && RL->getDecl() == RR->getDecl())
10755       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10756   }
10757 }
10758 
10759 // C99 6.5.16.1
10760 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10761                                        SourceLocation Loc,
10762                                        QualType CompoundType) {
10763   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10764 
10765   // Verify that LHS is a modifiable lvalue, and emit error if not.
10766   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10767     return QualType();
10768 
10769   QualType LHSType = LHSExpr->getType();
10770   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10771                                              CompoundType;
10772   // OpenCL v1.2 s6.1.1.1 p2:
10773   // The half data type can only be used to declare a pointer to a buffer that
10774   // contains half values
10775   if (getLangOpts().OpenCL && !getOpenCLOptions().isEnabled("cl_khr_fp16") &&
10776     LHSType->isHalfType()) {
10777     Diag(Loc, diag::err_opencl_half_load_store) << 1
10778         << LHSType.getUnqualifiedType();
10779     return QualType();
10780   }
10781 
10782   AssignConvertType ConvTy;
10783   if (CompoundType.isNull()) {
10784     Expr *RHSCheck = RHS.get();
10785 
10786     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10787 
10788     QualType LHSTy(LHSType);
10789     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10790     if (RHS.isInvalid())
10791       return QualType();
10792     // Special case of NSObject attributes on c-style pointer types.
10793     if (ConvTy == IncompatiblePointer &&
10794         ((Context.isObjCNSObjectType(LHSType) &&
10795           RHSType->isObjCObjectPointerType()) ||
10796          (Context.isObjCNSObjectType(RHSType) &&
10797           LHSType->isObjCObjectPointerType())))
10798       ConvTy = Compatible;
10799 
10800     if (ConvTy == Compatible &&
10801         LHSType->isObjCObjectType())
10802         Diag(Loc, diag::err_objc_object_assignment)
10803           << LHSType;
10804 
10805     // If the RHS is a unary plus or minus, check to see if they = and + are
10806     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10807     // instead of "x += 4".
10808     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10809       RHSCheck = ICE->getSubExpr();
10810     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10811       if ((UO->getOpcode() == UO_Plus ||
10812            UO->getOpcode() == UO_Minus) &&
10813           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10814           // Only if the two operators are exactly adjacent.
10815           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10816           // And there is a space or other character before the subexpr of the
10817           // unary +/-.  We don't want to warn on "x=-1".
10818           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10819           UO->getSubExpr()->getLocStart().isFileID()) {
10820         Diag(Loc, diag::warn_not_compound_assign)
10821           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10822           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10823       }
10824     }
10825 
10826     if (ConvTy == Compatible) {
10827       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10828         // Warn about retain cycles where a block captures the LHS, but
10829         // not if the LHS is a simple variable into which the block is
10830         // being stored...unless that variable can be captured by reference!
10831         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10832         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10833         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10834           checkRetainCycles(LHSExpr, RHS.get());
10835       }
10836 
10837       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong ||
10838           LHSType.isNonWeakInMRRWithObjCWeak(Context)) {
10839         // It is safe to assign a weak reference into a strong variable.
10840         // Although this code can still have problems:
10841         //   id x = self.weakProp;
10842         //   id y = self.weakProp;
10843         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10844         // paths through the function. This should be revisited if
10845         // -Wrepeated-use-of-weak is made flow-sensitive.
10846         // For ObjCWeak only, we do not warn if the assign is to a non-weak
10847         // variable, which will be valid for the current autorelease scope.
10848         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10849                              RHS.get()->getLocStart()))
10850           getCurFunction()->markSafeWeakUse(RHS.get());
10851 
10852       } else if (getLangOpts().ObjCAutoRefCount || getLangOpts().ObjCWeak) {
10853         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10854       }
10855     }
10856   } else {
10857     // Compound assignment "x += y"
10858     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10859   }
10860 
10861   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10862                                RHS.get(), AA_Assigning))
10863     return QualType();
10864 
10865   CheckForNullPointerDereference(*this, LHSExpr);
10866 
10867   // C99 6.5.16p3: The type of an assignment expression is the type of the
10868   // left operand unless the left operand has qualified type, in which case
10869   // it is the unqualified version of the type of the left operand.
10870   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10871   // is converted to the type of the assignment expression (above).
10872   // C++ 5.17p1: the type of the assignment expression is that of its left
10873   // operand.
10874   return (getLangOpts().CPlusPlus
10875           ? LHSType : LHSType.getUnqualifiedType());
10876 }
10877 
10878 // Only ignore explicit casts to void.
10879 static bool IgnoreCommaOperand(const Expr *E) {
10880   E = E->IgnoreParens();
10881 
10882   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10883     if (CE->getCastKind() == CK_ToVoid) {
10884       return true;
10885     }
10886   }
10887 
10888   return false;
10889 }
10890 
10891 // Look for instances where it is likely the comma operator is confused with
10892 // another operator.  There is a whitelist of acceptable expressions for the
10893 // left hand side of the comma operator, otherwise emit a warning.
10894 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10895   // No warnings in macros
10896   if (Loc.isMacroID())
10897     return;
10898 
10899   // Don't warn in template instantiations.
10900   if (inTemplateInstantiation())
10901     return;
10902 
10903   // Scope isn't fine-grained enough to whitelist the specific cases, so
10904   // instead, skip more than needed, then call back into here with the
10905   // CommaVisitor in SemaStmt.cpp.
10906   // The whitelisted locations are the initialization and increment portions
10907   // of a for loop.  The additional checks are on the condition of
10908   // if statements, do/while loops, and for loops.
10909   const unsigned ForIncrementFlags =
10910       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10911   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10912   const unsigned ScopeFlags = getCurScope()->getFlags();
10913   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10914       (ScopeFlags & ForInitFlags) == ForInitFlags)
10915     return;
10916 
10917   // If there are multiple comma operators used together, get the RHS of the
10918   // of the comma operator as the LHS.
10919   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10920     if (BO->getOpcode() != BO_Comma)
10921       break;
10922     LHS = BO->getRHS();
10923   }
10924 
10925   // Only allow some expressions on LHS to not warn.
10926   if (IgnoreCommaOperand(LHS))
10927     return;
10928 
10929   Diag(Loc, diag::warn_comma_operator);
10930   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10931       << LHS->getSourceRange()
10932       << FixItHint::CreateInsertion(LHS->getLocStart(),
10933                                     LangOpts.CPlusPlus ? "static_cast<void>("
10934                                                        : "(void)(")
10935       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10936                                     ")");
10937 }
10938 
10939 // C99 6.5.17
10940 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10941                                    SourceLocation Loc) {
10942   LHS = S.CheckPlaceholderExpr(LHS.get());
10943   RHS = S.CheckPlaceholderExpr(RHS.get());
10944   if (LHS.isInvalid() || RHS.isInvalid())
10945     return QualType();
10946 
10947   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10948   // operands, but not unary promotions.
10949   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10950 
10951   // So we treat the LHS as a ignored value, and in C++ we allow the
10952   // containing site to determine what should be done with the RHS.
10953   LHS = S.IgnoredValueConversions(LHS.get());
10954   if (LHS.isInvalid())
10955     return QualType();
10956 
10957   S.DiagnoseUnusedExprResult(LHS.get());
10958 
10959   if (!S.getLangOpts().CPlusPlus) {
10960     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10961     if (RHS.isInvalid())
10962       return QualType();
10963     if (!RHS.get()->getType()->isVoidType())
10964       S.RequireCompleteType(Loc, RHS.get()->getType(),
10965                             diag::err_incomplete_type);
10966   }
10967 
10968   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10969     S.DiagnoseCommaOperator(LHS.get(), Loc);
10970 
10971   return RHS.get()->getType();
10972 }
10973 
10974 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10975 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10976 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10977                                                ExprValueKind &VK,
10978                                                ExprObjectKind &OK,
10979                                                SourceLocation OpLoc,
10980                                                bool IsInc, bool IsPrefix) {
10981   if (Op->isTypeDependent())
10982     return S.Context.DependentTy;
10983 
10984   QualType ResType = Op->getType();
10985   // Atomic types can be used for increment / decrement where the non-atomic
10986   // versions can, so ignore the _Atomic() specifier for the purpose of
10987   // checking.
10988   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10989     ResType = ResAtomicType->getValueType();
10990 
10991   assert(!ResType.isNull() && "no type for increment/decrement expression");
10992 
10993   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10994     // Decrement of bool is not allowed.
10995     if (!IsInc) {
10996       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10997       return QualType();
10998     }
10999     // Increment of bool sets it to true, but is deprecated.
11000     S.Diag(OpLoc, S.getLangOpts().CPlusPlus17 ? diag::ext_increment_bool
11001                                               : diag::warn_increment_bool)
11002       << Op->getSourceRange();
11003   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
11004     // Error on enum increments and decrements in C++ mode
11005     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
11006     return QualType();
11007   } else if (ResType->isRealType()) {
11008     // OK!
11009   } else if (ResType->isPointerType()) {
11010     // C99 6.5.2.4p2, 6.5.6p2
11011     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
11012       return QualType();
11013   } else if (ResType->isObjCObjectPointerType()) {
11014     // On modern runtimes, ObjC pointer arithmetic is forbidden.
11015     // Otherwise, we just need a complete type.
11016     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
11017         checkArithmeticOnObjCPointer(S, OpLoc, Op))
11018       return QualType();
11019   } else if (ResType->isAnyComplexType()) {
11020     // C99 does not support ++/-- on complex types, we allow as an extension.
11021     S.Diag(OpLoc, diag::ext_integer_increment_complex)
11022       << ResType << Op->getSourceRange();
11023   } else if (ResType->isPlaceholderType()) {
11024     ExprResult PR = S.CheckPlaceholderExpr(Op);
11025     if (PR.isInvalid()) return QualType();
11026     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
11027                                           IsInc, IsPrefix);
11028   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
11029     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
11030   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
11031              (ResType->getAs<VectorType>()->getVectorKind() !=
11032               VectorType::AltiVecBool)) {
11033     // The z vector extensions allow ++ and -- for non-bool vectors.
11034   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
11035             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
11036     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
11037   } else {
11038     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
11039       << ResType << int(IsInc) << Op->getSourceRange();
11040     return QualType();
11041   }
11042   // At this point, we know we have a real, complex or pointer type.
11043   // Now make sure the operand is a modifiable lvalue.
11044   if (CheckForModifiableLvalue(Op, OpLoc, S))
11045     return QualType();
11046   // In C++, a prefix increment is the same type as the operand. Otherwise
11047   // (in C or with postfix), the increment is the unqualified type of the
11048   // operand.
11049   if (IsPrefix && S.getLangOpts().CPlusPlus) {
11050     VK = VK_LValue;
11051     OK = Op->getObjectKind();
11052     return ResType;
11053   } else {
11054     VK = VK_RValue;
11055     return ResType.getUnqualifiedType();
11056   }
11057 }
11058 
11059 
11060 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
11061 /// This routine allows us to typecheck complex/recursive expressions
11062 /// where the declaration is needed for type checking. We only need to
11063 /// handle cases when the expression references a function designator
11064 /// or is an lvalue. Here are some examples:
11065 ///  - &(x) => x
11066 ///  - &*****f => f for f a function designator.
11067 ///  - &s.xx => s
11068 ///  - &s.zz[1].yy -> s, if zz is an array
11069 ///  - *(x + 1) -> x, if x is an array
11070 ///  - &"123"[2] -> 0
11071 ///  - & __real__ x -> x
11072 static ValueDecl *getPrimaryDecl(Expr *E) {
11073   switch (E->getStmtClass()) {
11074   case Stmt::DeclRefExprClass:
11075     return cast<DeclRefExpr>(E)->getDecl();
11076   case Stmt::MemberExprClass:
11077     // If this is an arrow operator, the address is an offset from
11078     // the base's value, so the object the base refers to is
11079     // irrelevant.
11080     if (cast<MemberExpr>(E)->isArrow())
11081       return nullptr;
11082     // Otherwise, the expression refers to a part of the base
11083     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
11084   case Stmt::ArraySubscriptExprClass: {
11085     // FIXME: This code shouldn't be necessary!  We should catch the implicit
11086     // promotion of register arrays earlier.
11087     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
11088     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
11089       if (ICE->getSubExpr()->getType()->isArrayType())
11090         return getPrimaryDecl(ICE->getSubExpr());
11091     }
11092     return nullptr;
11093   }
11094   case Stmt::UnaryOperatorClass: {
11095     UnaryOperator *UO = cast<UnaryOperator>(E);
11096 
11097     switch(UO->getOpcode()) {
11098     case UO_Real:
11099     case UO_Imag:
11100     case UO_Extension:
11101       return getPrimaryDecl(UO->getSubExpr());
11102     default:
11103       return nullptr;
11104     }
11105   }
11106   case Stmt::ParenExprClass:
11107     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
11108   case Stmt::ImplicitCastExprClass:
11109     // If the result of an implicit cast is an l-value, we care about
11110     // the sub-expression; otherwise, the result here doesn't matter.
11111     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
11112   default:
11113     return nullptr;
11114   }
11115 }
11116 
11117 namespace {
11118   enum {
11119     AO_Bit_Field = 0,
11120     AO_Vector_Element = 1,
11121     AO_Property_Expansion = 2,
11122     AO_Register_Variable = 3,
11123     AO_No_Error = 4
11124   };
11125 }
11126 /// \brief Diagnose invalid operand for address of operations.
11127 ///
11128 /// \param Type The type of operand which cannot have its address taken.
11129 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
11130                                          Expr *E, unsigned Type) {
11131   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
11132 }
11133 
11134 /// CheckAddressOfOperand - The operand of & must be either a function
11135 /// designator or an lvalue designating an object. If it is an lvalue, the
11136 /// object cannot be declared with storage class register or be a bit field.
11137 /// Note: The usual conversions are *not* applied to the operand of the &
11138 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
11139 /// In C++, the operand might be an overloaded function name, in which case
11140 /// we allow the '&' but retain the overloaded-function type.
11141 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
11142   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
11143     if (PTy->getKind() == BuiltinType::Overload) {
11144       Expr *E = OrigOp.get()->IgnoreParens();
11145       if (!isa<OverloadExpr>(E)) {
11146         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
11147         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
11148           << OrigOp.get()->getSourceRange();
11149         return QualType();
11150       }
11151 
11152       OverloadExpr *Ovl = cast<OverloadExpr>(E);
11153       if (isa<UnresolvedMemberExpr>(Ovl))
11154         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
11155           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11156             << OrigOp.get()->getSourceRange();
11157           return QualType();
11158         }
11159 
11160       return Context.OverloadTy;
11161     }
11162 
11163     if (PTy->getKind() == BuiltinType::UnknownAny)
11164       return Context.UnknownAnyTy;
11165 
11166     if (PTy->getKind() == BuiltinType::BoundMember) {
11167       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11168         << OrigOp.get()->getSourceRange();
11169       return QualType();
11170     }
11171 
11172     OrigOp = CheckPlaceholderExpr(OrigOp.get());
11173     if (OrigOp.isInvalid()) return QualType();
11174   }
11175 
11176   if (OrigOp.get()->isTypeDependent())
11177     return Context.DependentTy;
11178 
11179   assert(!OrigOp.get()->getType()->isPlaceholderType());
11180 
11181   // Make sure to ignore parentheses in subsequent checks
11182   Expr *op = OrigOp.get()->IgnoreParens();
11183 
11184   // In OpenCL captures for blocks called as lambda functions
11185   // are located in the private address space. Blocks used in
11186   // enqueue_kernel can be located in a different address space
11187   // depending on a vendor implementation. Thus preventing
11188   // taking an address of the capture to avoid invalid AS casts.
11189   if (LangOpts.OpenCL) {
11190     auto* VarRef = dyn_cast<DeclRefExpr>(op);
11191     if (VarRef && VarRef->refersToEnclosingVariableOrCapture()) {
11192       Diag(op->getExprLoc(), diag::err_opencl_taking_address_capture);
11193       return QualType();
11194     }
11195   }
11196 
11197   if (getLangOpts().C99) {
11198     // Implement C99-only parts of addressof rules.
11199     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
11200       if (uOp->getOpcode() == UO_Deref)
11201         // Per C99 6.5.3.2, the address of a deref always returns a valid result
11202         // (assuming the deref expression is valid).
11203         return uOp->getSubExpr()->getType();
11204     }
11205     // Technically, there should be a check for array subscript
11206     // expressions here, but the result of one is always an lvalue anyway.
11207   }
11208   ValueDecl *dcl = getPrimaryDecl(op);
11209 
11210   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
11211     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
11212                                            op->getLocStart()))
11213       return QualType();
11214 
11215   Expr::LValueClassification lval = op->ClassifyLValue(Context);
11216   unsigned AddressOfError = AO_No_Error;
11217 
11218   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
11219     bool sfinae = (bool)isSFINAEContext();
11220     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
11221                                   : diag::ext_typecheck_addrof_temporary)
11222       << op->getType() << op->getSourceRange();
11223     if (sfinae)
11224       return QualType();
11225     // Materialize the temporary as an lvalue so that we can take its address.
11226     OrigOp = op =
11227         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
11228   } else if (isa<ObjCSelectorExpr>(op)) {
11229     return Context.getPointerType(op->getType());
11230   } else if (lval == Expr::LV_MemberFunction) {
11231     // If it's an instance method, make a member pointer.
11232     // The expression must have exactly the form &A::foo.
11233 
11234     // If the underlying expression isn't a decl ref, give up.
11235     if (!isa<DeclRefExpr>(op)) {
11236       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
11237         << OrigOp.get()->getSourceRange();
11238       return QualType();
11239     }
11240     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
11241     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
11242 
11243     // The id-expression was parenthesized.
11244     if (OrigOp.get() != DRE) {
11245       Diag(OpLoc, diag::err_parens_pointer_member_function)
11246         << OrigOp.get()->getSourceRange();
11247 
11248     // The method was named without a qualifier.
11249     } else if (!DRE->getQualifier()) {
11250       if (MD->getParent()->getName().empty())
11251         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11252           << op->getSourceRange();
11253       else {
11254         SmallString<32> Str;
11255         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
11256         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
11257           << op->getSourceRange()
11258           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
11259       }
11260     }
11261 
11262     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
11263     if (isa<CXXDestructorDecl>(MD))
11264       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
11265 
11266     QualType MPTy = Context.getMemberPointerType(
11267         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
11268     // Under the MS ABI, lock down the inheritance model now.
11269     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11270       (void)isCompleteType(OpLoc, MPTy);
11271     return MPTy;
11272   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
11273     // C99 6.5.3.2p1
11274     // The operand must be either an l-value or a function designator
11275     if (!op->getType()->isFunctionType()) {
11276       // Use a special diagnostic for loads from property references.
11277       if (isa<PseudoObjectExpr>(op)) {
11278         AddressOfError = AO_Property_Expansion;
11279       } else {
11280         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
11281           << op->getType() << op->getSourceRange();
11282         return QualType();
11283       }
11284     }
11285   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
11286     // The operand cannot be a bit-field
11287     AddressOfError = AO_Bit_Field;
11288   } else if (op->getObjectKind() == OK_VectorComponent) {
11289     // The operand cannot be an element of a vector
11290     AddressOfError = AO_Vector_Element;
11291   } else if (dcl) { // C99 6.5.3.2p1
11292     // We have an lvalue with a decl. Make sure the decl is not declared
11293     // with the register storage-class specifier.
11294     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
11295       // in C++ it is not error to take address of a register
11296       // variable (c++03 7.1.1P3)
11297       if (vd->getStorageClass() == SC_Register &&
11298           !getLangOpts().CPlusPlus) {
11299         AddressOfError = AO_Register_Variable;
11300       }
11301     } else if (isa<MSPropertyDecl>(dcl)) {
11302       AddressOfError = AO_Property_Expansion;
11303     } else if (isa<FunctionTemplateDecl>(dcl)) {
11304       return Context.OverloadTy;
11305     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
11306       // Okay: we can take the address of a field.
11307       // Could be a pointer to member, though, if there is an explicit
11308       // scope qualifier for the class.
11309       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
11310         DeclContext *Ctx = dcl->getDeclContext();
11311         if (Ctx && Ctx->isRecord()) {
11312           if (dcl->getType()->isReferenceType()) {
11313             Diag(OpLoc,
11314                  diag::err_cannot_form_pointer_to_member_of_reference_type)
11315               << dcl->getDeclName() << dcl->getType();
11316             return QualType();
11317           }
11318 
11319           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
11320             Ctx = Ctx->getParent();
11321 
11322           QualType MPTy = Context.getMemberPointerType(
11323               op->getType(),
11324               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
11325           // Under the MS ABI, lock down the inheritance model now.
11326           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
11327             (void)isCompleteType(OpLoc, MPTy);
11328           return MPTy;
11329         }
11330       }
11331     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
11332                !isa<BindingDecl>(dcl))
11333       llvm_unreachable("Unknown/unexpected decl type");
11334   }
11335 
11336   if (AddressOfError != AO_No_Error) {
11337     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
11338     return QualType();
11339   }
11340 
11341   if (lval == Expr::LV_IncompleteVoidType) {
11342     // Taking the address of a void variable is technically illegal, but we
11343     // allow it in cases which are otherwise valid.
11344     // Example: "extern void x; void* y = &x;".
11345     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
11346   }
11347 
11348   // If the operand has type "type", the result has type "pointer to type".
11349   if (op->getType()->isObjCObjectType())
11350     return Context.getObjCObjectPointerType(op->getType());
11351 
11352   CheckAddressOfPackedMember(op);
11353 
11354   return Context.getPointerType(op->getType());
11355 }
11356 
11357 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
11358   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
11359   if (!DRE)
11360     return;
11361   const Decl *D = DRE->getDecl();
11362   if (!D)
11363     return;
11364   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
11365   if (!Param)
11366     return;
11367   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
11368     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
11369       return;
11370   if (FunctionScopeInfo *FD = S.getCurFunction())
11371     if (!FD->ModifiedNonNullParams.count(Param))
11372       FD->ModifiedNonNullParams.insert(Param);
11373 }
11374 
11375 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
11376 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
11377                                         SourceLocation OpLoc) {
11378   if (Op->isTypeDependent())
11379     return S.Context.DependentTy;
11380 
11381   ExprResult ConvResult = S.UsualUnaryConversions(Op);
11382   if (ConvResult.isInvalid())
11383     return QualType();
11384   Op = ConvResult.get();
11385   QualType OpTy = Op->getType();
11386   QualType Result;
11387 
11388   if (isa<CXXReinterpretCastExpr>(Op)) {
11389     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
11390     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
11391                                      Op->getSourceRange());
11392   }
11393 
11394   if (const PointerType *PT = OpTy->getAs<PointerType>())
11395   {
11396     Result = PT->getPointeeType();
11397   }
11398   else if (const ObjCObjectPointerType *OPT =
11399              OpTy->getAs<ObjCObjectPointerType>())
11400     Result = OPT->getPointeeType();
11401   else {
11402     ExprResult PR = S.CheckPlaceholderExpr(Op);
11403     if (PR.isInvalid()) return QualType();
11404     if (PR.get() != Op)
11405       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
11406   }
11407 
11408   if (Result.isNull()) {
11409     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
11410       << OpTy << Op->getSourceRange();
11411     return QualType();
11412   }
11413 
11414   // Note that per both C89 and C99, indirection is always legal, even if Result
11415   // is an incomplete type or void.  It would be possible to warn about
11416   // dereferencing a void pointer, but it's completely well-defined, and such a
11417   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
11418   // for pointers to 'void' but is fine for any other pointer type:
11419   //
11420   // C++ [expr.unary.op]p1:
11421   //   [...] the expression to which [the unary * operator] is applied shall
11422   //   be a pointer to an object type, or a pointer to a function type
11423   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
11424     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
11425       << OpTy << Op->getSourceRange();
11426 
11427   // Dereferences are usually l-values...
11428   VK = VK_LValue;
11429 
11430   // ...except that certain expressions are never l-values in C.
11431   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
11432     VK = VK_RValue;
11433 
11434   return Result;
11435 }
11436 
11437 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
11438   BinaryOperatorKind Opc;
11439   switch (Kind) {
11440   default: llvm_unreachable("Unknown binop!");
11441   case tok::periodstar:           Opc = BO_PtrMemD; break;
11442   case tok::arrowstar:            Opc = BO_PtrMemI; break;
11443   case tok::star:                 Opc = BO_Mul; break;
11444   case tok::slash:                Opc = BO_Div; break;
11445   case tok::percent:              Opc = BO_Rem; break;
11446   case tok::plus:                 Opc = BO_Add; break;
11447   case tok::minus:                Opc = BO_Sub; break;
11448   case tok::lessless:             Opc = BO_Shl; break;
11449   case tok::greatergreater:       Opc = BO_Shr; break;
11450   case tok::lessequal:            Opc = BO_LE; break;
11451   case tok::less:                 Opc = BO_LT; break;
11452   case tok::greaterequal:         Opc = BO_GE; break;
11453   case tok::greater:              Opc = BO_GT; break;
11454   case tok::exclaimequal:         Opc = BO_NE; break;
11455   case tok::equalequal:           Opc = BO_EQ; break;
11456   case tok::spaceship:            Opc = BO_Cmp; break;
11457   case tok::amp:                  Opc = BO_And; break;
11458   case tok::caret:                Opc = BO_Xor; break;
11459   case tok::pipe:                 Opc = BO_Or; break;
11460   case tok::ampamp:               Opc = BO_LAnd; break;
11461   case tok::pipepipe:             Opc = BO_LOr; break;
11462   case tok::equal:                Opc = BO_Assign; break;
11463   case tok::starequal:            Opc = BO_MulAssign; break;
11464   case tok::slashequal:           Opc = BO_DivAssign; break;
11465   case tok::percentequal:         Opc = BO_RemAssign; break;
11466   case tok::plusequal:            Opc = BO_AddAssign; break;
11467   case tok::minusequal:           Opc = BO_SubAssign; break;
11468   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
11469   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
11470   case tok::ampequal:             Opc = BO_AndAssign; break;
11471   case tok::caretequal:           Opc = BO_XorAssign; break;
11472   case tok::pipeequal:            Opc = BO_OrAssign; break;
11473   case tok::comma:                Opc = BO_Comma; break;
11474   }
11475   return Opc;
11476 }
11477 
11478 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
11479   tok::TokenKind Kind) {
11480   UnaryOperatorKind Opc;
11481   switch (Kind) {
11482   default: llvm_unreachable("Unknown unary op!");
11483   case tok::plusplus:     Opc = UO_PreInc; break;
11484   case tok::minusminus:   Opc = UO_PreDec; break;
11485   case tok::amp:          Opc = UO_AddrOf; break;
11486   case tok::star:         Opc = UO_Deref; break;
11487   case tok::plus:         Opc = UO_Plus; break;
11488   case tok::minus:        Opc = UO_Minus; break;
11489   case tok::tilde:        Opc = UO_Not; break;
11490   case tok::exclaim:      Opc = UO_LNot; break;
11491   case tok::kw___real:    Opc = UO_Real; break;
11492   case tok::kw___imag:    Opc = UO_Imag; break;
11493   case tok::kw___extension__: Opc = UO_Extension; break;
11494   }
11495   return Opc;
11496 }
11497 
11498 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
11499 /// This warning suppressed in the event of macro expansions.
11500 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
11501                                    SourceLocation OpLoc, bool IsBuiltin) {
11502   if (S.inTemplateInstantiation())
11503     return;
11504   if (S.isUnevaluatedContext())
11505     return;
11506   if (OpLoc.isInvalid() || OpLoc.isMacroID())
11507     return;
11508   LHSExpr = LHSExpr->IgnoreParenImpCasts();
11509   RHSExpr = RHSExpr->IgnoreParenImpCasts();
11510   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
11511   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
11512   if (!LHSDeclRef || !RHSDeclRef ||
11513       LHSDeclRef->getLocation().isMacroID() ||
11514       RHSDeclRef->getLocation().isMacroID())
11515     return;
11516   const ValueDecl *LHSDecl =
11517     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
11518   const ValueDecl *RHSDecl =
11519     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
11520   if (LHSDecl != RHSDecl)
11521     return;
11522   if (LHSDecl->getType().isVolatileQualified())
11523     return;
11524   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
11525     if (RefTy->getPointeeType().isVolatileQualified())
11526       return;
11527 
11528   S.Diag(OpLoc, IsBuiltin ? diag::warn_self_assignment_builtin
11529                           : diag::warn_self_assignment_overloaded)
11530       << LHSDeclRef->getType() << LHSExpr->getSourceRange()
11531       << RHSExpr->getSourceRange();
11532 }
11533 
11534 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
11535 /// is usually indicative of introspection within the Objective-C pointer.
11536 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
11537                                           SourceLocation OpLoc) {
11538   if (!S.getLangOpts().ObjC1)
11539     return;
11540 
11541   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
11542   const Expr *LHS = L.get();
11543   const Expr *RHS = R.get();
11544 
11545   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11546     ObjCPointerExpr = LHS;
11547     OtherExpr = RHS;
11548   }
11549   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
11550     ObjCPointerExpr = RHS;
11551     OtherExpr = LHS;
11552   }
11553 
11554   // This warning is deliberately made very specific to reduce false
11555   // positives with logic that uses '&' for hashing.  This logic mainly
11556   // looks for code trying to introspect into tagged pointers, which
11557   // code should generally never do.
11558   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
11559     unsigned Diag = diag::warn_objc_pointer_masking;
11560     // Determine if we are introspecting the result of performSelectorXXX.
11561     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
11562     // Special case messages to -performSelector and friends, which
11563     // can return non-pointer values boxed in a pointer value.
11564     // Some clients may wish to silence warnings in this subcase.
11565     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
11566       Selector S = ME->getSelector();
11567       StringRef SelArg0 = S.getNameForSlot(0);
11568       if (SelArg0.startswith("performSelector"))
11569         Diag = diag::warn_objc_pointer_masking_performSelector;
11570     }
11571 
11572     S.Diag(OpLoc, Diag)
11573       << ObjCPointerExpr->getSourceRange();
11574   }
11575 }
11576 
11577 static NamedDecl *getDeclFromExpr(Expr *E) {
11578   if (!E)
11579     return nullptr;
11580   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
11581     return DRE->getDecl();
11582   if (auto *ME = dyn_cast<MemberExpr>(E))
11583     return ME->getMemberDecl();
11584   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
11585     return IRE->getDecl();
11586   return nullptr;
11587 }
11588 
11589 // This helper function promotes a binary operator's operands (which are of a
11590 // half vector type) to a vector of floats and then truncates the result to
11591 // a vector of either half or short.
11592 static ExprResult convertHalfVecBinOp(Sema &S, ExprResult LHS, ExprResult RHS,
11593                                       BinaryOperatorKind Opc, QualType ResultTy,
11594                                       ExprValueKind VK, ExprObjectKind OK,
11595                                       bool IsCompAssign, SourceLocation OpLoc,
11596                                       FPOptions FPFeatures) {
11597   auto &Context = S.getASTContext();
11598   assert((isVector(ResultTy, Context.HalfTy) ||
11599           isVector(ResultTy, Context.ShortTy)) &&
11600          "Result must be a vector of half or short");
11601   assert(isVector(LHS.get()->getType(), Context.HalfTy) &&
11602          isVector(RHS.get()->getType(), Context.HalfTy) &&
11603          "both operands expected to be a half vector");
11604 
11605   RHS = convertVector(RHS.get(), Context.FloatTy, S);
11606   QualType BinOpResTy = RHS.get()->getType();
11607 
11608   // If Opc is a comparison, ResultType is a vector of shorts. In that case,
11609   // change BinOpResTy to a vector of ints.
11610   if (isVector(ResultTy, Context.ShortTy))
11611     BinOpResTy = S.GetSignedVectorType(BinOpResTy);
11612 
11613   if (IsCompAssign)
11614     return new (Context) CompoundAssignOperator(
11615         LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, BinOpResTy, BinOpResTy,
11616         OpLoc, FPFeatures);
11617 
11618   LHS = convertVector(LHS.get(), Context.FloatTy, S);
11619   auto *BO = new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, BinOpResTy,
11620                                           VK, OK, OpLoc, FPFeatures);
11621   return convertVector(BO, ResultTy->getAs<VectorType>()->getElementType(), S);
11622 }
11623 
11624 static std::pair<ExprResult, ExprResult>
11625 CorrectDelayedTyposInBinOp(Sema &S, BinaryOperatorKind Opc, Expr *LHSExpr,
11626                            Expr *RHSExpr) {
11627   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11628   if (!S.getLangOpts().CPlusPlus) {
11629     // C cannot handle TypoExpr nodes on either side of a binop because it
11630     // doesn't handle dependent types properly, so make sure any TypoExprs have
11631     // been dealt with before checking the operands.
11632     LHS = S.CorrectDelayedTyposInExpr(LHS);
11633     RHS = S.CorrectDelayedTyposInExpr(RHS, [Opc, LHS](Expr *E) {
11634       if (Opc != BO_Assign)
11635         return ExprResult(E);
11636       // Avoid correcting the RHS to the same Expr as the LHS.
11637       Decl *D = getDeclFromExpr(E);
11638       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
11639     });
11640   }
11641   return std::make_pair(LHS, RHS);
11642 }
11643 
11644 /// Returns true if conversion between vectors of halfs and vectors of floats
11645 /// is needed.
11646 static bool needsConversionOfHalfVec(bool OpRequiresConversion, ASTContext &Ctx,
11647                                      QualType SrcType) {
11648   return OpRequiresConversion && !Ctx.getLangOpts().NativeHalfType &&
11649          !Ctx.getTargetInfo().useFP16ConversionIntrinsics() &&
11650          isVector(SrcType, Ctx.HalfTy);
11651 }
11652 
11653 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
11654 /// operator @p Opc at location @c TokLoc. This routine only supports
11655 /// built-in operations; ActOnBinOp handles overloaded operators.
11656 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
11657                                     BinaryOperatorKind Opc,
11658                                     Expr *LHSExpr, Expr *RHSExpr) {
11659   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
11660     // The syntax only allows initializer lists on the RHS of assignment,
11661     // so we don't need to worry about accepting invalid code for
11662     // non-assignment operators.
11663     // C++11 5.17p9:
11664     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
11665     //   of x = {} is x = T().
11666     InitializationKind Kind = InitializationKind::CreateDirectList(
11667         RHSExpr->getLocStart(), RHSExpr->getLocStart(), RHSExpr->getLocEnd());
11668     InitializedEntity Entity =
11669         InitializedEntity::InitializeTemporary(LHSExpr->getType());
11670     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
11671     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
11672     if (Init.isInvalid())
11673       return Init;
11674     RHSExpr = Init.get();
11675   }
11676 
11677   ExprResult LHS = LHSExpr, RHS = RHSExpr;
11678   QualType ResultTy;     // Result type of the binary operator.
11679   // The following two variables are used for compound assignment operators
11680   QualType CompLHSTy;    // Type of LHS after promotions for computation
11681   QualType CompResultTy; // Type of computation result
11682   ExprValueKind VK = VK_RValue;
11683   ExprObjectKind OK = OK_Ordinary;
11684   bool ConvertHalfVec = false;
11685 
11686   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
11687   if (!LHS.isUsable() || !RHS.isUsable())
11688     return ExprError();
11689 
11690   if (getLangOpts().OpenCL) {
11691     QualType LHSTy = LHSExpr->getType();
11692     QualType RHSTy = RHSExpr->getType();
11693     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
11694     // the ATOMIC_VAR_INIT macro.
11695     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
11696       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
11697       if (BO_Assign == Opc)
11698         Diag(OpLoc, diag::err_opencl_atomic_init) << 0 << SR;
11699       else
11700         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11701       return ExprError();
11702     }
11703 
11704     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11705     // only with a builtin functions and therefore should be disallowed here.
11706     if (LHSTy->isImageType() || RHSTy->isImageType() ||
11707         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
11708         LHSTy->isPipeType() || RHSTy->isPipeType() ||
11709         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
11710       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
11711       return ExprError();
11712     }
11713   }
11714 
11715   switch (Opc) {
11716   case BO_Assign:
11717     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
11718     if (getLangOpts().CPlusPlus &&
11719         LHS.get()->getObjectKind() != OK_ObjCProperty) {
11720       VK = LHS.get()->getValueKind();
11721       OK = LHS.get()->getObjectKind();
11722     }
11723     if (!ResultTy.isNull()) {
11724       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
11725       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
11726     }
11727     RecordModifiableNonNullParam(*this, LHS.get());
11728     break;
11729   case BO_PtrMemD:
11730   case BO_PtrMemI:
11731     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
11732                                             Opc == BO_PtrMemI);
11733     break;
11734   case BO_Mul:
11735   case BO_Div:
11736     ConvertHalfVec = true;
11737     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
11738                                            Opc == BO_Div);
11739     break;
11740   case BO_Rem:
11741     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
11742     break;
11743   case BO_Add:
11744     ConvertHalfVec = true;
11745     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
11746     break;
11747   case BO_Sub:
11748     ConvertHalfVec = true;
11749     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
11750     break;
11751   case BO_Shl:
11752   case BO_Shr:
11753     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
11754     break;
11755   case BO_LE:
11756   case BO_LT:
11757   case BO_GE:
11758   case BO_GT:
11759     ConvertHalfVec = true;
11760     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11761     break;
11762   case BO_EQ:
11763   case BO_NE:
11764     ConvertHalfVec = true;
11765     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
11766     break;
11767   case BO_Cmp:
11768     // FIXME: Implement proper semantic checking of '<=>'.
11769     ConvertHalfVec = true;
11770     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
11771     if (!ResultTy.isNull())
11772       ResultTy = Context.VoidTy;
11773     break;
11774   case BO_And:
11775     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11776     LLVM_FALLTHROUGH;
11777   case BO_Xor:
11778   case BO_Or:
11779     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11780     break;
11781   case BO_LAnd:
11782   case BO_LOr:
11783     ConvertHalfVec = true;
11784     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11785     break;
11786   case BO_MulAssign:
11787   case BO_DivAssign:
11788     ConvertHalfVec = true;
11789     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11790                                                Opc == BO_DivAssign);
11791     CompLHSTy = CompResultTy;
11792     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11793       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11794     break;
11795   case BO_RemAssign:
11796     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11797     CompLHSTy = CompResultTy;
11798     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11799       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11800     break;
11801   case BO_AddAssign:
11802     ConvertHalfVec = true;
11803     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11804     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11805       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11806     break;
11807   case BO_SubAssign:
11808     ConvertHalfVec = true;
11809     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11810     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11811       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11812     break;
11813   case BO_ShlAssign:
11814   case BO_ShrAssign:
11815     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11816     CompLHSTy = CompResultTy;
11817     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11818       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11819     break;
11820   case BO_AndAssign:
11821   case BO_OrAssign: // fallthrough
11822     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc, true);
11823     LLVM_FALLTHROUGH;
11824   case BO_XorAssign:
11825     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, Opc);
11826     CompLHSTy = CompResultTy;
11827     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11828       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11829     break;
11830   case BO_Comma:
11831     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11832     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11833       VK = RHS.get()->getValueKind();
11834       OK = RHS.get()->getObjectKind();
11835     }
11836     break;
11837   }
11838   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11839     return ExprError();
11840 
11841   // Some of the binary operations require promoting operands of half vector to
11842   // float vectors and truncating the result back to half vector. For now, we do
11843   // this only when HalfArgsAndReturn is set (that is, when the target is arm or
11844   // arm64).
11845   assert(isVector(RHS.get()->getType(), Context.HalfTy) ==
11846          isVector(LHS.get()->getType(), Context.HalfTy) &&
11847          "both sides are half vectors or neither sides are");
11848   ConvertHalfVec = needsConversionOfHalfVec(ConvertHalfVec, Context,
11849                                             LHS.get()->getType());
11850 
11851   // Check for array bounds violations for both sides of the BinaryOperator
11852   CheckArrayAccess(LHS.get());
11853   CheckArrayAccess(RHS.get());
11854 
11855   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11856     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11857                                                  &Context.Idents.get("object_setClass"),
11858                                                  SourceLocation(), LookupOrdinaryName);
11859     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11860       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11861       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11862       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11863       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11864       FixItHint::CreateInsertion(RHSLocEnd, ")");
11865     }
11866     else
11867       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11868   }
11869   else if (const ObjCIvarRefExpr *OIRE =
11870            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11871     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11872 
11873   // Opc is not a compound assignment if CompResultTy is null.
11874   if (CompResultTy.isNull()) {
11875     if (ConvertHalfVec)
11876       return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, false,
11877                                  OpLoc, FPFeatures);
11878     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11879                                         OK, OpLoc, FPFeatures);
11880   }
11881 
11882   // Handle compound assignments.
11883   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11884       OK_ObjCProperty) {
11885     VK = VK_LValue;
11886     OK = LHS.get()->getObjectKind();
11887   }
11888 
11889   if (ConvertHalfVec)
11890     return convertHalfVecBinOp(*this, LHS, RHS, Opc, ResultTy, VK, OK, true,
11891                                OpLoc, FPFeatures);
11892 
11893   return new (Context) CompoundAssignOperator(
11894       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11895       OpLoc, FPFeatures);
11896 }
11897 
11898 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11899 /// operators are mixed in a way that suggests that the programmer forgot that
11900 /// comparison operators have higher precedence. The most typical example of
11901 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11902 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11903                                       SourceLocation OpLoc, Expr *LHSExpr,
11904                                       Expr *RHSExpr) {
11905   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11906   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11907 
11908   // Check that one of the sides is a comparison operator and the other isn't.
11909   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11910   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11911   if (isLeftComp == isRightComp)
11912     return;
11913 
11914   // Bitwise operations are sometimes used as eager logical ops.
11915   // Don't diagnose this.
11916   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11917   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11918   if (isLeftBitwise || isRightBitwise)
11919     return;
11920 
11921   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11922                                                    OpLoc)
11923                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11924   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11925   SourceRange ParensRange = isLeftComp ?
11926       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11927     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11928 
11929   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11930     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11931   SuggestParentheses(Self, OpLoc,
11932     Self.PDiag(diag::note_precedence_silence) << OpStr,
11933     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11934   SuggestParentheses(Self, OpLoc,
11935     Self.PDiag(diag::note_precedence_bitwise_first)
11936       << BinaryOperator::getOpcodeStr(Opc),
11937     ParensRange);
11938 }
11939 
11940 /// \brief It accepts a '&&' expr that is inside a '||' one.
11941 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11942 /// in parentheses.
11943 static void
11944 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11945                                        BinaryOperator *Bop) {
11946   assert(Bop->getOpcode() == BO_LAnd);
11947   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11948       << Bop->getSourceRange() << OpLoc;
11949   SuggestParentheses(Self, Bop->getOperatorLoc(),
11950     Self.PDiag(diag::note_precedence_silence)
11951       << Bop->getOpcodeStr(),
11952     Bop->getSourceRange());
11953 }
11954 
11955 /// \brief Returns true if the given expression can be evaluated as a constant
11956 /// 'true'.
11957 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11958   bool Res;
11959   return !E->isValueDependent() &&
11960          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11961 }
11962 
11963 /// \brief Returns true if the given expression can be evaluated as a constant
11964 /// 'false'.
11965 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11966   bool Res;
11967   return !E->isValueDependent() &&
11968          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11969 }
11970 
11971 /// \brief Look for '&&' in the left hand of a '||' expr.
11972 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11973                                              Expr *LHSExpr, Expr *RHSExpr) {
11974   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11975     if (Bop->getOpcode() == BO_LAnd) {
11976       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11977       if (EvaluatesAsFalse(S, RHSExpr))
11978         return;
11979       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11980       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11981         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11982     } else if (Bop->getOpcode() == BO_LOr) {
11983       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11984         // If it's "a || b && 1 || c" we didn't warn earlier for
11985         // "a || b && 1", but warn now.
11986         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11987           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11988       }
11989     }
11990   }
11991 }
11992 
11993 /// \brief Look for '&&' in the right hand of a '||' expr.
11994 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11995                                              Expr *LHSExpr, Expr *RHSExpr) {
11996   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11997     if (Bop->getOpcode() == BO_LAnd) {
11998       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11999       if (EvaluatesAsFalse(S, LHSExpr))
12000         return;
12001       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
12002       if (!EvaluatesAsTrue(S, Bop->getRHS()))
12003         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
12004     }
12005   }
12006 }
12007 
12008 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
12009 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
12010 /// the '&' expression in parentheses.
12011 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
12012                                          SourceLocation OpLoc, Expr *SubExpr) {
12013   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12014     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
12015       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
12016         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
12017         << Bop->getSourceRange() << OpLoc;
12018       SuggestParentheses(S, Bop->getOperatorLoc(),
12019         S.PDiag(diag::note_precedence_silence)
12020           << Bop->getOpcodeStr(),
12021         Bop->getSourceRange());
12022     }
12023   }
12024 }
12025 
12026 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
12027                                     Expr *SubExpr, StringRef Shift) {
12028   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
12029     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
12030       StringRef Op = Bop->getOpcodeStr();
12031       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
12032           << Bop->getSourceRange() << OpLoc << Shift << Op;
12033       SuggestParentheses(S, Bop->getOperatorLoc(),
12034           S.PDiag(diag::note_precedence_silence) << Op,
12035           Bop->getSourceRange());
12036     }
12037   }
12038 }
12039 
12040 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
12041                                  Expr *LHSExpr, Expr *RHSExpr) {
12042   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
12043   if (!OCE)
12044     return;
12045 
12046   FunctionDecl *FD = OCE->getDirectCallee();
12047   if (!FD || !FD->isOverloadedOperator())
12048     return;
12049 
12050   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
12051   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
12052     return;
12053 
12054   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
12055       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
12056       << (Kind == OO_LessLess);
12057   SuggestParentheses(S, OCE->getOperatorLoc(),
12058                      S.PDiag(diag::note_precedence_silence)
12059                          << (Kind == OO_LessLess ? "<<" : ">>"),
12060                      OCE->getSourceRange());
12061   SuggestParentheses(S, OpLoc,
12062                      S.PDiag(diag::note_evaluate_comparison_first),
12063                      SourceRange(OCE->getArg(1)->getLocStart(),
12064                                  RHSExpr->getLocEnd()));
12065 }
12066 
12067 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
12068 /// precedence.
12069 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
12070                                     SourceLocation OpLoc, Expr *LHSExpr,
12071                                     Expr *RHSExpr){
12072   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
12073   if (BinaryOperator::isBitwiseOp(Opc))
12074     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
12075 
12076   // Diagnose "arg1 & arg2 | arg3"
12077   if ((Opc == BO_Or || Opc == BO_Xor) &&
12078       !OpLoc.isMacroID()/* Don't warn in macros. */) {
12079     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
12080     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
12081   }
12082 
12083   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
12084   // We don't warn for 'assert(a || b && "bad")' since this is safe.
12085   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
12086     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
12087     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
12088   }
12089 
12090   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
12091       || Opc == BO_Shr) {
12092     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
12093     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
12094     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
12095   }
12096 
12097   // Warn on overloaded shift operators and comparisons, such as:
12098   // cout << 5 == 4;
12099   if (BinaryOperator::isComparisonOp(Opc))
12100     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
12101 }
12102 
12103 // Binary Operators.  'Tok' is the token for the operator.
12104 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
12105                             tok::TokenKind Kind,
12106                             Expr *LHSExpr, Expr *RHSExpr) {
12107   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
12108   assert(LHSExpr && "ActOnBinOp(): missing left expression");
12109   assert(RHSExpr && "ActOnBinOp(): missing right expression");
12110 
12111   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
12112   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
12113 
12114   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
12115 }
12116 
12117 /// Build an overloaded binary operator expression in the given scope.
12118 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
12119                                        BinaryOperatorKind Opc,
12120                                        Expr *LHS, Expr *RHS) {
12121   switch (Opc) {
12122   case BO_Assign:
12123   case BO_DivAssign:
12124   case BO_RemAssign:
12125   case BO_SubAssign:
12126   case BO_AndAssign:
12127   case BO_OrAssign:
12128   case BO_XorAssign:
12129     DiagnoseSelfAssignment(S, LHS, RHS, OpLoc, false);
12130     CheckIdentityFieldAssignment(LHS, RHS, OpLoc, S);
12131     break;
12132   default:
12133     break;
12134   }
12135 
12136   // Find all of the overloaded operators visible from this
12137   // point. We perform both an operator-name lookup from the local
12138   // scope and an argument-dependent lookup based on the types of
12139   // the arguments.
12140   UnresolvedSet<16> Functions;
12141   OverloadedOperatorKind OverOp
12142     = BinaryOperator::getOverloadedOperator(Opc);
12143   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
12144     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
12145                                    RHS->getType(), Functions);
12146 
12147   // Build the (potentially-overloaded, potentially-dependent)
12148   // binary operation.
12149   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
12150 }
12151 
12152 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
12153                             BinaryOperatorKind Opc,
12154                             Expr *LHSExpr, Expr *RHSExpr) {
12155   ExprResult LHS, RHS;
12156   std::tie(LHS, RHS) = CorrectDelayedTyposInBinOp(*this, Opc, LHSExpr, RHSExpr);
12157   if (!LHS.isUsable() || !RHS.isUsable())
12158     return ExprError();
12159   LHSExpr = LHS.get();
12160   RHSExpr = RHS.get();
12161 
12162   // We want to end up calling one of checkPseudoObjectAssignment
12163   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
12164   // both expressions are overloadable or either is type-dependent),
12165   // or CreateBuiltinBinOp (in any other case).  We also want to get
12166   // any placeholder types out of the way.
12167 
12168   // Handle pseudo-objects in the LHS.
12169   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
12170     // Assignments with a pseudo-object l-value need special analysis.
12171     if (pty->getKind() == BuiltinType::PseudoObject &&
12172         BinaryOperator::isAssignmentOp(Opc))
12173       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
12174 
12175     // Don't resolve overloads if the other type is overloadable.
12176     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload) {
12177       // We can't actually test that if we still have a placeholder,
12178       // though.  Fortunately, none of the exceptions we see in that
12179       // code below are valid when the LHS is an overload set.  Note
12180       // that an overload set can be dependently-typed, but it never
12181       // instantiates to having an overloadable type.
12182       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12183       if (resolvedRHS.isInvalid()) return ExprError();
12184       RHSExpr = resolvedRHS.get();
12185 
12186       if (RHSExpr->isTypeDependent() ||
12187           RHSExpr->getType()->isOverloadableType())
12188         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12189     }
12190 
12191     // If we're instantiating "a.x < b" or "A::x < b" and 'x' names a function
12192     // template, diagnose the missing 'template' keyword instead of diagnosing
12193     // an invalid use of a bound member function.
12194     //
12195     // Note that "A::x < b" might be valid if 'b' has an overloadable type due
12196     // to C++1z [over.over]/1.4, but we already checked for that case above.
12197     if (Opc == BO_LT && inTemplateInstantiation() &&
12198         (pty->getKind() == BuiltinType::BoundMember ||
12199          pty->getKind() == BuiltinType::Overload)) {
12200       auto *OE = dyn_cast<OverloadExpr>(LHSExpr);
12201       if (OE && !OE->hasTemplateKeyword() && !OE->hasExplicitTemplateArgs() &&
12202           std::any_of(OE->decls_begin(), OE->decls_end(), [](NamedDecl *ND) {
12203             return isa<FunctionTemplateDecl>(ND);
12204           })) {
12205         Diag(OE->getQualifier() ? OE->getQualifierLoc().getBeginLoc()
12206                                 : OE->getNameLoc(),
12207              diag::err_template_kw_missing)
12208           << OE->getName().getAsString() << "";
12209         return ExprError();
12210       }
12211     }
12212 
12213     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
12214     if (LHS.isInvalid()) return ExprError();
12215     LHSExpr = LHS.get();
12216   }
12217 
12218   // Handle pseudo-objects in the RHS.
12219   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
12220     // An overload in the RHS can potentially be resolved by the type
12221     // being assigned to.
12222     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
12223       if (getLangOpts().CPlusPlus &&
12224           (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent() ||
12225            LHSExpr->getType()->isOverloadableType()))
12226         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12227 
12228       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12229     }
12230 
12231     // Don't resolve overloads if the other type is overloadable.
12232     if (getLangOpts().CPlusPlus && pty->getKind() == BuiltinType::Overload &&
12233         LHSExpr->getType()->isOverloadableType())
12234       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12235 
12236     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
12237     if (!resolvedRHS.isUsable()) return ExprError();
12238     RHSExpr = resolvedRHS.get();
12239   }
12240 
12241   if (getLangOpts().CPlusPlus) {
12242     // If either expression is type-dependent, always build an
12243     // overloaded op.
12244     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
12245       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12246 
12247     // Otherwise, build an overloaded op if either expression has an
12248     // overloadable type.
12249     if (LHSExpr->getType()->isOverloadableType() ||
12250         RHSExpr->getType()->isOverloadableType())
12251       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
12252   }
12253 
12254   // Build a built-in binary operation.
12255   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
12256 }
12257 
12258 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
12259   if (T.isNull() || T->isDependentType())
12260     return false;
12261 
12262   if (!T->isPromotableIntegerType())
12263     return true;
12264 
12265   return Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
12266 }
12267 
12268 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
12269                                       UnaryOperatorKind Opc,
12270                                       Expr *InputExpr) {
12271   ExprResult Input = InputExpr;
12272   ExprValueKind VK = VK_RValue;
12273   ExprObjectKind OK = OK_Ordinary;
12274   QualType resultType;
12275   bool CanOverflow = false;
12276 
12277   bool ConvertHalfVec = false;
12278   if (getLangOpts().OpenCL) {
12279     QualType Ty = InputExpr->getType();
12280     // The only legal unary operation for atomics is '&'.
12281     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
12282     // OpenCL special types - image, sampler, pipe, and blocks are to be used
12283     // only with a builtin functions and therefore should be disallowed here.
12284         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
12285         || Ty->isBlockPointerType())) {
12286       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12287                        << InputExpr->getType()
12288                        << Input.get()->getSourceRange());
12289     }
12290   }
12291   switch (Opc) {
12292   case UO_PreInc:
12293   case UO_PreDec:
12294   case UO_PostInc:
12295   case UO_PostDec:
12296     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
12297                                                 OpLoc,
12298                                                 Opc == UO_PreInc ||
12299                                                 Opc == UO_PostInc,
12300                                                 Opc == UO_PreInc ||
12301                                                 Opc == UO_PreDec);
12302     CanOverflow = isOverflowingIntegerType(Context, resultType);
12303     break;
12304   case UO_AddrOf:
12305     resultType = CheckAddressOfOperand(Input, OpLoc);
12306     RecordModifiableNonNullParam(*this, InputExpr);
12307     break;
12308   case UO_Deref: {
12309     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12310     if (Input.isInvalid()) return ExprError();
12311     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
12312     break;
12313   }
12314   case UO_Plus:
12315   case UO_Minus:
12316     CanOverflow = Opc == UO_Minus &&
12317                   isOverflowingIntegerType(Context, Input.get()->getType());
12318     Input = UsualUnaryConversions(Input.get());
12319     if (Input.isInvalid()) return ExprError();
12320     // Unary plus and minus require promoting an operand of half vector to a
12321     // float vector and truncating the result back to a half vector. For now, we
12322     // do this only when HalfArgsAndReturns is set (that is, when the target is
12323     // arm or arm64).
12324     ConvertHalfVec =
12325         needsConversionOfHalfVec(true, Context, Input.get()->getType());
12326 
12327     // If the operand is a half vector, promote it to a float vector.
12328     if (ConvertHalfVec)
12329       Input = convertVector(Input.get(), Context.FloatTy, *this);
12330     resultType = Input.get()->getType();
12331     if (resultType->isDependentType())
12332       break;
12333     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
12334       break;
12335     else if (resultType->isVectorType() &&
12336              // The z vector extensions don't allow + or - with bool vectors.
12337              (!Context.getLangOpts().ZVector ||
12338               resultType->getAs<VectorType>()->getVectorKind() !=
12339               VectorType::AltiVecBool))
12340       break;
12341     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
12342              Opc == UO_Plus &&
12343              resultType->isPointerType())
12344       break;
12345 
12346     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12347       << resultType << Input.get()->getSourceRange());
12348 
12349   case UO_Not: // bitwise complement
12350     Input = UsualUnaryConversions(Input.get());
12351     if (Input.isInvalid())
12352       return ExprError();
12353     resultType = Input.get()->getType();
12354 
12355     if (resultType->isDependentType())
12356       break;
12357     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
12358     if (resultType->isComplexType() || resultType->isComplexIntegerType())
12359       // C99 does not support '~' for complex conjugation.
12360       Diag(OpLoc, diag::ext_integer_complement_complex)
12361           << resultType << Input.get()->getSourceRange();
12362     else if (resultType->hasIntegerRepresentation())
12363       break;
12364     else if (resultType->isExtVectorType() && Context.getLangOpts().OpenCL) {
12365       // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
12366       // on vector float types.
12367       QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12368       if (!T->isIntegerType())
12369         return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12370                           << resultType << Input.get()->getSourceRange());
12371     } else {
12372       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12373                        << resultType << Input.get()->getSourceRange());
12374     }
12375     break;
12376 
12377   case UO_LNot: // logical negation
12378     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
12379     Input = DefaultFunctionArrayLvalueConversion(Input.get());
12380     if (Input.isInvalid()) return ExprError();
12381     resultType = Input.get()->getType();
12382 
12383     // Though we still have to promote half FP to float...
12384     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
12385       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
12386       resultType = Context.FloatTy;
12387     }
12388 
12389     if (resultType->isDependentType())
12390       break;
12391     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
12392       // C99 6.5.3.3p1: ok, fallthrough;
12393       if (Context.getLangOpts().CPlusPlus) {
12394         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
12395         // operand contextually converted to bool.
12396         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
12397                                   ScalarTypeToBooleanCastKind(resultType));
12398       } else if (Context.getLangOpts().OpenCL &&
12399                  Context.getLangOpts().OpenCLVersion < 120) {
12400         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12401         // operate on scalar float types.
12402         if (!resultType->isIntegerType() && !resultType->isPointerType())
12403           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12404                            << resultType << Input.get()->getSourceRange());
12405       }
12406     } else if (resultType->isExtVectorType()) {
12407       if (Context.getLangOpts().OpenCL &&
12408           Context.getLangOpts().OpenCLVersion < 120) {
12409         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
12410         // operate on vector float types.
12411         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
12412         if (!T->isIntegerType())
12413           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12414                            << resultType << Input.get()->getSourceRange());
12415       }
12416       // Vector logical not returns the signed variant of the operand type.
12417       resultType = GetSignedVectorType(resultType);
12418       break;
12419     } else {
12420       // FIXME: GCC's vector extension permits the usage of '!' with a vector
12421       //        type in C++. We should allow that here too.
12422       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
12423         << resultType << Input.get()->getSourceRange());
12424     }
12425 
12426     // LNot always has type int. C99 6.5.3.3p5.
12427     // In C++, it's bool. C++ 5.3.1p8
12428     resultType = Context.getLogicalOperationType();
12429     break;
12430   case UO_Real:
12431   case UO_Imag:
12432     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
12433     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
12434     // complex l-values to ordinary l-values and all other values to r-values.
12435     if (Input.isInvalid()) return ExprError();
12436     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
12437       if (Input.get()->getValueKind() != VK_RValue &&
12438           Input.get()->getObjectKind() == OK_Ordinary)
12439         VK = Input.get()->getValueKind();
12440     } else if (!getLangOpts().CPlusPlus) {
12441       // In C, a volatile scalar is read by __imag. In C++, it is not.
12442       Input = DefaultLvalueConversion(Input.get());
12443     }
12444     break;
12445   case UO_Extension:
12446     resultType = Input.get()->getType();
12447     VK = Input.get()->getValueKind();
12448     OK = Input.get()->getObjectKind();
12449     break;
12450   case UO_Coawait:
12451     // It's unnecessary to represent the pass-through operator co_await in the
12452     // AST; just return the input expression instead.
12453     assert(!Input.get()->getType()->isDependentType() &&
12454                    "the co_await expression must be non-dependant before "
12455                    "building operator co_await");
12456     return Input;
12457   }
12458   if (resultType.isNull() || Input.isInvalid())
12459     return ExprError();
12460 
12461   // Check for array bounds violations in the operand of the UnaryOperator,
12462   // except for the '*' and '&' operators that have to be handled specially
12463   // by CheckArrayAccess (as there are special cases like &array[arraysize]
12464   // that are explicitly defined as valid by the standard).
12465   if (Opc != UO_AddrOf && Opc != UO_Deref)
12466     CheckArrayAccess(Input.get());
12467 
12468   auto *UO = new (Context)
12469       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc, CanOverflow);
12470   // Convert the result back to a half vector.
12471   if (ConvertHalfVec)
12472     return convertVector(UO, Context.HalfTy, *this);
12473   return UO;
12474 }
12475 
12476 /// \brief Determine whether the given expression is a qualified member
12477 /// access expression, of a form that could be turned into a pointer to member
12478 /// with the address-of operator.
12479 static bool isQualifiedMemberAccess(Expr *E) {
12480   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12481     if (!DRE->getQualifier())
12482       return false;
12483 
12484     ValueDecl *VD = DRE->getDecl();
12485     if (!VD->isCXXClassMember())
12486       return false;
12487 
12488     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
12489       return true;
12490     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
12491       return Method->isInstance();
12492 
12493     return false;
12494   }
12495 
12496   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12497     if (!ULE->getQualifier())
12498       return false;
12499 
12500     for (NamedDecl *D : ULE->decls()) {
12501       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
12502         if (Method->isInstance())
12503           return true;
12504       } else {
12505         // Overload set does not contain methods.
12506         break;
12507       }
12508     }
12509 
12510     return false;
12511   }
12512 
12513   return false;
12514 }
12515 
12516 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
12517                               UnaryOperatorKind Opc, Expr *Input) {
12518   // First things first: handle placeholders so that the
12519   // overloaded-operator check considers the right type.
12520   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
12521     // Increment and decrement of pseudo-object references.
12522     if (pty->getKind() == BuiltinType::PseudoObject &&
12523         UnaryOperator::isIncrementDecrementOp(Opc))
12524       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
12525 
12526     // extension is always a builtin operator.
12527     if (Opc == UO_Extension)
12528       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12529 
12530     // & gets special logic for several kinds of placeholder.
12531     // The builtin code knows what to do.
12532     if (Opc == UO_AddrOf &&
12533         (pty->getKind() == BuiltinType::Overload ||
12534          pty->getKind() == BuiltinType::UnknownAny ||
12535          pty->getKind() == BuiltinType::BoundMember))
12536       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12537 
12538     // Anything else needs to be handled now.
12539     ExprResult Result = CheckPlaceholderExpr(Input);
12540     if (Result.isInvalid()) return ExprError();
12541     Input = Result.get();
12542   }
12543 
12544   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
12545       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
12546       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
12547     // Find all of the overloaded operators visible from this
12548     // point. We perform both an operator-name lookup from the local
12549     // scope and an argument-dependent lookup based on the types of
12550     // the arguments.
12551     UnresolvedSet<16> Functions;
12552     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
12553     if (S && OverOp != OO_None)
12554       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
12555                                    Functions);
12556 
12557     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
12558   }
12559 
12560   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12561 }
12562 
12563 // Unary Operators.  'Tok' is the token for the operator.
12564 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
12565                               tok::TokenKind Op, Expr *Input) {
12566   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
12567 }
12568 
12569 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
12570 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
12571                                 LabelDecl *TheDecl) {
12572   TheDecl->markUsed(Context);
12573   // Create the AST node.  The address of a label always has type 'void*'.
12574   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
12575                                      Context.getPointerType(Context.VoidTy));
12576 }
12577 
12578 /// Given the last statement in a statement-expression, check whether
12579 /// the result is a producing expression (like a call to an
12580 /// ns_returns_retained function) and, if so, rebuild it to hoist the
12581 /// release out of the full-expression.  Otherwise, return null.
12582 /// Cannot fail.
12583 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
12584   // Should always be wrapped with one of these.
12585   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
12586   if (!cleanups) return nullptr;
12587 
12588   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
12589   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
12590     return nullptr;
12591 
12592   // Splice out the cast.  This shouldn't modify any interesting
12593   // features of the statement.
12594   Expr *producer = cast->getSubExpr();
12595   assert(producer->getType() == cast->getType());
12596   assert(producer->getValueKind() == cast->getValueKind());
12597   cleanups->setSubExpr(producer);
12598   return cleanups;
12599 }
12600 
12601 void Sema::ActOnStartStmtExpr() {
12602   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12603 }
12604 
12605 void Sema::ActOnStmtExprError() {
12606   // Note that function is also called by TreeTransform when leaving a
12607   // StmtExpr scope without rebuilding anything.
12608 
12609   DiscardCleanupsInEvaluationContext();
12610   PopExpressionEvaluationContext();
12611 }
12612 
12613 ExprResult
12614 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
12615                     SourceLocation RPLoc) { // "({..})"
12616   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
12617   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
12618 
12619   if (hasAnyUnrecoverableErrorsInThisFunction())
12620     DiscardCleanupsInEvaluationContext();
12621   assert(!Cleanup.exprNeedsCleanups() &&
12622          "cleanups within StmtExpr not correctly bound!");
12623   PopExpressionEvaluationContext();
12624 
12625   // FIXME: there are a variety of strange constraints to enforce here, for
12626   // example, it is not possible to goto into a stmt expression apparently.
12627   // More semantic analysis is needed.
12628 
12629   // If there are sub-stmts in the compound stmt, take the type of the last one
12630   // as the type of the stmtexpr.
12631   QualType Ty = Context.VoidTy;
12632   bool StmtExprMayBindToTemp = false;
12633   if (!Compound->body_empty()) {
12634     Stmt *LastStmt = Compound->body_back();
12635     LabelStmt *LastLabelStmt = nullptr;
12636     // If LastStmt is a label, skip down through into the body.
12637     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
12638       LastLabelStmt = Label;
12639       LastStmt = Label->getSubStmt();
12640     }
12641 
12642     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
12643       // Do function/array conversion on the last expression, but not
12644       // lvalue-to-rvalue.  However, initialize an unqualified type.
12645       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
12646       if (LastExpr.isInvalid())
12647         return ExprError();
12648       Ty = LastExpr.get()->getType().getUnqualifiedType();
12649 
12650       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
12651         // In ARC, if the final expression ends in a consume, splice
12652         // the consume out and bind it later.  In the alternate case
12653         // (when dealing with a retainable type), the result
12654         // initialization will create a produce.  In both cases the
12655         // result will be +1, and we'll need to balance that out with
12656         // a bind.
12657         if (Expr *rebuiltLastStmt
12658               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
12659           LastExpr = rebuiltLastStmt;
12660         } else {
12661           LastExpr = PerformCopyInitialization(
12662                             InitializedEntity::InitializeResult(LPLoc,
12663                                                                 Ty,
12664                                                                 false),
12665                                                    SourceLocation(),
12666                                                LastExpr);
12667         }
12668 
12669         if (LastExpr.isInvalid())
12670           return ExprError();
12671         if (LastExpr.get() != nullptr) {
12672           if (!LastLabelStmt)
12673             Compound->setLastStmt(LastExpr.get());
12674           else
12675             LastLabelStmt->setSubStmt(LastExpr.get());
12676           StmtExprMayBindToTemp = true;
12677         }
12678       }
12679     }
12680   }
12681 
12682   // FIXME: Check that expression type is complete/non-abstract; statement
12683   // expressions are not lvalues.
12684   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
12685   if (StmtExprMayBindToTemp)
12686     return MaybeBindToTemporary(ResStmtExpr);
12687   return ResStmtExpr;
12688 }
12689 
12690 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
12691                                       TypeSourceInfo *TInfo,
12692                                       ArrayRef<OffsetOfComponent> Components,
12693                                       SourceLocation RParenLoc) {
12694   QualType ArgTy = TInfo->getType();
12695   bool Dependent = ArgTy->isDependentType();
12696   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
12697 
12698   // We must have at least one component that refers to the type, and the first
12699   // one is known to be a field designator.  Verify that the ArgTy represents
12700   // a struct/union/class.
12701   if (!Dependent && !ArgTy->isRecordType())
12702     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
12703                        << ArgTy << TypeRange);
12704 
12705   // Type must be complete per C99 7.17p3 because a declaring a variable
12706   // with an incomplete type would be ill-formed.
12707   if (!Dependent
12708       && RequireCompleteType(BuiltinLoc, ArgTy,
12709                              diag::err_offsetof_incomplete_type, TypeRange))
12710     return ExprError();
12711 
12712   bool DidWarnAboutNonPOD = false;
12713   QualType CurrentType = ArgTy;
12714   SmallVector<OffsetOfNode, 4> Comps;
12715   SmallVector<Expr*, 4> Exprs;
12716   for (const OffsetOfComponent &OC : Components) {
12717     if (OC.isBrackets) {
12718       // Offset of an array sub-field.  TODO: Should we allow vector elements?
12719       if (!CurrentType->isDependentType()) {
12720         const ArrayType *AT = Context.getAsArrayType(CurrentType);
12721         if(!AT)
12722           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
12723                            << CurrentType);
12724         CurrentType = AT->getElementType();
12725       } else
12726         CurrentType = Context.DependentTy;
12727 
12728       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
12729       if (IdxRval.isInvalid())
12730         return ExprError();
12731       Expr *Idx = IdxRval.get();
12732 
12733       // The expression must be an integral expression.
12734       // FIXME: An integral constant expression?
12735       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
12736           !Idx->getType()->isIntegerType())
12737         return ExprError(Diag(Idx->getLocStart(),
12738                               diag::err_typecheck_subscript_not_integer)
12739                          << Idx->getSourceRange());
12740 
12741       // Record this array index.
12742       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
12743       Exprs.push_back(Idx);
12744       continue;
12745     }
12746 
12747     // Offset of a field.
12748     if (CurrentType->isDependentType()) {
12749       // We have the offset of a field, but we can't look into the dependent
12750       // type. Just record the identifier of the field.
12751       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
12752       CurrentType = Context.DependentTy;
12753       continue;
12754     }
12755 
12756     // We need to have a complete type to look into.
12757     if (RequireCompleteType(OC.LocStart, CurrentType,
12758                             diag::err_offsetof_incomplete_type))
12759       return ExprError();
12760 
12761     // Look for the designated field.
12762     const RecordType *RC = CurrentType->getAs<RecordType>();
12763     if (!RC)
12764       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
12765                        << CurrentType);
12766     RecordDecl *RD = RC->getDecl();
12767 
12768     // C++ [lib.support.types]p5:
12769     //   The macro offsetof accepts a restricted set of type arguments in this
12770     //   International Standard. type shall be a POD structure or a POD union
12771     //   (clause 9).
12772     // C++11 [support.types]p4:
12773     //   If type is not a standard-layout class (Clause 9), the results are
12774     //   undefined.
12775     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
12776       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
12777       unsigned DiagID =
12778         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
12779                             : diag::ext_offsetof_non_pod_type;
12780 
12781       if (!IsSafe && !DidWarnAboutNonPOD &&
12782           DiagRuntimeBehavior(BuiltinLoc, nullptr,
12783                               PDiag(DiagID)
12784                               << SourceRange(Components[0].LocStart, OC.LocEnd)
12785                               << CurrentType))
12786         DidWarnAboutNonPOD = true;
12787     }
12788 
12789     // Look for the field.
12790     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
12791     LookupQualifiedName(R, RD);
12792     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
12793     IndirectFieldDecl *IndirectMemberDecl = nullptr;
12794     if (!MemberDecl) {
12795       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
12796         MemberDecl = IndirectMemberDecl->getAnonField();
12797     }
12798 
12799     if (!MemberDecl)
12800       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
12801                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
12802                                                               OC.LocEnd));
12803 
12804     // C99 7.17p3:
12805     //   (If the specified member is a bit-field, the behavior is undefined.)
12806     //
12807     // We diagnose this as an error.
12808     if (MemberDecl->isBitField()) {
12809       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
12810         << MemberDecl->getDeclName()
12811         << SourceRange(BuiltinLoc, RParenLoc);
12812       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
12813       return ExprError();
12814     }
12815 
12816     RecordDecl *Parent = MemberDecl->getParent();
12817     if (IndirectMemberDecl)
12818       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
12819 
12820     // If the member was found in a base class, introduce OffsetOfNodes for
12821     // the base class indirections.
12822     CXXBasePaths Paths;
12823     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
12824                       Paths)) {
12825       if (Paths.getDetectedVirtual()) {
12826         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
12827           << MemberDecl->getDeclName()
12828           << SourceRange(BuiltinLoc, RParenLoc);
12829         return ExprError();
12830       }
12831 
12832       CXXBasePath &Path = Paths.front();
12833       for (const CXXBasePathElement &B : Path)
12834         Comps.push_back(OffsetOfNode(B.Base));
12835     }
12836 
12837     if (IndirectMemberDecl) {
12838       for (auto *FI : IndirectMemberDecl->chain()) {
12839         assert(isa<FieldDecl>(FI));
12840         Comps.push_back(OffsetOfNode(OC.LocStart,
12841                                      cast<FieldDecl>(FI), OC.LocEnd));
12842       }
12843     } else
12844       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
12845 
12846     CurrentType = MemberDecl->getType().getNonReferenceType();
12847   }
12848 
12849   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
12850                               Comps, Exprs, RParenLoc);
12851 }
12852 
12853 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
12854                                       SourceLocation BuiltinLoc,
12855                                       SourceLocation TypeLoc,
12856                                       ParsedType ParsedArgTy,
12857                                       ArrayRef<OffsetOfComponent> Components,
12858                                       SourceLocation RParenLoc) {
12859 
12860   TypeSourceInfo *ArgTInfo;
12861   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
12862   if (ArgTy.isNull())
12863     return ExprError();
12864 
12865   if (!ArgTInfo)
12866     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
12867 
12868   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
12869 }
12870 
12871 
12872 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
12873                                  Expr *CondExpr,
12874                                  Expr *LHSExpr, Expr *RHSExpr,
12875                                  SourceLocation RPLoc) {
12876   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12877 
12878   ExprValueKind VK = VK_RValue;
12879   ExprObjectKind OK = OK_Ordinary;
12880   QualType resType;
12881   bool ValueDependent = false;
12882   bool CondIsTrue = false;
12883   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12884     resType = Context.DependentTy;
12885     ValueDependent = true;
12886   } else {
12887     // The conditional expression is required to be a constant expression.
12888     llvm::APSInt condEval(32);
12889     ExprResult CondICE
12890       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12891           diag::err_typecheck_choose_expr_requires_constant, false);
12892     if (CondICE.isInvalid())
12893       return ExprError();
12894     CondExpr = CondICE.get();
12895     CondIsTrue = condEval.getZExtValue();
12896 
12897     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12898     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12899 
12900     resType = ActiveExpr->getType();
12901     ValueDependent = ActiveExpr->isValueDependent();
12902     VK = ActiveExpr->getValueKind();
12903     OK = ActiveExpr->getObjectKind();
12904   }
12905 
12906   return new (Context)
12907       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12908                  CondIsTrue, resType->isDependentType(), ValueDependent);
12909 }
12910 
12911 //===----------------------------------------------------------------------===//
12912 // Clang Extensions.
12913 //===----------------------------------------------------------------------===//
12914 
12915 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12916 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12917   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12918 
12919   if (LangOpts.CPlusPlus) {
12920     Decl *ManglingContextDecl;
12921     if (MangleNumberingContext *MCtx =
12922             getCurrentMangleNumberContext(Block->getDeclContext(),
12923                                           ManglingContextDecl)) {
12924       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12925       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12926     }
12927   }
12928 
12929   PushBlockScope(CurScope, Block);
12930   CurContext->addDecl(Block);
12931   if (CurScope)
12932     PushDeclContext(CurScope, Block);
12933   else
12934     CurContext = Block;
12935 
12936   getCurBlock()->HasImplicitReturnType = true;
12937 
12938   // Enter a new evaluation context to insulate the block from any
12939   // cleanups from the enclosing full-expression.
12940   PushExpressionEvaluationContext(
12941       ExpressionEvaluationContext::PotentiallyEvaluated);
12942 }
12943 
12944 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12945                                Scope *CurScope) {
12946   assert(ParamInfo.getIdentifier() == nullptr &&
12947          "block-id should have no identifier!");
12948   assert(ParamInfo.getContext() == DeclaratorContext::BlockLiteralContext);
12949   BlockScopeInfo *CurBlock = getCurBlock();
12950 
12951   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12952   QualType T = Sig->getType();
12953 
12954   // FIXME: We should allow unexpanded parameter packs here, but that would,
12955   // in turn, make the block expression contain unexpanded parameter packs.
12956   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12957     // Drop the parameters.
12958     FunctionProtoType::ExtProtoInfo EPI;
12959     EPI.HasTrailingReturn = false;
12960     EPI.TypeQuals |= DeclSpec::TQ_const;
12961     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12962     Sig = Context.getTrivialTypeSourceInfo(T);
12963   }
12964 
12965   // GetTypeForDeclarator always produces a function type for a block
12966   // literal signature.  Furthermore, it is always a FunctionProtoType
12967   // unless the function was written with a typedef.
12968   assert(T->isFunctionType() &&
12969          "GetTypeForDeclarator made a non-function block signature");
12970 
12971   // Look for an explicit signature in that function type.
12972   FunctionProtoTypeLoc ExplicitSignature;
12973 
12974   if ((ExplicitSignature =
12975            Sig->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>())) {
12976 
12977     // Check whether that explicit signature was synthesized by
12978     // GetTypeForDeclarator.  If so, don't save that as part of the
12979     // written signature.
12980     if (ExplicitSignature.getLocalRangeBegin() ==
12981         ExplicitSignature.getLocalRangeEnd()) {
12982       // This would be much cheaper if we stored TypeLocs instead of
12983       // TypeSourceInfos.
12984       TypeLoc Result = ExplicitSignature.getReturnLoc();
12985       unsigned Size = Result.getFullDataSize();
12986       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12987       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12988 
12989       ExplicitSignature = FunctionProtoTypeLoc();
12990     }
12991   }
12992 
12993   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12994   CurBlock->FunctionType = T;
12995 
12996   const FunctionType *Fn = T->getAs<FunctionType>();
12997   QualType RetTy = Fn->getReturnType();
12998   bool isVariadic =
12999     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
13000 
13001   CurBlock->TheDecl->setIsVariadic(isVariadic);
13002 
13003   // Context.DependentTy is used as a placeholder for a missing block
13004   // return type.  TODO:  what should we do with declarators like:
13005   //   ^ * { ... }
13006   // If the answer is "apply template argument deduction"....
13007   if (RetTy != Context.DependentTy) {
13008     CurBlock->ReturnType = RetTy;
13009     CurBlock->TheDecl->setBlockMissingReturnType(false);
13010     CurBlock->HasImplicitReturnType = false;
13011   }
13012 
13013   // Push block parameters from the declarator if we had them.
13014   SmallVector<ParmVarDecl*, 8> Params;
13015   if (ExplicitSignature) {
13016     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
13017       ParmVarDecl *Param = ExplicitSignature.getParam(I);
13018       if (Param->getIdentifier() == nullptr &&
13019           !Param->isImplicit() &&
13020           !Param->isInvalidDecl() &&
13021           !getLangOpts().CPlusPlus)
13022         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
13023       Params.push_back(Param);
13024     }
13025 
13026   // Fake up parameter variables if we have a typedef, like
13027   //   ^ fntype { ... }
13028   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
13029     for (const auto &I : Fn->param_types()) {
13030       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
13031           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
13032       Params.push_back(Param);
13033     }
13034   }
13035 
13036   // Set the parameters on the block decl.
13037   if (!Params.empty()) {
13038     CurBlock->TheDecl->setParams(Params);
13039     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
13040                              /*CheckParameterNames=*/false);
13041   }
13042 
13043   // Finally we can process decl attributes.
13044   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
13045 
13046   // Put the parameter variables in scope.
13047   for (auto AI : CurBlock->TheDecl->parameters()) {
13048     AI->setOwningFunction(CurBlock->TheDecl);
13049 
13050     // If this has an identifier, add it to the scope stack.
13051     if (AI->getIdentifier()) {
13052       CheckShadow(CurBlock->TheScope, AI);
13053 
13054       PushOnScopeChains(AI, CurBlock->TheScope);
13055     }
13056   }
13057 }
13058 
13059 /// ActOnBlockError - If there is an error parsing a block, this callback
13060 /// is invoked to pop the information about the block from the action impl.
13061 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
13062   // Leave the expression-evaluation context.
13063   DiscardCleanupsInEvaluationContext();
13064   PopExpressionEvaluationContext();
13065 
13066   // Pop off CurBlock, handle nested blocks.
13067   PopDeclContext();
13068   PopFunctionScopeInfo();
13069 }
13070 
13071 /// ActOnBlockStmtExpr - This is called when the body of a block statement
13072 /// literal was successfully completed.  ^(int x){...}
13073 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
13074                                     Stmt *Body, Scope *CurScope) {
13075   // If blocks are disabled, emit an error.
13076   if (!LangOpts.Blocks)
13077     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
13078 
13079   // Leave the expression-evaluation context.
13080   if (hasAnyUnrecoverableErrorsInThisFunction())
13081     DiscardCleanupsInEvaluationContext();
13082   assert(!Cleanup.exprNeedsCleanups() &&
13083          "cleanups within block not correctly bound!");
13084   PopExpressionEvaluationContext();
13085 
13086   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
13087 
13088   if (BSI->HasImplicitReturnType)
13089     deduceClosureReturnType(*BSI);
13090 
13091   PopDeclContext();
13092 
13093   QualType RetTy = Context.VoidTy;
13094   if (!BSI->ReturnType.isNull())
13095     RetTy = BSI->ReturnType;
13096 
13097   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
13098   QualType BlockTy;
13099 
13100   // Set the captured variables on the block.
13101   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
13102   SmallVector<BlockDecl::Capture, 4> Captures;
13103   for (Capture &Cap : BSI->Captures) {
13104     if (Cap.isThisCapture())
13105       continue;
13106     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
13107                               Cap.isNested(), Cap.getInitExpr());
13108     Captures.push_back(NewCap);
13109   }
13110   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
13111 
13112   // If the user wrote a function type in some form, try to use that.
13113   if (!BSI->FunctionType.isNull()) {
13114     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
13115 
13116     FunctionType::ExtInfo Ext = FTy->getExtInfo();
13117     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
13118 
13119     // Turn protoless block types into nullary block types.
13120     if (isa<FunctionNoProtoType>(FTy)) {
13121       FunctionProtoType::ExtProtoInfo EPI;
13122       EPI.ExtInfo = Ext;
13123       BlockTy = Context.getFunctionType(RetTy, None, EPI);
13124 
13125     // Otherwise, if we don't need to change anything about the function type,
13126     // preserve its sugar structure.
13127     } else if (FTy->getReturnType() == RetTy &&
13128                (!NoReturn || FTy->getNoReturnAttr())) {
13129       BlockTy = BSI->FunctionType;
13130 
13131     // Otherwise, make the minimal modifications to the function type.
13132     } else {
13133       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
13134       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13135       EPI.TypeQuals = 0; // FIXME: silently?
13136       EPI.ExtInfo = Ext;
13137       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
13138     }
13139 
13140   // If we don't have a function type, just build one from nothing.
13141   } else {
13142     FunctionProtoType::ExtProtoInfo EPI;
13143     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
13144     BlockTy = Context.getFunctionType(RetTy, None, EPI);
13145   }
13146 
13147   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
13148   BlockTy = Context.getBlockPointerType(BlockTy);
13149 
13150   // If needed, diagnose invalid gotos and switches in the block.
13151   if (getCurFunction()->NeedsScopeChecking() &&
13152       !PP.isCodeCompletionEnabled())
13153     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
13154 
13155   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
13156 
13157   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13158     DiagnoseUnguardedAvailabilityViolations(BSI->TheDecl);
13159 
13160   // Try to apply the named return value optimization. We have to check again
13161   // if we can do this, though, because blocks keep return statements around
13162   // to deduce an implicit return type.
13163   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
13164       !BSI->TheDecl->isDependentContext())
13165     computeNRVO(Body, BSI);
13166 
13167   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
13168   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13169   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
13170 
13171   // If the block isn't obviously global, i.e. it captures anything at
13172   // all, then we need to do a few things in the surrounding context:
13173   if (Result->getBlockDecl()->hasCaptures()) {
13174     // First, this expression has a new cleanup object.
13175     ExprCleanupObjects.push_back(Result->getBlockDecl());
13176     Cleanup.setExprNeedsCleanups(true);
13177 
13178     // It also gets a branch-protected scope if any of the captured
13179     // variables needs destruction.
13180     for (const auto &CI : Result->getBlockDecl()->captures()) {
13181       const VarDecl *var = CI.getVariable();
13182       if (var->getType().isDestructedType() != QualType::DK_none) {
13183         setFunctionHasBranchProtectedScope();
13184         break;
13185       }
13186     }
13187   }
13188 
13189   return Result;
13190 }
13191 
13192 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
13193                             SourceLocation RPLoc) {
13194   TypeSourceInfo *TInfo;
13195   GetTypeFromParser(Ty, &TInfo);
13196   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
13197 }
13198 
13199 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
13200                                 Expr *E, TypeSourceInfo *TInfo,
13201                                 SourceLocation RPLoc) {
13202   Expr *OrigExpr = E;
13203   bool IsMS = false;
13204 
13205   // CUDA device code does not support varargs.
13206   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
13207     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
13208       CUDAFunctionTarget T = IdentifyCUDATarget(F);
13209       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
13210         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
13211     }
13212   }
13213 
13214   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
13215   // as Microsoft ABI on an actual Microsoft platform, where
13216   // __builtin_ms_va_list and __builtin_va_list are the same.)
13217   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
13218       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
13219     QualType MSVaListType = Context.getBuiltinMSVaListType();
13220     if (Context.hasSameType(MSVaListType, E->getType())) {
13221       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
13222         return ExprError();
13223       IsMS = true;
13224     }
13225   }
13226 
13227   // Get the va_list type
13228   QualType VaListType = Context.getBuiltinVaListType();
13229   if (!IsMS) {
13230     if (VaListType->isArrayType()) {
13231       // Deal with implicit array decay; for example, on x86-64,
13232       // va_list is an array, but it's supposed to decay to
13233       // a pointer for va_arg.
13234       VaListType = Context.getArrayDecayedType(VaListType);
13235       // Make sure the input expression also decays appropriately.
13236       ExprResult Result = UsualUnaryConversions(E);
13237       if (Result.isInvalid())
13238         return ExprError();
13239       E = Result.get();
13240     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
13241       // If va_list is a record type and we are compiling in C++ mode,
13242       // check the argument using reference binding.
13243       InitializedEntity Entity = InitializedEntity::InitializeParameter(
13244           Context, Context.getLValueReferenceType(VaListType), false);
13245       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
13246       if (Init.isInvalid())
13247         return ExprError();
13248       E = Init.getAs<Expr>();
13249     } else {
13250       // Otherwise, the va_list argument must be an l-value because
13251       // it is modified by va_arg.
13252       if (!E->isTypeDependent() &&
13253           CheckForModifiableLvalue(E, BuiltinLoc, *this))
13254         return ExprError();
13255     }
13256   }
13257 
13258   if (!IsMS && !E->isTypeDependent() &&
13259       !Context.hasSameType(VaListType, E->getType()))
13260     return ExprError(Diag(E->getLocStart(),
13261                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
13262       << OrigExpr->getType() << E->getSourceRange());
13263 
13264   if (!TInfo->getType()->isDependentType()) {
13265     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
13266                             diag::err_second_parameter_to_va_arg_incomplete,
13267                             TInfo->getTypeLoc()))
13268       return ExprError();
13269 
13270     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
13271                                TInfo->getType(),
13272                                diag::err_second_parameter_to_va_arg_abstract,
13273                                TInfo->getTypeLoc()))
13274       return ExprError();
13275 
13276     if (!TInfo->getType().isPODType(Context)) {
13277       Diag(TInfo->getTypeLoc().getBeginLoc(),
13278            TInfo->getType()->isObjCLifetimeType()
13279              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
13280              : diag::warn_second_parameter_to_va_arg_not_pod)
13281         << TInfo->getType()
13282         << TInfo->getTypeLoc().getSourceRange();
13283     }
13284 
13285     // Check for va_arg where arguments of the given type will be promoted
13286     // (i.e. this va_arg is guaranteed to have undefined behavior).
13287     QualType PromoteType;
13288     if (TInfo->getType()->isPromotableIntegerType()) {
13289       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
13290       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
13291         PromoteType = QualType();
13292     }
13293     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
13294       PromoteType = Context.DoubleTy;
13295     if (!PromoteType.isNull())
13296       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
13297                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
13298                           << TInfo->getType()
13299                           << PromoteType
13300                           << TInfo->getTypeLoc().getSourceRange());
13301   }
13302 
13303   QualType T = TInfo->getType().getNonLValueExprType(Context);
13304   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
13305 }
13306 
13307 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
13308   // The type of __null will be int or long, depending on the size of
13309   // pointers on the target.
13310   QualType Ty;
13311   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
13312   if (pw == Context.getTargetInfo().getIntWidth())
13313     Ty = Context.IntTy;
13314   else if (pw == Context.getTargetInfo().getLongWidth())
13315     Ty = Context.LongTy;
13316   else if (pw == Context.getTargetInfo().getLongLongWidth())
13317     Ty = Context.LongLongTy;
13318   else {
13319     llvm_unreachable("I don't know size of pointer!");
13320   }
13321 
13322   return new (Context) GNUNullExpr(Ty, TokenLoc);
13323 }
13324 
13325 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
13326                                               bool Diagnose) {
13327   if (!getLangOpts().ObjC1)
13328     return false;
13329 
13330   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
13331   if (!PT)
13332     return false;
13333 
13334   if (!PT->isObjCIdType()) {
13335     // Check if the destination is the 'NSString' interface.
13336     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
13337     if (!ID || !ID->getIdentifier()->isStr("NSString"))
13338       return false;
13339   }
13340 
13341   // Ignore any parens, implicit casts (should only be
13342   // array-to-pointer decays), and not-so-opaque values.  The last is
13343   // important for making this trigger for property assignments.
13344   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
13345   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
13346     if (OV->getSourceExpr())
13347       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
13348 
13349   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
13350   if (!SL || !SL->isAscii())
13351     return false;
13352   if (Diagnose) {
13353     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
13354       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
13355     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
13356   }
13357   return true;
13358 }
13359 
13360 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
13361                                               const Expr *SrcExpr) {
13362   if (!DstType->isFunctionPointerType() ||
13363       !SrcExpr->getType()->isFunctionType())
13364     return false;
13365 
13366   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
13367   if (!DRE)
13368     return false;
13369 
13370   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
13371   if (!FD)
13372     return false;
13373 
13374   return !S.checkAddressOfFunctionIsAvailable(FD,
13375                                               /*Complain=*/true,
13376                                               SrcExpr->getLocStart());
13377 }
13378 
13379 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
13380                                     SourceLocation Loc,
13381                                     QualType DstType, QualType SrcType,
13382                                     Expr *SrcExpr, AssignmentAction Action,
13383                                     bool *Complained) {
13384   if (Complained)
13385     *Complained = false;
13386 
13387   // Decode the result (notice that AST's are still created for extensions).
13388   bool CheckInferredResultType = false;
13389   bool isInvalid = false;
13390   unsigned DiagKind = 0;
13391   FixItHint Hint;
13392   ConversionFixItGenerator ConvHints;
13393   bool MayHaveConvFixit = false;
13394   bool MayHaveFunctionDiff = false;
13395   const ObjCInterfaceDecl *IFace = nullptr;
13396   const ObjCProtocolDecl *PDecl = nullptr;
13397 
13398   switch (ConvTy) {
13399   case Compatible:
13400       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
13401       return false;
13402 
13403   case PointerToInt:
13404     DiagKind = diag::ext_typecheck_convert_pointer_int;
13405     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13406     MayHaveConvFixit = true;
13407     break;
13408   case IntToPointer:
13409     DiagKind = diag::ext_typecheck_convert_int_pointer;
13410     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13411     MayHaveConvFixit = true;
13412     break;
13413   case IncompatiblePointer:
13414     if (Action == AA_Passing_CFAudited)
13415       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
13416     else if (SrcType->isFunctionPointerType() &&
13417              DstType->isFunctionPointerType())
13418       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
13419     else
13420       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
13421 
13422     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
13423       SrcType->isObjCObjectPointerType();
13424     if (Hint.isNull() && !CheckInferredResultType) {
13425       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13426     }
13427     else if (CheckInferredResultType) {
13428       SrcType = SrcType.getUnqualifiedType();
13429       DstType = DstType.getUnqualifiedType();
13430     }
13431     MayHaveConvFixit = true;
13432     break;
13433   case IncompatiblePointerSign:
13434     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
13435     break;
13436   case FunctionVoidPointer:
13437     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
13438     break;
13439   case IncompatiblePointerDiscardsQualifiers: {
13440     // Perform array-to-pointer decay if necessary.
13441     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
13442 
13443     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
13444     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
13445     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
13446       DiagKind = diag::err_typecheck_incompatible_address_space;
13447       break;
13448 
13449 
13450     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
13451       DiagKind = diag::err_typecheck_incompatible_ownership;
13452       break;
13453     }
13454 
13455     llvm_unreachable("unknown error case for discarding qualifiers!");
13456     // fallthrough
13457   }
13458   case CompatiblePointerDiscardsQualifiers:
13459     // If the qualifiers lost were because we were applying the
13460     // (deprecated) C++ conversion from a string literal to a char*
13461     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
13462     // Ideally, this check would be performed in
13463     // checkPointerTypesForAssignment. However, that would require a
13464     // bit of refactoring (so that the second argument is an
13465     // expression, rather than a type), which should be done as part
13466     // of a larger effort to fix checkPointerTypesForAssignment for
13467     // C++ semantics.
13468     if (getLangOpts().CPlusPlus &&
13469         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
13470       return false;
13471     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
13472     break;
13473   case IncompatibleNestedPointerQualifiers:
13474     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
13475     break;
13476   case IntToBlockPointer:
13477     DiagKind = diag::err_int_to_block_pointer;
13478     break;
13479   case IncompatibleBlockPointer:
13480     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
13481     break;
13482   case IncompatibleObjCQualifiedId: {
13483     if (SrcType->isObjCQualifiedIdType()) {
13484       const ObjCObjectPointerType *srcOPT =
13485                 SrcType->getAs<ObjCObjectPointerType>();
13486       for (auto *srcProto : srcOPT->quals()) {
13487         PDecl = srcProto;
13488         break;
13489       }
13490       if (const ObjCInterfaceType *IFaceT =
13491             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13492         IFace = IFaceT->getDecl();
13493     }
13494     else if (DstType->isObjCQualifiedIdType()) {
13495       const ObjCObjectPointerType *dstOPT =
13496         DstType->getAs<ObjCObjectPointerType>();
13497       for (auto *dstProto : dstOPT->quals()) {
13498         PDecl = dstProto;
13499         break;
13500       }
13501       if (const ObjCInterfaceType *IFaceT =
13502             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
13503         IFace = IFaceT->getDecl();
13504     }
13505     DiagKind = diag::warn_incompatible_qualified_id;
13506     break;
13507   }
13508   case IncompatibleVectors:
13509     DiagKind = diag::warn_incompatible_vectors;
13510     break;
13511   case IncompatibleObjCWeakRef:
13512     DiagKind = diag::err_arc_weak_unavailable_assign;
13513     break;
13514   case Incompatible:
13515     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
13516       if (Complained)
13517         *Complained = true;
13518       return true;
13519     }
13520 
13521     DiagKind = diag::err_typecheck_convert_incompatible;
13522     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
13523     MayHaveConvFixit = true;
13524     isInvalid = true;
13525     MayHaveFunctionDiff = true;
13526     break;
13527   }
13528 
13529   QualType FirstType, SecondType;
13530   switch (Action) {
13531   case AA_Assigning:
13532   case AA_Initializing:
13533     // The destination type comes first.
13534     FirstType = DstType;
13535     SecondType = SrcType;
13536     break;
13537 
13538   case AA_Returning:
13539   case AA_Passing:
13540   case AA_Passing_CFAudited:
13541   case AA_Converting:
13542   case AA_Sending:
13543   case AA_Casting:
13544     // The source type comes first.
13545     FirstType = SrcType;
13546     SecondType = DstType;
13547     break;
13548   }
13549 
13550   PartialDiagnostic FDiag = PDiag(DiagKind);
13551   if (Action == AA_Passing_CFAudited)
13552     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
13553   else
13554     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
13555 
13556   // If we can fix the conversion, suggest the FixIts.
13557   assert(ConvHints.isNull() || Hint.isNull());
13558   if (!ConvHints.isNull()) {
13559     for (FixItHint &H : ConvHints.Hints)
13560       FDiag << H;
13561   } else {
13562     FDiag << Hint;
13563   }
13564   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
13565 
13566   if (MayHaveFunctionDiff)
13567     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
13568 
13569   Diag(Loc, FDiag);
13570   if (DiagKind == diag::warn_incompatible_qualified_id &&
13571       PDecl && IFace && !IFace->hasDefinition())
13572       Diag(IFace->getLocation(), diag::note_incomplete_class_and_qualified_id)
13573         << IFace << PDecl;
13574 
13575   if (SecondType == Context.OverloadTy)
13576     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
13577                               FirstType, /*TakingAddress=*/true);
13578 
13579   if (CheckInferredResultType)
13580     EmitRelatedResultTypeNote(SrcExpr);
13581 
13582   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
13583     EmitRelatedResultTypeNoteForReturn(DstType);
13584 
13585   if (Complained)
13586     *Complained = true;
13587   return isInvalid;
13588 }
13589 
13590 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13591                                                  llvm::APSInt *Result) {
13592   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
13593   public:
13594     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13595       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
13596     }
13597   } Diagnoser;
13598 
13599   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
13600 }
13601 
13602 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
13603                                                  llvm::APSInt *Result,
13604                                                  unsigned DiagID,
13605                                                  bool AllowFold) {
13606   class IDDiagnoser : public VerifyICEDiagnoser {
13607     unsigned DiagID;
13608 
13609   public:
13610     IDDiagnoser(unsigned DiagID)
13611       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
13612 
13613     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
13614       S.Diag(Loc, DiagID) << SR;
13615     }
13616   } Diagnoser(DiagID);
13617 
13618   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
13619 }
13620 
13621 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
13622                                             SourceRange SR) {
13623   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
13624 }
13625 
13626 ExprResult
13627 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
13628                                       VerifyICEDiagnoser &Diagnoser,
13629                                       bool AllowFold) {
13630   SourceLocation DiagLoc = E->getLocStart();
13631 
13632   if (getLangOpts().CPlusPlus11) {
13633     // C++11 [expr.const]p5:
13634     //   If an expression of literal class type is used in a context where an
13635     //   integral constant expression is required, then that class type shall
13636     //   have a single non-explicit conversion function to an integral or
13637     //   unscoped enumeration type
13638     ExprResult Converted;
13639     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
13640     public:
13641       CXX11ConvertDiagnoser(bool Silent)
13642           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
13643                                 Silent, true) {}
13644 
13645       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
13646                                            QualType T) override {
13647         return S.Diag(Loc, diag::err_ice_not_integral) << T;
13648       }
13649 
13650       SemaDiagnosticBuilder diagnoseIncomplete(
13651           Sema &S, SourceLocation Loc, QualType T) override {
13652         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
13653       }
13654 
13655       SemaDiagnosticBuilder diagnoseExplicitConv(
13656           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13657         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
13658       }
13659 
13660       SemaDiagnosticBuilder noteExplicitConv(
13661           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13662         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13663                  << ConvTy->isEnumeralType() << ConvTy;
13664       }
13665 
13666       SemaDiagnosticBuilder diagnoseAmbiguous(
13667           Sema &S, SourceLocation Loc, QualType T) override {
13668         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
13669       }
13670 
13671       SemaDiagnosticBuilder noteAmbiguous(
13672           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
13673         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
13674                  << ConvTy->isEnumeralType() << ConvTy;
13675       }
13676 
13677       SemaDiagnosticBuilder diagnoseConversion(
13678           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
13679         llvm_unreachable("conversion functions are permitted");
13680       }
13681     } ConvertDiagnoser(Diagnoser.Suppress);
13682 
13683     Converted = PerformContextualImplicitConversion(DiagLoc, E,
13684                                                     ConvertDiagnoser);
13685     if (Converted.isInvalid())
13686       return Converted;
13687     E = Converted.get();
13688     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
13689       return ExprError();
13690   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13691     // An ICE must be of integral or unscoped enumeration type.
13692     if (!Diagnoser.Suppress)
13693       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13694     return ExprError();
13695   }
13696 
13697   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
13698   // in the non-ICE case.
13699   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
13700     if (Result)
13701       *Result = E->EvaluateKnownConstInt(Context);
13702     return E;
13703   }
13704 
13705   Expr::EvalResult EvalResult;
13706   SmallVector<PartialDiagnosticAt, 8> Notes;
13707   EvalResult.Diag = &Notes;
13708 
13709   // Try to evaluate the expression, and produce diagnostics explaining why it's
13710   // not a constant expression as a side-effect.
13711   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
13712                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
13713 
13714   // In C++11, we can rely on diagnostics being produced for any expression
13715   // which is not a constant expression. If no diagnostics were produced, then
13716   // this is a constant expression.
13717   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
13718     if (Result)
13719       *Result = EvalResult.Val.getInt();
13720     return E;
13721   }
13722 
13723   // If our only note is the usual "invalid subexpression" note, just point
13724   // the caret at its location rather than producing an essentially
13725   // redundant note.
13726   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13727         diag::note_invalid_subexpr_in_const_expr) {
13728     DiagLoc = Notes[0].first;
13729     Notes.clear();
13730   }
13731 
13732   if (!Folded || !AllowFold) {
13733     if (!Diagnoser.Suppress) {
13734       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
13735       for (const PartialDiagnosticAt &Note : Notes)
13736         Diag(Note.first, Note.second);
13737     }
13738 
13739     return ExprError();
13740   }
13741 
13742   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
13743   for (const PartialDiagnosticAt &Note : Notes)
13744     Diag(Note.first, Note.second);
13745 
13746   if (Result)
13747     *Result = EvalResult.Val.getInt();
13748   return E;
13749 }
13750 
13751 namespace {
13752   // Handle the case where we conclude a expression which we speculatively
13753   // considered to be unevaluated is actually evaluated.
13754   class TransformToPE : public TreeTransform<TransformToPE> {
13755     typedef TreeTransform<TransformToPE> BaseTransform;
13756 
13757   public:
13758     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
13759 
13760     // Make sure we redo semantic analysis
13761     bool AlwaysRebuild() { return true; }
13762 
13763     // Make sure we handle LabelStmts correctly.
13764     // FIXME: This does the right thing, but maybe we need a more general
13765     // fix to TreeTransform?
13766     StmtResult TransformLabelStmt(LabelStmt *S) {
13767       S->getDecl()->setStmt(nullptr);
13768       return BaseTransform::TransformLabelStmt(S);
13769     }
13770 
13771     // We need to special-case DeclRefExprs referring to FieldDecls which
13772     // are not part of a member pointer formation; normal TreeTransforming
13773     // doesn't catch this case because of the way we represent them in the AST.
13774     // FIXME: This is a bit ugly; is it really the best way to handle this
13775     // case?
13776     //
13777     // Error on DeclRefExprs referring to FieldDecls.
13778     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
13779       if (isa<FieldDecl>(E->getDecl()) &&
13780           !SemaRef.isUnevaluatedContext())
13781         return SemaRef.Diag(E->getLocation(),
13782                             diag::err_invalid_non_static_member_use)
13783             << E->getDecl() << E->getSourceRange();
13784 
13785       return BaseTransform::TransformDeclRefExpr(E);
13786     }
13787 
13788     // Exception: filter out member pointer formation
13789     ExprResult TransformUnaryOperator(UnaryOperator *E) {
13790       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
13791         return E;
13792 
13793       return BaseTransform::TransformUnaryOperator(E);
13794     }
13795 
13796     ExprResult TransformLambdaExpr(LambdaExpr *E) {
13797       // Lambdas never need to be transformed.
13798       return E;
13799     }
13800   };
13801 }
13802 
13803 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
13804   assert(isUnevaluatedContext() &&
13805          "Should only transform unevaluated expressions");
13806   ExprEvalContexts.back().Context =
13807       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
13808   if (isUnevaluatedContext())
13809     return E;
13810   return TransformToPE(*this).TransformExpr(E);
13811 }
13812 
13813 void
13814 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13815                                       Decl *LambdaContextDecl,
13816                                       bool IsDecltype) {
13817   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
13818                                 LambdaContextDecl, IsDecltype);
13819   Cleanup.reset();
13820   if (!MaybeODRUseExprs.empty())
13821     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
13822 }
13823 
13824 void
13825 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
13826                                       ReuseLambdaContextDecl_t,
13827                                       bool IsDecltype) {
13828   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
13829   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
13830 }
13831 
13832 void Sema::PopExpressionEvaluationContext() {
13833   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
13834   unsigned NumTypos = Rec.NumTypos;
13835 
13836   if (!Rec.Lambdas.empty()) {
13837     if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13838       unsigned D;
13839       if (Rec.isUnevaluated()) {
13840         // C++11 [expr.prim.lambda]p2:
13841         //   A lambda-expression shall not appear in an unevaluated operand
13842         //   (Clause 5).
13843         D = diag::err_lambda_unevaluated_operand;
13844       } else {
13845         // C++1y [expr.const]p2:
13846         //   A conditional-expression e is a core constant expression unless the
13847         //   evaluation of e, following the rules of the abstract machine, would
13848         //   evaluate [...] a lambda-expression.
13849         D = diag::err_lambda_in_constant_expression;
13850       }
13851 
13852       // C++1z allows lambda expressions as core constant expressions.
13853       // FIXME: In C++1z, reinstate the restrictions on lambda expressions (CWG
13854       // 1607) from appearing within template-arguments and array-bounds that
13855       // are part of function-signatures.  Be mindful that P0315 (Lambdas in
13856       // unevaluated contexts) might lift some of these restrictions in a
13857       // future version.
13858       if (!Rec.isConstantEvaluated() || !getLangOpts().CPlusPlus17)
13859         for (const auto *L : Rec.Lambdas)
13860           Diag(L->getLocStart(), D);
13861     } else {
13862       // Mark the capture expressions odr-used. This was deferred
13863       // during lambda expression creation.
13864       for (auto *Lambda : Rec.Lambdas) {
13865         for (auto *C : Lambda->capture_inits())
13866           MarkDeclarationsReferencedInExpr(C);
13867       }
13868     }
13869   }
13870 
13871   // When are coming out of an unevaluated context, clear out any
13872   // temporaries that we may have created as part of the evaluation of
13873   // the expression in that context: they aren't relevant because they
13874   // will never be constructed.
13875   if (Rec.isUnevaluated() || Rec.isConstantEvaluated()) {
13876     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
13877                              ExprCleanupObjects.end());
13878     Cleanup = Rec.ParentCleanup;
13879     CleanupVarDeclMarking();
13880     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
13881   // Otherwise, merge the contexts together.
13882   } else {
13883     Cleanup.mergeFrom(Rec.ParentCleanup);
13884     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
13885                             Rec.SavedMaybeODRUseExprs.end());
13886   }
13887 
13888   // Pop the current expression evaluation context off the stack.
13889   ExprEvalContexts.pop_back();
13890 
13891   if (!ExprEvalContexts.empty())
13892     ExprEvalContexts.back().NumTypos += NumTypos;
13893   else
13894     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13895                             "last ExpressionEvaluationContextRecord");
13896 }
13897 
13898 void Sema::DiscardCleanupsInEvaluationContext() {
13899   ExprCleanupObjects.erase(
13900          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13901          ExprCleanupObjects.end());
13902   Cleanup.reset();
13903   MaybeODRUseExprs.clear();
13904 }
13905 
13906 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13907   if (!E->getType()->isVariablyModifiedType())
13908     return E;
13909   return TransformToPotentiallyEvaluated(E);
13910 }
13911 
13912 /// Are we within a context in which some evaluation could be performed (be it
13913 /// constant evaluation or runtime evaluation)? Sadly, this notion is not quite
13914 /// captured by C++'s idea of an "unevaluated context".
13915 static bool isEvaluatableContext(Sema &SemaRef) {
13916   switch (SemaRef.ExprEvalContexts.back().Context) {
13917     case Sema::ExpressionEvaluationContext::Unevaluated:
13918     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13919     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13920       // Expressions in this context are never evaluated.
13921       return false;
13922 
13923     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13924     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13925     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13926       // Expressions in this context could be evaluated.
13927       return true;
13928 
13929     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13930       // Referenced declarations will only be used if the construct in the
13931       // containing expression is used, at which point we'll be given another
13932       // turn to mark them.
13933       return false;
13934   }
13935   llvm_unreachable("Invalid context");
13936 }
13937 
13938 /// Are we within a context in which references to resolved functions or to
13939 /// variables result in odr-use?
13940 static bool isOdrUseContext(Sema &SemaRef, bool SkipDependentUses = true) {
13941   // An expression in a template is not really an expression until it's been
13942   // instantiated, so it doesn't trigger odr-use.
13943   if (SkipDependentUses && SemaRef.CurContext->isDependentContext())
13944     return false;
13945 
13946   switch (SemaRef.ExprEvalContexts.back().Context) {
13947     case Sema::ExpressionEvaluationContext::Unevaluated:
13948     case Sema::ExpressionEvaluationContext::UnevaluatedList:
13949     case Sema::ExpressionEvaluationContext::UnevaluatedAbstract:
13950     case Sema::ExpressionEvaluationContext::DiscardedStatement:
13951       return false;
13952 
13953     case Sema::ExpressionEvaluationContext::ConstantEvaluated:
13954     case Sema::ExpressionEvaluationContext::PotentiallyEvaluated:
13955       return true;
13956 
13957     case Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
13958       return false;
13959   }
13960   llvm_unreachable("Invalid context");
13961 }
13962 
13963 static bool isImplicitlyDefinableConstexprFunction(FunctionDecl *Func) {
13964   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13965   return Func->isConstexpr() &&
13966          (Func->isImplicitlyInstantiable() || (MD && !MD->isUserProvided()));
13967 }
13968 
13969 /// \brief Mark a function referenced, and check whether it is odr-used
13970 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13971 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13972                                   bool MightBeOdrUse) {
13973   assert(Func && "No function?");
13974 
13975   Func->setReferenced();
13976 
13977   // C++11 [basic.def.odr]p3:
13978   //   A function whose name appears as a potentially-evaluated expression is
13979   //   odr-used if it is the unique lookup result or the selected member of a
13980   //   set of overloaded functions [...].
13981   //
13982   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13983   // can just check that here.
13984   bool OdrUse = MightBeOdrUse && isOdrUseContext(*this);
13985 
13986   // Determine whether we require a function definition to exist, per
13987   // C++11 [temp.inst]p3:
13988   //   Unless a function template specialization has been explicitly
13989   //   instantiated or explicitly specialized, the function template
13990   //   specialization is implicitly instantiated when the specialization is
13991   //   referenced in a context that requires a function definition to exist.
13992   //
13993   // That is either when this is an odr-use, or when a usage of a constexpr
13994   // function occurs within an evaluatable context.
13995   bool NeedDefinition =
13996       OdrUse || (isEvaluatableContext(*this) &&
13997                  isImplicitlyDefinableConstexprFunction(Func));
13998 
13999   // C++14 [temp.expl.spec]p6:
14000   //   If a template [...] is explicitly specialized then that specialization
14001   //   shall be declared before the first use of that specialization that would
14002   //   cause an implicit instantiation to take place, in every translation unit
14003   //   in which such a use occurs
14004   if (NeedDefinition &&
14005       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
14006        Func->getMemberSpecializationInfo()))
14007     checkSpecializationVisibility(Loc, Func);
14008 
14009   // C++14 [except.spec]p17:
14010   //   An exception-specification is considered to be needed when:
14011   //   - the function is odr-used or, if it appears in an unevaluated operand,
14012   //     would be odr-used if the expression were potentially-evaluated;
14013   //
14014   // Note, we do this even if MightBeOdrUse is false. That indicates that the
14015   // function is a pure virtual function we're calling, and in that case the
14016   // function was selected by overload resolution and we need to resolve its
14017   // exception specification for a different reason.
14018   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
14019   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
14020     ResolveExceptionSpec(Loc, FPT);
14021 
14022   // If we don't need to mark the function as used, and we don't need to
14023   // try to provide a definition, there's nothing more to do.
14024   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
14025       (!NeedDefinition || Func->getBody()))
14026     return;
14027 
14028   // Note that this declaration has been used.
14029   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
14030     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
14031     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
14032       if (Constructor->isDefaultConstructor()) {
14033         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
14034           return;
14035         DefineImplicitDefaultConstructor(Loc, Constructor);
14036       } else if (Constructor->isCopyConstructor()) {
14037         DefineImplicitCopyConstructor(Loc, Constructor);
14038       } else if (Constructor->isMoveConstructor()) {
14039         DefineImplicitMoveConstructor(Loc, Constructor);
14040       }
14041     } else if (Constructor->getInheritedConstructor()) {
14042       DefineInheritingConstructor(Loc, Constructor);
14043     }
14044   } else if (CXXDestructorDecl *Destructor =
14045                  dyn_cast<CXXDestructorDecl>(Func)) {
14046     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
14047     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
14048       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
14049         return;
14050       DefineImplicitDestructor(Loc, Destructor);
14051     }
14052     if (Destructor->isVirtual() && getLangOpts().AppleKext)
14053       MarkVTableUsed(Loc, Destructor->getParent());
14054   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
14055     if (MethodDecl->isOverloadedOperator() &&
14056         MethodDecl->getOverloadedOperator() == OO_Equal) {
14057       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
14058       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
14059         if (MethodDecl->isCopyAssignmentOperator())
14060           DefineImplicitCopyAssignment(Loc, MethodDecl);
14061         else if (MethodDecl->isMoveAssignmentOperator())
14062           DefineImplicitMoveAssignment(Loc, MethodDecl);
14063       }
14064     } else if (isa<CXXConversionDecl>(MethodDecl) &&
14065                MethodDecl->getParent()->isLambda()) {
14066       CXXConversionDecl *Conversion =
14067           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
14068       if (Conversion->isLambdaToBlockPointerConversion())
14069         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
14070       else
14071         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
14072     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
14073       MarkVTableUsed(Loc, MethodDecl->getParent());
14074   }
14075 
14076   // Recursive functions should be marked when used from another function.
14077   // FIXME: Is this really right?
14078   if (CurContext == Func) return;
14079 
14080   // Implicit instantiation of function templates and member functions of
14081   // class templates.
14082   if (Func->isImplicitlyInstantiable()) {
14083     TemplateSpecializationKind TSK = Func->getTemplateSpecializationKind();
14084     SourceLocation PointOfInstantiation = Func->getPointOfInstantiation();
14085     bool FirstInstantiation = PointOfInstantiation.isInvalid();
14086     if (FirstInstantiation) {
14087       PointOfInstantiation = Loc;
14088       Func->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14089     } else if (TSK != TSK_ImplicitInstantiation) {
14090       // Use the point of use as the point of instantiation, instead of the
14091       // point of explicit instantiation (which we track as the actual point of
14092       // instantiation). This gives better backtraces in diagnostics.
14093       PointOfInstantiation = Loc;
14094     }
14095 
14096     if (FirstInstantiation || TSK != TSK_ImplicitInstantiation ||
14097         Func->isConstexpr()) {
14098       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
14099           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
14100           CodeSynthesisContexts.size())
14101         PendingLocalImplicitInstantiations.push_back(
14102             std::make_pair(Func, PointOfInstantiation));
14103       else if (Func->isConstexpr())
14104         // Do not defer instantiations of constexpr functions, to avoid the
14105         // expression evaluator needing to call back into Sema if it sees a
14106         // call to such a function.
14107         InstantiateFunctionDefinition(PointOfInstantiation, Func);
14108       else {
14109         Func->setInstantiationIsPending(true);
14110         PendingInstantiations.push_back(std::make_pair(Func,
14111                                                        PointOfInstantiation));
14112         // Notify the consumer that a function was implicitly instantiated.
14113         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
14114       }
14115     }
14116   } else {
14117     // Walk redefinitions, as some of them may be instantiable.
14118     for (auto i : Func->redecls()) {
14119       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
14120         MarkFunctionReferenced(Loc, i, OdrUse);
14121     }
14122   }
14123 
14124   if (!OdrUse) return;
14125 
14126   // Keep track of used but undefined functions.
14127   if (!Func->isDefined()) {
14128     if (mightHaveNonExternalLinkage(Func))
14129       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14130     else if (Func->getMostRecentDecl()->isInlined() &&
14131              !LangOpts.GNUInline &&
14132              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
14133       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14134     else if (isExternalWithNoLinkageType(Func))
14135       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
14136   }
14137 
14138   Func->markUsed(Context);
14139 }
14140 
14141 static void
14142 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
14143                                    ValueDecl *var, DeclContext *DC) {
14144   DeclContext *VarDC = var->getDeclContext();
14145 
14146   //  If the parameter still belongs to the translation unit, then
14147   //  we're actually just using one parameter in the declaration of
14148   //  the next.
14149   if (isa<ParmVarDecl>(var) &&
14150       isa<TranslationUnitDecl>(VarDC))
14151     return;
14152 
14153   // For C code, don't diagnose about capture if we're not actually in code
14154   // right now; it's impossible to write a non-constant expression outside of
14155   // function context, so we'll get other (more useful) diagnostics later.
14156   //
14157   // For C++, things get a bit more nasty... it would be nice to suppress this
14158   // diagnostic for certain cases like using a local variable in an array bound
14159   // for a member of a local class, but the correct predicate is not obvious.
14160   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
14161     return;
14162 
14163   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
14164   unsigned ContextKind = 3; // unknown
14165   if (isa<CXXMethodDecl>(VarDC) &&
14166       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
14167     ContextKind = 2;
14168   } else if (isa<FunctionDecl>(VarDC)) {
14169     ContextKind = 0;
14170   } else if (isa<BlockDecl>(VarDC)) {
14171     ContextKind = 1;
14172   }
14173 
14174   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
14175     << var << ValueKind << ContextKind << VarDC;
14176   S.Diag(var->getLocation(), diag::note_entity_declared_at)
14177       << var;
14178 
14179   // FIXME: Add additional diagnostic info about class etc. which prevents
14180   // capture.
14181 }
14182 
14183 
14184 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
14185                                       bool &SubCapturesAreNested,
14186                                       QualType &CaptureType,
14187                                       QualType &DeclRefType) {
14188    // Check whether we've already captured it.
14189   if (CSI->CaptureMap.count(Var)) {
14190     // If we found a capture, any subcaptures are nested.
14191     SubCapturesAreNested = true;
14192 
14193     // Retrieve the capture type for this variable.
14194     CaptureType = CSI->getCapture(Var).getCaptureType();
14195 
14196     // Compute the type of an expression that refers to this variable.
14197     DeclRefType = CaptureType.getNonReferenceType();
14198 
14199     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
14200     // are mutable in the sense that user can change their value - they are
14201     // private instances of the captured declarations.
14202     const Capture &Cap = CSI->getCapture(Var);
14203     if (Cap.isCopyCapture() &&
14204         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
14205         !(isa<CapturedRegionScopeInfo>(CSI) &&
14206           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
14207       DeclRefType.addConst();
14208     return true;
14209   }
14210   return false;
14211 }
14212 
14213 // Only block literals, captured statements, and lambda expressions can
14214 // capture; other scopes don't work.
14215 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
14216                                  SourceLocation Loc,
14217                                  const bool Diagnose, Sema &S) {
14218   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
14219     return getLambdaAwareParentOfDeclContext(DC);
14220   else if (Var->hasLocalStorage()) {
14221     if (Diagnose)
14222        diagnoseUncapturableValueReference(S, Loc, Var, DC);
14223   }
14224   return nullptr;
14225 }
14226 
14227 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14228 // certain types of variables (unnamed, variably modified types etc.)
14229 // so check for eligibility.
14230 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
14231                                  SourceLocation Loc,
14232                                  const bool Diagnose, Sema &S) {
14233 
14234   bool IsBlock = isa<BlockScopeInfo>(CSI);
14235   bool IsLambda = isa<LambdaScopeInfo>(CSI);
14236 
14237   // Lambdas are not allowed to capture unnamed variables
14238   // (e.g. anonymous unions).
14239   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
14240   // assuming that's the intent.
14241   if (IsLambda && !Var->getDeclName()) {
14242     if (Diagnose) {
14243       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
14244       S.Diag(Var->getLocation(), diag::note_declared_at);
14245     }
14246     return false;
14247   }
14248 
14249   // Prohibit variably-modified types in blocks; they're difficult to deal with.
14250   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
14251     if (Diagnose) {
14252       S.Diag(Loc, diag::err_ref_vm_type);
14253       S.Diag(Var->getLocation(), diag::note_previous_decl)
14254         << Var->getDeclName();
14255     }
14256     return false;
14257   }
14258   // Prohibit structs with flexible array members too.
14259   // We cannot capture what is in the tail end of the struct.
14260   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
14261     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
14262       if (Diagnose) {
14263         if (IsBlock)
14264           S.Diag(Loc, diag::err_ref_flexarray_type);
14265         else
14266           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
14267             << Var->getDeclName();
14268         S.Diag(Var->getLocation(), diag::note_previous_decl)
14269           << Var->getDeclName();
14270       }
14271       return false;
14272     }
14273   }
14274   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14275   // Lambdas and captured statements are not allowed to capture __block
14276   // variables; they don't support the expected semantics.
14277   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
14278     if (Diagnose) {
14279       S.Diag(Loc, diag::err_capture_block_variable)
14280         << Var->getDeclName() << !IsLambda;
14281       S.Diag(Var->getLocation(), diag::note_previous_decl)
14282         << Var->getDeclName();
14283     }
14284     return false;
14285   }
14286   // OpenCL v2.0 s6.12.5: Blocks cannot reference/capture other blocks
14287   if (S.getLangOpts().OpenCL && IsBlock &&
14288       Var->getType()->isBlockPointerType()) {
14289     if (Diagnose)
14290       S.Diag(Loc, diag::err_opencl_block_ref_block);
14291     return false;
14292   }
14293 
14294   return true;
14295 }
14296 
14297 // Returns true if the capture by block was successful.
14298 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
14299                                  SourceLocation Loc,
14300                                  const bool BuildAndDiagnose,
14301                                  QualType &CaptureType,
14302                                  QualType &DeclRefType,
14303                                  const bool Nested,
14304                                  Sema &S) {
14305   Expr *CopyExpr = nullptr;
14306   bool ByRef = false;
14307 
14308   // Blocks are not allowed to capture arrays.
14309   if (CaptureType->isArrayType()) {
14310     if (BuildAndDiagnose) {
14311       S.Diag(Loc, diag::err_ref_array_type);
14312       S.Diag(Var->getLocation(), diag::note_previous_decl)
14313       << Var->getDeclName();
14314     }
14315     return false;
14316   }
14317 
14318   // Forbid the block-capture of autoreleasing variables.
14319   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14320     if (BuildAndDiagnose) {
14321       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
14322         << /*block*/ 0;
14323       S.Diag(Var->getLocation(), diag::note_previous_decl)
14324         << Var->getDeclName();
14325     }
14326     return false;
14327   }
14328 
14329   // Warn about implicitly autoreleasing indirect parameters captured by blocks.
14330   if (const auto *PT = CaptureType->getAs<PointerType>()) {
14331     // This function finds out whether there is an AttributedType of kind
14332     // attr_objc_ownership in Ty. The existence of AttributedType of kind
14333     // attr_objc_ownership implies __autoreleasing was explicitly specified
14334     // rather than being added implicitly by the compiler.
14335     auto IsObjCOwnershipAttributedType = [](QualType Ty) {
14336       while (const auto *AttrTy = Ty->getAs<AttributedType>()) {
14337         if (AttrTy->getAttrKind() == AttributedType::attr_objc_ownership)
14338           return true;
14339 
14340         // Peel off AttributedTypes that are not of kind objc_ownership.
14341         Ty = AttrTy->getModifiedType();
14342       }
14343 
14344       return false;
14345     };
14346 
14347     QualType PointeeTy = PT->getPointeeType();
14348 
14349     if (PointeeTy->getAs<ObjCObjectPointerType>() &&
14350         PointeeTy.getObjCLifetime() == Qualifiers::OCL_Autoreleasing &&
14351         !IsObjCOwnershipAttributedType(PointeeTy)) {
14352       if (BuildAndDiagnose) {
14353         SourceLocation VarLoc = Var->getLocation();
14354         S.Diag(Loc, diag::warn_block_capture_autoreleasing);
14355         {
14356           auto AddAutoreleaseNote =
14357               S.Diag(VarLoc, diag::note_declare_parameter_autoreleasing);
14358           // Provide a fix-it for the '__autoreleasing' keyword at the
14359           // appropriate location in the variable's type.
14360           if (const auto *TSI = Var->getTypeSourceInfo()) {
14361             PointerTypeLoc PTL =
14362                 TSI->getTypeLoc().getAsAdjusted<PointerTypeLoc>();
14363             if (PTL) {
14364               SourceLocation Loc = PTL.getPointeeLoc().getEndLoc();
14365               Loc = Lexer::getLocForEndOfToken(Loc, 0, S.getSourceManager(),
14366                                                S.getLangOpts());
14367               if (Loc.isValid()) {
14368                 StringRef CharAtLoc = Lexer::getSourceText(
14369                     CharSourceRange::getCharRange(Loc, Loc.getLocWithOffset(1)),
14370                     S.getSourceManager(), S.getLangOpts());
14371                 AddAutoreleaseNote << FixItHint::CreateInsertion(
14372                     Loc, CharAtLoc.empty() || !isWhitespace(CharAtLoc[0])
14373                              ? " __autoreleasing "
14374                              : " __autoreleasing");
14375               }
14376             }
14377           }
14378         }
14379         S.Diag(VarLoc, diag::note_declare_parameter_strong);
14380       }
14381     }
14382   }
14383 
14384   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
14385   if (HasBlocksAttr || CaptureType->isReferenceType() ||
14386       (S.getLangOpts().OpenMP && S.isOpenMPCapturedDecl(Var))) {
14387     // Block capture by reference does not change the capture or
14388     // declaration reference types.
14389     ByRef = true;
14390   } else {
14391     // Block capture by copy introduces 'const'.
14392     CaptureType = CaptureType.getNonReferenceType().withConst();
14393     DeclRefType = CaptureType;
14394 
14395     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
14396       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
14397         // The capture logic needs the destructor, so make sure we mark it.
14398         // Usually this is unnecessary because most local variables have
14399         // their destructors marked at declaration time, but parameters are
14400         // an exception because it's technically only the call site that
14401         // actually requires the destructor.
14402         if (isa<ParmVarDecl>(Var))
14403           S.FinalizeVarWithDestructor(Var, Record);
14404 
14405         // Enter a new evaluation context to insulate the copy
14406         // full-expression.
14407         EnterExpressionEvaluationContext scope(
14408             S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
14409 
14410         // According to the blocks spec, the capture of a variable from
14411         // the stack requires a const copy constructor.  This is not true
14412         // of the copy/move done to move a __block variable to the heap.
14413         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
14414                                                   DeclRefType.withConst(),
14415                                                   VK_LValue, Loc);
14416 
14417         ExprResult Result
14418           = S.PerformCopyInitialization(
14419               InitializedEntity::InitializeBlock(Var->getLocation(),
14420                                                   CaptureType, false),
14421               Loc, DeclRef);
14422 
14423         // Build a full-expression copy expression if initialization
14424         // succeeded and used a non-trivial constructor.  Recover from
14425         // errors by pretending that the copy isn't necessary.
14426         if (!Result.isInvalid() &&
14427             !cast<CXXConstructExpr>(Result.get())->getConstructor()
14428                 ->isTrivial()) {
14429           Result = S.MaybeCreateExprWithCleanups(Result);
14430           CopyExpr = Result.get();
14431         }
14432       }
14433     }
14434   }
14435 
14436   // Actually capture the variable.
14437   if (BuildAndDiagnose)
14438     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
14439                     SourceLocation(), CaptureType, CopyExpr);
14440 
14441   return true;
14442 
14443 }
14444 
14445 
14446 /// \brief Capture the given variable in the captured region.
14447 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
14448                                     VarDecl *Var,
14449                                     SourceLocation Loc,
14450                                     const bool BuildAndDiagnose,
14451                                     QualType &CaptureType,
14452                                     QualType &DeclRefType,
14453                                     const bool RefersToCapturedVariable,
14454                                     Sema &S) {
14455   // By default, capture variables by reference.
14456   bool ByRef = true;
14457   // Using an LValue reference type is consistent with Lambdas (see below).
14458   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
14459     if (S.isOpenMPCapturedDecl(Var)) {
14460       bool HasConst = DeclRefType.isConstQualified();
14461       DeclRefType = DeclRefType.getUnqualifiedType();
14462       // Don't lose diagnostics about assignments to const.
14463       if (HasConst)
14464         DeclRefType.addConst();
14465     }
14466     ByRef = S.isOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
14467   }
14468 
14469   if (ByRef)
14470     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14471   else
14472     CaptureType = DeclRefType;
14473 
14474   Expr *CopyExpr = nullptr;
14475   if (BuildAndDiagnose) {
14476     // The current implementation assumes that all variables are captured
14477     // by references. Since there is no capture by copy, no expression
14478     // evaluation will be needed.
14479     RecordDecl *RD = RSI->TheRecordDecl;
14480 
14481     FieldDecl *Field
14482       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
14483                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
14484                           nullptr, false, ICIS_NoInit);
14485     Field->setImplicit(true);
14486     Field->setAccess(AS_private);
14487     RD->addDecl(Field);
14488     if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP)
14489       S.setOpenMPCaptureKind(Field, Var, RSI->OpenMPLevel);
14490 
14491     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
14492                                             DeclRefType, VK_LValue, Loc);
14493     Var->setReferenced(true);
14494     Var->markUsed(S.Context);
14495   }
14496 
14497   // Actually capture the variable.
14498   if (BuildAndDiagnose)
14499     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
14500                     SourceLocation(), CaptureType, CopyExpr);
14501 
14502 
14503   return true;
14504 }
14505 
14506 /// \brief Create a field within the lambda class for the variable
14507 /// being captured.
14508 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
14509                                     QualType FieldType, QualType DeclRefType,
14510                                     SourceLocation Loc,
14511                                     bool RefersToCapturedVariable) {
14512   CXXRecordDecl *Lambda = LSI->Lambda;
14513 
14514   // Build the non-static data member.
14515   FieldDecl *Field
14516     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
14517                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
14518                         nullptr, false, ICIS_NoInit);
14519   Field->setImplicit(true);
14520   Field->setAccess(AS_private);
14521   Lambda->addDecl(Field);
14522 }
14523 
14524 /// \brief Capture the given variable in the lambda.
14525 static bool captureInLambda(LambdaScopeInfo *LSI,
14526                             VarDecl *Var,
14527                             SourceLocation Loc,
14528                             const bool BuildAndDiagnose,
14529                             QualType &CaptureType,
14530                             QualType &DeclRefType,
14531                             const bool RefersToCapturedVariable,
14532                             const Sema::TryCaptureKind Kind,
14533                             SourceLocation EllipsisLoc,
14534                             const bool IsTopScope,
14535                             Sema &S) {
14536 
14537   // Determine whether we are capturing by reference or by value.
14538   bool ByRef = false;
14539   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
14540     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
14541   } else {
14542     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
14543   }
14544 
14545   // Compute the type of the field that will capture this variable.
14546   if (ByRef) {
14547     // C++11 [expr.prim.lambda]p15:
14548     //   An entity is captured by reference if it is implicitly or
14549     //   explicitly captured but not captured by copy. It is
14550     //   unspecified whether additional unnamed non-static data
14551     //   members are declared in the closure type for entities
14552     //   captured by reference.
14553     //
14554     // FIXME: It is not clear whether we want to build an lvalue reference
14555     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
14556     // to do the former, while EDG does the latter. Core issue 1249 will
14557     // clarify, but for now we follow GCC because it's a more permissive and
14558     // easily defensible position.
14559     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
14560   } else {
14561     // C++11 [expr.prim.lambda]p14:
14562     //   For each entity captured by copy, an unnamed non-static
14563     //   data member is declared in the closure type. The
14564     //   declaration order of these members is unspecified. The type
14565     //   of such a data member is the type of the corresponding
14566     //   captured entity if the entity is not a reference to an
14567     //   object, or the referenced type otherwise. [Note: If the
14568     //   captured entity is a reference to a function, the
14569     //   corresponding data member is also a reference to a
14570     //   function. - end note ]
14571     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
14572       if (!RefType->getPointeeType()->isFunctionType())
14573         CaptureType = RefType->getPointeeType();
14574     }
14575 
14576     // Forbid the lambda copy-capture of autoreleasing variables.
14577     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
14578       if (BuildAndDiagnose) {
14579         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
14580         S.Diag(Var->getLocation(), diag::note_previous_decl)
14581           << Var->getDeclName();
14582       }
14583       return false;
14584     }
14585 
14586     // Make sure that by-copy captures are of a complete and non-abstract type.
14587     if (BuildAndDiagnose) {
14588       if (!CaptureType->isDependentType() &&
14589           S.RequireCompleteType(Loc, CaptureType,
14590                                 diag::err_capture_of_incomplete_type,
14591                                 Var->getDeclName()))
14592         return false;
14593 
14594       if (S.RequireNonAbstractType(Loc, CaptureType,
14595                                    diag::err_capture_of_abstract_type))
14596         return false;
14597     }
14598   }
14599 
14600   // Capture this variable in the lambda.
14601   if (BuildAndDiagnose)
14602     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
14603                             RefersToCapturedVariable);
14604 
14605   // Compute the type of a reference to this captured variable.
14606   if (ByRef)
14607     DeclRefType = CaptureType.getNonReferenceType();
14608   else {
14609     // C++ [expr.prim.lambda]p5:
14610     //   The closure type for a lambda-expression has a public inline
14611     //   function call operator [...]. This function call operator is
14612     //   declared const (9.3.1) if and only if the lambda-expression's
14613     //   parameter-declaration-clause is not followed by mutable.
14614     DeclRefType = CaptureType.getNonReferenceType();
14615     if (!LSI->Mutable && !CaptureType->isReferenceType())
14616       DeclRefType.addConst();
14617   }
14618 
14619   // Add the capture.
14620   if (BuildAndDiagnose)
14621     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
14622                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
14623 
14624   return true;
14625 }
14626 
14627 bool Sema::tryCaptureVariable(
14628     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
14629     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
14630     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
14631   // An init-capture is notionally from the context surrounding its
14632   // declaration, but its parent DC is the lambda class.
14633   DeclContext *VarDC = Var->getDeclContext();
14634   if (Var->isInitCapture())
14635     VarDC = VarDC->getParent();
14636 
14637   DeclContext *DC = CurContext;
14638   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
14639       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
14640   // We need to sync up the Declaration Context with the
14641   // FunctionScopeIndexToStopAt
14642   if (FunctionScopeIndexToStopAt) {
14643     unsigned FSIndex = FunctionScopes.size() - 1;
14644     while (FSIndex != MaxFunctionScopesIndex) {
14645       DC = getLambdaAwareParentOfDeclContext(DC);
14646       --FSIndex;
14647     }
14648   }
14649 
14650 
14651   // If the variable is declared in the current context, there is no need to
14652   // capture it.
14653   if (VarDC == DC) return true;
14654 
14655   // Capture global variables if it is required to use private copy of this
14656   // variable.
14657   bool IsGlobal = !Var->hasLocalStorage();
14658   if (IsGlobal && !(LangOpts.OpenMP && isOpenMPCapturedDecl(Var)))
14659     return true;
14660   Var = Var->getCanonicalDecl();
14661 
14662   // Walk up the stack to determine whether we can capture the variable,
14663   // performing the "simple" checks that don't depend on type. We stop when
14664   // we've either hit the declared scope of the variable or find an existing
14665   // capture of that variable.  We start from the innermost capturing-entity
14666   // (the DC) and ensure that all intervening capturing-entities
14667   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
14668   // declcontext can either capture the variable or have already captured
14669   // the variable.
14670   CaptureType = Var->getType();
14671   DeclRefType = CaptureType.getNonReferenceType();
14672   bool Nested = false;
14673   bool Explicit = (Kind != TryCapture_Implicit);
14674   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
14675   do {
14676     // Only block literals, captured statements, and lambda expressions can
14677     // capture; other scopes don't work.
14678     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
14679                                                               ExprLoc,
14680                                                               BuildAndDiagnose,
14681                                                               *this);
14682     // We need to check for the parent *first* because, if we *have*
14683     // private-captured a global variable, we need to recursively capture it in
14684     // intermediate blocks, lambdas, etc.
14685     if (!ParentDC) {
14686       if (IsGlobal) {
14687         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
14688         break;
14689       }
14690       return true;
14691     }
14692 
14693     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
14694     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
14695 
14696 
14697     // Check whether we've already captured it.
14698     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
14699                                              DeclRefType)) {
14700       CSI->getCapture(Var).markUsed(BuildAndDiagnose);
14701       break;
14702     }
14703     // If we are instantiating a generic lambda call operator body,
14704     // we do not want to capture new variables.  What was captured
14705     // during either a lambdas transformation or initial parsing
14706     // should be used.
14707     if (isGenericLambdaCallOperatorSpecialization(DC)) {
14708       if (BuildAndDiagnose) {
14709         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14710         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
14711           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14712           Diag(Var->getLocation(), diag::note_previous_decl)
14713              << Var->getDeclName();
14714           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
14715         } else
14716           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
14717       }
14718       return true;
14719     }
14720     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
14721     // certain types of variables (unnamed, variably modified types etc.)
14722     // so check for eligibility.
14723     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
14724        return true;
14725 
14726     // Try to capture variable-length arrays types.
14727     if (Var->getType()->isVariablyModifiedType()) {
14728       // We're going to walk down into the type and look for VLA
14729       // expressions.
14730       QualType QTy = Var->getType();
14731       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
14732         QTy = PVD->getOriginalType();
14733       captureVariablyModifiedType(Context, QTy, CSI);
14734     }
14735 
14736     if (getLangOpts().OpenMP) {
14737       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14738         // OpenMP private variables should not be captured in outer scope, so
14739         // just break here. Similarly, global variables that are captured in a
14740         // target region should not be captured outside the scope of the region.
14741         if (RSI->CapRegionKind == CR_OpenMP) {
14742           bool IsOpenMPPrivateDecl = isOpenMPPrivateDecl(Var, RSI->OpenMPLevel);
14743           auto IsTargetCap = !IsOpenMPPrivateDecl &&
14744                              isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
14745           // When we detect target captures we are looking from inside the
14746           // target region, therefore we need to propagate the capture from the
14747           // enclosing region. Therefore, the capture is not initially nested.
14748           if (IsTargetCap)
14749             adjustOpenMPTargetScopeIndex(FunctionScopesIndex, RSI->OpenMPLevel);
14750 
14751           if (IsTargetCap || IsOpenMPPrivateDecl) {
14752             Nested = !IsTargetCap;
14753             DeclRefType = DeclRefType.getUnqualifiedType();
14754             CaptureType = Context.getLValueReferenceType(DeclRefType);
14755             break;
14756           }
14757         }
14758       }
14759     }
14760     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
14761       // No capture-default, and this is not an explicit capture
14762       // so cannot capture this variable.
14763       if (BuildAndDiagnose) {
14764         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
14765         Diag(Var->getLocation(), diag::note_previous_decl)
14766           << Var->getDeclName();
14767         if (cast<LambdaScopeInfo>(CSI)->Lambda)
14768           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
14769                diag::note_lambda_decl);
14770         // FIXME: If we error out because an outer lambda can not implicitly
14771         // capture a variable that an inner lambda explicitly captures, we
14772         // should have the inner lambda do the explicit capture - because
14773         // it makes for cleaner diagnostics later.  This would purely be done
14774         // so that the diagnostic does not misleadingly claim that a variable
14775         // can not be captured by a lambda implicitly even though it is captured
14776         // explicitly.  Suggestion:
14777         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
14778         //    at the function head
14779         //  - cache the StartingDeclContext - this must be a lambda
14780         //  - captureInLambda in the innermost lambda the variable.
14781       }
14782       return true;
14783     }
14784 
14785     FunctionScopesIndex--;
14786     DC = ParentDC;
14787     Explicit = false;
14788   } while (!VarDC->Equals(DC));
14789 
14790   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
14791   // computing the type of the capture at each step, checking type-specific
14792   // requirements, and adding captures if requested.
14793   // If the variable had already been captured previously, we start capturing
14794   // at the lambda nested within that one.
14795   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
14796        ++I) {
14797     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
14798 
14799     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
14800       if (!captureInBlock(BSI, Var, ExprLoc,
14801                           BuildAndDiagnose, CaptureType,
14802                           DeclRefType, Nested, *this))
14803         return true;
14804       Nested = true;
14805     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
14806       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
14807                                    BuildAndDiagnose, CaptureType,
14808                                    DeclRefType, Nested, *this))
14809         return true;
14810       Nested = true;
14811     } else {
14812       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
14813       if (!captureInLambda(LSI, Var, ExprLoc,
14814                            BuildAndDiagnose, CaptureType,
14815                            DeclRefType, Nested, Kind, EllipsisLoc,
14816                             /*IsTopScope*/I == N - 1, *this))
14817         return true;
14818       Nested = true;
14819     }
14820   }
14821   return false;
14822 }
14823 
14824 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
14825                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
14826   QualType CaptureType;
14827   QualType DeclRefType;
14828   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
14829                             /*BuildAndDiagnose=*/true, CaptureType,
14830                             DeclRefType, nullptr);
14831 }
14832 
14833 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
14834   QualType CaptureType;
14835   QualType DeclRefType;
14836   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14837                              /*BuildAndDiagnose=*/false, CaptureType,
14838                              DeclRefType, nullptr);
14839 }
14840 
14841 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
14842   QualType CaptureType;
14843   QualType DeclRefType;
14844 
14845   // Determine whether we can capture this variable.
14846   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
14847                          /*BuildAndDiagnose=*/false, CaptureType,
14848                          DeclRefType, nullptr))
14849     return QualType();
14850 
14851   return DeclRefType;
14852 }
14853 
14854 
14855 
14856 // If either the type of the variable or the initializer is dependent,
14857 // return false. Otherwise, determine whether the variable is a constant
14858 // expression. Use this if you need to know if a variable that might or
14859 // might not be dependent is truly a constant expression.
14860 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
14861     ASTContext &Context) {
14862 
14863   if (Var->getType()->isDependentType())
14864     return false;
14865   const VarDecl *DefVD = nullptr;
14866   Var->getAnyInitializer(DefVD);
14867   if (!DefVD)
14868     return false;
14869   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
14870   Expr *Init = cast<Expr>(Eval->Value);
14871   if (Init->isValueDependent())
14872     return false;
14873   return IsVariableAConstantExpression(Var, Context);
14874 }
14875 
14876 
14877 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
14878   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
14879   // an object that satisfies the requirements for appearing in a
14880   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
14881   // is immediately applied."  This function handles the lvalue-to-rvalue
14882   // conversion part.
14883   MaybeODRUseExprs.erase(E->IgnoreParens());
14884 
14885   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
14886   // to a variable that is a constant expression, and if so, identify it as
14887   // a reference to a variable that does not involve an odr-use of that
14888   // variable.
14889   if (LambdaScopeInfo *LSI = getCurLambda()) {
14890     Expr *SansParensExpr = E->IgnoreParens();
14891     VarDecl *Var = nullptr;
14892     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
14893       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
14894     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
14895       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
14896 
14897     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
14898       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
14899   }
14900 }
14901 
14902 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
14903   Res = CorrectDelayedTyposInExpr(Res);
14904 
14905   if (!Res.isUsable())
14906     return Res;
14907 
14908   // If a constant-expression is a reference to a variable where we delay
14909   // deciding whether it is an odr-use, just assume we will apply the
14910   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
14911   // (a non-type template argument), we have special handling anyway.
14912   UpdateMarkingForLValueToRValue(Res.get());
14913   return Res;
14914 }
14915 
14916 void Sema::CleanupVarDeclMarking() {
14917   for (Expr *E : MaybeODRUseExprs) {
14918     VarDecl *Var;
14919     SourceLocation Loc;
14920     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14921       Var = cast<VarDecl>(DRE->getDecl());
14922       Loc = DRE->getLocation();
14923     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
14924       Var = cast<VarDecl>(ME->getMemberDecl());
14925       Loc = ME->getMemberLoc();
14926     } else {
14927       llvm_unreachable("Unexpected expression");
14928     }
14929 
14930     MarkVarDeclODRUsed(Var, Loc, *this,
14931                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
14932   }
14933 
14934   MaybeODRUseExprs.clear();
14935 }
14936 
14937 
14938 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
14939                                     VarDecl *Var, Expr *E) {
14940   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
14941          "Invalid Expr argument to DoMarkVarDeclReferenced");
14942   Var->setReferenced();
14943 
14944   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
14945 
14946   bool OdrUseContext = isOdrUseContext(SemaRef);
14947   bool UsableInConstantExpr =
14948       Var->isUsableInConstantExpressions(SemaRef.Context);
14949   bool NeedDefinition =
14950       OdrUseContext || (isEvaluatableContext(SemaRef) && UsableInConstantExpr);
14951 
14952   VarTemplateSpecializationDecl *VarSpec =
14953       dyn_cast<VarTemplateSpecializationDecl>(Var);
14954   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14955          "Can't instantiate a partial template specialization.");
14956 
14957   // If this might be a member specialization of a static data member, check
14958   // the specialization is visible. We already did the checks for variable
14959   // template specializations when we created them.
14960   if (NeedDefinition && TSK != TSK_Undeclared &&
14961       !isa<VarTemplateSpecializationDecl>(Var))
14962     SemaRef.checkSpecializationVisibility(Loc, Var);
14963 
14964   // Perform implicit instantiation of static data members, static data member
14965   // templates of class templates, and variable template specializations. Delay
14966   // instantiations of variable templates, except for those that could be used
14967   // in a constant expression.
14968   if (NeedDefinition && isTemplateInstantiation(TSK)) {
14969     // Per C++17 [temp.explicit]p10, we may instantiate despite an explicit
14970     // instantiation declaration if a variable is usable in a constant
14971     // expression (among other cases).
14972     bool TryInstantiating =
14973         TSK == TSK_ImplicitInstantiation ||
14974         (TSK == TSK_ExplicitInstantiationDeclaration && UsableInConstantExpr);
14975 
14976     if (TryInstantiating) {
14977       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14978       bool FirstInstantiation = PointOfInstantiation.isInvalid();
14979       if (FirstInstantiation) {
14980         PointOfInstantiation = Loc;
14981         Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
14982       }
14983 
14984       bool InstantiationDependent = false;
14985       bool IsNonDependent =
14986           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14987                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14988                   : true;
14989 
14990       // Do not instantiate specializations that are still type-dependent.
14991       if (IsNonDependent) {
14992         if (UsableInConstantExpr) {
14993           // Do not defer instantiations of variables that could be used in a
14994           // constant expression.
14995           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14996         } else if (FirstInstantiation ||
14997                    isa<VarTemplateSpecializationDecl>(Var)) {
14998           // FIXME: For a specialization of a variable template, we don't
14999           // distinguish between "declaration and type implicitly instantiated"
15000           // and "implicit instantiation of definition requested", so we have
15001           // no direct way to avoid enqueueing the pending instantiation
15002           // multiple times.
15003           SemaRef.PendingInstantiations
15004               .push_back(std::make_pair(Var, PointOfInstantiation));
15005         }
15006       }
15007     }
15008   }
15009 
15010   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
15011   // the requirements for appearing in a constant expression (5.19) and, if
15012   // it is an object, the lvalue-to-rvalue conversion (4.1)
15013   // is immediately applied."  We check the first part here, and
15014   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
15015   // Note that we use the C++11 definition everywhere because nothing in
15016   // C++03 depends on whether we get the C++03 version correct. The second
15017   // part does not apply to references, since they are not objects.
15018   if (OdrUseContext && E &&
15019       IsVariableAConstantExpression(Var, SemaRef.Context)) {
15020     // A reference initialized by a constant expression can never be
15021     // odr-used, so simply ignore it.
15022     if (!Var->getType()->isReferenceType() ||
15023         (SemaRef.LangOpts.OpenMP && SemaRef.isOpenMPCapturedDecl(Var)))
15024       SemaRef.MaybeODRUseExprs.insert(E);
15025   } else if (OdrUseContext) {
15026     MarkVarDeclODRUsed(Var, Loc, SemaRef,
15027                        /*MaxFunctionScopeIndex ptr*/ nullptr);
15028   } else if (isOdrUseContext(SemaRef, /*SkipDependentUses*/false)) {
15029     // If this is a dependent context, we don't need to mark variables as
15030     // odr-used, but we may still need to track them for lambda capture.
15031     // FIXME: Do we also need to do this inside dependent typeid expressions
15032     // (which are modeled as unevaluated at this point)?
15033     const bool RefersToEnclosingScope =
15034         (SemaRef.CurContext != Var->getDeclContext() &&
15035          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
15036     if (RefersToEnclosingScope) {
15037       LambdaScopeInfo *const LSI =
15038           SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true);
15039       if (LSI && (!LSI->CallOperator ||
15040                   !LSI->CallOperator->Encloses(Var->getDeclContext()))) {
15041         // If a variable could potentially be odr-used, defer marking it so
15042         // until we finish analyzing the full expression for any
15043         // lvalue-to-rvalue
15044         // or discarded value conversions that would obviate odr-use.
15045         // Add it to the list of potential captures that will be analyzed
15046         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
15047         // unless the variable is a reference that was initialized by a constant
15048         // expression (this will never need to be captured or odr-used).
15049         assert(E && "Capture variable should be used in an expression.");
15050         if (!Var->getType()->isReferenceType() ||
15051             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
15052           LSI->addPotentialCapture(E->IgnoreParens());
15053       }
15054     }
15055   }
15056 }
15057 
15058 /// \brief Mark a variable referenced, and check whether it is odr-used
15059 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
15060 /// used directly for normal expressions referring to VarDecl.
15061 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
15062   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
15063 }
15064 
15065 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
15066                                Decl *D, Expr *E, bool MightBeOdrUse) {
15067   if (SemaRef.isInOpenMPDeclareTargetContext())
15068     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
15069 
15070   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
15071     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
15072     return;
15073   }
15074 
15075   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
15076 
15077   // If this is a call to a method via a cast, also mark the method in the
15078   // derived class used in case codegen can devirtualize the call.
15079   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
15080   if (!ME)
15081     return;
15082   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
15083   if (!MD)
15084     return;
15085   // Only attempt to devirtualize if this is truly a virtual call.
15086   bool IsVirtualCall = MD->isVirtual() &&
15087                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
15088   if (!IsVirtualCall)
15089     return;
15090 
15091   // If it's possible to devirtualize the call, mark the called function
15092   // referenced.
15093   CXXMethodDecl *DM = MD->getDevirtualizedMethod(
15094       ME->getBase(), SemaRef.getLangOpts().AppleKext);
15095   if (DM)
15096     SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
15097 }
15098 
15099 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
15100 void Sema::MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base) {
15101   // TODO: update this with DR# once a defect report is filed.
15102   // C++11 defect. The address of a pure member should not be an ODR use, even
15103   // if it's a qualified reference.
15104   bool OdrUse = true;
15105   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
15106     if (Method->isVirtual() &&
15107         !Method->getDevirtualizedMethod(Base, getLangOpts().AppleKext))
15108       OdrUse = false;
15109   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
15110 }
15111 
15112 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
15113 void Sema::MarkMemberReferenced(MemberExpr *E) {
15114   // C++11 [basic.def.odr]p2:
15115   //   A non-overloaded function whose name appears as a potentially-evaluated
15116   //   expression or a member of a set of candidate functions, if selected by
15117   //   overload resolution when referred to from a potentially-evaluated
15118   //   expression, is odr-used, unless it is a pure virtual function and its
15119   //   name is not explicitly qualified.
15120   bool MightBeOdrUse = true;
15121   if (E->performsVirtualDispatch(getLangOpts())) {
15122     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
15123       if (Method->isPure())
15124         MightBeOdrUse = false;
15125   }
15126   SourceLocation Loc = E->getMemberLoc().isValid() ?
15127                             E->getMemberLoc() : E->getLocStart();
15128   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
15129 }
15130 
15131 /// \brief Perform marking for a reference to an arbitrary declaration.  It
15132 /// marks the declaration referenced, and performs odr-use checking for
15133 /// functions and variables. This method should not be used when building a
15134 /// normal expression which refers to a variable.
15135 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
15136                                  bool MightBeOdrUse) {
15137   if (MightBeOdrUse) {
15138     if (auto *VD = dyn_cast<VarDecl>(D)) {
15139       MarkVariableReferenced(Loc, VD);
15140       return;
15141     }
15142   }
15143   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
15144     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
15145     return;
15146   }
15147   D->setReferenced();
15148 }
15149 
15150 namespace {
15151   // Mark all of the declarations used by a type as referenced.
15152   // FIXME: Not fully implemented yet! We need to have a better understanding
15153   // of when we're entering a context we should not recurse into.
15154   // FIXME: This is and EvaluatedExprMarker are more-or-less equivalent to
15155   // TreeTransforms rebuilding the type in a new context. Rather than
15156   // duplicating the TreeTransform logic, we should consider reusing it here.
15157   // Currently that causes problems when rebuilding LambdaExprs.
15158   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
15159     Sema &S;
15160     SourceLocation Loc;
15161 
15162   public:
15163     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
15164 
15165     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
15166 
15167     bool TraverseTemplateArgument(const TemplateArgument &Arg);
15168   };
15169 }
15170 
15171 bool MarkReferencedDecls::TraverseTemplateArgument(
15172     const TemplateArgument &Arg) {
15173   {
15174     // A non-type template argument is a constant-evaluated context.
15175     EnterExpressionEvaluationContext Evaluated(
15176         S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
15177     if (Arg.getKind() == TemplateArgument::Declaration) {
15178       if (Decl *D = Arg.getAsDecl())
15179         S.MarkAnyDeclReferenced(Loc, D, true);
15180     } else if (Arg.getKind() == TemplateArgument::Expression) {
15181       S.MarkDeclarationsReferencedInExpr(Arg.getAsExpr(), false);
15182     }
15183   }
15184 
15185   return Inherited::TraverseTemplateArgument(Arg);
15186 }
15187 
15188 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
15189   MarkReferencedDecls Marker(*this, Loc);
15190   Marker.TraverseType(T);
15191 }
15192 
15193 namespace {
15194   /// \brief Helper class that marks all of the declarations referenced by
15195   /// potentially-evaluated subexpressions as "referenced".
15196   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
15197     Sema &S;
15198     bool SkipLocalVariables;
15199 
15200   public:
15201     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
15202 
15203     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
15204       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
15205 
15206     void VisitDeclRefExpr(DeclRefExpr *E) {
15207       // If we were asked not to visit local variables, don't.
15208       if (SkipLocalVariables) {
15209         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
15210           if (VD->hasLocalStorage())
15211             return;
15212       }
15213 
15214       S.MarkDeclRefReferenced(E);
15215     }
15216 
15217     void VisitMemberExpr(MemberExpr *E) {
15218       S.MarkMemberReferenced(E);
15219       Inherited::VisitMemberExpr(E);
15220     }
15221 
15222     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
15223       S.MarkFunctionReferenced(E->getLocStart(),
15224             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
15225       Visit(E->getSubExpr());
15226     }
15227 
15228     void VisitCXXNewExpr(CXXNewExpr *E) {
15229       if (E->getOperatorNew())
15230         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
15231       if (E->getOperatorDelete())
15232         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15233       Inherited::VisitCXXNewExpr(E);
15234     }
15235 
15236     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
15237       if (E->getOperatorDelete())
15238         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
15239       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
15240       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
15241         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
15242         S.MarkFunctionReferenced(E->getLocStart(),
15243                                     S.LookupDestructor(Record));
15244       }
15245 
15246       Inherited::VisitCXXDeleteExpr(E);
15247     }
15248 
15249     void VisitCXXConstructExpr(CXXConstructExpr *E) {
15250       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
15251       Inherited::VisitCXXConstructExpr(E);
15252     }
15253 
15254     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
15255       Visit(E->getExpr());
15256     }
15257 
15258     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
15259       Inherited::VisitImplicitCastExpr(E);
15260 
15261       if (E->getCastKind() == CK_LValueToRValue)
15262         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
15263     }
15264   };
15265 }
15266 
15267 /// \brief Mark any declarations that appear within this expression or any
15268 /// potentially-evaluated subexpressions as "referenced".
15269 ///
15270 /// \param SkipLocalVariables If true, don't mark local variables as
15271 /// 'referenced'.
15272 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
15273                                             bool SkipLocalVariables) {
15274   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
15275 }
15276 
15277 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
15278 /// of the program being compiled.
15279 ///
15280 /// This routine emits the given diagnostic when the code currently being
15281 /// type-checked is "potentially evaluated", meaning that there is a
15282 /// possibility that the code will actually be executable. Code in sizeof()
15283 /// expressions, code used only during overload resolution, etc., are not
15284 /// potentially evaluated. This routine will suppress such diagnostics or,
15285 /// in the absolutely nutty case of potentially potentially evaluated
15286 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
15287 /// later.
15288 ///
15289 /// This routine should be used for all diagnostics that describe the run-time
15290 /// behavior of a program, such as passing a non-POD value through an ellipsis.
15291 /// Failure to do so will likely result in spurious diagnostics or failures
15292 /// during overload resolution or within sizeof/alignof/typeof/typeid.
15293 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
15294                                const PartialDiagnostic &PD) {
15295   switch (ExprEvalContexts.back().Context) {
15296   case ExpressionEvaluationContext::Unevaluated:
15297   case ExpressionEvaluationContext::UnevaluatedList:
15298   case ExpressionEvaluationContext::UnevaluatedAbstract:
15299   case ExpressionEvaluationContext::DiscardedStatement:
15300     // The argument will never be evaluated, so don't complain.
15301     break;
15302 
15303   case ExpressionEvaluationContext::ConstantEvaluated:
15304     // Relevant diagnostics should be produced by constant evaluation.
15305     break;
15306 
15307   case ExpressionEvaluationContext::PotentiallyEvaluated:
15308   case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
15309     if (Statement && getCurFunctionOrMethodDecl()) {
15310       FunctionScopes.back()->PossiblyUnreachableDiags.
15311         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
15312       return true;
15313     }
15314 
15315     // The initializer of a constexpr variable or of the first declaration of a
15316     // static data member is not syntactically a constant evaluated constant,
15317     // but nonetheless is always required to be a constant expression, so we
15318     // can skip diagnosing.
15319     // FIXME: Using the mangling context here is a hack.
15320     if (auto *VD = dyn_cast_or_null<VarDecl>(
15321             ExprEvalContexts.back().ManglingContextDecl)) {
15322       if (VD->isConstexpr() ||
15323           (VD->isStaticDataMember() && VD->isFirstDecl() && !VD->isInline()))
15324         break;
15325       // FIXME: For any other kind of variable, we should build a CFG for its
15326       // initializer and check whether the context in question is reachable.
15327     }
15328 
15329     Diag(Loc, PD);
15330     return true;
15331   }
15332 
15333   return false;
15334 }
15335 
15336 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
15337                                CallExpr *CE, FunctionDecl *FD) {
15338   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
15339     return false;
15340 
15341   // If we're inside a decltype's expression, don't check for a valid return
15342   // type or construct temporaries until we know whether this is the last call.
15343   if (ExprEvalContexts.back().IsDecltype) {
15344     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
15345     return false;
15346   }
15347 
15348   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
15349     FunctionDecl *FD;
15350     CallExpr *CE;
15351 
15352   public:
15353     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
15354       : FD(FD), CE(CE) { }
15355 
15356     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
15357       if (!FD) {
15358         S.Diag(Loc, diag::err_call_incomplete_return)
15359           << T << CE->getSourceRange();
15360         return;
15361       }
15362 
15363       S.Diag(Loc, diag::err_call_function_incomplete_return)
15364         << CE->getSourceRange() << FD->getDeclName() << T;
15365       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
15366           << FD->getDeclName();
15367     }
15368   } Diagnoser(FD, CE);
15369 
15370   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
15371     return true;
15372 
15373   return false;
15374 }
15375 
15376 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
15377 // will prevent this condition from triggering, which is what we want.
15378 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
15379   SourceLocation Loc;
15380 
15381   unsigned diagnostic = diag::warn_condition_is_assignment;
15382   bool IsOrAssign = false;
15383 
15384   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
15385     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
15386       return;
15387 
15388     IsOrAssign = Op->getOpcode() == BO_OrAssign;
15389 
15390     // Greylist some idioms by putting them into a warning subcategory.
15391     if (ObjCMessageExpr *ME
15392           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
15393       Selector Sel = ME->getSelector();
15394 
15395       // self = [<foo> init...]
15396       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
15397         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15398 
15399       // <foo> = [<bar> nextObject]
15400       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
15401         diagnostic = diag::warn_condition_is_idiomatic_assignment;
15402     }
15403 
15404     Loc = Op->getOperatorLoc();
15405   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
15406     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
15407       return;
15408 
15409     IsOrAssign = Op->getOperator() == OO_PipeEqual;
15410     Loc = Op->getOperatorLoc();
15411   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
15412     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
15413   else {
15414     // Not an assignment.
15415     return;
15416   }
15417 
15418   Diag(Loc, diagnostic) << E->getSourceRange();
15419 
15420   SourceLocation Open = E->getLocStart();
15421   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
15422   Diag(Loc, diag::note_condition_assign_silence)
15423         << FixItHint::CreateInsertion(Open, "(")
15424         << FixItHint::CreateInsertion(Close, ")");
15425 
15426   if (IsOrAssign)
15427     Diag(Loc, diag::note_condition_or_assign_to_comparison)
15428       << FixItHint::CreateReplacement(Loc, "!=");
15429   else
15430     Diag(Loc, diag::note_condition_assign_to_comparison)
15431       << FixItHint::CreateReplacement(Loc, "==");
15432 }
15433 
15434 /// \brief Redundant parentheses over an equality comparison can indicate
15435 /// that the user intended an assignment used as condition.
15436 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
15437   // Don't warn if the parens came from a macro.
15438   SourceLocation parenLoc = ParenE->getLocStart();
15439   if (parenLoc.isInvalid() || parenLoc.isMacroID())
15440     return;
15441   // Don't warn for dependent expressions.
15442   if (ParenE->isTypeDependent())
15443     return;
15444 
15445   Expr *E = ParenE->IgnoreParens();
15446 
15447   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
15448     if (opE->getOpcode() == BO_EQ &&
15449         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
15450                                                            == Expr::MLV_Valid) {
15451       SourceLocation Loc = opE->getOperatorLoc();
15452 
15453       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
15454       SourceRange ParenERange = ParenE->getSourceRange();
15455       Diag(Loc, diag::note_equality_comparison_silence)
15456         << FixItHint::CreateRemoval(ParenERange.getBegin())
15457         << FixItHint::CreateRemoval(ParenERange.getEnd());
15458       Diag(Loc, diag::note_equality_comparison_to_assign)
15459         << FixItHint::CreateReplacement(Loc, "=");
15460     }
15461 }
15462 
15463 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
15464                                        bool IsConstexpr) {
15465   DiagnoseAssignmentAsCondition(E);
15466   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
15467     DiagnoseEqualityWithExtraParens(parenE);
15468 
15469   ExprResult result = CheckPlaceholderExpr(E);
15470   if (result.isInvalid()) return ExprError();
15471   E = result.get();
15472 
15473   if (!E->isTypeDependent()) {
15474     if (getLangOpts().CPlusPlus)
15475       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
15476 
15477     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
15478     if (ERes.isInvalid())
15479       return ExprError();
15480     E = ERes.get();
15481 
15482     QualType T = E->getType();
15483     if (!T->isScalarType()) { // C99 6.8.4.1p1
15484       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
15485         << T << E->getSourceRange();
15486       return ExprError();
15487     }
15488     CheckBoolLikeConversion(E, Loc);
15489   }
15490 
15491   return E;
15492 }
15493 
15494 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
15495                                            Expr *SubExpr, ConditionKind CK) {
15496   // Empty conditions are valid in for-statements.
15497   if (!SubExpr)
15498     return ConditionResult();
15499 
15500   ExprResult Cond;
15501   switch (CK) {
15502   case ConditionKind::Boolean:
15503     Cond = CheckBooleanCondition(Loc, SubExpr);
15504     break;
15505 
15506   case ConditionKind::ConstexprIf:
15507     Cond = CheckBooleanCondition(Loc, SubExpr, true);
15508     break;
15509 
15510   case ConditionKind::Switch:
15511     Cond = CheckSwitchCondition(Loc, SubExpr);
15512     break;
15513   }
15514   if (Cond.isInvalid())
15515     return ConditionError();
15516 
15517   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
15518   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
15519   if (!FullExpr.get())
15520     return ConditionError();
15521 
15522   return ConditionResult(*this, nullptr, FullExpr,
15523                          CK == ConditionKind::ConstexprIf);
15524 }
15525 
15526 namespace {
15527   /// A visitor for rebuilding a call to an __unknown_any expression
15528   /// to have an appropriate type.
15529   struct RebuildUnknownAnyFunction
15530     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
15531 
15532     Sema &S;
15533 
15534     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
15535 
15536     ExprResult VisitStmt(Stmt *S) {
15537       llvm_unreachable("unexpected statement!");
15538     }
15539 
15540     ExprResult VisitExpr(Expr *E) {
15541       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
15542         << E->getSourceRange();
15543       return ExprError();
15544     }
15545 
15546     /// Rebuild an expression which simply semantically wraps another
15547     /// expression which it shares the type and value kind of.
15548     template <class T> ExprResult rebuildSugarExpr(T *E) {
15549       ExprResult SubResult = Visit(E->getSubExpr());
15550       if (SubResult.isInvalid()) return ExprError();
15551 
15552       Expr *SubExpr = SubResult.get();
15553       E->setSubExpr(SubExpr);
15554       E->setType(SubExpr->getType());
15555       E->setValueKind(SubExpr->getValueKind());
15556       assert(E->getObjectKind() == OK_Ordinary);
15557       return E;
15558     }
15559 
15560     ExprResult VisitParenExpr(ParenExpr *E) {
15561       return rebuildSugarExpr(E);
15562     }
15563 
15564     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15565       return rebuildSugarExpr(E);
15566     }
15567 
15568     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15569       ExprResult SubResult = Visit(E->getSubExpr());
15570       if (SubResult.isInvalid()) return ExprError();
15571 
15572       Expr *SubExpr = SubResult.get();
15573       E->setSubExpr(SubExpr);
15574       E->setType(S.Context.getPointerType(SubExpr->getType()));
15575       assert(E->getValueKind() == VK_RValue);
15576       assert(E->getObjectKind() == OK_Ordinary);
15577       return E;
15578     }
15579 
15580     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
15581       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
15582 
15583       E->setType(VD->getType());
15584 
15585       assert(E->getValueKind() == VK_RValue);
15586       if (S.getLangOpts().CPlusPlus &&
15587           !(isa<CXXMethodDecl>(VD) &&
15588             cast<CXXMethodDecl>(VD)->isInstance()))
15589         E->setValueKind(VK_LValue);
15590 
15591       return E;
15592     }
15593 
15594     ExprResult VisitMemberExpr(MemberExpr *E) {
15595       return resolveDecl(E, E->getMemberDecl());
15596     }
15597 
15598     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15599       return resolveDecl(E, E->getDecl());
15600     }
15601   };
15602 }
15603 
15604 /// Given a function expression of unknown-any type, try to rebuild it
15605 /// to have a function type.
15606 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
15607   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
15608   if (Result.isInvalid()) return ExprError();
15609   return S.DefaultFunctionArrayConversion(Result.get());
15610 }
15611 
15612 namespace {
15613   /// A visitor for rebuilding an expression of type __unknown_anytype
15614   /// into one which resolves the type directly on the referring
15615   /// expression.  Strict preservation of the original source
15616   /// structure is not a goal.
15617   struct RebuildUnknownAnyExpr
15618     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
15619 
15620     Sema &S;
15621 
15622     /// The current destination type.
15623     QualType DestType;
15624 
15625     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
15626       : S(S), DestType(CastType) {}
15627 
15628     ExprResult VisitStmt(Stmt *S) {
15629       llvm_unreachable("unexpected statement!");
15630     }
15631 
15632     ExprResult VisitExpr(Expr *E) {
15633       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15634         << E->getSourceRange();
15635       return ExprError();
15636     }
15637 
15638     ExprResult VisitCallExpr(CallExpr *E);
15639     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
15640 
15641     /// Rebuild an expression which simply semantically wraps another
15642     /// expression which it shares the type and value kind of.
15643     template <class T> ExprResult rebuildSugarExpr(T *E) {
15644       ExprResult SubResult = Visit(E->getSubExpr());
15645       if (SubResult.isInvalid()) return ExprError();
15646       Expr *SubExpr = SubResult.get();
15647       E->setSubExpr(SubExpr);
15648       E->setType(SubExpr->getType());
15649       E->setValueKind(SubExpr->getValueKind());
15650       assert(E->getObjectKind() == OK_Ordinary);
15651       return E;
15652     }
15653 
15654     ExprResult VisitParenExpr(ParenExpr *E) {
15655       return rebuildSugarExpr(E);
15656     }
15657 
15658     ExprResult VisitUnaryExtension(UnaryOperator *E) {
15659       return rebuildSugarExpr(E);
15660     }
15661 
15662     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
15663       const PointerType *Ptr = DestType->getAs<PointerType>();
15664       if (!Ptr) {
15665         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
15666           << E->getSourceRange();
15667         return ExprError();
15668       }
15669 
15670       if (isa<CallExpr>(E->getSubExpr())) {
15671         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof_call)
15672           << E->getSourceRange();
15673         return ExprError();
15674       }
15675 
15676       assert(E->getValueKind() == VK_RValue);
15677       assert(E->getObjectKind() == OK_Ordinary);
15678       E->setType(DestType);
15679 
15680       // Build the sub-expression as if it were an object of the pointee type.
15681       DestType = Ptr->getPointeeType();
15682       ExprResult SubResult = Visit(E->getSubExpr());
15683       if (SubResult.isInvalid()) return ExprError();
15684       E->setSubExpr(SubResult.get());
15685       return E;
15686     }
15687 
15688     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
15689 
15690     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
15691 
15692     ExprResult VisitMemberExpr(MemberExpr *E) {
15693       return resolveDecl(E, E->getMemberDecl());
15694     }
15695 
15696     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
15697       return resolveDecl(E, E->getDecl());
15698     }
15699   };
15700 }
15701 
15702 /// Rebuilds a call expression which yielded __unknown_anytype.
15703 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
15704   Expr *CalleeExpr = E->getCallee();
15705 
15706   enum FnKind {
15707     FK_MemberFunction,
15708     FK_FunctionPointer,
15709     FK_BlockPointer
15710   };
15711 
15712   FnKind Kind;
15713   QualType CalleeType = CalleeExpr->getType();
15714   if (CalleeType == S.Context.BoundMemberTy) {
15715     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
15716     Kind = FK_MemberFunction;
15717     CalleeType = Expr::findBoundMemberType(CalleeExpr);
15718   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
15719     CalleeType = Ptr->getPointeeType();
15720     Kind = FK_FunctionPointer;
15721   } else {
15722     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
15723     Kind = FK_BlockPointer;
15724   }
15725   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
15726 
15727   // Verify that this is a legal result type of a function.
15728   if (DestType->isArrayType() || DestType->isFunctionType()) {
15729     unsigned diagID = diag::err_func_returning_array_function;
15730     if (Kind == FK_BlockPointer)
15731       diagID = diag::err_block_returning_array_function;
15732 
15733     S.Diag(E->getExprLoc(), diagID)
15734       << DestType->isFunctionType() << DestType;
15735     return ExprError();
15736   }
15737 
15738   // Otherwise, go ahead and set DestType as the call's result.
15739   E->setType(DestType.getNonLValueExprType(S.Context));
15740   E->setValueKind(Expr::getValueKindForType(DestType));
15741   assert(E->getObjectKind() == OK_Ordinary);
15742 
15743   // Rebuild the function type, replacing the result type with DestType.
15744   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
15745   if (Proto) {
15746     // __unknown_anytype(...) is a special case used by the debugger when
15747     // it has no idea what a function's signature is.
15748     //
15749     // We want to build this call essentially under the K&R
15750     // unprototyped rules, but making a FunctionNoProtoType in C++
15751     // would foul up all sorts of assumptions.  However, we cannot
15752     // simply pass all arguments as variadic arguments, nor can we
15753     // portably just call the function under a non-variadic type; see
15754     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
15755     // However, it turns out that in practice it is generally safe to
15756     // call a function declared as "A foo(B,C,D);" under the prototype
15757     // "A foo(B,C,D,...);".  The only known exception is with the
15758     // Windows ABI, where any variadic function is implicitly cdecl
15759     // regardless of its normal CC.  Therefore we change the parameter
15760     // types to match the types of the arguments.
15761     //
15762     // This is a hack, but it is far superior to moving the
15763     // corresponding target-specific code from IR-gen to Sema/AST.
15764 
15765     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
15766     SmallVector<QualType, 8> ArgTypes;
15767     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
15768       ArgTypes.reserve(E->getNumArgs());
15769       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
15770         Expr *Arg = E->getArg(i);
15771         QualType ArgType = Arg->getType();
15772         if (E->isLValue()) {
15773           ArgType = S.Context.getLValueReferenceType(ArgType);
15774         } else if (E->isXValue()) {
15775           ArgType = S.Context.getRValueReferenceType(ArgType);
15776         }
15777         ArgTypes.push_back(ArgType);
15778       }
15779       ParamTypes = ArgTypes;
15780     }
15781     DestType = S.Context.getFunctionType(DestType, ParamTypes,
15782                                          Proto->getExtProtoInfo());
15783   } else {
15784     DestType = S.Context.getFunctionNoProtoType(DestType,
15785                                                 FnType->getExtInfo());
15786   }
15787 
15788   // Rebuild the appropriate pointer-to-function type.
15789   switch (Kind) {
15790   case FK_MemberFunction:
15791     // Nothing to do.
15792     break;
15793 
15794   case FK_FunctionPointer:
15795     DestType = S.Context.getPointerType(DestType);
15796     break;
15797 
15798   case FK_BlockPointer:
15799     DestType = S.Context.getBlockPointerType(DestType);
15800     break;
15801   }
15802 
15803   // Finally, we can recurse.
15804   ExprResult CalleeResult = Visit(CalleeExpr);
15805   if (!CalleeResult.isUsable()) return ExprError();
15806   E->setCallee(CalleeResult.get());
15807 
15808   // Bind a temporary if necessary.
15809   return S.MaybeBindToTemporary(E);
15810 }
15811 
15812 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
15813   // Verify that this is a legal result type of a call.
15814   if (DestType->isArrayType() || DestType->isFunctionType()) {
15815     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
15816       << DestType->isFunctionType() << DestType;
15817     return ExprError();
15818   }
15819 
15820   // Rewrite the method result type if available.
15821   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
15822     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
15823     Method->setReturnType(DestType);
15824   }
15825 
15826   // Change the type of the message.
15827   E->setType(DestType.getNonReferenceType());
15828   E->setValueKind(Expr::getValueKindForType(DestType));
15829 
15830   return S.MaybeBindToTemporary(E);
15831 }
15832 
15833 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
15834   // The only case we should ever see here is a function-to-pointer decay.
15835   if (E->getCastKind() == CK_FunctionToPointerDecay) {
15836     assert(E->getValueKind() == VK_RValue);
15837     assert(E->getObjectKind() == OK_Ordinary);
15838 
15839     E->setType(DestType);
15840 
15841     // Rebuild the sub-expression as the pointee (function) type.
15842     DestType = DestType->castAs<PointerType>()->getPointeeType();
15843 
15844     ExprResult Result = Visit(E->getSubExpr());
15845     if (!Result.isUsable()) return ExprError();
15846 
15847     E->setSubExpr(Result.get());
15848     return E;
15849   } else if (E->getCastKind() == CK_LValueToRValue) {
15850     assert(E->getValueKind() == VK_RValue);
15851     assert(E->getObjectKind() == OK_Ordinary);
15852 
15853     assert(isa<BlockPointerType>(E->getType()));
15854 
15855     E->setType(DestType);
15856 
15857     // The sub-expression has to be a lvalue reference, so rebuild it as such.
15858     DestType = S.Context.getLValueReferenceType(DestType);
15859 
15860     ExprResult Result = Visit(E->getSubExpr());
15861     if (!Result.isUsable()) return ExprError();
15862 
15863     E->setSubExpr(Result.get());
15864     return E;
15865   } else {
15866     llvm_unreachable("Unhandled cast type!");
15867   }
15868 }
15869 
15870 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
15871   ExprValueKind ValueKind = VK_LValue;
15872   QualType Type = DestType;
15873 
15874   // We know how to make this work for certain kinds of decls:
15875 
15876   //  - functions
15877   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
15878     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
15879       DestType = Ptr->getPointeeType();
15880       ExprResult Result = resolveDecl(E, VD);
15881       if (Result.isInvalid()) return ExprError();
15882       return S.ImpCastExprToType(Result.get(), Type,
15883                                  CK_FunctionToPointerDecay, VK_RValue);
15884     }
15885 
15886     if (!Type->isFunctionType()) {
15887       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
15888         << VD << E->getSourceRange();
15889       return ExprError();
15890     }
15891     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
15892       // We must match the FunctionDecl's type to the hack introduced in
15893       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
15894       // type. See the lengthy commentary in that routine.
15895       QualType FDT = FD->getType();
15896       const FunctionType *FnType = FDT->castAs<FunctionType>();
15897       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
15898       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
15899       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
15900         SourceLocation Loc = FD->getLocation();
15901         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
15902                                       FD->getDeclContext(),
15903                                       Loc, Loc, FD->getNameInfo().getName(),
15904                                       DestType, FD->getTypeSourceInfo(),
15905                                       SC_None, false/*isInlineSpecified*/,
15906                                       FD->hasPrototype(),
15907                                       false/*isConstexprSpecified*/);
15908 
15909         if (FD->getQualifier())
15910           NewFD->setQualifierInfo(FD->getQualifierLoc());
15911 
15912         SmallVector<ParmVarDecl*, 16> Params;
15913         for (const auto &AI : FT->param_types()) {
15914           ParmVarDecl *Param =
15915             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
15916           Param->setScopeInfo(0, Params.size());
15917           Params.push_back(Param);
15918         }
15919         NewFD->setParams(Params);
15920         DRE->setDecl(NewFD);
15921         VD = DRE->getDecl();
15922       }
15923     }
15924 
15925     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
15926       if (MD->isInstance()) {
15927         ValueKind = VK_RValue;
15928         Type = S.Context.BoundMemberTy;
15929       }
15930 
15931     // Function references aren't l-values in C.
15932     if (!S.getLangOpts().CPlusPlus)
15933       ValueKind = VK_RValue;
15934 
15935   //  - variables
15936   } else if (isa<VarDecl>(VD)) {
15937     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
15938       Type = RefTy->getPointeeType();
15939     } else if (Type->isFunctionType()) {
15940       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
15941         << VD << E->getSourceRange();
15942       return ExprError();
15943     }
15944 
15945   //  - nothing else
15946   } else {
15947     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
15948       << VD << E->getSourceRange();
15949     return ExprError();
15950   }
15951 
15952   // Modifying the declaration like this is friendly to IR-gen but
15953   // also really dangerous.
15954   VD->setType(DestType);
15955   E->setType(Type);
15956   E->setValueKind(ValueKind);
15957   return E;
15958 }
15959 
15960 /// Check a cast of an unknown-any type.  We intentionally only
15961 /// trigger this for C-style casts.
15962 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
15963                                      Expr *CastExpr, CastKind &CastKind,
15964                                      ExprValueKind &VK, CXXCastPath &Path) {
15965   // The type we're casting to must be either void or complete.
15966   if (!CastType->isVoidType() &&
15967       RequireCompleteType(TypeRange.getBegin(), CastType,
15968                           diag::err_typecheck_cast_to_incomplete))
15969     return ExprError();
15970 
15971   // Rewrite the casted expression from scratch.
15972   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
15973   if (!result.isUsable()) return ExprError();
15974 
15975   CastExpr = result.get();
15976   VK = CastExpr->getValueKind();
15977   CastKind = CK_NoOp;
15978 
15979   return CastExpr;
15980 }
15981 
15982 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
15983   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
15984 }
15985 
15986 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
15987                                     Expr *arg, QualType &paramType) {
15988   // If the syntactic form of the argument is not an explicit cast of
15989   // any sort, just do default argument promotion.
15990   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15991   if (!castArg) {
15992     ExprResult result = DefaultArgumentPromotion(arg);
15993     if (result.isInvalid()) return ExprError();
15994     paramType = result.get()->getType();
15995     return result;
15996   }
15997 
15998   // Otherwise, use the type that was written in the explicit cast.
15999   assert(!arg->hasPlaceholderType());
16000   paramType = castArg->getTypeAsWritten();
16001 
16002   // Copy-initialize a parameter of that type.
16003   InitializedEntity entity =
16004     InitializedEntity::InitializeParameter(Context, paramType,
16005                                            /*consumed*/ false);
16006   return PerformCopyInitialization(entity, callLoc, arg);
16007 }
16008 
16009 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
16010   Expr *orig = E;
16011   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
16012   while (true) {
16013     E = E->IgnoreParenImpCasts();
16014     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
16015       E = call->getCallee();
16016       diagID = diag::err_uncasted_call_of_unknown_any;
16017     } else {
16018       break;
16019     }
16020   }
16021 
16022   SourceLocation loc;
16023   NamedDecl *d;
16024   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
16025     loc = ref->getLocation();
16026     d = ref->getDecl();
16027   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
16028     loc = mem->getMemberLoc();
16029     d = mem->getMemberDecl();
16030   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
16031     diagID = diag::err_uncasted_call_of_unknown_any;
16032     loc = msg->getSelectorStartLoc();
16033     d = msg->getMethodDecl();
16034     if (!d) {
16035       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
16036         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
16037         << orig->getSourceRange();
16038       return ExprError();
16039     }
16040   } else {
16041     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
16042       << E->getSourceRange();
16043     return ExprError();
16044   }
16045 
16046   S.Diag(loc, diagID) << d << orig->getSourceRange();
16047 
16048   // Never recoverable.
16049   return ExprError();
16050 }
16051 
16052 /// Check for operands with placeholder types and complain if found.
16053 /// Returns ExprError() if there was an error and no recovery was possible.
16054 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
16055   if (!getLangOpts().CPlusPlus) {
16056     // C cannot handle TypoExpr nodes on either side of a binop because it
16057     // doesn't handle dependent types properly, so make sure any TypoExprs have
16058     // been dealt with before checking the operands.
16059     ExprResult Result = CorrectDelayedTyposInExpr(E);
16060     if (!Result.isUsable()) return ExprError();
16061     E = Result.get();
16062   }
16063 
16064   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
16065   if (!placeholderType) return E;
16066 
16067   switch (placeholderType->getKind()) {
16068 
16069   // Overloaded expressions.
16070   case BuiltinType::Overload: {
16071     // Try to resolve a single function template specialization.
16072     // This is obligatory.
16073     ExprResult Result = E;
16074     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
16075       return Result;
16076 
16077     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
16078     // leaves Result unchanged on failure.
16079     Result = E;
16080     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
16081       return Result;
16082 
16083     // If that failed, try to recover with a call.
16084     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
16085                          /*complain*/ true);
16086     return Result;
16087   }
16088 
16089   // Bound member functions.
16090   case BuiltinType::BoundMember: {
16091     ExprResult result = E;
16092     const Expr *BME = E->IgnoreParens();
16093     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
16094     // Try to give a nicer diagnostic if it is a bound member that we recognize.
16095     if (isa<CXXPseudoDestructorExpr>(BME)) {
16096       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
16097     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
16098       if (ME->getMemberNameInfo().getName().getNameKind() ==
16099           DeclarationName::CXXDestructorName)
16100         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
16101     }
16102     tryToRecoverWithCall(result, PD,
16103                          /*complain*/ true);
16104     return result;
16105   }
16106 
16107   // ARC unbridged casts.
16108   case BuiltinType::ARCUnbridgedCast: {
16109     Expr *realCast = stripARCUnbridgedCast(E);
16110     diagnoseARCUnbridgedCast(realCast);
16111     return realCast;
16112   }
16113 
16114   // Expressions of unknown type.
16115   case BuiltinType::UnknownAny:
16116     return diagnoseUnknownAnyExpr(*this, E);
16117 
16118   // Pseudo-objects.
16119   case BuiltinType::PseudoObject:
16120     return checkPseudoObjectRValue(E);
16121 
16122   case BuiltinType::BuiltinFn: {
16123     // Accept __noop without parens by implicitly converting it to a call expr.
16124     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
16125     if (DRE) {
16126       auto *FD = cast<FunctionDecl>(DRE->getDecl());
16127       if (FD->getBuiltinID() == Builtin::BI__noop) {
16128         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
16129                               CK_BuiltinFnToFnPtr).get();
16130         return new (Context) CallExpr(Context, E, None, Context.IntTy,
16131                                       VK_RValue, SourceLocation());
16132       }
16133     }
16134 
16135     Diag(E->getLocStart(), diag::err_builtin_fn_use);
16136     return ExprError();
16137   }
16138 
16139   // Expressions of unknown type.
16140   case BuiltinType::OMPArraySection:
16141     Diag(E->getLocStart(), diag::err_omp_array_section_use);
16142     return ExprError();
16143 
16144   // Everything else should be impossible.
16145 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
16146   case BuiltinType::Id:
16147 #include "clang/Basic/OpenCLImageTypes.def"
16148 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
16149 #define PLACEHOLDER_TYPE(Id, SingletonId)
16150 #include "clang/AST/BuiltinTypes.def"
16151     break;
16152   }
16153 
16154   llvm_unreachable("invalid placeholder type!");
16155 }
16156 
16157 bool Sema::CheckCaseExpression(Expr *E) {
16158   if (E->isTypeDependent())
16159     return true;
16160   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
16161     return E->getType()->isIntegralOrEnumerationType();
16162   return false;
16163 }
16164 
16165 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
16166 ExprResult
16167 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
16168   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
16169          "Unknown Objective-C Boolean value!");
16170   QualType BoolT = Context.ObjCBuiltinBoolTy;
16171   if (!Context.getBOOLDecl()) {
16172     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
16173                         Sema::LookupOrdinaryName);
16174     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
16175       NamedDecl *ND = Result.getFoundDecl();
16176       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
16177         Context.setBOOLDecl(TD);
16178     }
16179   }
16180   if (Context.getBOOLDecl())
16181     BoolT = Context.getBOOLType();
16182   return new (Context)
16183       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
16184 }
16185 
16186 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
16187     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
16188     SourceLocation RParen) {
16189 
16190   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
16191 
16192   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
16193                            [&](const AvailabilitySpec &Spec) {
16194                              return Spec.getPlatform() == Platform;
16195                            });
16196 
16197   VersionTuple Version;
16198   if (Spec != AvailSpecs.end())
16199     Version = Spec->getVersion();
16200 
16201   // The use of `@available` in the enclosing function should be analyzed to
16202   // warn when it's used inappropriately (i.e. not if(@available)).
16203   if (getCurFunctionOrMethodDecl())
16204     getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
16205   else if (getCurBlock() || getCurLambda())
16206     getCurFunction()->HasPotentialAvailabilityViolations = true;
16207 
16208   return new (Context)
16209       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
16210 }
16211