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       const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
84       if (DC && !DC->hasAttr<UnusedAttr>())
85         S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
86     }
87   }
88 }
89 
90 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
91   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
92   if (!OMD)
93     return false;
94   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
95   if (!OID)
96     return false;
97 
98   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
99     if (ObjCMethodDecl *CatMeth =
100             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
101       if (!CatMeth->hasAttr<AvailabilityAttr>())
102         return true;
103   return false;
104 }
105 
106 AvailabilityResult Sema::ShouldDiagnoseAvailabilityOfDecl(
107     NamedDecl *&D, VersionTuple ContextVersion, std::string *Message) {
108   AvailabilityResult Result = D->getAvailability(Message, ContextVersion);
109 
110   // For typedefs, if the typedef declaration appears available look
111   // to the underlying type to see if it is more restrictive.
112   while (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
113     if (Result == AR_Available) {
114       if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
115         D = TT->getDecl();
116         Result = D->getAvailability(Message, ContextVersion);
117         continue;
118       }
119     }
120     break;
121   }
122 
123   // Forward class declarations get their attributes from their definition.
124   if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) {
125     if (IDecl->getDefinition()) {
126       D = IDecl->getDefinition();
127       Result = D->getAvailability(Message, ContextVersion);
128     }
129   }
130 
131   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
132     if (Result == AR_Available) {
133       const DeclContext *DC = ECD->getDeclContext();
134       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
135         Result = TheEnumDecl->getAvailability(Message, ContextVersion);
136     }
137 
138   switch (Result) {
139   case AR_Available:
140     return Result;
141 
142   case AR_Unavailable:
143   case AR_Deprecated:
144     return getCurContextAvailability() != Result ? Result : AR_Available;
145 
146   case AR_NotYetIntroduced: {
147     // Don't do this for enums, they can't be redeclared.
148     if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
149       return AR_Available;
150 
151     bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
152     // Objective-C method declarations in categories are not modelled as
153     // redeclarations, so manually look for a redeclaration in a category
154     // if necessary.
155     if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
156       Warn = false;
157     // In general, D will point to the most recent redeclaration. However,
158     // for `@class A;` decls, this isn't true -- manually go through the
159     // redecl chain in that case.
160     if (Warn && isa<ObjCInterfaceDecl>(D))
161       for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
162            Redecl = Redecl->getPreviousDecl())
163         if (!Redecl->hasAttr<AvailabilityAttr>() ||
164             Redecl->getAttr<AvailabilityAttr>()->isInherited())
165           Warn = false;
166 
167     return Warn ? AR_NotYetIntroduced : AR_Available;
168   }
169   }
170   llvm_unreachable("Unknown availability result!");
171 }
172 
173 static void
174 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
175                            const ObjCInterfaceDecl *UnknownObjCClass,
176                            bool ObjCPropertyAccess) {
177   VersionTuple ContextVersion;
178   if (const DeclContext *DC = S.getCurObjCLexicalContext())
179     ContextVersion = S.getVersionForDecl(cast<Decl>(DC));
180 
181   std::string Message;
182   // See if this declaration is unavailable, deprecated, or partial in the
183   // current context.
184   if (AvailabilityResult Result =
185           S.ShouldDiagnoseAvailabilityOfDecl(D, ContextVersion, &Message)) {
186 
187     if (Result == AR_NotYetIntroduced && S.getCurFunctionOrMethodDecl()) {
188       S.getEnclosingFunction()->HasPotentialAvailabilityViolations = true;
189       return;
190     }
191 
192     const ObjCPropertyDecl *ObjCPDecl = nullptr;
193     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
194       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
195         AvailabilityResult PDeclResult =
196             PD->getAvailability(nullptr, ContextVersion);
197         if (PDeclResult == Result)
198           ObjCPDecl = PD;
199       }
200     }
201 
202     S.EmitAvailabilityWarning(Result, D, Message, Loc, UnknownObjCClass,
203                               ObjCPDecl, ObjCPropertyAccess);
204   }
205 }
206 
207 /// \brief Emit a note explaining that this function is deleted.
208 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
209   assert(Decl->isDeleted());
210 
211   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
212 
213   if (Method && Method->isDeleted() && Method->isDefaulted()) {
214     // If the method was explicitly defaulted, point at that declaration.
215     if (!Method->isImplicit())
216       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
217 
218     // Try to diagnose why this special member function was implicitly
219     // deleted. This might fail, if that reason no longer applies.
220     CXXSpecialMember CSM = getSpecialMember(Method);
221     if (CSM != CXXInvalid)
222       ShouldDeleteSpecialMember(Method, CSM, nullptr, /*Diagnose=*/true);
223 
224     return;
225   }
226 
227   auto *Ctor = dyn_cast<CXXConstructorDecl>(Decl);
228   if (Ctor && Ctor->isInheritingConstructor())
229     return NoteDeletedInheritingConstructor(Ctor);
230 
231   Diag(Decl->getLocation(), diag::note_availability_specified_here)
232     << Decl << true;
233 }
234 
235 /// \brief Determine whether a FunctionDecl was ever declared with an
236 /// explicit storage class.
237 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
238   for (auto I : D->redecls()) {
239     if (I->getStorageClass() != SC_None)
240       return true;
241   }
242   return false;
243 }
244 
245 /// \brief Check whether we're in an extern inline function and referring to a
246 /// variable or function with internal linkage (C11 6.7.4p3).
247 ///
248 /// This is only a warning because we used to silently accept this code, but
249 /// in many cases it will not behave correctly. This is not enabled in C++ mode
250 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
251 /// and so while there may still be user mistakes, most of the time we can't
252 /// prove that there are errors.
253 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
254                                                       const NamedDecl *D,
255                                                       SourceLocation Loc) {
256   // This is disabled under C++; there are too many ways for this to fire in
257   // contexts where the warning is a false positive, or where it is technically
258   // correct but benign.
259   if (S.getLangOpts().CPlusPlus)
260     return;
261 
262   // Check if this is an inlined function or method.
263   FunctionDecl *Current = S.getCurFunctionDecl();
264   if (!Current)
265     return;
266   if (!Current->isInlined())
267     return;
268   if (!Current->isExternallyVisible())
269     return;
270 
271   // Check if the decl has internal linkage.
272   if (D->getFormalLinkage() != InternalLinkage)
273     return;
274 
275   // Downgrade from ExtWarn to Extension if
276   //  (1) the supposedly external inline function is in the main file,
277   //      and probably won't be included anywhere else.
278   //  (2) the thing we're referencing is a pure function.
279   //  (3) the thing we're referencing is another inline function.
280   // This last can give us false negatives, but it's better than warning on
281   // wrappers for simple C library functions.
282   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
283   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
284   if (!DowngradeWarning && UsedFn)
285     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
286 
287   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
288                                : diag::ext_internal_in_extern_inline)
289     << /*IsVar=*/!UsedFn << D;
290 
291   S.MaybeSuggestAddingStaticToDecl(Current);
292 
293   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
294       << D;
295 }
296 
297 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
298   const FunctionDecl *First = Cur->getFirstDecl();
299 
300   // Suggest "static" on the function, if possible.
301   if (!hasAnyExplicitStorageClass(First)) {
302     SourceLocation DeclBegin = First->getSourceRange().getBegin();
303     Diag(DeclBegin, diag::note_convert_inline_to_static)
304       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
305   }
306 }
307 
308 /// \brief Determine whether the use of this declaration is valid, and
309 /// emit any corresponding diagnostics.
310 ///
311 /// This routine diagnoses various problems with referencing
312 /// declarations that can occur when using a declaration. For example,
313 /// it might warn if a deprecated or unavailable declaration is being
314 /// used, or produce an error (and return true) if a C++0x deleted
315 /// function is being used.
316 ///
317 /// \returns true if there was an error (this declaration cannot be
318 /// referenced), false otherwise.
319 ///
320 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
321                              const ObjCInterfaceDecl *UnknownObjCClass,
322                              bool ObjCPropertyAccess) {
323   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
324     // If there were any diagnostics suppressed by template argument deduction,
325     // emit them now.
326     auto Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
327     if (Pos != SuppressedDiagnostics.end()) {
328       for (const PartialDiagnosticAt &Suppressed : Pos->second)
329         Diag(Suppressed.first, Suppressed.second);
330 
331       // Clear out the list of suppressed diagnostics, so that we don't emit
332       // them again for this specialization. However, we don't obsolete this
333       // entry from the table, because we want to avoid ever emitting these
334       // diagnostics again.
335       Pos->second.clear();
336     }
337 
338     // C++ [basic.start.main]p3:
339     //   The function 'main' shall not be used within a program.
340     if (cast<FunctionDecl>(D)->isMain())
341       Diag(Loc, diag::ext_main_used);
342   }
343 
344   // See if this is an auto-typed variable whose initializer we are parsing.
345   if (ParsingInitForAutoVars.count(D)) {
346     if (isa<BindingDecl>(D)) {
347       Diag(Loc, diag::err_binding_cannot_appear_in_own_initializer)
348         << D->getDeclName();
349     } else {
350       const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
351 
352       Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
353         << D->getDeclName() << (unsigned)AT->getKeyword();
354     }
355     return true;
356   }
357 
358   // See if this is a deleted function.
359   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
360     if (FD->isDeleted()) {
361       auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);
362       if (Ctor && Ctor->isInheritingConstructor())
363         Diag(Loc, diag::err_deleted_inherited_ctor_use)
364             << Ctor->getParent()
365             << Ctor->getInheritedConstructor().getConstructor()->getParent();
366       else
367         Diag(Loc, diag::err_deleted_function_use);
368       NoteDeletedFunction(FD);
369       return true;
370     }
371 
372     // If the function has a deduced return type, and we can't deduce it,
373     // then we can't use it either.
374     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
375         DeduceReturnType(FD, Loc))
376       return true;
377   }
378 
379   // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
380   // Only the variables omp_in and omp_out are allowed in the combiner.
381   // Only the variables omp_priv and omp_orig are allowed in the
382   // initializer-clause.
383   auto *DRD = dyn_cast<OMPDeclareReductionDecl>(CurContext);
384   if (LangOpts.OpenMP && DRD && !CurContext->containsDecl(D) &&
385       isa<VarDecl>(D)) {
386     Diag(Loc, diag::err_omp_wrong_var_in_declare_reduction)
387         << getCurFunction()->HasOMPDeclareReductionCombiner;
388     Diag(D->getLocation(), diag::note_entity_declared_at) << D;
389     return true;
390   }
391   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
392                              ObjCPropertyAccess);
393 
394   DiagnoseUnusedOfDecl(*this, D, Loc);
395 
396   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
397 
398   return false;
399 }
400 
401 /// \brief Retrieve the message suffix that should be added to a
402 /// diagnostic complaining about the given function being deleted or
403 /// unavailable.
404 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
405   std::string Message;
406   if (FD->getAvailability(&Message))
407     return ": " + Message;
408 
409   return std::string();
410 }
411 
412 /// DiagnoseSentinelCalls - This routine checks whether a call or
413 /// message-send is to a declaration with the sentinel attribute, and
414 /// if so, it checks that the requirements of the sentinel are
415 /// satisfied.
416 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
417                                  ArrayRef<Expr *> Args) {
418   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
419   if (!attr)
420     return;
421 
422   // The number of formal parameters of the declaration.
423   unsigned numFormalParams;
424 
425   // The kind of declaration.  This is also an index into a %select in
426   // the diagnostic.
427   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
428 
429   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
430     numFormalParams = MD->param_size();
431     calleeType = CT_Method;
432   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
433     numFormalParams = FD->param_size();
434     calleeType = CT_Function;
435   } else if (isa<VarDecl>(D)) {
436     QualType type = cast<ValueDecl>(D)->getType();
437     const FunctionType *fn = nullptr;
438     if (const PointerType *ptr = type->getAs<PointerType>()) {
439       fn = ptr->getPointeeType()->getAs<FunctionType>();
440       if (!fn) return;
441       calleeType = CT_Function;
442     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
443       fn = ptr->getPointeeType()->castAs<FunctionType>();
444       calleeType = CT_Block;
445     } else {
446       return;
447     }
448 
449     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
450       numFormalParams = proto->getNumParams();
451     } else {
452       numFormalParams = 0;
453     }
454   } else {
455     return;
456   }
457 
458   // "nullPos" is the number of formal parameters at the end which
459   // effectively count as part of the variadic arguments.  This is
460   // useful if you would prefer to not have *any* formal parameters,
461   // but the language forces you to have at least one.
462   unsigned nullPos = attr->getNullPos();
463   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
464   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
465 
466   // The number of arguments which should follow the sentinel.
467   unsigned numArgsAfterSentinel = attr->getSentinel();
468 
469   // If there aren't enough arguments for all the formal parameters,
470   // the sentinel, and the args after the sentinel, complain.
471   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
472     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
473     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
474     return;
475   }
476 
477   // Otherwise, find the sentinel expression.
478   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
479   if (!sentinelExpr) return;
480   if (sentinelExpr->isValueDependent()) return;
481   if (Context.isSentinelNullExpr(sentinelExpr)) return;
482 
483   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
484   // or 'NULL' if those are actually defined in the context.  Only use
485   // 'nil' for ObjC methods, where it's much more likely that the
486   // variadic arguments form a list of object pointers.
487   SourceLocation MissingNilLoc
488     = getLocForEndOfToken(sentinelExpr->getLocEnd());
489   std::string NullValue;
490   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
491     NullValue = "nil";
492   else if (getLangOpts().CPlusPlus11)
493     NullValue = "nullptr";
494   else if (PP.isMacroDefined("NULL"))
495     NullValue = "NULL";
496   else
497     NullValue = "(void*) 0";
498 
499   if (MissingNilLoc.isInvalid())
500     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
501   else
502     Diag(MissingNilLoc, diag::warn_missing_sentinel)
503       << int(calleeType)
504       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
505   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
506 }
507 
508 SourceRange Sema::getExprRange(Expr *E) const {
509   return E ? E->getSourceRange() : SourceRange();
510 }
511 
512 //===----------------------------------------------------------------------===//
513 //  Standard Promotions and Conversions
514 //===----------------------------------------------------------------------===//
515 
516 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
517 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
518   // Handle any placeholder expressions which made it here.
519   if (E->getType()->isPlaceholderType()) {
520     ExprResult result = CheckPlaceholderExpr(E);
521     if (result.isInvalid()) return ExprError();
522     E = result.get();
523   }
524 
525   QualType Ty = E->getType();
526   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
527 
528   if (Ty->isFunctionType()) {
529     // If we are here, we are not calling a function but taking
530     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
531     if (getLangOpts().OpenCL) {
532       if (Diagnose)
533         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
534       return ExprError();
535     }
536 
537     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
538       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
539         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
540           return ExprError();
541 
542     E = ImpCastExprToType(E, Context.getPointerType(Ty),
543                           CK_FunctionToPointerDecay).get();
544   } else if (Ty->isArrayType()) {
545     // In C90 mode, arrays only promote to pointers if the array expression is
546     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
547     // type 'array of type' is converted to an expression that has type 'pointer
548     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
549     // that has type 'array of type' ...".  The relevant change is "an lvalue"
550     // (C90) to "an expression" (C99).
551     //
552     // C++ 4.2p1:
553     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
554     // T" can be converted to an rvalue of type "pointer to T".
555     //
556     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
557       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
558                             CK_ArrayToPointerDecay).get();
559   }
560   return E;
561 }
562 
563 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
564   // Check to see if we are dereferencing a null pointer.  If so,
565   // and if not volatile-qualified, this is undefined behavior that the
566   // optimizer will delete, so warn about it.  People sometimes try to use this
567   // to get a deterministic trap and are surprised by clang's behavior.  This
568   // only handles the pattern "*null", which is a very syntactic check.
569   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
570     if (UO->getOpcode() == UO_Deref &&
571         UO->getSubExpr()->IgnoreParenCasts()->
572           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
573         !UO->getType().isVolatileQualified()) {
574     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
575                           S.PDiag(diag::warn_indirection_through_null)
576                             << UO->getSubExpr()->getSourceRange());
577     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
578                         S.PDiag(diag::note_indirection_through_null));
579   }
580 }
581 
582 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
583                                     SourceLocation AssignLoc,
584                                     const Expr* RHS) {
585   const ObjCIvarDecl *IV = OIRE->getDecl();
586   if (!IV)
587     return;
588 
589   DeclarationName MemberName = IV->getDeclName();
590   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
591   if (!Member || !Member->isStr("isa"))
592     return;
593 
594   const Expr *Base = OIRE->getBase();
595   QualType BaseType = Base->getType();
596   if (OIRE->isArrow())
597     BaseType = BaseType->getPointeeType();
598   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
599     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
600       ObjCInterfaceDecl *ClassDeclared = nullptr;
601       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
602       if (!ClassDeclared->getSuperClass()
603           && (*ClassDeclared->ivar_begin()) == IV) {
604         if (RHS) {
605           NamedDecl *ObjectSetClass =
606             S.LookupSingleName(S.TUScope,
607                                &S.Context.Idents.get("object_setClass"),
608                                SourceLocation(), S.LookupOrdinaryName);
609           if (ObjectSetClass) {
610             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
611             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
612             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
613             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
614                                                      AssignLoc), ",") <<
615             FixItHint::CreateInsertion(RHSLocEnd, ")");
616           }
617           else
618             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
619         } else {
620           NamedDecl *ObjectGetClass =
621             S.LookupSingleName(S.TUScope,
622                                &S.Context.Idents.get("object_getClass"),
623                                SourceLocation(), S.LookupOrdinaryName);
624           if (ObjectGetClass)
625             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
626             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
627             FixItHint::CreateReplacement(
628                                          SourceRange(OIRE->getOpLoc(),
629                                                      OIRE->getLocEnd()), ")");
630           else
631             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
632         }
633         S.Diag(IV->getLocation(), diag::note_ivar_decl);
634       }
635     }
636 }
637 
638 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
639   // Handle any placeholder expressions which made it here.
640   if (E->getType()->isPlaceholderType()) {
641     ExprResult result = CheckPlaceholderExpr(E);
642     if (result.isInvalid()) return ExprError();
643     E = result.get();
644   }
645 
646   // C++ [conv.lval]p1:
647   //   A glvalue of a non-function, non-array type T can be
648   //   converted to a prvalue.
649   if (!E->isGLValue()) return E;
650 
651   QualType T = E->getType();
652   assert(!T.isNull() && "r-value conversion on typeless expression?");
653 
654   // We don't want to throw lvalue-to-rvalue casts on top of
655   // expressions of certain types in C++.
656   if (getLangOpts().CPlusPlus &&
657       (E->getType() == Context.OverloadTy ||
658        T->isDependentType() ||
659        T->isRecordType()))
660     return E;
661 
662   // The C standard is actually really unclear on this point, and
663   // DR106 tells us what the result should be but not why.  It's
664   // generally best to say that void types just doesn't undergo
665   // lvalue-to-rvalue at all.  Note that expressions of unqualified
666   // 'void' type are never l-values, but qualified void can be.
667   if (T->isVoidType())
668     return E;
669 
670   // OpenCL usually rejects direct accesses to values of 'half' type.
671   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
672       T->isHalfType()) {
673     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
674       << 0 << T;
675     return ExprError();
676   }
677 
678   CheckForNullPointerDereference(*this, E);
679   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
680     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
681                                      &Context.Idents.get("object_getClass"),
682                                      SourceLocation(), LookupOrdinaryName);
683     if (ObjectGetClass)
684       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
685         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
686         FixItHint::CreateReplacement(
687                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
688     else
689       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
690   }
691   else if (const ObjCIvarRefExpr *OIRE =
692             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
693     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
694 
695   // C++ [conv.lval]p1:
696   //   [...] If T is a non-class type, the type of the prvalue is the
697   //   cv-unqualified version of T. Otherwise, the type of the
698   //   rvalue is T.
699   //
700   // C99 6.3.2.1p2:
701   //   If the lvalue has qualified type, the value has the unqualified
702   //   version of the type of the lvalue; otherwise, the value has the
703   //   type of the lvalue.
704   if (T.hasQualifiers())
705     T = T.getUnqualifiedType();
706 
707   // Under the MS ABI, lock down the inheritance model now.
708   if (T->isMemberPointerType() &&
709       Context.getTargetInfo().getCXXABI().isMicrosoft())
710     (void)isCompleteType(E->getExprLoc(), T);
711 
712   UpdateMarkingForLValueToRValue(E);
713 
714   // Loading a __weak object implicitly retains the value, so we need a cleanup to
715   // balance that.
716   if (getLangOpts().ObjCAutoRefCount &&
717       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
718     Cleanup.setExprNeedsCleanups(true);
719 
720   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
721                                             nullptr, VK_RValue);
722 
723   // C11 6.3.2.1p2:
724   //   ... if the lvalue has atomic type, the value has the non-atomic version
725   //   of the type of the lvalue ...
726   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
727     T = Atomic->getValueType().getUnqualifiedType();
728     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
729                                    nullptr, VK_RValue);
730   }
731 
732   return Res;
733 }
734 
735 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
736   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
737   if (Res.isInvalid())
738     return ExprError();
739   Res = DefaultLvalueConversion(Res.get());
740   if (Res.isInvalid())
741     return ExprError();
742   return Res;
743 }
744 
745 /// CallExprUnaryConversions - a special case of an unary conversion
746 /// performed on a function designator of a call expression.
747 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
748   QualType Ty = E->getType();
749   ExprResult Res = E;
750   // Only do implicit cast for a function type, but not for a pointer
751   // to function type.
752   if (Ty->isFunctionType()) {
753     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
754                             CK_FunctionToPointerDecay).get();
755     if (Res.isInvalid())
756       return ExprError();
757   }
758   Res = DefaultLvalueConversion(Res.get());
759   if (Res.isInvalid())
760     return ExprError();
761   return Res.get();
762 }
763 
764 /// UsualUnaryConversions - Performs various conversions that are common to most
765 /// operators (C99 6.3). The conversions of array and function types are
766 /// sometimes suppressed. For example, the array->pointer conversion doesn't
767 /// apply if the array is an argument to the sizeof or address (&) operators.
768 /// In these instances, this routine should *not* be called.
769 ExprResult Sema::UsualUnaryConversions(Expr *E) {
770   // First, convert to an r-value.
771   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
772   if (Res.isInvalid())
773     return ExprError();
774   E = Res.get();
775 
776   QualType Ty = E->getType();
777   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
778 
779   // Half FP have to be promoted to float unless it is natively supported
780   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
781     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
782 
783   // Try to perform integral promotions if the object has a theoretically
784   // promotable type.
785   if (Ty->isIntegralOrUnscopedEnumerationType()) {
786     // C99 6.3.1.1p2:
787     //
788     //   The following may be used in an expression wherever an int or
789     //   unsigned int may be used:
790     //     - an object or expression with an integer type whose integer
791     //       conversion rank is less than or equal to the rank of int
792     //       and unsigned int.
793     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
794     //
795     //   If an int can represent all values of the original type, the
796     //   value is converted to an int; otherwise, it is converted to an
797     //   unsigned int. These are called the integer promotions. All
798     //   other types are unchanged by the integer promotions.
799 
800     QualType PTy = Context.isPromotableBitField(E);
801     if (!PTy.isNull()) {
802       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
803       return E;
804     }
805     if (Ty->isPromotableIntegerType()) {
806       QualType PT = Context.getPromotedIntegerType(Ty);
807       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
808       return E;
809     }
810   }
811   return E;
812 }
813 
814 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
815 /// do not have a prototype. Arguments that have type float or __fp16
816 /// are promoted to double. All other argument types are converted by
817 /// UsualUnaryConversions().
818 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
819   QualType Ty = E->getType();
820   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
821 
822   ExprResult Res = UsualUnaryConversions(E);
823   if (Res.isInvalid())
824     return ExprError();
825   E = Res.get();
826 
827   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
828   // double.
829   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
830   if (BTy && (BTy->getKind() == BuiltinType::Half ||
831               BTy->getKind() == BuiltinType::Float))
832     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
833 
834   // C++ performs lvalue-to-rvalue conversion as a default argument
835   // promotion, even on class types, but note:
836   //   C++11 [conv.lval]p2:
837   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
838   //     operand or a subexpression thereof the value contained in the
839   //     referenced object is not accessed. Otherwise, if the glvalue
840   //     has a class type, the conversion copy-initializes a temporary
841   //     of type T from the glvalue and the result of the conversion
842   //     is a prvalue for the temporary.
843   // FIXME: add some way to gate this entire thing for correctness in
844   // potentially potentially evaluated contexts.
845   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
846     ExprResult Temp = PerformCopyInitialization(
847                        InitializedEntity::InitializeTemporary(E->getType()),
848                                                 E->getExprLoc(), E);
849     if (Temp.isInvalid())
850       return ExprError();
851     E = Temp.get();
852   }
853 
854   return E;
855 }
856 
857 /// Determine the degree of POD-ness for an expression.
858 /// Incomplete types are considered POD, since this check can be performed
859 /// when we're in an unevaluated context.
860 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
861   if (Ty->isIncompleteType()) {
862     // C++11 [expr.call]p7:
863     //   After these conversions, if the argument does not have arithmetic,
864     //   enumeration, pointer, pointer to member, or class type, the program
865     //   is ill-formed.
866     //
867     // Since we've already performed array-to-pointer and function-to-pointer
868     // decay, the only such type in C++ is cv void. This also handles
869     // initializer lists as variadic arguments.
870     if (Ty->isVoidType())
871       return VAK_Invalid;
872 
873     if (Ty->isObjCObjectType())
874       return VAK_Invalid;
875     return VAK_Valid;
876   }
877 
878   if (Ty.isCXX98PODType(Context))
879     return VAK_Valid;
880 
881   // C++11 [expr.call]p7:
882   //   Passing a potentially-evaluated argument of class type (Clause 9)
883   //   having a non-trivial copy constructor, a non-trivial move constructor,
884   //   or a non-trivial destructor, with no corresponding parameter,
885   //   is conditionally-supported with implementation-defined semantics.
886   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
887     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
888       if (!Record->hasNonTrivialCopyConstructor() &&
889           !Record->hasNonTrivialMoveConstructor() &&
890           !Record->hasNonTrivialDestructor())
891         return VAK_ValidInCXX11;
892 
893   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
894     return VAK_Valid;
895 
896   if (Ty->isObjCObjectType())
897     return VAK_Invalid;
898 
899   if (getLangOpts().MSVCCompat)
900     return VAK_MSVCUndefined;
901 
902   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
903   // permitted to reject them. We should consider doing so.
904   return VAK_Undefined;
905 }
906 
907 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
908   // Don't allow one to pass an Objective-C interface to a vararg.
909   const QualType &Ty = E->getType();
910   VarArgKind VAK = isValidVarArgType(Ty);
911 
912   // Complain about passing non-POD types through varargs.
913   switch (VAK) {
914   case VAK_ValidInCXX11:
915     DiagRuntimeBehavior(
916         E->getLocStart(), nullptr,
917         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
918           << Ty << CT);
919     // Fall through.
920   case VAK_Valid:
921     if (Ty->isRecordType()) {
922       // This is unlikely to be what the user intended. If the class has a
923       // 'c_str' member function, the user probably meant to call that.
924       DiagRuntimeBehavior(E->getLocStart(), nullptr,
925                           PDiag(diag::warn_pass_class_arg_to_vararg)
926                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
927     }
928     break;
929 
930   case VAK_Undefined:
931   case VAK_MSVCUndefined:
932     DiagRuntimeBehavior(
933         E->getLocStart(), nullptr,
934         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
935           << getLangOpts().CPlusPlus11 << Ty << CT);
936     break;
937 
938   case VAK_Invalid:
939     if (Ty->isObjCObjectType())
940       DiagRuntimeBehavior(
941           E->getLocStart(), nullptr,
942           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
943             << Ty << CT);
944     else
945       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
946         << isa<InitListExpr>(E) << Ty << CT;
947     break;
948   }
949 }
950 
951 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
952 /// will create a trap if the resulting type is not a POD type.
953 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
954                                                   FunctionDecl *FDecl) {
955   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
956     // Strip the unbridged-cast placeholder expression off, if applicable.
957     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
958         (CT == VariadicMethod ||
959          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
960       E = stripARCUnbridgedCast(E);
961 
962     // Otherwise, do normal placeholder checking.
963     } else {
964       ExprResult ExprRes = CheckPlaceholderExpr(E);
965       if (ExprRes.isInvalid())
966         return ExprError();
967       E = ExprRes.get();
968     }
969   }
970 
971   ExprResult ExprRes = DefaultArgumentPromotion(E);
972   if (ExprRes.isInvalid())
973     return ExprError();
974   E = ExprRes.get();
975 
976   // Diagnostics regarding non-POD argument types are
977   // emitted along with format string checking in Sema::CheckFunctionCall().
978   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
979     // Turn this into a trap.
980     CXXScopeSpec SS;
981     SourceLocation TemplateKWLoc;
982     UnqualifiedId Name;
983     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
984                        E->getLocStart());
985     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
986                                           Name, true, false);
987     if (TrapFn.isInvalid())
988       return ExprError();
989 
990     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
991                                     E->getLocStart(), None,
992                                     E->getLocEnd());
993     if (Call.isInvalid())
994       return ExprError();
995 
996     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
997                                   Call.get(), E);
998     if (Comma.isInvalid())
999       return ExprError();
1000     return Comma.get();
1001   }
1002 
1003   if (!getLangOpts().CPlusPlus &&
1004       RequireCompleteType(E->getExprLoc(), E->getType(),
1005                           diag::err_call_incomplete_argument))
1006     return ExprError();
1007 
1008   return E;
1009 }
1010 
1011 /// \brief Converts an integer to complex float type.  Helper function of
1012 /// UsualArithmeticConversions()
1013 ///
1014 /// \return false if the integer expression is an integer type and is
1015 /// successfully converted to the complex type.
1016 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
1017                                                   ExprResult &ComplexExpr,
1018                                                   QualType IntTy,
1019                                                   QualType ComplexTy,
1020                                                   bool SkipCast) {
1021   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1022   if (SkipCast) return false;
1023   if (IntTy->isIntegerType()) {
1024     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1025     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1026     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1027                                   CK_FloatingRealToComplex);
1028   } else {
1029     assert(IntTy->isComplexIntegerType());
1030     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1031                                   CK_IntegralComplexToFloatingComplex);
1032   }
1033   return false;
1034 }
1035 
1036 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1037 /// UsualArithmeticConversions()
1038 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1039                                              ExprResult &RHS, QualType LHSType,
1040                                              QualType RHSType,
1041                                              bool IsCompAssign) {
1042   // if we have an integer operand, the result is the complex type.
1043   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1044                                              /*skipCast*/false))
1045     return LHSType;
1046   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1047                                              /*skipCast*/IsCompAssign))
1048     return RHSType;
1049 
1050   // This handles complex/complex, complex/float, or float/complex.
1051   // When both operands are complex, the shorter operand is converted to the
1052   // type of the longer, and that is the type of the result. This corresponds
1053   // to what is done when combining two real floating-point operands.
1054   // The fun begins when size promotion occur across type domains.
1055   // From H&S 6.3.4: When one operand is complex and the other is a real
1056   // floating-point type, the less precise type is converted, within it's
1057   // real or complex domain, to the precision of the other type. For example,
1058   // when combining a "long double" with a "double _Complex", the
1059   // "double _Complex" is promoted to "long double _Complex".
1060 
1061   // Compute the rank of the two types, regardless of whether they are complex.
1062   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1063 
1064   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1065   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1066   QualType LHSElementType =
1067       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1068   QualType RHSElementType =
1069       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1070 
1071   QualType ResultType = S.Context.getComplexType(LHSElementType);
1072   if (Order < 0) {
1073     // Promote the precision of the LHS if not an assignment.
1074     ResultType = S.Context.getComplexType(RHSElementType);
1075     if (!IsCompAssign) {
1076       if (LHSComplexType)
1077         LHS =
1078             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1079       else
1080         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1081     }
1082   } else if (Order > 0) {
1083     // Promote the precision of the RHS.
1084     if (RHSComplexType)
1085       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1086     else
1087       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1088   }
1089   return ResultType;
1090 }
1091 
1092 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1093 /// of UsualArithmeticConversions()
1094 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1095                                            ExprResult &IntExpr,
1096                                            QualType FloatTy, QualType IntTy,
1097                                            bool ConvertFloat, bool ConvertInt) {
1098   if (IntTy->isIntegerType()) {
1099     if (ConvertInt)
1100       // Convert intExpr to the lhs floating point type.
1101       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1102                                     CK_IntegralToFloating);
1103     return FloatTy;
1104   }
1105 
1106   // Convert both sides to the appropriate complex float.
1107   assert(IntTy->isComplexIntegerType());
1108   QualType result = S.Context.getComplexType(FloatTy);
1109 
1110   // _Complex int -> _Complex float
1111   if (ConvertInt)
1112     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1113                                   CK_IntegralComplexToFloatingComplex);
1114 
1115   // float -> _Complex float
1116   if (ConvertFloat)
1117     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1118                                     CK_FloatingRealToComplex);
1119 
1120   return result;
1121 }
1122 
1123 /// \brief Handle arithmethic conversion with floating point types.  Helper
1124 /// function of UsualArithmeticConversions()
1125 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1126                                       ExprResult &RHS, QualType LHSType,
1127                                       QualType RHSType, bool IsCompAssign) {
1128   bool LHSFloat = LHSType->isRealFloatingType();
1129   bool RHSFloat = RHSType->isRealFloatingType();
1130 
1131   // If we have two real floating types, convert the smaller operand
1132   // to the bigger result.
1133   if (LHSFloat && RHSFloat) {
1134     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1135     if (order > 0) {
1136       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1137       return LHSType;
1138     }
1139 
1140     assert(order < 0 && "illegal float comparison");
1141     if (!IsCompAssign)
1142       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1143     return RHSType;
1144   }
1145 
1146   if (LHSFloat) {
1147     // Half FP has to be promoted to float unless it is natively supported
1148     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1149       LHSType = S.Context.FloatTy;
1150 
1151     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1152                                       /*convertFloat=*/!IsCompAssign,
1153                                       /*convertInt=*/ true);
1154   }
1155   assert(RHSFloat);
1156   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1157                                     /*convertInt=*/ true,
1158                                     /*convertFloat=*/!IsCompAssign);
1159 }
1160 
1161 /// \brief Diagnose attempts to convert between __float128 and long double if
1162 /// there is no support for such conversion. Helper function of
1163 /// UsualArithmeticConversions().
1164 static bool unsupportedTypeConversion(const Sema &S, QualType LHSType,
1165                                       QualType RHSType) {
1166   /*  No issue converting if at least one of the types is not a floating point
1167       type or the two types have the same rank.
1168   */
1169   if (!LHSType->isFloatingType() || !RHSType->isFloatingType() ||
1170       S.Context.getFloatingTypeOrder(LHSType, RHSType) == 0)
1171     return false;
1172 
1173   assert(LHSType->isFloatingType() && RHSType->isFloatingType() &&
1174          "The remaining types must be floating point types.");
1175 
1176   auto *LHSComplex = LHSType->getAs<ComplexType>();
1177   auto *RHSComplex = RHSType->getAs<ComplexType>();
1178 
1179   QualType LHSElemType = LHSComplex ?
1180     LHSComplex->getElementType() : LHSType;
1181   QualType RHSElemType = RHSComplex ?
1182     RHSComplex->getElementType() : RHSType;
1183 
1184   // No issue if the two types have the same representation
1185   if (&S.Context.getFloatTypeSemantics(LHSElemType) ==
1186       &S.Context.getFloatTypeSemantics(RHSElemType))
1187     return false;
1188 
1189   bool Float128AndLongDouble = (LHSElemType == S.Context.Float128Ty &&
1190                                 RHSElemType == S.Context.LongDoubleTy);
1191   Float128AndLongDouble |= (LHSElemType == S.Context.LongDoubleTy &&
1192                             RHSElemType == S.Context.Float128Ty);
1193 
1194   /* We've handled the situation where __float128 and long double have the same
1195      representation. The only other allowable conversion is if long double is
1196      really just double.
1197   */
1198   return Float128AndLongDouble &&
1199     (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) !=
1200      &llvm::APFloat::IEEEdouble);
1201 }
1202 
1203 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1204 
1205 namespace {
1206 /// These helper callbacks are placed in an anonymous namespace to
1207 /// permit their use as function template parameters.
1208 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1209   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1210 }
1211 
1212 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1213   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1214                              CK_IntegralComplexCast);
1215 }
1216 }
1217 
1218 /// \brief Handle integer arithmetic conversions.  Helper function of
1219 /// UsualArithmeticConversions()
1220 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1221 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1222                                         ExprResult &RHS, QualType LHSType,
1223                                         QualType RHSType, bool IsCompAssign) {
1224   // The rules for this case are in C99 6.3.1.8
1225   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1226   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1227   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1228   if (LHSSigned == RHSSigned) {
1229     // Same signedness; use the higher-ranked type
1230     if (order >= 0) {
1231       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1232       return LHSType;
1233     } else if (!IsCompAssign)
1234       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1235     return RHSType;
1236   } else if (order != (LHSSigned ? 1 : -1)) {
1237     // The unsigned type has greater than or equal rank to the
1238     // signed type, so use the unsigned type
1239     if (RHSSigned) {
1240       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1241       return LHSType;
1242     } else if (!IsCompAssign)
1243       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1244     return RHSType;
1245   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1246     // The two types are different widths; if we are here, that
1247     // means the signed type is larger than the unsigned type, so
1248     // use the signed type.
1249     if (LHSSigned) {
1250       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1251       return LHSType;
1252     } else if (!IsCompAssign)
1253       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1254     return RHSType;
1255   } else {
1256     // The signed type is higher-ranked than the unsigned type,
1257     // but isn't actually any bigger (like unsigned int and long
1258     // on most 32-bit systems).  Use the unsigned type corresponding
1259     // to the signed type.
1260     QualType result =
1261       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1262     RHS = (*doRHSCast)(S, RHS.get(), result);
1263     if (!IsCompAssign)
1264       LHS = (*doLHSCast)(S, LHS.get(), result);
1265     return result;
1266   }
1267 }
1268 
1269 /// \brief Handle conversions with GCC complex int extension.  Helper function
1270 /// of UsualArithmeticConversions()
1271 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1272                                            ExprResult &RHS, QualType LHSType,
1273                                            QualType RHSType,
1274                                            bool IsCompAssign) {
1275   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1276   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1277 
1278   if (LHSComplexInt && RHSComplexInt) {
1279     QualType LHSEltType = LHSComplexInt->getElementType();
1280     QualType RHSEltType = RHSComplexInt->getElementType();
1281     QualType ScalarType =
1282       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1283         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1284 
1285     return S.Context.getComplexType(ScalarType);
1286   }
1287 
1288   if (LHSComplexInt) {
1289     QualType LHSEltType = LHSComplexInt->getElementType();
1290     QualType ScalarType =
1291       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1292         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1293     QualType ComplexType = S.Context.getComplexType(ScalarType);
1294     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1295                               CK_IntegralRealToComplex);
1296 
1297     return ComplexType;
1298   }
1299 
1300   assert(RHSComplexInt);
1301 
1302   QualType RHSEltType = RHSComplexInt->getElementType();
1303   QualType ScalarType =
1304     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1305       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1306   QualType ComplexType = S.Context.getComplexType(ScalarType);
1307 
1308   if (!IsCompAssign)
1309     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1310                               CK_IntegralRealToComplex);
1311   return ComplexType;
1312 }
1313 
1314 /// UsualArithmeticConversions - Performs various conversions that are common to
1315 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1316 /// routine returns the first non-arithmetic type found. The client is
1317 /// responsible for emitting appropriate error diagnostics.
1318 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1319                                           bool IsCompAssign) {
1320   if (!IsCompAssign) {
1321     LHS = UsualUnaryConversions(LHS.get());
1322     if (LHS.isInvalid())
1323       return QualType();
1324   }
1325 
1326   RHS = UsualUnaryConversions(RHS.get());
1327   if (RHS.isInvalid())
1328     return QualType();
1329 
1330   // For conversion purposes, we ignore any qualifiers.
1331   // For example, "const float" and "float" are equivalent.
1332   QualType LHSType =
1333     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1334   QualType RHSType =
1335     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1336 
1337   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1338   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1339     LHSType = AtomicLHS->getValueType();
1340 
1341   // If both types are identical, no conversion is needed.
1342   if (LHSType == RHSType)
1343     return LHSType;
1344 
1345   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1346   // The caller can deal with this (e.g. pointer + int).
1347   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1348     return QualType();
1349 
1350   // Apply unary and bitfield promotions to the LHS's type.
1351   QualType LHSUnpromotedType = LHSType;
1352   if (LHSType->isPromotableIntegerType())
1353     LHSType = Context.getPromotedIntegerType(LHSType);
1354   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1355   if (!LHSBitfieldPromoteTy.isNull())
1356     LHSType = LHSBitfieldPromoteTy;
1357   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1358     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1359 
1360   // If both types are identical, no conversion is needed.
1361   if (LHSType == RHSType)
1362     return LHSType;
1363 
1364   // At this point, we have two different arithmetic types.
1365 
1366   // Diagnose attempts to convert between __float128 and long double where
1367   // such conversions currently can't be handled.
1368   if (unsupportedTypeConversion(*this, LHSType, RHSType))
1369     return QualType();
1370 
1371   // Handle complex types first (C99 6.3.1.8p1).
1372   if (LHSType->isComplexType() || RHSType->isComplexType())
1373     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1374                                         IsCompAssign);
1375 
1376   // Now handle "real" floating types (i.e. float, double, long double).
1377   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1378     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1379                                  IsCompAssign);
1380 
1381   // Handle GCC complex int extension.
1382   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1383     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1384                                       IsCompAssign);
1385 
1386   // Finally, we have two differing integer types.
1387   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1388            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1389 }
1390 
1391 
1392 //===----------------------------------------------------------------------===//
1393 //  Semantic Analysis for various Expression Types
1394 //===----------------------------------------------------------------------===//
1395 
1396 
1397 ExprResult
1398 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1399                                 SourceLocation DefaultLoc,
1400                                 SourceLocation RParenLoc,
1401                                 Expr *ControllingExpr,
1402                                 ArrayRef<ParsedType> ArgTypes,
1403                                 ArrayRef<Expr *> ArgExprs) {
1404   unsigned NumAssocs = ArgTypes.size();
1405   assert(NumAssocs == ArgExprs.size());
1406 
1407   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1408   for (unsigned i = 0; i < NumAssocs; ++i) {
1409     if (ArgTypes[i])
1410       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1411     else
1412       Types[i] = nullptr;
1413   }
1414 
1415   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1416                                              ControllingExpr,
1417                                              llvm::makeArrayRef(Types, NumAssocs),
1418                                              ArgExprs);
1419   delete [] Types;
1420   return ER;
1421 }
1422 
1423 ExprResult
1424 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1425                                  SourceLocation DefaultLoc,
1426                                  SourceLocation RParenLoc,
1427                                  Expr *ControllingExpr,
1428                                  ArrayRef<TypeSourceInfo *> Types,
1429                                  ArrayRef<Expr *> Exprs) {
1430   unsigned NumAssocs = Types.size();
1431   assert(NumAssocs == Exprs.size());
1432 
1433   // Decay and strip qualifiers for the controlling expression type, and handle
1434   // placeholder type replacement. See committee discussion from WG14 DR423.
1435   {
1436     EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
1437     ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1438     if (R.isInvalid())
1439       return ExprError();
1440     ControllingExpr = R.get();
1441   }
1442 
1443   // The controlling expression is an unevaluated operand, so side effects are
1444   // likely unintended.
1445   if (ActiveTemplateInstantiations.empty() &&
1446       ControllingExpr->HasSideEffects(Context, false))
1447     Diag(ControllingExpr->getExprLoc(),
1448          diag::warn_side_effects_unevaluated_context);
1449 
1450   bool TypeErrorFound = false,
1451        IsResultDependent = ControllingExpr->isTypeDependent(),
1452        ContainsUnexpandedParameterPack
1453          = ControllingExpr->containsUnexpandedParameterPack();
1454 
1455   for (unsigned i = 0; i < NumAssocs; ++i) {
1456     if (Exprs[i]->containsUnexpandedParameterPack())
1457       ContainsUnexpandedParameterPack = true;
1458 
1459     if (Types[i]) {
1460       if (Types[i]->getType()->containsUnexpandedParameterPack())
1461         ContainsUnexpandedParameterPack = true;
1462 
1463       if (Types[i]->getType()->isDependentType()) {
1464         IsResultDependent = true;
1465       } else {
1466         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1467         // complete object type other than a variably modified type."
1468         unsigned D = 0;
1469         if (Types[i]->getType()->isIncompleteType())
1470           D = diag::err_assoc_type_incomplete;
1471         else if (!Types[i]->getType()->isObjectType())
1472           D = diag::err_assoc_type_nonobject;
1473         else if (Types[i]->getType()->isVariablyModifiedType())
1474           D = diag::err_assoc_type_variably_modified;
1475 
1476         if (D != 0) {
1477           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1478             << Types[i]->getTypeLoc().getSourceRange()
1479             << Types[i]->getType();
1480           TypeErrorFound = true;
1481         }
1482 
1483         // C11 6.5.1.1p2 "No two generic associations in the same generic
1484         // selection shall specify compatible types."
1485         for (unsigned j = i+1; j < NumAssocs; ++j)
1486           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1487               Context.typesAreCompatible(Types[i]->getType(),
1488                                          Types[j]->getType())) {
1489             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1490                  diag::err_assoc_compatible_types)
1491               << Types[j]->getTypeLoc().getSourceRange()
1492               << Types[j]->getType()
1493               << Types[i]->getType();
1494             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1495                  diag::note_compat_assoc)
1496               << Types[i]->getTypeLoc().getSourceRange()
1497               << Types[i]->getType();
1498             TypeErrorFound = true;
1499           }
1500       }
1501     }
1502   }
1503   if (TypeErrorFound)
1504     return ExprError();
1505 
1506   // If we determined that the generic selection is result-dependent, don't
1507   // try to compute the result expression.
1508   if (IsResultDependent)
1509     return new (Context) GenericSelectionExpr(
1510         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1511         ContainsUnexpandedParameterPack);
1512 
1513   SmallVector<unsigned, 1> CompatIndices;
1514   unsigned DefaultIndex = -1U;
1515   for (unsigned i = 0; i < NumAssocs; ++i) {
1516     if (!Types[i])
1517       DefaultIndex = i;
1518     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1519                                         Types[i]->getType()))
1520       CompatIndices.push_back(i);
1521   }
1522 
1523   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1524   // type compatible with at most one of the types named in its generic
1525   // association list."
1526   if (CompatIndices.size() > 1) {
1527     // We strip parens here because the controlling expression is typically
1528     // parenthesized in macro definitions.
1529     ControllingExpr = ControllingExpr->IgnoreParens();
1530     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1531       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1532       << (unsigned) CompatIndices.size();
1533     for (unsigned I : CompatIndices) {
1534       Diag(Types[I]->getTypeLoc().getBeginLoc(),
1535            diag::note_compat_assoc)
1536         << Types[I]->getTypeLoc().getSourceRange()
1537         << Types[I]->getType();
1538     }
1539     return ExprError();
1540   }
1541 
1542   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1543   // its controlling expression shall have type compatible with exactly one of
1544   // the types named in its generic association list."
1545   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1546     // We strip parens here because the controlling expression is typically
1547     // parenthesized in macro definitions.
1548     ControllingExpr = ControllingExpr->IgnoreParens();
1549     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1550       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1551     return ExprError();
1552   }
1553 
1554   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1555   // type name that is compatible with the type of the controlling expression,
1556   // then the result expression of the generic selection is the expression
1557   // in that generic association. Otherwise, the result expression of the
1558   // generic selection is the expression in the default generic association."
1559   unsigned ResultIndex =
1560     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1561 
1562   return new (Context) GenericSelectionExpr(
1563       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1564       ContainsUnexpandedParameterPack, ResultIndex);
1565 }
1566 
1567 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1568 /// location of the token and the offset of the ud-suffix within it.
1569 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1570                                      unsigned Offset) {
1571   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1572                                         S.getLangOpts());
1573 }
1574 
1575 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1576 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1577 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1578                                                  IdentifierInfo *UDSuffix,
1579                                                  SourceLocation UDSuffixLoc,
1580                                                  ArrayRef<Expr*> Args,
1581                                                  SourceLocation LitEndLoc) {
1582   assert(Args.size() <= 2 && "too many arguments for literal operator");
1583 
1584   QualType ArgTy[2];
1585   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1586     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1587     if (ArgTy[ArgIdx]->isArrayType())
1588       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1589   }
1590 
1591   DeclarationName OpName =
1592     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1593   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1594   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1595 
1596   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1597   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1598                               /*AllowRaw*/false, /*AllowTemplate*/false,
1599                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1600     return ExprError();
1601 
1602   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1603 }
1604 
1605 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1606 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1607 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1608 /// multiple tokens.  However, the common case is that StringToks points to one
1609 /// string.
1610 ///
1611 ExprResult
1612 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1613   assert(!StringToks.empty() && "Must have at least one string!");
1614 
1615   StringLiteralParser Literal(StringToks, PP);
1616   if (Literal.hadError)
1617     return ExprError();
1618 
1619   SmallVector<SourceLocation, 4> StringTokLocs;
1620   for (const Token &Tok : StringToks)
1621     StringTokLocs.push_back(Tok.getLocation());
1622 
1623   QualType CharTy = Context.CharTy;
1624   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1625   if (Literal.isWide()) {
1626     CharTy = Context.getWideCharType();
1627     Kind = StringLiteral::Wide;
1628   } else if (Literal.isUTF8()) {
1629     Kind = StringLiteral::UTF8;
1630   } else if (Literal.isUTF16()) {
1631     CharTy = Context.Char16Ty;
1632     Kind = StringLiteral::UTF16;
1633   } else if (Literal.isUTF32()) {
1634     CharTy = Context.Char32Ty;
1635     Kind = StringLiteral::UTF32;
1636   } else if (Literal.isPascal()) {
1637     CharTy = Context.UnsignedCharTy;
1638   }
1639 
1640   QualType CharTyConst = CharTy;
1641   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1642   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1643     CharTyConst.addConst();
1644 
1645   // Get an array type for the string, according to C99 6.4.5.  This includes
1646   // the nul terminator character as well as the string length for pascal
1647   // strings.
1648   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1649                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1650                                  ArrayType::Normal, 0);
1651 
1652   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1653   if (getLangOpts().OpenCL) {
1654     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1655   }
1656 
1657   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1658   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1659                                              Kind, Literal.Pascal, StrTy,
1660                                              &StringTokLocs[0],
1661                                              StringTokLocs.size());
1662   if (Literal.getUDSuffix().empty())
1663     return Lit;
1664 
1665   // We're building a user-defined literal.
1666   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1667   SourceLocation UDSuffixLoc =
1668     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1669                    Literal.getUDSuffixOffset());
1670 
1671   // Make sure we're allowed user-defined literals here.
1672   if (!UDLScope)
1673     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1674 
1675   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1676   //   operator "" X (str, len)
1677   QualType SizeType = Context.getSizeType();
1678 
1679   DeclarationName OpName =
1680     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1681   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1682   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1683 
1684   QualType ArgTy[] = {
1685     Context.getArrayDecayedType(StrTy), SizeType
1686   };
1687 
1688   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1689   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1690                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1691                                 /*AllowStringTemplate*/true)) {
1692 
1693   case LOLR_Cooked: {
1694     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1695     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1696                                                     StringTokLocs[0]);
1697     Expr *Args[] = { Lit, LenArg };
1698 
1699     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1700   }
1701 
1702   case LOLR_StringTemplate: {
1703     TemplateArgumentListInfo ExplicitArgs;
1704 
1705     unsigned CharBits = Context.getIntWidth(CharTy);
1706     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1707     llvm::APSInt Value(CharBits, CharIsUnsigned);
1708 
1709     TemplateArgument TypeArg(CharTy);
1710     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1711     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1712 
1713     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1714       Value = Lit->getCodeUnit(I);
1715       TemplateArgument Arg(Context, Value, CharTy);
1716       TemplateArgumentLocInfo ArgInfo;
1717       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1718     }
1719     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1720                                     &ExplicitArgs);
1721   }
1722   case LOLR_Raw:
1723   case LOLR_Template:
1724     llvm_unreachable("unexpected literal operator lookup result");
1725   case LOLR_Error:
1726     return ExprError();
1727   }
1728   llvm_unreachable("unexpected literal operator lookup result");
1729 }
1730 
1731 ExprResult
1732 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1733                        SourceLocation Loc,
1734                        const CXXScopeSpec *SS) {
1735   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1736   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1737 }
1738 
1739 /// BuildDeclRefExpr - Build an expression that references a
1740 /// declaration that does not require a closure capture.
1741 ExprResult
1742 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1743                        const DeclarationNameInfo &NameInfo,
1744                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1745                        const TemplateArgumentListInfo *TemplateArgs) {
1746   if (getLangOpts().CUDA)
1747     if (FunctionDecl *Callee = dyn_cast<FunctionDecl>(D))
1748       if (!CheckCUDACall(NameInfo.getLoc(), Callee))
1749         return ExprError();
1750 
1751   bool RefersToCapturedVariable =
1752       isa<VarDecl>(D) &&
1753       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1754 
1755   DeclRefExpr *E;
1756   if (isa<VarTemplateSpecializationDecl>(D)) {
1757     VarTemplateSpecializationDecl *VarSpec =
1758         cast<VarTemplateSpecializationDecl>(D);
1759 
1760     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1761                                         : NestedNameSpecifierLoc(),
1762                             VarSpec->getTemplateKeywordLoc(), D,
1763                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1764                             FoundD, TemplateArgs);
1765   } else {
1766     assert(!TemplateArgs && "No template arguments for non-variable"
1767                             " template specialization references");
1768     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1769                                         : NestedNameSpecifierLoc(),
1770                             SourceLocation(), D, RefersToCapturedVariable,
1771                             NameInfo, Ty, VK, FoundD);
1772   }
1773 
1774   MarkDeclRefReferenced(E);
1775 
1776   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1777       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1778       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1779       recordUseOfEvaluatedWeak(E);
1780 
1781   if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1782     UnusedPrivateFields.remove(FD);
1783     // Just in case we're building an illegal pointer-to-member.
1784     if (FD->isBitField())
1785       E->setObjectKind(OK_BitField);
1786   }
1787 
1788   // C++ [expr.prim]/8: The expression [...] is a bit-field if the identifier
1789   // designates a bit-field.
1790   if (auto *BD = dyn_cast<BindingDecl>(D))
1791     if (auto *BE = BD->getBinding())
1792       E->setObjectKind(BE->getObjectKind());
1793 
1794   return E;
1795 }
1796 
1797 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1798 /// possibly a list of template arguments.
1799 ///
1800 /// If this produces template arguments, it is permitted to call
1801 /// DecomposeTemplateName.
1802 ///
1803 /// This actually loses a lot of source location information for
1804 /// non-standard name kinds; we should consider preserving that in
1805 /// some way.
1806 void
1807 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1808                              TemplateArgumentListInfo &Buffer,
1809                              DeclarationNameInfo &NameInfo,
1810                              const TemplateArgumentListInfo *&TemplateArgs) {
1811   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1812     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1813     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1814 
1815     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1816                                        Id.TemplateId->NumArgs);
1817     translateTemplateArguments(TemplateArgsPtr, Buffer);
1818 
1819     TemplateName TName = Id.TemplateId->Template.get();
1820     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1821     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1822     TemplateArgs = &Buffer;
1823   } else {
1824     NameInfo = GetNameFromUnqualifiedId(Id);
1825     TemplateArgs = nullptr;
1826   }
1827 }
1828 
1829 static void emitEmptyLookupTypoDiagnostic(
1830     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1831     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1832     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1833   DeclContext *Ctx =
1834       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1835   if (!TC) {
1836     // Emit a special diagnostic for failed member lookups.
1837     // FIXME: computing the declaration context might fail here (?)
1838     if (Ctx)
1839       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1840                                                  << SS.getRange();
1841     else
1842       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1843     return;
1844   }
1845 
1846   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1847   bool DroppedSpecifier =
1848       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1849   unsigned NoteID = TC.getCorrectionDeclAs<ImplicitParamDecl>()
1850                         ? diag::note_implicit_param_decl
1851                         : diag::note_previous_decl;
1852   if (!Ctx)
1853     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1854                          SemaRef.PDiag(NoteID));
1855   else
1856     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1857                                  << Typo << Ctx << DroppedSpecifier
1858                                  << SS.getRange(),
1859                          SemaRef.PDiag(NoteID));
1860 }
1861 
1862 /// Diagnose an empty lookup.
1863 ///
1864 /// \return false if new lookup candidates were found
1865 bool
1866 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1867                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1868                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1869                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1870   DeclarationName Name = R.getLookupName();
1871 
1872   unsigned diagnostic = diag::err_undeclared_var_use;
1873   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1874   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1875       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1876       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1877     diagnostic = diag::err_undeclared_use;
1878     diagnostic_suggest = diag::err_undeclared_use_suggest;
1879   }
1880 
1881   // If the original lookup was an unqualified lookup, fake an
1882   // unqualified lookup.  This is useful when (for example) the
1883   // original lookup would not have found something because it was a
1884   // dependent name.
1885   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1886   while (DC) {
1887     if (isa<CXXRecordDecl>(DC)) {
1888       LookupQualifiedName(R, DC);
1889 
1890       if (!R.empty()) {
1891         // Don't give errors about ambiguities in this lookup.
1892         R.suppressDiagnostics();
1893 
1894         // During a default argument instantiation the CurContext points
1895         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1896         // function parameter list, hence add an explicit check.
1897         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1898                               ActiveTemplateInstantiations.back().Kind ==
1899             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1900         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1901         bool isInstance = CurMethod &&
1902                           CurMethod->isInstance() &&
1903                           DC == CurMethod->getParent() && !isDefaultArgument;
1904 
1905         // Give a code modification hint to insert 'this->'.
1906         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1907         // Actually quite difficult!
1908         if (getLangOpts().MSVCCompat)
1909           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1910         if (isInstance) {
1911           Diag(R.getNameLoc(), diagnostic) << Name
1912             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1913           CheckCXXThisCapture(R.getNameLoc());
1914         } else {
1915           Diag(R.getNameLoc(), diagnostic) << Name;
1916         }
1917 
1918         // Do we really want to note all of these?
1919         for (NamedDecl *D : R)
1920           Diag(D->getLocation(), diag::note_dependent_var_use);
1921 
1922         // Return true if we are inside a default argument instantiation
1923         // and the found name refers to an instance member function, otherwise
1924         // the function calling DiagnoseEmptyLookup will try to create an
1925         // implicit member call and this is wrong for default argument.
1926         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1927           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1928           return true;
1929         }
1930 
1931         // Tell the callee to try to recover.
1932         return false;
1933       }
1934 
1935       R.clear();
1936     }
1937 
1938     // In Microsoft mode, if we are performing lookup from within a friend
1939     // function definition declared at class scope then we must set
1940     // DC to the lexical parent to be able to search into the parent
1941     // class.
1942     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1943         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1944         DC->getLexicalParent()->isRecord())
1945       DC = DC->getLexicalParent();
1946     else
1947       DC = DC->getParent();
1948   }
1949 
1950   // We didn't find anything, so try to correct for a typo.
1951   TypoCorrection Corrected;
1952   if (S && Out) {
1953     SourceLocation TypoLoc = R.getNameLoc();
1954     assert(!ExplicitTemplateArgs &&
1955            "Diagnosing an empty lookup with explicit template args!");
1956     *Out = CorrectTypoDelayed(
1957         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1958         [=](const TypoCorrection &TC) {
1959           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1960                                         diagnostic, diagnostic_suggest);
1961         },
1962         nullptr, CTK_ErrorRecovery);
1963     if (*Out)
1964       return true;
1965   } else if (S && (Corrected =
1966                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1967                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1968     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1969     bool DroppedSpecifier =
1970         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1971     R.setLookupName(Corrected.getCorrection());
1972 
1973     bool AcceptableWithRecovery = false;
1974     bool AcceptableWithoutRecovery = false;
1975     NamedDecl *ND = Corrected.getFoundDecl();
1976     if (ND) {
1977       if (Corrected.isOverloaded()) {
1978         OverloadCandidateSet OCS(R.getNameLoc(),
1979                                  OverloadCandidateSet::CSK_Normal);
1980         OverloadCandidateSet::iterator Best;
1981         for (NamedDecl *CD : Corrected) {
1982           if (FunctionTemplateDecl *FTD =
1983                    dyn_cast<FunctionTemplateDecl>(CD))
1984             AddTemplateOverloadCandidate(
1985                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1986                 Args, OCS);
1987           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
1988             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1989               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1990                                    Args, OCS);
1991         }
1992         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1993         case OR_Success:
1994           ND = Best->FoundDecl;
1995           Corrected.setCorrectionDecl(ND);
1996           break;
1997         default:
1998           // FIXME: Arbitrarily pick the first declaration for the note.
1999           Corrected.setCorrectionDecl(ND);
2000           break;
2001         }
2002       }
2003       R.addDecl(ND);
2004       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
2005         CXXRecordDecl *Record = nullptr;
2006         if (Corrected.getCorrectionSpecifier()) {
2007           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
2008           Record = Ty->getAsCXXRecordDecl();
2009         }
2010         if (!Record)
2011           Record = cast<CXXRecordDecl>(
2012               ND->getDeclContext()->getRedeclContext());
2013         R.setNamingClass(Record);
2014       }
2015 
2016       auto *UnderlyingND = ND->getUnderlyingDecl();
2017       AcceptableWithRecovery = isa<ValueDecl>(UnderlyingND) ||
2018                                isa<FunctionTemplateDecl>(UnderlyingND);
2019       // FIXME: If we ended up with a typo for a type name or
2020       // Objective-C class name, we're in trouble because the parser
2021       // is in the wrong place to recover. Suggest the typo
2022       // correction, but don't make it a fix-it since we're not going
2023       // to recover well anyway.
2024       AcceptableWithoutRecovery =
2025           isa<TypeDecl>(UnderlyingND) || isa<ObjCInterfaceDecl>(UnderlyingND);
2026     } else {
2027       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
2028       // because we aren't able to recover.
2029       AcceptableWithoutRecovery = true;
2030     }
2031 
2032     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
2033       unsigned NoteID = Corrected.getCorrectionDeclAs<ImplicitParamDecl>()
2034                             ? diag::note_implicit_param_decl
2035                             : diag::note_previous_decl;
2036       if (SS.isEmpty())
2037         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
2038                      PDiag(NoteID), AcceptableWithRecovery);
2039       else
2040         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
2041                                   << Name << computeDeclContext(SS, false)
2042                                   << DroppedSpecifier << SS.getRange(),
2043                      PDiag(NoteID), AcceptableWithRecovery);
2044 
2045       // Tell the callee whether to try to recover.
2046       return !AcceptableWithRecovery;
2047     }
2048   }
2049   R.clear();
2050 
2051   // Emit a special diagnostic for failed member lookups.
2052   // FIXME: computing the declaration context might fail here (?)
2053   if (!SS.isEmpty()) {
2054     Diag(R.getNameLoc(), diag::err_no_member)
2055       << Name << computeDeclContext(SS, false)
2056       << SS.getRange();
2057     return true;
2058   }
2059 
2060   // Give up, we can't recover.
2061   Diag(R.getNameLoc(), diagnostic) << Name;
2062   return true;
2063 }
2064 
2065 /// In Microsoft mode, if we are inside a template class whose parent class has
2066 /// dependent base classes, and we can't resolve an unqualified identifier, then
2067 /// assume the identifier is a member of a dependent base class.  We can only
2068 /// recover successfully in static methods, instance methods, and other contexts
2069 /// where 'this' is available.  This doesn't precisely match MSVC's
2070 /// instantiation model, but it's close enough.
2071 static Expr *
2072 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2073                                DeclarationNameInfo &NameInfo,
2074                                SourceLocation TemplateKWLoc,
2075                                const TemplateArgumentListInfo *TemplateArgs) {
2076   // Only try to recover from lookup into dependent bases in static methods or
2077   // contexts where 'this' is available.
2078   QualType ThisType = S.getCurrentThisType();
2079   const CXXRecordDecl *RD = nullptr;
2080   if (!ThisType.isNull())
2081     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2082   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2083     RD = MD->getParent();
2084   if (!RD || !RD->hasAnyDependentBases())
2085     return nullptr;
2086 
2087   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2088   // is available, suggest inserting 'this->' as a fixit.
2089   SourceLocation Loc = NameInfo.getLoc();
2090   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2091   DB << NameInfo.getName() << RD;
2092 
2093   if (!ThisType.isNull()) {
2094     DB << FixItHint::CreateInsertion(Loc, "this->");
2095     return CXXDependentScopeMemberExpr::Create(
2096         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2097         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2098         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2099   }
2100 
2101   // Synthesize a fake NNS that points to the derived class.  This will
2102   // perform name lookup during template instantiation.
2103   CXXScopeSpec SS;
2104   auto *NNS =
2105       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2106   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2107   return DependentScopeDeclRefExpr::Create(
2108       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2109       TemplateArgs);
2110 }
2111 
2112 ExprResult
2113 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2114                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2115                         bool HasTrailingLParen, bool IsAddressOfOperand,
2116                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2117                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2118   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2119          "cannot be direct & operand and have a trailing lparen");
2120   if (SS.isInvalid())
2121     return ExprError();
2122 
2123   TemplateArgumentListInfo TemplateArgsBuffer;
2124 
2125   // Decompose the UnqualifiedId into the following data.
2126   DeclarationNameInfo NameInfo;
2127   const TemplateArgumentListInfo *TemplateArgs;
2128   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2129 
2130   DeclarationName Name = NameInfo.getName();
2131   IdentifierInfo *II = Name.getAsIdentifierInfo();
2132   SourceLocation NameLoc = NameInfo.getLoc();
2133 
2134   // C++ [temp.dep.expr]p3:
2135   //   An id-expression is type-dependent if it contains:
2136   //     -- an identifier that was declared with a dependent type,
2137   //        (note: handled after lookup)
2138   //     -- a template-id that is dependent,
2139   //        (note: handled in BuildTemplateIdExpr)
2140   //     -- a conversion-function-id that specifies a dependent type,
2141   //     -- a nested-name-specifier that contains a class-name that
2142   //        names a dependent type.
2143   // Determine whether this is a member of an unknown specialization;
2144   // we need to handle these differently.
2145   bool DependentID = false;
2146   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2147       Name.getCXXNameType()->isDependentType()) {
2148     DependentID = true;
2149   } else if (SS.isSet()) {
2150     if (DeclContext *DC = computeDeclContext(SS, false)) {
2151       if (RequireCompleteDeclContext(SS, DC))
2152         return ExprError();
2153     } else {
2154       DependentID = true;
2155     }
2156   }
2157 
2158   if (DependentID)
2159     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2160                                       IsAddressOfOperand, TemplateArgs);
2161 
2162   // Perform the required lookup.
2163   LookupResult R(*this, NameInfo,
2164                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2165                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2166   if (TemplateArgs) {
2167     // Lookup the template name again to correctly establish the context in
2168     // which it was found. This is really unfortunate as we already did the
2169     // lookup to determine that it was a template name in the first place. If
2170     // this becomes a performance hit, we can work harder to preserve those
2171     // results until we get here but it's likely not worth it.
2172     bool MemberOfUnknownSpecialization;
2173     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2174                        MemberOfUnknownSpecialization);
2175 
2176     if (MemberOfUnknownSpecialization ||
2177         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2178       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2179                                         IsAddressOfOperand, TemplateArgs);
2180   } else {
2181     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2182     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2183 
2184     // If the result might be in a dependent base class, this is a dependent
2185     // id-expression.
2186     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2187       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2188                                         IsAddressOfOperand, TemplateArgs);
2189 
2190     // If this reference is in an Objective-C method, then we need to do
2191     // some special Objective-C lookup, too.
2192     if (IvarLookupFollowUp) {
2193       ExprResult E(LookupInObjCMethod(R, S, II, true));
2194       if (E.isInvalid())
2195         return ExprError();
2196 
2197       if (Expr *Ex = E.getAs<Expr>())
2198         return Ex;
2199     }
2200   }
2201 
2202   if (R.isAmbiguous())
2203     return ExprError();
2204 
2205   // This could be an implicitly declared function reference (legal in C90,
2206   // extension in C99, forbidden in C++).
2207   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2208     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2209     if (D) R.addDecl(D);
2210   }
2211 
2212   // Determine whether this name might be a candidate for
2213   // argument-dependent lookup.
2214   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2215 
2216   if (R.empty() && !ADL) {
2217     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2218       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2219                                                    TemplateKWLoc, TemplateArgs))
2220         return E;
2221     }
2222 
2223     // Don't diagnose an empty lookup for inline assembly.
2224     if (IsInlineAsmIdentifier)
2225       return ExprError();
2226 
2227     // If this name wasn't predeclared and if this is not a function
2228     // call, diagnose the problem.
2229     TypoExpr *TE = nullptr;
2230     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2231         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2232     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2233     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2234            "Typo correction callback misconfigured");
2235     if (CCC) {
2236       // Make sure the callback knows what the typo being diagnosed is.
2237       CCC->setTypoName(II);
2238       if (SS.isValid())
2239         CCC->setTypoNNS(SS.getScopeRep());
2240     }
2241     if (DiagnoseEmptyLookup(S, SS, R,
2242                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2243                             nullptr, None, &TE)) {
2244       if (TE && KeywordReplacement) {
2245         auto &State = getTypoExprState(TE);
2246         auto BestTC = State.Consumer->getNextCorrection();
2247         if (BestTC.isKeyword()) {
2248           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2249           if (State.DiagHandler)
2250             State.DiagHandler(BestTC);
2251           KeywordReplacement->startToken();
2252           KeywordReplacement->setKind(II->getTokenID());
2253           KeywordReplacement->setIdentifierInfo(II);
2254           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2255           // Clean up the state associated with the TypoExpr, since it has
2256           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2257           clearDelayedTypo(TE);
2258           // Signal that a correction to a keyword was performed by returning a
2259           // valid-but-null ExprResult.
2260           return (Expr*)nullptr;
2261         }
2262         State.Consumer->resetCorrectionStream();
2263       }
2264       return TE ? TE : ExprError();
2265     }
2266 
2267     assert(!R.empty() &&
2268            "DiagnoseEmptyLookup returned false but added no results");
2269 
2270     // If we found an Objective-C instance variable, let
2271     // LookupInObjCMethod build the appropriate expression to
2272     // reference the ivar.
2273     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2274       R.clear();
2275       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2276       // In a hopelessly buggy code, Objective-C instance variable
2277       // lookup fails and no expression will be built to reference it.
2278       if (!E.isInvalid() && !E.get())
2279         return ExprError();
2280       return E;
2281     }
2282   }
2283 
2284   // This is guaranteed from this point on.
2285   assert(!R.empty() || ADL);
2286 
2287   // Check whether this might be a C++ implicit instance member access.
2288   // C++ [class.mfct.non-static]p3:
2289   //   When an id-expression that is not part of a class member access
2290   //   syntax and not used to form a pointer to member is used in the
2291   //   body of a non-static member function of class X, if name lookup
2292   //   resolves the name in the id-expression to a non-static non-type
2293   //   member of some class C, the id-expression is transformed into a
2294   //   class member access expression using (*this) as the
2295   //   postfix-expression to the left of the . operator.
2296   //
2297   // But we don't actually need to do this for '&' operands if R
2298   // resolved to a function or overloaded function set, because the
2299   // expression is ill-formed if it actually works out to be a
2300   // non-static member function:
2301   //
2302   // C++ [expr.ref]p4:
2303   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2304   //   [t]he expression can be used only as the left-hand operand of a
2305   //   member function call.
2306   //
2307   // There are other safeguards against such uses, but it's important
2308   // to get this right here so that we don't end up making a
2309   // spuriously dependent expression if we're inside a dependent
2310   // instance method.
2311   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2312     bool MightBeImplicitMember;
2313     if (!IsAddressOfOperand)
2314       MightBeImplicitMember = true;
2315     else if (!SS.isEmpty())
2316       MightBeImplicitMember = false;
2317     else if (R.isOverloadedResult())
2318       MightBeImplicitMember = false;
2319     else if (R.isUnresolvableResult())
2320       MightBeImplicitMember = true;
2321     else
2322       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2323                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2324                               isa<MSPropertyDecl>(R.getFoundDecl());
2325 
2326     if (MightBeImplicitMember)
2327       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2328                                              R, TemplateArgs, S);
2329   }
2330 
2331   if (TemplateArgs || TemplateKWLoc.isValid()) {
2332 
2333     // In C++1y, if this is a variable template id, then check it
2334     // in BuildTemplateIdExpr().
2335     // The single lookup result must be a variable template declaration.
2336     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2337         Id.TemplateId->Kind == TNK_Var_template) {
2338       assert(R.getAsSingle<VarTemplateDecl>() &&
2339              "There should only be one declaration found.");
2340     }
2341 
2342     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2343   }
2344 
2345   return BuildDeclarationNameExpr(SS, R, ADL);
2346 }
2347 
2348 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2349 /// declaration name, generally during template instantiation.
2350 /// There's a large number of things which don't need to be done along
2351 /// this path.
2352 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2353     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2354     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2355   DeclContext *DC = computeDeclContext(SS, false);
2356   if (!DC)
2357     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2358                                      NameInfo, /*TemplateArgs=*/nullptr);
2359 
2360   if (RequireCompleteDeclContext(SS, DC))
2361     return ExprError();
2362 
2363   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2364   LookupQualifiedName(R, DC);
2365 
2366   if (R.isAmbiguous())
2367     return ExprError();
2368 
2369   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2370     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2371                                      NameInfo, /*TemplateArgs=*/nullptr);
2372 
2373   if (R.empty()) {
2374     Diag(NameInfo.getLoc(), diag::err_no_member)
2375       << NameInfo.getName() << DC << SS.getRange();
2376     return ExprError();
2377   }
2378 
2379   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2380     // Diagnose a missing typename if this resolved unambiguously to a type in
2381     // a dependent context.  If we can recover with a type, downgrade this to
2382     // a warning in Microsoft compatibility mode.
2383     unsigned DiagID = diag::err_typename_missing;
2384     if (RecoveryTSI && getLangOpts().MSVCCompat)
2385       DiagID = diag::ext_typename_missing;
2386     SourceLocation Loc = SS.getBeginLoc();
2387     auto D = Diag(Loc, DiagID);
2388     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2389       << SourceRange(Loc, NameInfo.getEndLoc());
2390 
2391     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2392     // context.
2393     if (!RecoveryTSI)
2394       return ExprError();
2395 
2396     // Only issue the fixit if we're prepared to recover.
2397     D << FixItHint::CreateInsertion(Loc, "typename ");
2398 
2399     // Recover by pretending this was an elaborated type.
2400     QualType Ty = Context.getTypeDeclType(TD);
2401     TypeLocBuilder TLB;
2402     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2403 
2404     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2405     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2406     QTL.setElaboratedKeywordLoc(SourceLocation());
2407     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2408 
2409     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2410 
2411     return ExprEmpty();
2412   }
2413 
2414   // Defend against this resolving to an implicit member access. We usually
2415   // won't get here if this might be a legitimate a class member (we end up in
2416   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2417   // a pointer-to-member or in an unevaluated context in C++11.
2418   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2419     return BuildPossibleImplicitMemberExpr(SS,
2420                                            /*TemplateKWLoc=*/SourceLocation(),
2421                                            R, /*TemplateArgs=*/nullptr, S);
2422 
2423   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2424 }
2425 
2426 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2427 /// detected that we're currently inside an ObjC method.  Perform some
2428 /// additional lookup.
2429 ///
2430 /// Ideally, most of this would be done by lookup, but there's
2431 /// actually quite a lot of extra work involved.
2432 ///
2433 /// Returns a null sentinel to indicate trivial success.
2434 ExprResult
2435 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2436                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2437   SourceLocation Loc = Lookup.getNameLoc();
2438   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2439 
2440   // Check for error condition which is already reported.
2441   if (!CurMethod)
2442     return ExprError();
2443 
2444   // There are two cases to handle here.  1) scoped lookup could have failed,
2445   // in which case we should look for an ivar.  2) scoped lookup could have
2446   // found a decl, but that decl is outside the current instance method (i.e.
2447   // a global variable).  In these two cases, we do a lookup for an ivar with
2448   // this name, if the lookup sucedes, we replace it our current decl.
2449 
2450   // If we're in a class method, we don't normally want to look for
2451   // ivars.  But if we don't find anything else, and there's an
2452   // ivar, that's an error.
2453   bool IsClassMethod = CurMethod->isClassMethod();
2454 
2455   bool LookForIvars;
2456   if (Lookup.empty())
2457     LookForIvars = true;
2458   else if (IsClassMethod)
2459     LookForIvars = false;
2460   else
2461     LookForIvars = (Lookup.isSingleResult() &&
2462                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2463   ObjCInterfaceDecl *IFace = nullptr;
2464   if (LookForIvars) {
2465     IFace = CurMethod->getClassInterface();
2466     ObjCInterfaceDecl *ClassDeclared;
2467     ObjCIvarDecl *IV = nullptr;
2468     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2469       // Diagnose using an ivar in a class method.
2470       if (IsClassMethod)
2471         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2472                          << IV->getDeclName());
2473 
2474       // If we're referencing an invalid decl, just return this as a silent
2475       // error node.  The error diagnostic was already emitted on the decl.
2476       if (IV->isInvalidDecl())
2477         return ExprError();
2478 
2479       // Check if referencing a field with __attribute__((deprecated)).
2480       if (DiagnoseUseOfDecl(IV, Loc))
2481         return ExprError();
2482 
2483       // Diagnose the use of an ivar outside of the declaring class.
2484       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2485           !declaresSameEntity(ClassDeclared, IFace) &&
2486           !getLangOpts().DebuggerSupport)
2487         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2488 
2489       // FIXME: This should use a new expr for a direct reference, don't
2490       // turn this into Self->ivar, just return a BareIVarExpr or something.
2491       IdentifierInfo &II = Context.Idents.get("self");
2492       UnqualifiedId SelfName;
2493       SelfName.setIdentifier(&II, SourceLocation());
2494       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2495       CXXScopeSpec SelfScopeSpec;
2496       SourceLocation TemplateKWLoc;
2497       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2498                                               SelfName, false, false);
2499       if (SelfExpr.isInvalid())
2500         return ExprError();
2501 
2502       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2503       if (SelfExpr.isInvalid())
2504         return ExprError();
2505 
2506       MarkAnyDeclReferenced(Loc, IV, true);
2507 
2508       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2509       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2510           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2511         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2512 
2513       ObjCIvarRefExpr *Result = new (Context)
2514           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2515                           IV->getLocation(), SelfExpr.get(), true, true);
2516 
2517       if (getLangOpts().ObjCAutoRefCount) {
2518         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2519           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2520             recordUseOfEvaluatedWeak(Result);
2521         }
2522         if (CurContext->isClosure())
2523           Diag(Loc, diag::warn_implicitly_retains_self)
2524             << FixItHint::CreateInsertion(Loc, "self->");
2525       }
2526 
2527       return Result;
2528     }
2529   } else if (CurMethod->isInstanceMethod()) {
2530     // We should warn if a local variable hides an ivar.
2531     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2532       ObjCInterfaceDecl *ClassDeclared;
2533       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2534         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2535             declaresSameEntity(IFace, ClassDeclared))
2536           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2537       }
2538     }
2539   } else if (Lookup.isSingleResult() &&
2540              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2541     // If accessing a stand-alone ivar in a class method, this is an error.
2542     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2543       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2544                        << IV->getDeclName());
2545   }
2546 
2547   if (Lookup.empty() && II && AllowBuiltinCreation) {
2548     // FIXME. Consolidate this with similar code in LookupName.
2549     if (unsigned BuiltinID = II->getBuiltinID()) {
2550       if (!(getLangOpts().CPlusPlus &&
2551             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2552         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2553                                            S, Lookup.isForRedeclaration(),
2554                                            Lookup.getNameLoc());
2555         if (D) Lookup.addDecl(D);
2556       }
2557     }
2558   }
2559   // Sentinel value saying that we didn't do anything special.
2560   return ExprResult((Expr *)nullptr);
2561 }
2562 
2563 /// \brief Cast a base object to a member's actual type.
2564 ///
2565 /// Logically this happens in three phases:
2566 ///
2567 /// * First we cast from the base type to the naming class.
2568 ///   The naming class is the class into which we were looking
2569 ///   when we found the member;  it's the qualifier type if a
2570 ///   qualifier was provided, and otherwise it's the base type.
2571 ///
2572 /// * Next we cast from the naming class to the declaring class.
2573 ///   If the member we found was brought into a class's scope by
2574 ///   a using declaration, this is that class;  otherwise it's
2575 ///   the class declaring the member.
2576 ///
2577 /// * Finally we cast from the declaring class to the "true"
2578 ///   declaring class of the member.  This conversion does not
2579 ///   obey access control.
2580 ExprResult
2581 Sema::PerformObjectMemberConversion(Expr *From,
2582                                     NestedNameSpecifier *Qualifier,
2583                                     NamedDecl *FoundDecl,
2584                                     NamedDecl *Member) {
2585   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2586   if (!RD)
2587     return From;
2588 
2589   QualType DestRecordType;
2590   QualType DestType;
2591   QualType FromRecordType;
2592   QualType FromType = From->getType();
2593   bool PointerConversions = false;
2594   if (isa<FieldDecl>(Member)) {
2595     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2596 
2597     if (FromType->getAs<PointerType>()) {
2598       DestType = Context.getPointerType(DestRecordType);
2599       FromRecordType = FromType->getPointeeType();
2600       PointerConversions = true;
2601     } else {
2602       DestType = DestRecordType;
2603       FromRecordType = FromType;
2604     }
2605   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2606     if (Method->isStatic())
2607       return From;
2608 
2609     DestType = Method->getThisType(Context);
2610     DestRecordType = DestType->getPointeeType();
2611 
2612     if (FromType->getAs<PointerType>()) {
2613       FromRecordType = FromType->getPointeeType();
2614       PointerConversions = true;
2615     } else {
2616       FromRecordType = FromType;
2617       DestType = DestRecordType;
2618     }
2619   } else {
2620     // No conversion necessary.
2621     return From;
2622   }
2623 
2624   if (DestType->isDependentType() || FromType->isDependentType())
2625     return From;
2626 
2627   // If the unqualified types are the same, no conversion is necessary.
2628   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2629     return From;
2630 
2631   SourceRange FromRange = From->getSourceRange();
2632   SourceLocation FromLoc = FromRange.getBegin();
2633 
2634   ExprValueKind VK = From->getValueKind();
2635 
2636   // C++ [class.member.lookup]p8:
2637   //   [...] Ambiguities can often be resolved by qualifying a name with its
2638   //   class name.
2639   //
2640   // If the member was a qualified name and the qualified referred to a
2641   // specific base subobject type, we'll cast to that intermediate type
2642   // first and then to the object in which the member is declared. That allows
2643   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2644   //
2645   //   class Base { public: int x; };
2646   //   class Derived1 : public Base { };
2647   //   class Derived2 : public Base { };
2648   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2649   //
2650   //   void VeryDerived::f() {
2651   //     x = 17; // error: ambiguous base subobjects
2652   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2653   //   }
2654   if (Qualifier && Qualifier->getAsType()) {
2655     QualType QType = QualType(Qualifier->getAsType(), 0);
2656     assert(QType->isRecordType() && "lookup done with non-record type");
2657 
2658     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2659 
2660     // In C++98, the qualifier type doesn't actually have to be a base
2661     // type of the object type, in which case we just ignore it.
2662     // Otherwise build the appropriate casts.
2663     if (IsDerivedFrom(FromLoc, FromRecordType, QRecordType)) {
2664       CXXCastPath BasePath;
2665       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2666                                        FromLoc, FromRange, &BasePath))
2667         return ExprError();
2668 
2669       if (PointerConversions)
2670         QType = Context.getPointerType(QType);
2671       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2672                                VK, &BasePath).get();
2673 
2674       FromType = QType;
2675       FromRecordType = QRecordType;
2676 
2677       // If the qualifier type was the same as the destination type,
2678       // we're done.
2679       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2680         return From;
2681     }
2682   }
2683 
2684   bool IgnoreAccess = false;
2685 
2686   // If we actually found the member through a using declaration, cast
2687   // down to the using declaration's type.
2688   //
2689   // Pointer equality is fine here because only one declaration of a
2690   // class ever has member declarations.
2691   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2692     assert(isa<UsingShadowDecl>(FoundDecl));
2693     QualType URecordType = Context.getTypeDeclType(
2694                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2695 
2696     // We only need to do this if the naming-class to declaring-class
2697     // conversion is non-trivial.
2698     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2699       assert(IsDerivedFrom(FromLoc, FromRecordType, URecordType));
2700       CXXCastPath BasePath;
2701       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2702                                        FromLoc, FromRange, &BasePath))
2703         return ExprError();
2704 
2705       QualType UType = URecordType;
2706       if (PointerConversions)
2707         UType = Context.getPointerType(UType);
2708       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2709                                VK, &BasePath).get();
2710       FromType = UType;
2711       FromRecordType = URecordType;
2712     }
2713 
2714     // We don't do access control for the conversion from the
2715     // declaring class to the true declaring class.
2716     IgnoreAccess = true;
2717   }
2718 
2719   CXXCastPath BasePath;
2720   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2721                                    FromLoc, FromRange, &BasePath,
2722                                    IgnoreAccess))
2723     return ExprError();
2724 
2725   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2726                            VK, &BasePath);
2727 }
2728 
2729 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2730                                       const LookupResult &R,
2731                                       bool HasTrailingLParen) {
2732   // Only when used directly as the postfix-expression of a call.
2733   if (!HasTrailingLParen)
2734     return false;
2735 
2736   // Never if a scope specifier was provided.
2737   if (SS.isSet())
2738     return false;
2739 
2740   // Only in C++ or ObjC++.
2741   if (!getLangOpts().CPlusPlus)
2742     return false;
2743 
2744   // Turn off ADL when we find certain kinds of declarations during
2745   // normal lookup:
2746   for (NamedDecl *D : R) {
2747     // C++0x [basic.lookup.argdep]p3:
2748     //     -- a declaration of a class member
2749     // Since using decls preserve this property, we check this on the
2750     // original decl.
2751     if (D->isCXXClassMember())
2752       return false;
2753 
2754     // C++0x [basic.lookup.argdep]p3:
2755     //     -- a block-scope function declaration that is not a
2756     //        using-declaration
2757     // NOTE: we also trigger this for function templates (in fact, we
2758     // don't check the decl type at all, since all other decl types
2759     // turn off ADL anyway).
2760     if (isa<UsingShadowDecl>(D))
2761       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2762     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2763       return false;
2764 
2765     // C++0x [basic.lookup.argdep]p3:
2766     //     -- a declaration that is neither a function or a function
2767     //        template
2768     // And also for builtin functions.
2769     if (isa<FunctionDecl>(D)) {
2770       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2771 
2772       // But also builtin functions.
2773       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2774         return false;
2775     } else if (!isa<FunctionTemplateDecl>(D))
2776       return false;
2777   }
2778 
2779   return true;
2780 }
2781 
2782 
2783 /// Diagnoses obvious problems with the use of the given declaration
2784 /// as an expression.  This is only actually called for lookups that
2785 /// were not overloaded, and it doesn't promise that the declaration
2786 /// will in fact be used.
2787 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2788   if (isa<TypedefNameDecl>(D)) {
2789     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2790     return true;
2791   }
2792 
2793   if (isa<ObjCInterfaceDecl>(D)) {
2794     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2795     return true;
2796   }
2797 
2798   if (isa<NamespaceDecl>(D)) {
2799     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2800     return true;
2801   }
2802 
2803   return false;
2804 }
2805 
2806 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2807                                           LookupResult &R, bool NeedsADL,
2808                                           bool AcceptInvalidDecl) {
2809   // If this is a single, fully-resolved result and we don't need ADL,
2810   // just build an ordinary singleton decl ref.
2811   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2812     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2813                                     R.getRepresentativeDecl(), nullptr,
2814                                     AcceptInvalidDecl);
2815 
2816   // We only need to check the declaration if there's exactly one
2817   // result, because in the overloaded case the results can only be
2818   // functions and function templates.
2819   if (R.isSingleResult() &&
2820       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2821     return ExprError();
2822 
2823   // Otherwise, just build an unresolved lookup expression.  Suppress
2824   // any lookup-related diagnostics; we'll hash these out later, when
2825   // we've picked a target.
2826   R.suppressDiagnostics();
2827 
2828   UnresolvedLookupExpr *ULE
2829     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2830                                    SS.getWithLocInContext(Context),
2831                                    R.getLookupNameInfo(),
2832                                    NeedsADL, R.isOverloadedResult(),
2833                                    R.begin(), R.end());
2834 
2835   return ULE;
2836 }
2837 
2838 static void
2839 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
2840                                    ValueDecl *var, DeclContext *DC);
2841 
2842 /// \brief Complete semantic analysis for a reference to the given declaration.
2843 ExprResult Sema::BuildDeclarationNameExpr(
2844     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2845     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2846     bool AcceptInvalidDecl) {
2847   assert(D && "Cannot refer to a NULL declaration");
2848   assert(!isa<FunctionTemplateDecl>(D) &&
2849          "Cannot refer unambiguously to a function template");
2850 
2851   SourceLocation Loc = NameInfo.getLoc();
2852   if (CheckDeclInExpr(*this, Loc, D))
2853     return ExprError();
2854 
2855   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2856     // Specifically diagnose references to class templates that are missing
2857     // a template argument list.
2858     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2859                                            << Template << SS.getRange();
2860     Diag(Template->getLocation(), diag::note_template_decl_here);
2861     return ExprError();
2862   }
2863 
2864   // Make sure that we're referring to a value.
2865   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2866   if (!VD) {
2867     Diag(Loc, diag::err_ref_non_value)
2868       << D << SS.getRange();
2869     Diag(D->getLocation(), diag::note_declared_at);
2870     return ExprError();
2871   }
2872 
2873   // Check whether this declaration can be used. Note that we suppress
2874   // this check when we're going to perform argument-dependent lookup
2875   // on this function name, because this might not be the function
2876   // that overload resolution actually selects.
2877   if (DiagnoseUseOfDecl(VD, Loc))
2878     return ExprError();
2879 
2880   // Only create DeclRefExpr's for valid Decl's.
2881   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2882     return ExprError();
2883 
2884   // Handle members of anonymous structs and unions.  If we got here,
2885   // and the reference is to a class member indirect field, then this
2886   // must be the subject of a pointer-to-member expression.
2887   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2888     if (!indirectField->isCXXClassMember())
2889       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2890                                                       indirectField);
2891 
2892   {
2893     QualType type = VD->getType();
2894     ExprValueKind valueKind = VK_RValue;
2895 
2896     switch (D->getKind()) {
2897     // Ignore all the non-ValueDecl kinds.
2898 #define ABSTRACT_DECL(kind)
2899 #define VALUE(type, base)
2900 #define DECL(type, base) \
2901     case Decl::type:
2902 #include "clang/AST/DeclNodes.inc"
2903       llvm_unreachable("invalid value decl kind");
2904 
2905     // These shouldn't make it here.
2906     case Decl::ObjCAtDefsField:
2907     case Decl::ObjCIvar:
2908       llvm_unreachable("forming non-member reference to ivar?");
2909 
2910     // Enum constants are always r-values and never references.
2911     // Unresolved using declarations are dependent.
2912     case Decl::EnumConstant:
2913     case Decl::UnresolvedUsingValue:
2914     case Decl::OMPDeclareReduction:
2915       valueKind = VK_RValue;
2916       break;
2917 
2918     // Fields and indirect fields that got here must be for
2919     // pointer-to-member expressions; we just call them l-values for
2920     // internal consistency, because this subexpression doesn't really
2921     // exist in the high-level semantics.
2922     case Decl::Field:
2923     case Decl::IndirectField:
2924       assert(getLangOpts().CPlusPlus &&
2925              "building reference to field in C?");
2926 
2927       // These can't have reference type in well-formed programs, but
2928       // for internal consistency we do this anyway.
2929       type = type.getNonReferenceType();
2930       valueKind = VK_LValue;
2931       break;
2932 
2933     // Non-type template parameters are either l-values or r-values
2934     // depending on the type.
2935     case Decl::NonTypeTemplateParm: {
2936       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2937         type = reftype->getPointeeType();
2938         valueKind = VK_LValue; // even if the parameter is an r-value reference
2939         break;
2940       }
2941 
2942       // For non-references, we need to strip qualifiers just in case
2943       // the template parameter was declared as 'const int' or whatever.
2944       valueKind = VK_RValue;
2945       type = type.getUnqualifiedType();
2946       break;
2947     }
2948 
2949     case Decl::Var:
2950     case Decl::VarTemplateSpecialization:
2951     case Decl::VarTemplatePartialSpecialization:
2952     case Decl::Decomposition:
2953     case Decl::OMPCapturedExpr:
2954       // In C, "extern void blah;" is valid and is an r-value.
2955       if (!getLangOpts().CPlusPlus &&
2956           !type.hasQualifiers() &&
2957           type->isVoidType()) {
2958         valueKind = VK_RValue;
2959         break;
2960       }
2961       // fallthrough
2962 
2963     case Decl::ImplicitParam:
2964     case Decl::ParmVar: {
2965       // These are always l-values.
2966       valueKind = VK_LValue;
2967       type = type.getNonReferenceType();
2968 
2969       // FIXME: Does the addition of const really only apply in
2970       // potentially-evaluated contexts? Since the variable isn't actually
2971       // captured in an unevaluated context, it seems that the answer is no.
2972       if (!isUnevaluatedContext()) {
2973         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2974         if (!CapturedType.isNull())
2975           type = CapturedType;
2976       }
2977 
2978       break;
2979     }
2980 
2981     case Decl::Binding: {
2982       // These are always lvalues.
2983       valueKind = VK_LValue;
2984       type = type.getNonReferenceType();
2985       // FIXME: Support lambda-capture of BindingDecls, once CWG actually
2986       // decides how that's supposed to work.
2987       auto *BD = cast<BindingDecl>(VD);
2988       if (BD->getDeclContext()->isFunctionOrMethod() &&
2989           BD->getDeclContext() != CurContext)
2990         diagnoseUncapturableValueReference(*this, Loc, BD, CurContext);
2991       break;
2992     }
2993 
2994     case Decl::Function: {
2995       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2996         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2997           type = Context.BuiltinFnTy;
2998           valueKind = VK_RValue;
2999           break;
3000         }
3001       }
3002 
3003       const FunctionType *fty = type->castAs<FunctionType>();
3004 
3005       // If we're referring to a function with an __unknown_anytype
3006       // result type, make the entire expression __unknown_anytype.
3007       if (fty->getReturnType() == Context.UnknownAnyTy) {
3008         type = Context.UnknownAnyTy;
3009         valueKind = VK_RValue;
3010         break;
3011       }
3012 
3013       // Functions are l-values in C++.
3014       if (getLangOpts().CPlusPlus) {
3015         valueKind = VK_LValue;
3016         break;
3017       }
3018 
3019       // C99 DR 316 says that, if a function type comes from a
3020       // function definition (without a prototype), that type is only
3021       // used for checking compatibility. Therefore, when referencing
3022       // the function, we pretend that we don't have the full function
3023       // type.
3024       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
3025           isa<FunctionProtoType>(fty))
3026         type = Context.getFunctionNoProtoType(fty->getReturnType(),
3027                                               fty->getExtInfo());
3028 
3029       // Functions are r-values in C.
3030       valueKind = VK_RValue;
3031       break;
3032     }
3033 
3034     case Decl::MSProperty:
3035       valueKind = VK_LValue;
3036       break;
3037 
3038     case Decl::CXXMethod:
3039       // If we're referring to a method with an __unknown_anytype
3040       // result type, make the entire expression __unknown_anytype.
3041       // This should only be possible with a type written directly.
3042       if (const FunctionProtoType *proto
3043             = dyn_cast<FunctionProtoType>(VD->getType()))
3044         if (proto->getReturnType() == Context.UnknownAnyTy) {
3045           type = Context.UnknownAnyTy;
3046           valueKind = VK_RValue;
3047           break;
3048         }
3049 
3050       // C++ methods are l-values if static, r-values if non-static.
3051       if (cast<CXXMethodDecl>(VD)->isStatic()) {
3052         valueKind = VK_LValue;
3053         break;
3054       }
3055       // fallthrough
3056 
3057     case Decl::CXXConversion:
3058     case Decl::CXXDestructor:
3059     case Decl::CXXConstructor:
3060       valueKind = VK_RValue;
3061       break;
3062     }
3063 
3064     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
3065                             TemplateArgs);
3066   }
3067 }
3068 
3069 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
3070                                     SmallString<32> &Target) {
3071   Target.resize(CharByteWidth * (Source.size() + 1));
3072   char *ResultPtr = &Target[0];
3073   const UTF8 *ErrorPtr;
3074   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
3075   (void)success;
3076   assert(success);
3077   Target.resize(ResultPtr - &Target[0]);
3078 }
3079 
3080 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
3081                                      PredefinedExpr::IdentType IT) {
3082   // Pick the current block, lambda, captured statement or function.
3083   Decl *currentDecl = nullptr;
3084   if (const BlockScopeInfo *BSI = getCurBlock())
3085     currentDecl = BSI->TheDecl;
3086   else if (const LambdaScopeInfo *LSI = getCurLambda())
3087     currentDecl = LSI->CallOperator;
3088   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3089     currentDecl = CSI->TheCapturedDecl;
3090   else
3091     currentDecl = getCurFunctionOrMethodDecl();
3092 
3093   if (!currentDecl) {
3094     Diag(Loc, diag::ext_predef_outside_function);
3095     currentDecl = Context.getTranslationUnitDecl();
3096   }
3097 
3098   QualType ResTy;
3099   StringLiteral *SL = nullptr;
3100   if (cast<DeclContext>(currentDecl)->isDependentContext())
3101     ResTy = Context.DependentTy;
3102   else {
3103     // Pre-defined identifiers are of type char[x], where x is the length of
3104     // the string.
3105     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3106     unsigned Length = Str.length();
3107 
3108     llvm::APInt LengthI(32, Length + 1);
3109     if (IT == PredefinedExpr::LFunction) {
3110       ResTy = Context.WideCharTy.withConst();
3111       SmallString<32> RawChars;
3112       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3113                               Str, RawChars);
3114       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3115                                            /*IndexTypeQuals*/ 0);
3116       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3117                                  /*Pascal*/ false, ResTy, Loc);
3118     } else {
3119       ResTy = Context.CharTy.withConst();
3120       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3121                                            /*IndexTypeQuals*/ 0);
3122       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3123                                  /*Pascal*/ false, ResTy, Loc);
3124     }
3125   }
3126 
3127   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3128 }
3129 
3130 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3131   PredefinedExpr::IdentType IT;
3132 
3133   switch (Kind) {
3134   default: llvm_unreachable("Unknown simple primary expr!");
3135   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3136   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3137   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3138   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3139   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3140   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3141   }
3142 
3143   return BuildPredefinedExpr(Loc, IT);
3144 }
3145 
3146 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3147   SmallString<16> CharBuffer;
3148   bool Invalid = false;
3149   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3150   if (Invalid)
3151     return ExprError();
3152 
3153   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3154                             PP, Tok.getKind());
3155   if (Literal.hadError())
3156     return ExprError();
3157 
3158   QualType Ty;
3159   if (Literal.isWide())
3160     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3161   else if (Literal.isUTF16())
3162     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3163   else if (Literal.isUTF32())
3164     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3165   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3166     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3167   else
3168     Ty = Context.CharTy;  // 'x' -> char in C++
3169 
3170   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3171   if (Literal.isWide())
3172     Kind = CharacterLiteral::Wide;
3173   else if (Literal.isUTF16())
3174     Kind = CharacterLiteral::UTF16;
3175   else if (Literal.isUTF32())
3176     Kind = CharacterLiteral::UTF32;
3177   else if (Literal.isUTF8())
3178     Kind = CharacterLiteral::UTF8;
3179 
3180   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3181                                              Tok.getLocation());
3182 
3183   if (Literal.getUDSuffix().empty())
3184     return Lit;
3185 
3186   // We're building a user-defined literal.
3187   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3188   SourceLocation UDSuffixLoc =
3189     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3190 
3191   // Make sure we're allowed user-defined literals here.
3192   if (!UDLScope)
3193     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3194 
3195   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3196   //   operator "" X (ch)
3197   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3198                                         Lit, Tok.getLocation());
3199 }
3200 
3201 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3202   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3203   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3204                                 Context.IntTy, Loc);
3205 }
3206 
3207 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3208                                   QualType Ty, SourceLocation Loc) {
3209   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3210 
3211   using llvm::APFloat;
3212   APFloat Val(Format);
3213 
3214   APFloat::opStatus result = Literal.GetFloatValue(Val);
3215 
3216   // Overflow is always an error, but underflow is only an error if
3217   // we underflowed to zero (APFloat reports denormals as underflow).
3218   if ((result & APFloat::opOverflow) ||
3219       ((result & APFloat::opUnderflow) && Val.isZero())) {
3220     unsigned diagnostic;
3221     SmallString<20> buffer;
3222     if (result & APFloat::opOverflow) {
3223       diagnostic = diag::warn_float_overflow;
3224       APFloat::getLargest(Format).toString(buffer);
3225     } else {
3226       diagnostic = diag::warn_float_underflow;
3227       APFloat::getSmallest(Format).toString(buffer);
3228     }
3229 
3230     S.Diag(Loc, diagnostic)
3231       << Ty
3232       << StringRef(buffer.data(), buffer.size());
3233   }
3234 
3235   bool isExact = (result == APFloat::opOK);
3236   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3237 }
3238 
3239 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3240   assert(E && "Invalid expression");
3241 
3242   if (E->isValueDependent())
3243     return false;
3244 
3245   QualType QT = E->getType();
3246   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3247     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3248     return true;
3249   }
3250 
3251   llvm::APSInt ValueAPS;
3252   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3253 
3254   if (R.isInvalid())
3255     return true;
3256 
3257   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3258   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3259     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3260         << ValueAPS.toString(10) << ValueIsPositive;
3261     return true;
3262   }
3263 
3264   return false;
3265 }
3266 
3267 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3268   // Fast path for a single digit (which is quite common).  A single digit
3269   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3270   if (Tok.getLength() == 1) {
3271     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3272     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3273   }
3274 
3275   SmallString<128> SpellingBuffer;
3276   // NumericLiteralParser wants to overread by one character.  Add padding to
3277   // the buffer in case the token is copied to the buffer.  If getSpelling()
3278   // returns a StringRef to the memory buffer, it should have a null char at
3279   // the EOF, so it is also safe.
3280   SpellingBuffer.resize(Tok.getLength() + 1);
3281 
3282   // Get the spelling of the token, which eliminates trigraphs, etc.
3283   bool Invalid = false;
3284   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3285   if (Invalid)
3286     return ExprError();
3287 
3288   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3289   if (Literal.hadError)
3290     return ExprError();
3291 
3292   if (Literal.hasUDSuffix()) {
3293     // We're building a user-defined literal.
3294     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3295     SourceLocation UDSuffixLoc =
3296       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3297 
3298     // Make sure we're allowed user-defined literals here.
3299     if (!UDLScope)
3300       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3301 
3302     QualType CookedTy;
3303     if (Literal.isFloatingLiteral()) {
3304       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3305       // long double, the literal is treated as a call of the form
3306       //   operator "" X (f L)
3307       CookedTy = Context.LongDoubleTy;
3308     } else {
3309       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3310       // unsigned long long, the literal is treated as a call of the form
3311       //   operator "" X (n ULL)
3312       CookedTy = Context.UnsignedLongLongTy;
3313     }
3314 
3315     DeclarationName OpName =
3316       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3317     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3318     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3319 
3320     SourceLocation TokLoc = Tok.getLocation();
3321 
3322     // Perform literal operator lookup to determine if we're building a raw
3323     // literal or a cooked one.
3324     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3325     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3326                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3327                                   /*AllowStringTemplate*/false)) {
3328     case LOLR_Error:
3329       return ExprError();
3330 
3331     case LOLR_Cooked: {
3332       Expr *Lit;
3333       if (Literal.isFloatingLiteral()) {
3334         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3335       } else {
3336         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3337         if (Literal.GetIntegerValue(ResultVal))
3338           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3339               << /* Unsigned */ 1;
3340         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3341                                      Tok.getLocation());
3342       }
3343       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3344     }
3345 
3346     case LOLR_Raw: {
3347       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3348       // literal is treated as a call of the form
3349       //   operator "" X ("n")
3350       unsigned Length = Literal.getUDSuffixOffset();
3351       QualType StrTy = Context.getConstantArrayType(
3352           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3353           ArrayType::Normal, 0);
3354       Expr *Lit = StringLiteral::Create(
3355           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3356           /*Pascal*/false, StrTy, &TokLoc, 1);
3357       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3358     }
3359 
3360     case LOLR_Template: {
3361       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3362       // template), L is treated as a call fo the form
3363       //   operator "" X <'c1', 'c2', ... 'ck'>()
3364       // where n is the source character sequence c1 c2 ... ck.
3365       TemplateArgumentListInfo ExplicitArgs;
3366       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3367       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3368       llvm::APSInt Value(CharBits, CharIsUnsigned);
3369       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3370         Value = TokSpelling[I];
3371         TemplateArgument Arg(Context, Value, Context.CharTy);
3372         TemplateArgumentLocInfo ArgInfo;
3373         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3374       }
3375       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3376                                       &ExplicitArgs);
3377     }
3378     case LOLR_StringTemplate:
3379       llvm_unreachable("unexpected literal operator lookup result");
3380     }
3381   }
3382 
3383   Expr *Res;
3384 
3385   if (Literal.isFloatingLiteral()) {
3386     QualType Ty;
3387     if (Literal.isHalf){
3388       if (getOpenCLOptions().cl_khr_fp16)
3389         Ty = Context.HalfTy;
3390       else {
3391         Diag(Tok.getLocation(), diag::err_half_const_requires_fp16);
3392         return ExprError();
3393       }
3394     } else if (Literal.isFloat)
3395       Ty = Context.FloatTy;
3396     else if (Literal.isLong)
3397       Ty = Context.LongDoubleTy;
3398     else if (Literal.isFloat128)
3399       Ty = Context.Float128Ty;
3400     else
3401       Ty = Context.DoubleTy;
3402 
3403     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3404 
3405     if (Ty == Context.DoubleTy) {
3406       if (getLangOpts().SinglePrecisionConstants) {
3407         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3408       } else if (getLangOpts().OpenCL &&
3409                  !((getLangOpts().OpenCLVersion >= 120) ||
3410                    getOpenCLOptions().cl_khr_fp64)) {
3411         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3412         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3413       }
3414     }
3415   } else if (!Literal.isIntegerLiteral()) {
3416     return ExprError();
3417   } else {
3418     QualType Ty;
3419 
3420     // 'long long' is a C99 or C++11 feature.
3421     if (!getLangOpts().C99 && Literal.isLongLong) {
3422       if (getLangOpts().CPlusPlus)
3423         Diag(Tok.getLocation(),
3424              getLangOpts().CPlusPlus11 ?
3425              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3426       else
3427         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3428     }
3429 
3430     // Get the value in the widest-possible width.
3431     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3432     llvm::APInt ResultVal(MaxWidth, 0);
3433 
3434     if (Literal.GetIntegerValue(ResultVal)) {
3435       // If this value didn't fit into uintmax_t, error and force to ull.
3436       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3437           << /* Unsigned */ 1;
3438       Ty = Context.UnsignedLongLongTy;
3439       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3440              "long long is not intmax_t?");
3441     } else {
3442       // If this value fits into a ULL, try to figure out what else it fits into
3443       // according to the rules of C99 6.4.4.1p5.
3444 
3445       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3446       // be an unsigned int.
3447       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3448 
3449       // Check from smallest to largest, picking the smallest type we can.
3450       unsigned Width = 0;
3451 
3452       // Microsoft specific integer suffixes are explicitly sized.
3453       if (Literal.MicrosoftInteger) {
3454         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3455           Width = 8;
3456           Ty = Context.CharTy;
3457         } else {
3458           Width = Literal.MicrosoftInteger;
3459           Ty = Context.getIntTypeForBitwidth(Width,
3460                                              /*Signed=*/!Literal.isUnsigned);
3461         }
3462       }
3463 
3464       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3465         // Are int/unsigned possibilities?
3466         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3467 
3468         // Does it fit in a unsigned int?
3469         if (ResultVal.isIntN(IntSize)) {
3470           // Does it fit in a signed int?
3471           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3472             Ty = Context.IntTy;
3473           else if (AllowUnsigned)
3474             Ty = Context.UnsignedIntTy;
3475           Width = IntSize;
3476         }
3477       }
3478 
3479       // Are long/unsigned long possibilities?
3480       if (Ty.isNull() && !Literal.isLongLong) {
3481         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3482 
3483         // Does it fit in a unsigned long?
3484         if (ResultVal.isIntN(LongSize)) {
3485           // Does it fit in a signed long?
3486           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3487             Ty = Context.LongTy;
3488           else if (AllowUnsigned)
3489             Ty = Context.UnsignedLongTy;
3490           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3491           // is compatible.
3492           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3493             const unsigned LongLongSize =
3494                 Context.getTargetInfo().getLongLongWidth();
3495             Diag(Tok.getLocation(),
3496                  getLangOpts().CPlusPlus
3497                      ? Literal.isLong
3498                            ? diag::warn_old_implicitly_unsigned_long_cxx
3499                            : /*C++98 UB*/ diag::
3500                                  ext_old_implicitly_unsigned_long_cxx
3501                      : diag::warn_old_implicitly_unsigned_long)
3502                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3503                                             : /*will be ill-formed*/ 1);
3504             Ty = Context.UnsignedLongTy;
3505           }
3506           Width = LongSize;
3507         }
3508       }
3509 
3510       // Check long long if needed.
3511       if (Ty.isNull()) {
3512         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3513 
3514         // Does it fit in a unsigned long long?
3515         if (ResultVal.isIntN(LongLongSize)) {
3516           // Does it fit in a signed long long?
3517           // To be compatible with MSVC, hex integer literals ending with the
3518           // LL or i64 suffix are always signed in Microsoft mode.
3519           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3520               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3521             Ty = Context.LongLongTy;
3522           else if (AllowUnsigned)
3523             Ty = Context.UnsignedLongLongTy;
3524           Width = LongLongSize;
3525         }
3526       }
3527 
3528       // If we still couldn't decide a type, we probably have something that
3529       // does not fit in a signed long long, but has no U suffix.
3530       if (Ty.isNull()) {
3531         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3532         Ty = Context.UnsignedLongLongTy;
3533         Width = Context.getTargetInfo().getLongLongWidth();
3534       }
3535 
3536       if (ResultVal.getBitWidth() != Width)
3537         ResultVal = ResultVal.trunc(Width);
3538     }
3539     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3540   }
3541 
3542   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3543   if (Literal.isImaginary)
3544     Res = new (Context) ImaginaryLiteral(Res,
3545                                         Context.getComplexType(Res->getType()));
3546 
3547   return Res;
3548 }
3549 
3550 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3551   assert(E && "ActOnParenExpr() missing expr");
3552   return new (Context) ParenExpr(L, R, E);
3553 }
3554 
3555 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3556                                          SourceLocation Loc,
3557                                          SourceRange ArgRange) {
3558   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3559   // scalar or vector data type argument..."
3560   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3561   // type (C99 6.2.5p18) or void.
3562   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3563     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3564       << T << ArgRange;
3565     return true;
3566   }
3567 
3568   assert((T->isVoidType() || !T->isIncompleteType()) &&
3569          "Scalar types should always be complete");
3570   return false;
3571 }
3572 
3573 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3574                                            SourceLocation Loc,
3575                                            SourceRange ArgRange,
3576                                            UnaryExprOrTypeTrait TraitKind) {
3577   // Invalid types must be hard errors for SFINAE in C++.
3578   if (S.LangOpts.CPlusPlus)
3579     return true;
3580 
3581   // C99 6.5.3.4p1:
3582   if (T->isFunctionType() &&
3583       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3584     // sizeof(function)/alignof(function) is allowed as an extension.
3585     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3586       << TraitKind << ArgRange;
3587     return false;
3588   }
3589 
3590   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3591   // this is an error (OpenCL v1.1 s6.3.k)
3592   if (T->isVoidType()) {
3593     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3594                                         : diag::ext_sizeof_alignof_void_type;
3595     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3596     return false;
3597   }
3598 
3599   return true;
3600 }
3601 
3602 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3603                                              SourceLocation Loc,
3604                                              SourceRange ArgRange,
3605                                              UnaryExprOrTypeTrait TraitKind) {
3606   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3607   // runtime doesn't allow it.
3608   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3609     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3610       << T << (TraitKind == UETT_SizeOf)
3611       << ArgRange;
3612     return true;
3613   }
3614 
3615   return false;
3616 }
3617 
3618 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3619 /// pointer type is equal to T) and emit a warning if it is.
3620 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3621                                      Expr *E) {
3622   // Don't warn if the operation changed the type.
3623   if (T != E->getType())
3624     return;
3625 
3626   // Now look for array decays.
3627   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3628   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3629     return;
3630 
3631   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3632                                              << ICE->getType()
3633                                              << ICE->getSubExpr()->getType();
3634 }
3635 
3636 /// \brief Check the constraints on expression operands to unary type expression
3637 /// and type traits.
3638 ///
3639 /// Completes any types necessary and validates the constraints on the operand
3640 /// expression. The logic mostly mirrors the type-based overload, but may modify
3641 /// the expression as it completes the type for that expression through template
3642 /// instantiation, etc.
3643 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3644                                             UnaryExprOrTypeTrait ExprKind) {
3645   QualType ExprTy = E->getType();
3646   assert(!ExprTy->isReferenceType());
3647 
3648   if (ExprKind == UETT_VecStep)
3649     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3650                                         E->getSourceRange());
3651 
3652   // Whitelist some types as extensions
3653   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3654                                       E->getSourceRange(), ExprKind))
3655     return false;
3656 
3657   // 'alignof' applied to an expression only requires the base element type of
3658   // the expression to be complete. 'sizeof' requires the expression's type to
3659   // be complete (and will attempt to complete it if it's an array of unknown
3660   // bound).
3661   if (ExprKind == UETT_AlignOf) {
3662     if (RequireCompleteType(E->getExprLoc(),
3663                             Context.getBaseElementType(E->getType()),
3664                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3665                             E->getSourceRange()))
3666       return true;
3667   } else {
3668     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3669                                 ExprKind, E->getSourceRange()))
3670       return true;
3671   }
3672 
3673   // Completing the expression's type may have changed it.
3674   ExprTy = E->getType();
3675   assert(!ExprTy->isReferenceType());
3676 
3677   if (ExprTy->isFunctionType()) {
3678     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3679       << ExprKind << E->getSourceRange();
3680     return true;
3681   }
3682 
3683   // The operand for sizeof and alignof is in an unevaluated expression context,
3684   // so side effects could result in unintended consequences.
3685   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3686       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3687     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3688 
3689   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3690                                        E->getSourceRange(), ExprKind))
3691     return true;
3692 
3693   if (ExprKind == UETT_SizeOf) {
3694     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3695       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3696         QualType OType = PVD->getOriginalType();
3697         QualType Type = PVD->getType();
3698         if (Type->isPointerType() && OType->isArrayType()) {
3699           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3700             << Type << OType;
3701           Diag(PVD->getLocation(), diag::note_declared_at);
3702         }
3703       }
3704     }
3705 
3706     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3707     // decays into a pointer and returns an unintended result. This is most
3708     // likely a typo for "sizeof(array) op x".
3709     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3710       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3711                                BO->getLHS());
3712       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3713                                BO->getRHS());
3714     }
3715   }
3716 
3717   return false;
3718 }
3719 
3720 /// \brief Check the constraints on operands to unary expression and type
3721 /// traits.
3722 ///
3723 /// This will complete any types necessary, and validate the various constraints
3724 /// on those operands.
3725 ///
3726 /// The UsualUnaryConversions() function is *not* called by this routine.
3727 /// C99 6.3.2.1p[2-4] all state:
3728 ///   Except when it is the operand of the sizeof operator ...
3729 ///
3730 /// C++ [expr.sizeof]p4
3731 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3732 ///   standard conversions are not applied to the operand of sizeof.
3733 ///
3734 /// This policy is followed for all of the unary trait expressions.
3735 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3736                                             SourceLocation OpLoc,
3737                                             SourceRange ExprRange,
3738                                             UnaryExprOrTypeTrait ExprKind) {
3739   if (ExprType->isDependentType())
3740     return false;
3741 
3742   // C++ [expr.sizeof]p2:
3743   //     When applied to a reference or a reference type, the result
3744   //     is the size of the referenced type.
3745   // C++11 [expr.alignof]p3:
3746   //     When alignof is applied to a reference type, the result
3747   //     shall be the alignment of the referenced type.
3748   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3749     ExprType = Ref->getPointeeType();
3750 
3751   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3752   //   When alignof or _Alignof is applied to an array type, the result
3753   //   is the alignment of the element type.
3754   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3755     ExprType = Context.getBaseElementType(ExprType);
3756 
3757   if (ExprKind == UETT_VecStep)
3758     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3759 
3760   // Whitelist some types as extensions
3761   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3762                                       ExprKind))
3763     return false;
3764 
3765   if (RequireCompleteType(OpLoc, ExprType,
3766                           diag::err_sizeof_alignof_incomplete_type,
3767                           ExprKind, ExprRange))
3768     return true;
3769 
3770   if (ExprType->isFunctionType()) {
3771     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3772       << ExprKind << ExprRange;
3773     return true;
3774   }
3775 
3776   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3777                                        ExprKind))
3778     return true;
3779 
3780   return false;
3781 }
3782 
3783 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3784   E = E->IgnoreParens();
3785 
3786   // Cannot know anything else if the expression is dependent.
3787   if (E->isTypeDependent())
3788     return false;
3789 
3790   if (E->getObjectKind() == OK_BitField) {
3791     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3792        << 1 << E->getSourceRange();
3793     return true;
3794   }
3795 
3796   ValueDecl *D = nullptr;
3797   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3798     D = DRE->getDecl();
3799   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3800     D = ME->getMemberDecl();
3801   }
3802 
3803   // If it's a field, require the containing struct to have a
3804   // complete definition so that we can compute the layout.
3805   //
3806   // This can happen in C++11 onwards, either by naming the member
3807   // in a way that is not transformed into a member access expression
3808   // (in an unevaluated operand, for instance), or by naming the member
3809   // in a trailing-return-type.
3810   //
3811   // For the record, since __alignof__ on expressions is a GCC
3812   // extension, GCC seems to permit this but always gives the
3813   // nonsensical answer 0.
3814   //
3815   // We don't really need the layout here --- we could instead just
3816   // directly check for all the appropriate alignment-lowing
3817   // attributes --- but that would require duplicating a lot of
3818   // logic that just isn't worth duplicating for such a marginal
3819   // use-case.
3820   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3821     // Fast path this check, since we at least know the record has a
3822     // definition if we can find a member of it.
3823     if (!FD->getParent()->isCompleteDefinition()) {
3824       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3825         << E->getSourceRange();
3826       return true;
3827     }
3828 
3829     // Otherwise, if it's a field, and the field doesn't have
3830     // reference type, then it must have a complete type (or be a
3831     // flexible array member, which we explicitly want to
3832     // white-list anyway), which makes the following checks trivial.
3833     if (!FD->getType()->isReferenceType())
3834       return false;
3835   }
3836 
3837   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3838 }
3839 
3840 bool Sema::CheckVecStepExpr(Expr *E) {
3841   E = E->IgnoreParens();
3842 
3843   // Cannot know anything else if the expression is dependent.
3844   if (E->isTypeDependent())
3845     return false;
3846 
3847   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3848 }
3849 
3850 static void captureVariablyModifiedType(ASTContext &Context, QualType T,
3851                                         CapturingScopeInfo *CSI) {
3852   assert(T->isVariablyModifiedType());
3853   assert(CSI != nullptr);
3854 
3855   // We're going to walk down into the type and look for VLA expressions.
3856   do {
3857     const Type *Ty = T.getTypePtr();
3858     switch (Ty->getTypeClass()) {
3859 #define TYPE(Class, Base)
3860 #define ABSTRACT_TYPE(Class, Base)
3861 #define NON_CANONICAL_TYPE(Class, Base)
3862 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
3863 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
3864 #include "clang/AST/TypeNodes.def"
3865       T = QualType();
3866       break;
3867     // These types are never variably-modified.
3868     case Type::Builtin:
3869     case Type::Complex:
3870     case Type::Vector:
3871     case Type::ExtVector:
3872     case Type::Record:
3873     case Type::Enum:
3874     case Type::Elaborated:
3875     case Type::TemplateSpecialization:
3876     case Type::ObjCObject:
3877     case Type::ObjCInterface:
3878     case Type::ObjCObjectPointer:
3879     case Type::Pipe:
3880       llvm_unreachable("type class is never variably-modified!");
3881     case Type::Adjusted:
3882       T = cast<AdjustedType>(Ty)->getOriginalType();
3883       break;
3884     case Type::Decayed:
3885       T = cast<DecayedType>(Ty)->getPointeeType();
3886       break;
3887     case Type::Pointer:
3888       T = cast<PointerType>(Ty)->getPointeeType();
3889       break;
3890     case Type::BlockPointer:
3891       T = cast<BlockPointerType>(Ty)->getPointeeType();
3892       break;
3893     case Type::LValueReference:
3894     case Type::RValueReference:
3895       T = cast<ReferenceType>(Ty)->getPointeeType();
3896       break;
3897     case Type::MemberPointer:
3898       T = cast<MemberPointerType>(Ty)->getPointeeType();
3899       break;
3900     case Type::ConstantArray:
3901     case Type::IncompleteArray:
3902       // Losing element qualification here is fine.
3903       T = cast<ArrayType>(Ty)->getElementType();
3904       break;
3905     case Type::VariableArray: {
3906       // Losing element qualification here is fine.
3907       const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
3908 
3909       // Unknown size indication requires no size computation.
3910       // Otherwise, evaluate and record it.
3911       if (auto Size = VAT->getSizeExpr()) {
3912         if (!CSI->isVLATypeCaptured(VAT)) {
3913           RecordDecl *CapRecord = nullptr;
3914           if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
3915             CapRecord = LSI->Lambda;
3916           } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
3917             CapRecord = CRSI->TheRecordDecl;
3918           }
3919           if (CapRecord) {
3920             auto ExprLoc = Size->getExprLoc();
3921             auto SizeType = Context.getSizeType();
3922             // Build the non-static data member.
3923             auto Field =
3924                 FieldDecl::Create(Context, CapRecord, ExprLoc, ExprLoc,
3925                                   /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
3926                                   /*BW*/ nullptr, /*Mutable*/ false,
3927                                   /*InitStyle*/ ICIS_NoInit);
3928             Field->setImplicit(true);
3929             Field->setAccess(AS_private);
3930             Field->setCapturedVLAType(VAT);
3931             CapRecord->addDecl(Field);
3932 
3933             CSI->addVLATypeCapture(ExprLoc, SizeType);
3934           }
3935         }
3936       }
3937       T = VAT->getElementType();
3938       break;
3939     }
3940     case Type::FunctionProto:
3941     case Type::FunctionNoProto:
3942       T = cast<FunctionType>(Ty)->getReturnType();
3943       break;
3944     case Type::Paren:
3945     case Type::TypeOf:
3946     case Type::UnaryTransform:
3947     case Type::Attributed:
3948     case Type::SubstTemplateTypeParm:
3949     case Type::PackExpansion:
3950       // Keep walking after single level desugaring.
3951       T = T.getSingleStepDesugaredType(Context);
3952       break;
3953     case Type::Typedef:
3954       T = cast<TypedefType>(Ty)->desugar();
3955       break;
3956     case Type::Decltype:
3957       T = cast<DecltypeType>(Ty)->desugar();
3958       break;
3959     case Type::Auto:
3960       T = cast<AutoType>(Ty)->getDeducedType();
3961       break;
3962     case Type::TypeOfExpr:
3963       T = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
3964       break;
3965     case Type::Atomic:
3966       T = cast<AtomicType>(Ty)->getValueType();
3967       break;
3968     }
3969   } while (!T.isNull() && T->isVariablyModifiedType());
3970 }
3971 
3972 /// \brief Build a sizeof or alignof expression given a type operand.
3973 ExprResult
3974 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3975                                      SourceLocation OpLoc,
3976                                      UnaryExprOrTypeTrait ExprKind,
3977                                      SourceRange R) {
3978   if (!TInfo)
3979     return ExprError();
3980 
3981   QualType T = TInfo->getType();
3982 
3983   if (!T->isDependentType() &&
3984       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3985     return ExprError();
3986 
3987   if (T->isVariablyModifiedType() && FunctionScopes.size() > 1) {
3988     if (auto *TT = T->getAs<TypedefType>()) {
3989       for (auto I = FunctionScopes.rbegin(),
3990                 E = std::prev(FunctionScopes.rend());
3991            I != E; ++I) {
3992         auto *CSI = dyn_cast<CapturingScopeInfo>(*I);
3993         if (CSI == nullptr)
3994           break;
3995         DeclContext *DC = nullptr;
3996         if (auto *LSI = dyn_cast<LambdaScopeInfo>(CSI))
3997           DC = LSI->CallOperator;
3998         else if (auto *CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI))
3999           DC = CRSI->TheCapturedDecl;
4000         else if (auto *BSI = dyn_cast<BlockScopeInfo>(CSI))
4001           DC = BSI->TheDecl;
4002         if (DC) {
4003           if (DC->containsDecl(TT->getDecl()))
4004             break;
4005           captureVariablyModifiedType(Context, T, CSI);
4006         }
4007       }
4008     }
4009   }
4010 
4011   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4012   return new (Context) UnaryExprOrTypeTraitExpr(
4013       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
4014 }
4015 
4016 /// \brief Build a sizeof or alignof expression given an expression
4017 /// operand.
4018 ExprResult
4019 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
4020                                      UnaryExprOrTypeTrait ExprKind) {
4021   ExprResult PE = CheckPlaceholderExpr(E);
4022   if (PE.isInvalid())
4023     return ExprError();
4024 
4025   E = PE.get();
4026 
4027   // Verify that the operand is valid.
4028   bool isInvalid = false;
4029   if (E->isTypeDependent()) {
4030     // Delay type-checking for type-dependent expressions.
4031   } else if (ExprKind == UETT_AlignOf) {
4032     isInvalid = CheckAlignOfExpr(*this, E);
4033   } else if (ExprKind == UETT_VecStep) {
4034     isInvalid = CheckVecStepExpr(E);
4035   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
4036       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
4037       isInvalid = true;
4038   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
4039     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
4040     isInvalid = true;
4041   } else {
4042     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
4043   }
4044 
4045   if (isInvalid)
4046     return ExprError();
4047 
4048   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
4049     PE = TransformToPotentiallyEvaluated(E);
4050     if (PE.isInvalid()) return ExprError();
4051     E = PE.get();
4052   }
4053 
4054   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
4055   return new (Context) UnaryExprOrTypeTraitExpr(
4056       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
4057 }
4058 
4059 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
4060 /// expr and the same for @c alignof and @c __alignof
4061 /// Note that the ArgRange is invalid if isType is false.
4062 ExprResult
4063 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
4064                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
4065                                     void *TyOrEx, SourceRange ArgRange) {
4066   // If error parsing type, ignore.
4067   if (!TyOrEx) return ExprError();
4068 
4069   if (IsType) {
4070     TypeSourceInfo *TInfo;
4071     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
4072     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
4073   }
4074 
4075   Expr *ArgEx = (Expr *)TyOrEx;
4076   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
4077   return Result;
4078 }
4079 
4080 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
4081                                      bool IsReal) {
4082   if (V.get()->isTypeDependent())
4083     return S.Context.DependentTy;
4084 
4085   // _Real and _Imag are only l-values for normal l-values.
4086   if (V.get()->getObjectKind() != OK_Ordinary) {
4087     V = S.DefaultLvalueConversion(V.get());
4088     if (V.isInvalid())
4089       return QualType();
4090   }
4091 
4092   // These operators return the element type of a complex type.
4093   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
4094     return CT->getElementType();
4095 
4096   // Otherwise they pass through real integer and floating point types here.
4097   if (V.get()->getType()->isArithmeticType())
4098     return V.get()->getType();
4099 
4100   // Test for placeholders.
4101   ExprResult PR = S.CheckPlaceholderExpr(V.get());
4102   if (PR.isInvalid()) return QualType();
4103   if (PR.get() != V.get()) {
4104     V = PR;
4105     return CheckRealImagOperand(S, V, Loc, IsReal);
4106   }
4107 
4108   // Reject anything else.
4109   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
4110     << (IsReal ? "__real" : "__imag");
4111   return QualType();
4112 }
4113 
4114 
4115 
4116 ExprResult
4117 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
4118                           tok::TokenKind Kind, Expr *Input) {
4119   UnaryOperatorKind Opc;
4120   switch (Kind) {
4121   default: llvm_unreachable("Unknown unary op!");
4122   case tok::plusplus:   Opc = UO_PostInc; break;
4123   case tok::minusminus: Opc = UO_PostDec; break;
4124   }
4125 
4126   // Since this might is a postfix expression, get rid of ParenListExprs.
4127   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
4128   if (Result.isInvalid()) return ExprError();
4129   Input = Result.get();
4130 
4131   return BuildUnaryOp(S, OpLoc, Opc, Input);
4132 }
4133 
4134 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
4135 ///
4136 /// \return true on error
4137 static bool checkArithmeticOnObjCPointer(Sema &S,
4138                                          SourceLocation opLoc,
4139                                          Expr *op) {
4140   assert(op->getType()->isObjCObjectPointerType());
4141   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
4142       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
4143     return false;
4144 
4145   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
4146     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
4147     << op->getSourceRange();
4148   return true;
4149 }
4150 
4151 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
4152   auto *BaseNoParens = Base->IgnoreParens();
4153   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
4154     return MSProp->getPropertyDecl()->getType()->isArrayType();
4155   return isa<MSPropertySubscriptExpr>(BaseNoParens);
4156 }
4157 
4158 ExprResult
4159 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
4160                               Expr *idx, SourceLocation rbLoc) {
4161   if (base && !base->getType().isNull() &&
4162       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
4163     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
4164                                     /*Length=*/nullptr, rbLoc);
4165 
4166   // Since this might be a postfix expression, get rid of ParenListExprs.
4167   if (isa<ParenListExpr>(base)) {
4168     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
4169     if (result.isInvalid()) return ExprError();
4170     base = result.get();
4171   }
4172 
4173   // Handle any non-overload placeholder types in the base and index
4174   // expressions.  We can't handle overloads here because the other
4175   // operand might be an overloadable type, in which case the overload
4176   // resolution for the operator overload should get the first crack
4177   // at the overload.
4178   bool IsMSPropertySubscript = false;
4179   if (base->getType()->isNonOverloadPlaceholderType()) {
4180     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
4181     if (!IsMSPropertySubscript) {
4182       ExprResult result = CheckPlaceholderExpr(base);
4183       if (result.isInvalid())
4184         return ExprError();
4185       base = result.get();
4186     }
4187   }
4188   if (idx->getType()->isNonOverloadPlaceholderType()) {
4189     ExprResult result = CheckPlaceholderExpr(idx);
4190     if (result.isInvalid()) return ExprError();
4191     idx = result.get();
4192   }
4193 
4194   // Build an unanalyzed expression if either operand is type-dependent.
4195   if (getLangOpts().CPlusPlus &&
4196       (base->isTypeDependent() || idx->isTypeDependent())) {
4197     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
4198                                             VK_LValue, OK_Ordinary, rbLoc);
4199   }
4200 
4201   // MSDN, property (C++)
4202   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
4203   // This attribute can also be used in the declaration of an empty array in a
4204   // class or structure definition. For example:
4205   // __declspec(property(get=GetX, put=PutX)) int x[];
4206   // The above statement indicates that x[] can be used with one or more array
4207   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
4208   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
4209   if (IsMSPropertySubscript) {
4210     // Build MS property subscript expression if base is MS property reference
4211     // or MS property subscript.
4212     return new (Context) MSPropertySubscriptExpr(
4213         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
4214   }
4215 
4216   // Use C++ overloaded-operator rules if either operand has record
4217   // type.  The spec says to do this if either type is *overloadable*,
4218   // but enum types can't declare subscript operators or conversion
4219   // operators, so there's nothing interesting for overload resolution
4220   // to do if there aren't any record types involved.
4221   //
4222   // ObjC pointers have their own subscripting logic that is not tied
4223   // to overload resolution and so should not take this path.
4224   if (getLangOpts().CPlusPlus &&
4225       (base->getType()->isRecordType() ||
4226        (!base->getType()->isObjCObjectPointerType() &&
4227         idx->getType()->isRecordType()))) {
4228     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
4229   }
4230 
4231   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
4232 }
4233 
4234 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
4235                                           Expr *LowerBound,
4236                                           SourceLocation ColonLoc, Expr *Length,
4237                                           SourceLocation RBLoc) {
4238   if (Base->getType()->isPlaceholderType() &&
4239       !Base->getType()->isSpecificPlaceholderType(
4240           BuiltinType::OMPArraySection)) {
4241     ExprResult Result = CheckPlaceholderExpr(Base);
4242     if (Result.isInvalid())
4243       return ExprError();
4244     Base = Result.get();
4245   }
4246   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4247     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4248     if (Result.isInvalid())
4249       return ExprError();
4250     Result = DefaultLvalueConversion(Result.get());
4251     if (Result.isInvalid())
4252       return ExprError();
4253     LowerBound = Result.get();
4254   }
4255   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4256     ExprResult Result = CheckPlaceholderExpr(Length);
4257     if (Result.isInvalid())
4258       return ExprError();
4259     Result = DefaultLvalueConversion(Result.get());
4260     if (Result.isInvalid())
4261       return ExprError();
4262     Length = Result.get();
4263   }
4264 
4265   // Build an unanalyzed expression if either operand is type-dependent.
4266   if (Base->isTypeDependent() ||
4267       (LowerBound &&
4268        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4269       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4270     return new (Context)
4271         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4272                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4273   }
4274 
4275   // Perform default conversions.
4276   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4277   QualType ResultTy;
4278   if (OriginalTy->isAnyPointerType()) {
4279     ResultTy = OriginalTy->getPointeeType();
4280   } else if (OriginalTy->isArrayType()) {
4281     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4282   } else {
4283     return ExprError(
4284         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4285         << Base->getSourceRange());
4286   }
4287   // C99 6.5.2.1p1
4288   if (LowerBound) {
4289     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4290                                                       LowerBound);
4291     if (Res.isInvalid())
4292       return ExprError(Diag(LowerBound->getExprLoc(),
4293                             diag::err_omp_typecheck_section_not_integer)
4294                        << 0 << LowerBound->getSourceRange());
4295     LowerBound = Res.get();
4296 
4297     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4298         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4299       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4300           << 0 << LowerBound->getSourceRange();
4301   }
4302   if (Length) {
4303     auto Res =
4304         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4305     if (Res.isInvalid())
4306       return ExprError(Diag(Length->getExprLoc(),
4307                             diag::err_omp_typecheck_section_not_integer)
4308                        << 1 << Length->getSourceRange());
4309     Length = Res.get();
4310 
4311     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4312         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4313       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4314           << 1 << Length->getSourceRange();
4315   }
4316 
4317   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4318   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4319   // type. Note that functions are not objects, and that (in C99 parlance)
4320   // incomplete types are not object types.
4321   if (ResultTy->isFunctionType()) {
4322     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4323         << ResultTy << Base->getSourceRange();
4324     return ExprError();
4325   }
4326 
4327   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4328                           diag::err_omp_section_incomplete_type, Base))
4329     return ExprError();
4330 
4331   if (LowerBound && !OriginalTy->isAnyPointerType()) {
4332     llvm::APSInt LowerBoundValue;
4333     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4334       // OpenMP 4.5, [2.4 Array Sections]
4335       // The array section must be a subset of the original array.
4336       if (LowerBoundValue.isNegative()) {
4337         Diag(LowerBound->getExprLoc(), diag::err_omp_section_not_subset_of_array)
4338             << LowerBound->getSourceRange();
4339         return ExprError();
4340       }
4341     }
4342   }
4343 
4344   if (Length) {
4345     llvm::APSInt LengthValue;
4346     if (Length->EvaluateAsInt(LengthValue, Context)) {
4347       // OpenMP 4.5, [2.4 Array Sections]
4348       // The length must evaluate to non-negative integers.
4349       if (LengthValue.isNegative()) {
4350         Diag(Length->getExprLoc(), diag::err_omp_section_length_negative)
4351             << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4352             << Length->getSourceRange();
4353         return ExprError();
4354       }
4355     }
4356   } else if (ColonLoc.isValid() &&
4357              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4358                                       !OriginalTy->isVariableArrayType()))) {
4359     // OpenMP 4.5, [2.4 Array Sections]
4360     // When the size of the array dimension is not known, the length must be
4361     // specified explicitly.
4362     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4363         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4364     return ExprError();
4365   }
4366 
4367   if (!Base->getType()->isSpecificPlaceholderType(
4368           BuiltinType::OMPArraySection)) {
4369     ExprResult Result = DefaultFunctionArrayLvalueConversion(Base);
4370     if (Result.isInvalid())
4371       return ExprError();
4372     Base = Result.get();
4373   }
4374   return new (Context)
4375       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4376                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4377 }
4378 
4379 ExprResult
4380 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4381                                       Expr *Idx, SourceLocation RLoc) {
4382   Expr *LHSExp = Base;
4383   Expr *RHSExp = Idx;
4384 
4385   // Perform default conversions.
4386   if (!LHSExp->getType()->getAs<VectorType>()) {
4387     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4388     if (Result.isInvalid())
4389       return ExprError();
4390     LHSExp = Result.get();
4391   }
4392   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4393   if (Result.isInvalid())
4394     return ExprError();
4395   RHSExp = Result.get();
4396 
4397   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4398   ExprValueKind VK = VK_LValue;
4399   ExprObjectKind OK = OK_Ordinary;
4400 
4401   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4402   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4403   // in the subscript position. As a result, we need to derive the array base
4404   // and index from the expression types.
4405   Expr *BaseExpr, *IndexExpr;
4406   QualType ResultType;
4407   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4408     BaseExpr = LHSExp;
4409     IndexExpr = RHSExp;
4410     ResultType = Context.DependentTy;
4411   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4412     BaseExpr = LHSExp;
4413     IndexExpr = RHSExp;
4414     ResultType = PTy->getPointeeType();
4415   } else if (const ObjCObjectPointerType *PTy =
4416                LHSTy->getAs<ObjCObjectPointerType>()) {
4417     BaseExpr = LHSExp;
4418     IndexExpr = RHSExp;
4419 
4420     // Use custom logic if this should be the pseudo-object subscript
4421     // expression.
4422     if (!LangOpts.isSubscriptPointerArithmetic())
4423       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4424                                           nullptr);
4425 
4426     ResultType = PTy->getPointeeType();
4427   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4428      // Handle the uncommon case of "123[Ptr]".
4429     BaseExpr = RHSExp;
4430     IndexExpr = LHSExp;
4431     ResultType = PTy->getPointeeType();
4432   } else if (const ObjCObjectPointerType *PTy =
4433                RHSTy->getAs<ObjCObjectPointerType>()) {
4434      // Handle the uncommon case of "123[Ptr]".
4435     BaseExpr = RHSExp;
4436     IndexExpr = LHSExp;
4437     ResultType = PTy->getPointeeType();
4438     if (!LangOpts.isSubscriptPointerArithmetic()) {
4439       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4440         << ResultType << BaseExpr->getSourceRange();
4441       return ExprError();
4442     }
4443   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4444     BaseExpr = LHSExp;    // vectors: V[123]
4445     IndexExpr = RHSExp;
4446     VK = LHSExp->getValueKind();
4447     if (VK != VK_RValue)
4448       OK = OK_VectorComponent;
4449 
4450     // FIXME: need to deal with const...
4451     ResultType = VTy->getElementType();
4452   } else if (LHSTy->isArrayType()) {
4453     // If we see an array that wasn't promoted by
4454     // DefaultFunctionArrayLvalueConversion, it must be an array that
4455     // wasn't promoted because of the C90 rule that doesn't
4456     // allow promoting non-lvalue arrays.  Warn, then
4457     // force the promotion here.
4458     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4459         LHSExp->getSourceRange();
4460     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4461                                CK_ArrayToPointerDecay).get();
4462     LHSTy = LHSExp->getType();
4463 
4464     BaseExpr = LHSExp;
4465     IndexExpr = RHSExp;
4466     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4467   } else if (RHSTy->isArrayType()) {
4468     // Same as previous, except for 123[f().a] case
4469     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4470         RHSExp->getSourceRange();
4471     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4472                                CK_ArrayToPointerDecay).get();
4473     RHSTy = RHSExp->getType();
4474 
4475     BaseExpr = RHSExp;
4476     IndexExpr = LHSExp;
4477     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4478   } else {
4479     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4480        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4481   }
4482   // C99 6.5.2.1p1
4483   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4484     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4485                      << IndexExpr->getSourceRange());
4486 
4487   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4488        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4489          && !IndexExpr->isTypeDependent())
4490     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4491 
4492   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4493   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4494   // type. Note that Functions are not objects, and that (in C99 parlance)
4495   // incomplete types are not object types.
4496   if (ResultType->isFunctionType()) {
4497     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4498       << ResultType << BaseExpr->getSourceRange();
4499     return ExprError();
4500   }
4501 
4502   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4503     // GNU extension: subscripting on pointer to void
4504     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4505       << BaseExpr->getSourceRange();
4506 
4507     // C forbids expressions of unqualified void type from being l-values.
4508     // See IsCForbiddenLValueType.
4509     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4510   } else if (!ResultType->isDependentType() &&
4511       RequireCompleteType(LLoc, ResultType,
4512                           diag::err_subscript_incomplete_type, BaseExpr))
4513     return ExprError();
4514 
4515   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4516          !ResultType.isCForbiddenLValueType());
4517 
4518   return new (Context)
4519       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4520 }
4521 
4522 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4523                                         FunctionDecl *FD,
4524                                         ParmVarDecl *Param) {
4525   if (Param->hasUnparsedDefaultArg()) {
4526     Diag(CallLoc,
4527          diag::err_use_of_default_argument_to_function_declared_later) <<
4528       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4529     Diag(UnparsedDefaultArgLocs[Param],
4530          diag::note_default_argument_declared_here);
4531     return ExprError();
4532   }
4533 
4534   if (Param->hasUninstantiatedDefaultArg()) {
4535     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4536 
4537     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4538                                                  Param);
4539 
4540     // Instantiate the expression.
4541     MultiLevelTemplateArgumentList MutiLevelArgList
4542       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4543 
4544     InstantiatingTemplate Inst(*this, CallLoc, Param,
4545                                MutiLevelArgList.getInnermost());
4546     if (Inst.isInvalid())
4547       return ExprError();
4548     if (Inst.isAlreadyInstantiating()) {
4549       Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4550       Param->setInvalidDecl();
4551       return ExprError();
4552     }
4553 
4554     ExprResult Result;
4555     {
4556       // C++ [dcl.fct.default]p5:
4557       //   The names in the [default argument] expression are bound, and
4558       //   the semantic constraints are checked, at the point where the
4559       //   default argument expression appears.
4560       ContextRAII SavedContext(*this, FD);
4561       LocalInstantiationScope Local(*this);
4562       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4563     }
4564     if (Result.isInvalid())
4565       return ExprError();
4566 
4567     // Check the expression as an initializer for the parameter.
4568     InitializedEntity Entity
4569       = InitializedEntity::InitializeParameter(Context, Param);
4570     InitializationKind Kind
4571       = InitializationKind::CreateCopy(Param->getLocation(),
4572              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4573     Expr *ResultE = Result.getAs<Expr>();
4574 
4575     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4576     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4577     if (Result.isInvalid())
4578       return ExprError();
4579 
4580     Result = ActOnFinishFullExpr(Result.getAs<Expr>(),
4581                                  Param->getOuterLocStart());
4582     if (Result.isInvalid())
4583       return ExprError();
4584 
4585     // Remember the instantiated default argument.
4586     Param->setDefaultArg(Result.getAs<Expr>());
4587     if (ASTMutationListener *L = getASTMutationListener()) {
4588       L->DefaultArgumentInstantiated(Param);
4589     }
4590   }
4591 
4592   // If the default argument expression is not set yet, we are building it now.
4593   if (!Param->hasInit()) {
4594     Diag(Param->getLocStart(), diag::err_recursive_default_argument) << FD;
4595     Param->setInvalidDecl();
4596     return ExprError();
4597   }
4598 
4599   // If the default expression creates temporaries, we need to
4600   // push them to the current stack of expression temporaries so they'll
4601   // be properly destroyed.
4602   // FIXME: We should really be rebuilding the default argument with new
4603   // bound temporaries; see the comment in PR5810.
4604   // We don't need to do that with block decls, though, because
4605   // blocks in default argument expression can never capture anything.
4606   if (auto Init = dyn_cast<ExprWithCleanups>(Param->getInit())) {
4607     // Set the "needs cleanups" bit regardless of whether there are
4608     // any explicit objects.
4609     Cleanup.setExprNeedsCleanups(Init->cleanupsHaveSideEffects());
4610 
4611     // Append all the objects to the cleanup list.  Right now, this
4612     // should always be a no-op, because blocks in default argument
4613     // expressions should never be able to capture anything.
4614     assert(!Init->getNumObjects() &&
4615            "default argument expression has capturing blocks?");
4616   }
4617 
4618   // We already type-checked the argument, so we know it works.
4619   // Just mark all of the declarations in this potentially-evaluated expression
4620   // as being "referenced".
4621   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4622                                    /*SkipLocalVariables=*/true);
4623   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4624 }
4625 
4626 
4627 Sema::VariadicCallType
4628 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4629                           Expr *Fn) {
4630   if (Proto && Proto->isVariadic()) {
4631     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4632       return VariadicConstructor;
4633     else if (Fn && Fn->getType()->isBlockPointerType())
4634       return VariadicBlock;
4635     else if (FDecl) {
4636       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4637         if (Method->isInstance())
4638           return VariadicMethod;
4639     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4640       return VariadicMethod;
4641     return VariadicFunction;
4642   }
4643   return VariadicDoesNotApply;
4644 }
4645 
4646 namespace {
4647 class FunctionCallCCC : public FunctionCallFilterCCC {
4648 public:
4649   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4650                   unsigned NumArgs, MemberExpr *ME)
4651       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4652         FunctionName(FuncName) {}
4653 
4654   bool ValidateCandidate(const TypoCorrection &candidate) override {
4655     if (!candidate.getCorrectionSpecifier() ||
4656         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4657       return false;
4658     }
4659 
4660     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4661   }
4662 
4663 private:
4664   const IdentifierInfo *const FunctionName;
4665 };
4666 }
4667 
4668 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4669                                                FunctionDecl *FDecl,
4670                                                ArrayRef<Expr *> Args) {
4671   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4672   DeclarationName FuncName = FDecl->getDeclName();
4673   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4674 
4675   if (TypoCorrection Corrected = S.CorrectTypo(
4676           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4677           S.getScopeForContext(S.CurContext), nullptr,
4678           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4679                                              Args.size(), ME),
4680           Sema::CTK_ErrorRecovery)) {
4681     if (NamedDecl *ND = Corrected.getFoundDecl()) {
4682       if (Corrected.isOverloaded()) {
4683         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4684         OverloadCandidateSet::iterator Best;
4685         for (NamedDecl *CD : Corrected) {
4686           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(CD))
4687             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4688                                    OCS);
4689         }
4690         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4691         case OR_Success:
4692           ND = Best->FoundDecl;
4693           Corrected.setCorrectionDecl(ND);
4694           break;
4695         default:
4696           break;
4697         }
4698       }
4699       ND = ND->getUnderlyingDecl();
4700       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))
4701         return Corrected;
4702     }
4703   }
4704   return TypoCorrection();
4705 }
4706 
4707 /// ConvertArgumentsForCall - Converts the arguments specified in
4708 /// Args/NumArgs to the parameter types of the function FDecl with
4709 /// function prototype Proto. Call is the call expression itself, and
4710 /// Fn is the function expression. For a C++ member function, this
4711 /// routine does not attempt to convert the object argument. Returns
4712 /// true if the call is ill-formed.
4713 bool
4714 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4715                               FunctionDecl *FDecl,
4716                               const FunctionProtoType *Proto,
4717                               ArrayRef<Expr *> Args,
4718                               SourceLocation RParenLoc,
4719                               bool IsExecConfig) {
4720   // Bail out early if calling a builtin with custom typechecking.
4721   if (FDecl)
4722     if (unsigned ID = FDecl->getBuiltinID())
4723       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4724         return false;
4725 
4726   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4727   // assignment, to the types of the corresponding parameter, ...
4728   unsigned NumParams = Proto->getNumParams();
4729   bool Invalid = false;
4730   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4731   unsigned FnKind = Fn->getType()->isBlockPointerType()
4732                        ? 1 /* block */
4733                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4734                                        : 0 /* function */);
4735 
4736   // If too few arguments are available (and we don't have default
4737   // arguments for the remaining parameters), don't make the call.
4738   if (Args.size() < NumParams) {
4739     if (Args.size() < MinArgs) {
4740       TypoCorrection TC;
4741       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4742         unsigned diag_id =
4743             MinArgs == NumParams && !Proto->isVariadic()
4744                 ? diag::err_typecheck_call_too_few_args_suggest
4745                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4746         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4747                                         << static_cast<unsigned>(Args.size())
4748                                         << TC.getCorrectionRange());
4749       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4750         Diag(RParenLoc,
4751              MinArgs == NumParams && !Proto->isVariadic()
4752                  ? diag::err_typecheck_call_too_few_args_one
4753                  : diag::err_typecheck_call_too_few_args_at_least_one)
4754             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4755       else
4756         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4757                             ? diag::err_typecheck_call_too_few_args
4758                             : diag::err_typecheck_call_too_few_args_at_least)
4759             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4760             << Fn->getSourceRange();
4761 
4762       // Emit the location of the prototype.
4763       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4764         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4765           << FDecl;
4766 
4767       return true;
4768     }
4769     Call->setNumArgs(Context, NumParams);
4770   }
4771 
4772   // If too many are passed and not variadic, error on the extras and drop
4773   // them.
4774   if (Args.size() > NumParams) {
4775     if (!Proto->isVariadic()) {
4776       TypoCorrection TC;
4777       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4778         unsigned diag_id =
4779             MinArgs == NumParams && !Proto->isVariadic()
4780                 ? diag::err_typecheck_call_too_many_args_suggest
4781                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4782         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4783                                         << static_cast<unsigned>(Args.size())
4784                                         << TC.getCorrectionRange());
4785       } else if (NumParams == 1 && FDecl &&
4786                  FDecl->getParamDecl(0)->getDeclName())
4787         Diag(Args[NumParams]->getLocStart(),
4788              MinArgs == NumParams
4789                  ? diag::err_typecheck_call_too_many_args_one
4790                  : diag::err_typecheck_call_too_many_args_at_most_one)
4791             << FnKind << FDecl->getParamDecl(0)
4792             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4793             << SourceRange(Args[NumParams]->getLocStart(),
4794                            Args.back()->getLocEnd());
4795       else
4796         Diag(Args[NumParams]->getLocStart(),
4797              MinArgs == NumParams
4798                  ? diag::err_typecheck_call_too_many_args
4799                  : diag::err_typecheck_call_too_many_args_at_most)
4800             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4801             << Fn->getSourceRange()
4802             << SourceRange(Args[NumParams]->getLocStart(),
4803                            Args.back()->getLocEnd());
4804 
4805       // Emit the location of the prototype.
4806       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4807         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4808           << FDecl;
4809 
4810       // This deletes the extra arguments.
4811       Call->setNumArgs(Context, NumParams);
4812       return true;
4813     }
4814   }
4815   SmallVector<Expr *, 8> AllArgs;
4816   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4817 
4818   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4819                                    Proto, 0, Args, AllArgs, CallType);
4820   if (Invalid)
4821     return true;
4822   unsigned TotalNumArgs = AllArgs.size();
4823   for (unsigned i = 0; i < TotalNumArgs; ++i)
4824     Call->setArg(i, AllArgs[i]);
4825 
4826   return false;
4827 }
4828 
4829 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4830                                   const FunctionProtoType *Proto,
4831                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4832                                   SmallVectorImpl<Expr *> &AllArgs,
4833                                   VariadicCallType CallType, bool AllowExplicit,
4834                                   bool IsListInitialization) {
4835   unsigned NumParams = Proto->getNumParams();
4836   bool Invalid = false;
4837   size_t ArgIx = 0;
4838   // Continue to check argument types (even if we have too few/many args).
4839   for (unsigned i = FirstParam; i < NumParams; i++) {
4840     QualType ProtoArgType = Proto->getParamType(i);
4841 
4842     Expr *Arg;
4843     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4844     if (ArgIx < Args.size()) {
4845       Arg = Args[ArgIx++];
4846 
4847       if (RequireCompleteType(Arg->getLocStart(),
4848                               ProtoArgType,
4849                               diag::err_call_incomplete_argument, Arg))
4850         return true;
4851 
4852       // Strip the unbridged-cast placeholder expression off, if applicable.
4853       bool CFAudited = false;
4854       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4855           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4856           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4857         Arg = stripARCUnbridgedCast(Arg);
4858       else if (getLangOpts().ObjCAutoRefCount &&
4859                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4860                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4861         CFAudited = true;
4862 
4863       InitializedEntity Entity =
4864           Param ? InitializedEntity::InitializeParameter(Context, Param,
4865                                                          ProtoArgType)
4866                 : InitializedEntity::InitializeParameter(
4867                       Context, ProtoArgType, Proto->isParamConsumed(i));
4868 
4869       // Remember that parameter belongs to a CF audited API.
4870       if (CFAudited)
4871         Entity.setParameterCFAudited();
4872 
4873       ExprResult ArgE = PerformCopyInitialization(
4874           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4875       if (ArgE.isInvalid())
4876         return true;
4877 
4878       Arg = ArgE.getAs<Expr>();
4879     } else {
4880       assert(Param && "can't use default arguments without a known callee");
4881 
4882       ExprResult ArgExpr =
4883         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4884       if (ArgExpr.isInvalid())
4885         return true;
4886 
4887       Arg = ArgExpr.getAs<Expr>();
4888     }
4889 
4890     // Check for array bounds violations for each argument to the call. This
4891     // check only triggers warnings when the argument isn't a more complex Expr
4892     // with its own checking, such as a BinaryOperator.
4893     CheckArrayAccess(Arg);
4894 
4895     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4896     CheckStaticArrayArgument(CallLoc, Param, Arg);
4897 
4898     AllArgs.push_back(Arg);
4899   }
4900 
4901   // If this is a variadic call, handle args passed through "...".
4902   if (CallType != VariadicDoesNotApply) {
4903     // Assume that extern "C" functions with variadic arguments that
4904     // return __unknown_anytype aren't *really* variadic.
4905     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4906         FDecl->isExternC()) {
4907       for (Expr *A : Args.slice(ArgIx)) {
4908         QualType paramType; // ignored
4909         ExprResult arg = checkUnknownAnyArg(CallLoc, A, paramType);
4910         Invalid |= arg.isInvalid();
4911         AllArgs.push_back(arg.get());
4912       }
4913 
4914     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4915     } else {
4916       for (Expr *A : Args.slice(ArgIx)) {
4917         ExprResult Arg = DefaultVariadicArgumentPromotion(A, CallType, FDecl);
4918         Invalid |= Arg.isInvalid();
4919         AllArgs.push_back(Arg.get());
4920       }
4921     }
4922 
4923     // Check for array bounds violations.
4924     for (Expr *A : Args.slice(ArgIx))
4925       CheckArrayAccess(A);
4926   }
4927   return Invalid;
4928 }
4929 
4930 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4931   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4932   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4933     TL = DTL.getOriginalLoc();
4934   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4935     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4936       << ATL.getLocalSourceRange();
4937 }
4938 
4939 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4940 /// array parameter, check that it is non-null, and that if it is formed by
4941 /// array-to-pointer decay, the underlying array is sufficiently large.
4942 ///
4943 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4944 /// array type derivation, then for each call to the function, the value of the
4945 /// corresponding actual argument shall provide access to the first element of
4946 /// an array with at least as many elements as specified by the size expression.
4947 void
4948 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4949                                ParmVarDecl *Param,
4950                                const Expr *ArgExpr) {
4951   // Static array parameters are not supported in C++.
4952   if (!Param || getLangOpts().CPlusPlus)
4953     return;
4954 
4955   QualType OrigTy = Param->getOriginalType();
4956 
4957   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4958   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4959     return;
4960 
4961   if (ArgExpr->isNullPointerConstant(Context,
4962                                      Expr::NPC_NeverValueDependent)) {
4963     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4964     DiagnoseCalleeStaticArrayParam(*this, Param);
4965     return;
4966   }
4967 
4968   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4969   if (!CAT)
4970     return;
4971 
4972   const ConstantArrayType *ArgCAT =
4973     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4974   if (!ArgCAT)
4975     return;
4976 
4977   if (ArgCAT->getSize().ult(CAT->getSize())) {
4978     Diag(CallLoc, diag::warn_static_array_too_small)
4979       << ArgExpr->getSourceRange()
4980       << (unsigned) ArgCAT->getSize().getZExtValue()
4981       << (unsigned) CAT->getSize().getZExtValue();
4982     DiagnoseCalleeStaticArrayParam(*this, Param);
4983   }
4984 }
4985 
4986 /// Given a function expression of unknown-any type, try to rebuild it
4987 /// to have a function type.
4988 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4989 
4990 /// Is the given type a placeholder that we need to lower out
4991 /// immediately during argument processing?
4992 static bool isPlaceholderToRemoveAsArg(QualType type) {
4993   // Placeholders are never sugared.
4994   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4995   if (!placeholder) return false;
4996 
4997   switch (placeholder->getKind()) {
4998   // Ignore all the non-placeholder types.
4999 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
5000   case BuiltinType::Id:
5001 #include "clang/Basic/OpenCLImageTypes.def"
5002 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
5003 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
5004 #include "clang/AST/BuiltinTypes.def"
5005     return false;
5006 
5007   // We cannot lower out overload sets; they might validly be resolved
5008   // by the call machinery.
5009   case BuiltinType::Overload:
5010     return false;
5011 
5012   // Unbridged casts in ARC can be handled in some call positions and
5013   // should be left in place.
5014   case BuiltinType::ARCUnbridgedCast:
5015     return false;
5016 
5017   // Pseudo-objects should be converted as soon as possible.
5018   case BuiltinType::PseudoObject:
5019     return true;
5020 
5021   // The debugger mode could theoretically but currently does not try
5022   // to resolve unknown-typed arguments based on known parameter types.
5023   case BuiltinType::UnknownAny:
5024     return true;
5025 
5026   // These are always invalid as call arguments and should be reported.
5027   case BuiltinType::BoundMember:
5028   case BuiltinType::BuiltinFn:
5029   case BuiltinType::OMPArraySection:
5030     return true;
5031 
5032   }
5033   llvm_unreachable("bad builtin type kind");
5034 }
5035 
5036 /// Check an argument list for placeholders that we won't try to
5037 /// handle later.
5038 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
5039   // Apply this processing to all the arguments at once instead of
5040   // dying at the first failure.
5041   bool hasInvalid = false;
5042   for (size_t i = 0, e = args.size(); i != e; i++) {
5043     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
5044       ExprResult result = S.CheckPlaceholderExpr(args[i]);
5045       if (result.isInvalid()) hasInvalid = true;
5046       else args[i] = result.get();
5047     } else if (hasInvalid) {
5048       (void)S.CorrectDelayedTyposInExpr(args[i]);
5049     }
5050   }
5051   return hasInvalid;
5052 }
5053 
5054 /// If a builtin function has a pointer argument with no explicit address
5055 /// space, then it should be able to accept a pointer to any address
5056 /// space as input.  In order to do this, we need to replace the
5057 /// standard builtin declaration with one that uses the same address space
5058 /// as the call.
5059 ///
5060 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
5061 ///                  it does not contain any pointer arguments without
5062 ///                  an address space qualifer.  Otherwise the rewritten
5063 ///                  FunctionDecl is returned.
5064 /// TODO: Handle pointer return types.
5065 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
5066                                                 const FunctionDecl *FDecl,
5067                                                 MultiExprArg ArgExprs) {
5068 
5069   QualType DeclType = FDecl->getType();
5070   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
5071 
5072   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
5073       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
5074     return nullptr;
5075 
5076   bool NeedsNewDecl = false;
5077   unsigned i = 0;
5078   SmallVector<QualType, 8> OverloadParams;
5079 
5080   for (QualType ParamType : FT->param_types()) {
5081 
5082     // Convert array arguments to pointer to simplify type lookup.
5083     ExprResult ArgRes =
5084         Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]);
5085     if (ArgRes.isInvalid())
5086       return nullptr;
5087     Expr *Arg = ArgRes.get();
5088     QualType ArgType = Arg->getType();
5089     if (!ParamType->isPointerType() ||
5090         ParamType.getQualifiers().hasAddressSpace() ||
5091         !ArgType->isPointerType() ||
5092         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
5093       OverloadParams.push_back(ParamType);
5094       continue;
5095     }
5096 
5097     NeedsNewDecl = true;
5098     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
5099 
5100     QualType PointeeType = ParamType->getPointeeType();
5101     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
5102     OverloadParams.push_back(Context.getPointerType(PointeeType));
5103   }
5104 
5105   if (!NeedsNewDecl)
5106     return nullptr;
5107 
5108   FunctionProtoType::ExtProtoInfo EPI;
5109   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
5110                                                 OverloadParams, EPI);
5111   DeclContext *Parent = Context.getTranslationUnitDecl();
5112   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
5113                                                     FDecl->getLocation(),
5114                                                     FDecl->getLocation(),
5115                                                     FDecl->getIdentifier(),
5116                                                     OverloadTy,
5117                                                     /*TInfo=*/nullptr,
5118                                                     SC_Extern, false,
5119                                                     /*hasPrototype=*/true);
5120   SmallVector<ParmVarDecl*, 16> Params;
5121   FT = cast<FunctionProtoType>(OverloadTy);
5122   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
5123     QualType ParamType = FT->getParamType(i);
5124     ParmVarDecl *Parm =
5125         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
5126                                 SourceLocation(), nullptr, ParamType,
5127                                 /*TInfo=*/nullptr, SC_None, nullptr);
5128     Parm->setScopeInfo(0, i);
5129     Params.push_back(Parm);
5130   }
5131   OverloadDecl->setParams(Params);
5132   return OverloadDecl;
5133 }
5134 
5135 static bool isNumberOfArgsValidForCall(Sema &S, const FunctionDecl *Callee,
5136                                        std::size_t NumArgs) {
5137   if (S.TooManyArguments(Callee->getNumParams(), NumArgs,
5138                          /*PartialOverloading=*/false))
5139     return Callee->isVariadic();
5140   return Callee->getMinRequiredArguments() <= NumArgs;
5141 }
5142 
5143 static ExprResult ActOnCallExprImpl(Sema &S, Scope *Scope, Expr *Fn,
5144                                     SourceLocation LParenLoc,
5145                                     MultiExprArg ArgExprs,
5146                                     SourceLocation RParenLoc, Expr *ExecConfig,
5147                                     bool IsExecConfig) {
5148   // Since this might be a postfix expression, get rid of ParenListExprs.
5149   ExprResult Result = S.MaybeConvertParenListExprToParenExpr(Scope, Fn);
5150   if (Result.isInvalid()) return ExprError();
5151   Fn = Result.get();
5152 
5153   if (checkArgsForPlaceholders(S, ArgExprs))
5154     return ExprError();
5155 
5156   if (S.getLangOpts().CPlusPlus) {
5157     // If this is a pseudo-destructor expression, build the call immediately.
5158     if (isa<CXXPseudoDestructorExpr>(Fn)) {
5159       if (!ArgExprs.empty()) {
5160         // Pseudo-destructor calls should not have any arguments.
5161         S.Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
5162             << FixItHint::CreateRemoval(
5163                    SourceRange(ArgExprs.front()->getLocStart(),
5164                                ArgExprs.back()->getLocEnd()));
5165       }
5166 
5167       return new (S.Context)
5168           CallExpr(S.Context, Fn, None, S.Context.VoidTy, VK_RValue, RParenLoc);
5169     }
5170     if (Fn->getType() == S.Context.PseudoObjectTy) {
5171       ExprResult result = S.CheckPlaceholderExpr(Fn);
5172       if (result.isInvalid()) return ExprError();
5173       Fn = result.get();
5174     }
5175 
5176     // Determine whether this is a dependent call inside a C++ template,
5177     // in which case we won't do any semantic analysis now.
5178     bool Dependent = false;
5179     if (Fn->isTypeDependent())
5180       Dependent = true;
5181     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
5182       Dependent = true;
5183 
5184     if (Dependent) {
5185       if (ExecConfig) {
5186         return new (S.Context) CUDAKernelCallExpr(
5187             S.Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
5188             S.Context.DependentTy, VK_RValue, RParenLoc);
5189       } else {
5190         return new (S.Context)
5191             CallExpr(S.Context, Fn, ArgExprs, S.Context.DependentTy, VK_RValue,
5192                      RParenLoc);
5193       }
5194     }
5195 
5196     // Determine whether this is a call to an object (C++ [over.call.object]).
5197     if (Fn->getType()->isRecordType())
5198       return S.BuildCallToObjectOfClassType(Scope, Fn, LParenLoc, ArgExprs,
5199                                             RParenLoc);
5200 
5201     if (Fn->getType() == S.Context.UnknownAnyTy) {
5202       ExprResult result = rebuildUnknownAnyFunction(S, Fn);
5203       if (result.isInvalid()) return ExprError();
5204       Fn = result.get();
5205     }
5206 
5207     if (Fn->getType() == S.Context.BoundMemberTy) {
5208       return S.BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5209                                          RParenLoc);
5210     }
5211   }
5212 
5213   // Check for overloaded calls.  This can happen even in C due to extensions.
5214   if (Fn->getType() == S.Context.OverloadTy) {
5215     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
5216 
5217     // We aren't supposed to apply this logic for if there'Scope an '&'
5218     // involved.
5219     if (!find.HasFormOfMemberPointer) {
5220       OverloadExpr *ovl = find.Expression;
5221       if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(ovl))
5222         return S.BuildOverloadedCallExpr(
5223             Scope, Fn, ULE, LParenLoc, ArgExprs, RParenLoc, ExecConfig,
5224             /*AllowTypoCorrection=*/true, find.IsAddressOfOperand);
5225       return S.BuildCallToMemberFunction(Scope, Fn, LParenLoc, ArgExprs,
5226                                          RParenLoc);
5227     }
5228   }
5229 
5230   // If we're directly calling a function, get the appropriate declaration.
5231   if (Fn->getType() == S.Context.UnknownAnyTy) {
5232     ExprResult result = rebuildUnknownAnyFunction(S, Fn);
5233     if (result.isInvalid()) return ExprError();
5234     Fn = result.get();
5235   }
5236 
5237   Expr *NakedFn = Fn->IgnoreParens();
5238 
5239   bool CallingNDeclIndirectly = false;
5240   NamedDecl *NDecl = nullptr;
5241   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn)) {
5242     if (UnOp->getOpcode() == UO_AddrOf) {
5243       CallingNDeclIndirectly = true;
5244       NakedFn = UnOp->getSubExpr()->IgnoreParens();
5245     }
5246   }
5247 
5248   if (isa<DeclRefExpr>(NakedFn)) {
5249     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
5250 
5251     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
5252     if (FDecl && FDecl->getBuiltinID()) {
5253       // Rewrite the function decl for this builtin by replacing parameters
5254       // with no explicit address space with the address space of the arguments
5255       // in ArgExprs.
5256       if ((FDecl =
5257                rewriteBuiltinFunctionDecl(&S, S.Context, FDecl, ArgExprs))) {
5258         NDecl = FDecl;
5259         Fn = DeclRefExpr::Create(
5260             S.Context, FDecl->getQualifierLoc(), SourceLocation(), FDecl, false,
5261             SourceLocation(), FDecl->getType(), Fn->getValueKind(), FDecl);
5262       }
5263     }
5264   } else if (isa<MemberExpr>(NakedFn))
5265     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
5266 
5267   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
5268     if (CallingNDeclIndirectly &&
5269         !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
5270                                              Fn->getLocStart()))
5271       return ExprError();
5272 
5273     // CheckEnableIf assumes that the we're passing in a sane number of args for
5274     // FD, but that doesn't always hold true here. This is because, in some
5275     // cases, we'll emit a diag about an ill-formed function call, but then
5276     // we'll continue on as if the function call wasn't ill-formed. So, if the
5277     // number of args looks incorrect, don't do enable_if checks; we should've
5278     // already emitted an error about the bad call.
5279     if (FD->hasAttr<EnableIfAttr>() &&
5280         isNumberOfArgsValidForCall(S, FD, ArgExprs.size())) {
5281       if (const EnableIfAttr *Attr = S.CheckEnableIf(FD, ArgExprs, true)) {
5282         S.Diag(Fn->getLocStart(),
5283                isa<CXXMethodDecl>(FD)
5284                    ? diag::err_ovl_no_viable_member_function_in_call
5285                    : diag::err_ovl_no_viable_function_in_call)
5286             << FD << FD->getSourceRange();
5287         S.Diag(FD->getLocation(),
5288                diag::note_ovl_candidate_disabled_by_enable_if_attr)
5289             << Attr->getCond()->getSourceRange() << Attr->getMessage();
5290       }
5291     }
5292   }
5293 
5294   return S.BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5295                                  ExecConfig, IsExecConfig);
5296 }
5297 
5298 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
5299 /// This provides the location of the left/right parens and a list of comma
5300 /// locations.
5301 ExprResult Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
5302                                MultiExprArg ArgExprs, SourceLocation RParenLoc,
5303                                Expr *ExecConfig, bool IsExecConfig) {
5304   ExprResult Ret = ActOnCallExprImpl(*this, S, Fn, LParenLoc, ArgExprs,
5305                                      RParenLoc, ExecConfig, IsExecConfig);
5306 
5307   // If appropriate, check that this is a valid CUDA call (and emit an error if
5308   // the call is not allowed).
5309   if (getLangOpts().CUDA && Ret.isUsable())
5310     if (auto *Call = dyn_cast<CallExpr>(Ret.get()))
5311       if (auto *FD = Call->getDirectCallee())
5312         if (!CheckCUDACall(Call->getLocStart(), FD))
5313           return ExprError();
5314 
5315   return Ret;
5316 }
5317 
5318 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5319 ///
5320 /// __builtin_astype( value, dst type )
5321 ///
5322 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5323                                  SourceLocation BuiltinLoc,
5324                                  SourceLocation RParenLoc) {
5325   ExprValueKind VK = VK_RValue;
5326   ExprObjectKind OK = OK_Ordinary;
5327   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5328   QualType SrcTy = E->getType();
5329   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5330     return ExprError(Diag(BuiltinLoc,
5331                           diag::err_invalid_astype_of_different_size)
5332                      << DstTy
5333                      << SrcTy
5334                      << E->getSourceRange());
5335   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5336 }
5337 
5338 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5339 /// provided arguments.
5340 ///
5341 /// __builtin_convertvector( value, dst type )
5342 ///
5343 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5344                                         SourceLocation BuiltinLoc,
5345                                         SourceLocation RParenLoc) {
5346   TypeSourceInfo *TInfo;
5347   GetTypeFromParser(ParsedDestTy, &TInfo);
5348   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5349 }
5350 
5351 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5352 /// i.e. an expression not of \p OverloadTy.  The expression should
5353 /// unary-convert to an expression of function-pointer or
5354 /// block-pointer type.
5355 ///
5356 /// \param NDecl the declaration being called, if available
5357 ExprResult
5358 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5359                             SourceLocation LParenLoc,
5360                             ArrayRef<Expr *> Args,
5361                             SourceLocation RParenLoc,
5362                             Expr *Config, bool IsExecConfig) {
5363   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5364   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5365 
5366   // Functions with 'interrupt' attribute cannot be called directly.
5367   if (FDecl && FDecl->hasAttr<AnyX86InterruptAttr>()) {
5368     Diag(Fn->getExprLoc(), diag::err_anyx86_interrupt_called);
5369     return ExprError();
5370   }
5371 
5372   // Promote the function operand.
5373   // We special-case function promotion here because we only allow promoting
5374   // builtin functions to function pointers in the callee of a call.
5375   ExprResult Result;
5376   if (BuiltinID &&
5377       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5378     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5379                                CK_BuiltinFnToFnPtr).get();
5380   } else {
5381     Result = CallExprUnaryConversions(Fn);
5382   }
5383   if (Result.isInvalid())
5384     return ExprError();
5385   Fn = Result.get();
5386 
5387   // Make the call expr early, before semantic checks.  This guarantees cleanup
5388   // of arguments and function on error.
5389   CallExpr *TheCall;
5390   if (Config)
5391     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5392                                                cast<CallExpr>(Config), Args,
5393                                                Context.BoolTy, VK_RValue,
5394                                                RParenLoc);
5395   else
5396     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5397                                      VK_RValue, RParenLoc);
5398 
5399   if (!getLangOpts().CPlusPlus) {
5400     // C cannot always handle TypoExpr nodes in builtin calls and direct
5401     // function calls as their argument checking don't necessarily handle
5402     // dependent types properly, so make sure any TypoExprs have been
5403     // dealt with.
5404     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5405     if (!Result.isUsable()) return ExprError();
5406     TheCall = dyn_cast<CallExpr>(Result.get());
5407     if (!TheCall) return Result;
5408     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5409   }
5410 
5411   // Bail out early if calling a builtin with custom typechecking.
5412   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5413     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5414 
5415  retry:
5416   const FunctionType *FuncT;
5417   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5418     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5419     // have type pointer to function".
5420     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5421     if (!FuncT)
5422       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5423                          << Fn->getType() << Fn->getSourceRange());
5424   } else if (const BlockPointerType *BPT =
5425                Fn->getType()->getAs<BlockPointerType>()) {
5426     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5427   } else {
5428     // Handle calls to expressions of unknown-any type.
5429     if (Fn->getType() == Context.UnknownAnyTy) {
5430       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5431       if (rewrite.isInvalid()) return ExprError();
5432       Fn = rewrite.get();
5433       TheCall->setCallee(Fn);
5434       goto retry;
5435     }
5436 
5437     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5438       << Fn->getType() << Fn->getSourceRange());
5439   }
5440 
5441   if (getLangOpts().CUDA) {
5442     if (Config) {
5443       // CUDA: Kernel calls must be to global functions
5444       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5445         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5446             << FDecl->getName() << Fn->getSourceRange());
5447 
5448       // CUDA: Kernel function must have 'void' return type
5449       if (!FuncT->getReturnType()->isVoidType())
5450         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5451             << Fn->getType() << Fn->getSourceRange());
5452     } else {
5453       // CUDA: Calls to global functions must be configured
5454       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5455         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5456             << FDecl->getName() << Fn->getSourceRange());
5457     }
5458   }
5459 
5460   // Check for a valid return type
5461   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5462                           FDecl))
5463     return ExprError();
5464 
5465   // We know the result type of the call, set it.
5466   TheCall->setType(FuncT->getCallResultType(Context));
5467   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5468 
5469   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5470   if (Proto) {
5471     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5472                                 IsExecConfig))
5473       return ExprError();
5474   } else {
5475     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5476 
5477     if (FDecl) {
5478       // Check if we have too few/too many template arguments, based
5479       // on our knowledge of the function definition.
5480       const FunctionDecl *Def = nullptr;
5481       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5482         Proto = Def->getType()->getAs<FunctionProtoType>();
5483        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5484           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5485           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5486       }
5487 
5488       // If the function we're calling isn't a function prototype, but we have
5489       // a function prototype from a prior declaratiom, use that prototype.
5490       if (!FDecl->hasPrototype())
5491         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5492     }
5493 
5494     // Promote the arguments (C99 6.5.2.2p6).
5495     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5496       Expr *Arg = Args[i];
5497 
5498       if (Proto && i < Proto->getNumParams()) {
5499         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5500             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5501         ExprResult ArgE =
5502             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5503         if (ArgE.isInvalid())
5504           return true;
5505 
5506         Arg = ArgE.getAs<Expr>();
5507 
5508       } else {
5509         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5510 
5511         if (ArgE.isInvalid())
5512           return true;
5513 
5514         Arg = ArgE.getAs<Expr>();
5515       }
5516 
5517       if (RequireCompleteType(Arg->getLocStart(),
5518                               Arg->getType(),
5519                               diag::err_call_incomplete_argument, Arg))
5520         return ExprError();
5521 
5522       TheCall->setArg(i, Arg);
5523     }
5524   }
5525 
5526   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5527     if (!Method->isStatic())
5528       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5529         << Fn->getSourceRange());
5530 
5531   // Check for sentinels
5532   if (NDecl)
5533     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5534 
5535   // Do special checking on direct calls to functions.
5536   if (FDecl) {
5537     if (CheckFunctionCall(FDecl, TheCall, Proto))
5538       return ExprError();
5539 
5540     if (BuiltinID)
5541       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5542   } else if (NDecl) {
5543     if (CheckPointerCall(NDecl, TheCall, Proto))
5544       return ExprError();
5545   } else {
5546     if (CheckOtherCall(TheCall, Proto))
5547       return ExprError();
5548   }
5549 
5550   return MaybeBindToTemporary(TheCall);
5551 }
5552 
5553 ExprResult
5554 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5555                            SourceLocation RParenLoc, Expr *InitExpr) {
5556   assert(Ty && "ActOnCompoundLiteral(): missing type");
5557   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5558 
5559   TypeSourceInfo *TInfo;
5560   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5561   if (!TInfo)
5562     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5563 
5564   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5565 }
5566 
5567 ExprResult
5568 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5569                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5570   QualType literalType = TInfo->getType();
5571 
5572   if (literalType->isArrayType()) {
5573     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5574           diag::err_illegal_decl_array_incomplete_type,
5575           SourceRange(LParenLoc,
5576                       LiteralExpr->getSourceRange().getEnd())))
5577       return ExprError();
5578     if (literalType->isVariableArrayType())
5579       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5580         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5581   } else if (!literalType->isDependentType() &&
5582              RequireCompleteType(LParenLoc, literalType,
5583                diag::err_typecheck_decl_incomplete_type,
5584                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5585     return ExprError();
5586 
5587   InitializedEntity Entity
5588     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5589   InitializationKind Kind
5590     = InitializationKind::CreateCStyleCast(LParenLoc,
5591                                            SourceRange(LParenLoc, RParenLoc),
5592                                            /*InitList=*/true);
5593   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5594   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5595                                       &literalType);
5596   if (Result.isInvalid())
5597     return ExprError();
5598   LiteralExpr = Result.get();
5599 
5600   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5601   if (isFileScope &&
5602       !LiteralExpr->isTypeDependent() &&
5603       !LiteralExpr->isValueDependent() &&
5604       !literalType->isDependentType()) { // 6.5.2.5p3
5605     if (CheckForConstantInitializer(LiteralExpr, literalType))
5606       return ExprError();
5607   }
5608 
5609   // In C, compound literals are l-values for some reason.
5610   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5611 
5612   return MaybeBindToTemporary(
5613            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5614                                              VK, LiteralExpr, isFileScope));
5615 }
5616 
5617 ExprResult
5618 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5619                     SourceLocation RBraceLoc) {
5620   // Immediately handle non-overload placeholders.  Overloads can be
5621   // resolved contextually, but everything else here can't.
5622   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5623     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5624       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5625 
5626       // Ignore failures; dropping the entire initializer list because
5627       // of one failure would be terrible for indexing/etc.
5628       if (result.isInvalid()) continue;
5629 
5630       InitArgList[I] = result.get();
5631     }
5632   }
5633 
5634   // Semantic analysis for initializers is done by ActOnDeclarator() and
5635   // CheckInitializer() - it requires knowledge of the object being intialized.
5636 
5637   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5638                                                RBraceLoc);
5639   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5640   return E;
5641 }
5642 
5643 /// Do an explicit extend of the given block pointer if we're in ARC.
5644 void Sema::maybeExtendBlockObject(ExprResult &E) {
5645   assert(E.get()->getType()->isBlockPointerType());
5646   assert(E.get()->isRValue());
5647 
5648   // Only do this in an r-value context.
5649   if (!getLangOpts().ObjCAutoRefCount) return;
5650 
5651   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5652                                CK_ARCExtendBlockObject, E.get(),
5653                                /*base path*/ nullptr, VK_RValue);
5654   Cleanup.setExprNeedsCleanups(true);
5655 }
5656 
5657 /// Prepare a conversion of the given expression to an ObjC object
5658 /// pointer type.
5659 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5660   QualType type = E.get()->getType();
5661   if (type->isObjCObjectPointerType()) {
5662     return CK_BitCast;
5663   } else if (type->isBlockPointerType()) {
5664     maybeExtendBlockObject(E);
5665     return CK_BlockPointerToObjCPointerCast;
5666   } else {
5667     assert(type->isPointerType());
5668     return CK_CPointerToObjCPointerCast;
5669   }
5670 }
5671 
5672 /// Prepares for a scalar cast, performing all the necessary stages
5673 /// except the final cast and returning the kind required.
5674 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5675   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5676   // Also, callers should have filtered out the invalid cases with
5677   // pointers.  Everything else should be possible.
5678 
5679   QualType SrcTy = Src.get()->getType();
5680   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5681     return CK_NoOp;
5682 
5683   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5684   case Type::STK_MemberPointer:
5685     llvm_unreachable("member pointer type in C");
5686 
5687   case Type::STK_CPointer:
5688   case Type::STK_BlockPointer:
5689   case Type::STK_ObjCObjectPointer:
5690     switch (DestTy->getScalarTypeKind()) {
5691     case Type::STK_CPointer: {
5692       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5693       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5694       if (SrcAS != DestAS)
5695         return CK_AddressSpaceConversion;
5696       return CK_BitCast;
5697     }
5698     case Type::STK_BlockPointer:
5699       return (SrcKind == Type::STK_BlockPointer
5700                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5701     case Type::STK_ObjCObjectPointer:
5702       if (SrcKind == Type::STK_ObjCObjectPointer)
5703         return CK_BitCast;
5704       if (SrcKind == Type::STK_CPointer)
5705         return CK_CPointerToObjCPointerCast;
5706       maybeExtendBlockObject(Src);
5707       return CK_BlockPointerToObjCPointerCast;
5708     case Type::STK_Bool:
5709       return CK_PointerToBoolean;
5710     case Type::STK_Integral:
5711       return CK_PointerToIntegral;
5712     case Type::STK_Floating:
5713     case Type::STK_FloatingComplex:
5714     case Type::STK_IntegralComplex:
5715     case Type::STK_MemberPointer:
5716       llvm_unreachable("illegal cast from pointer");
5717     }
5718     llvm_unreachable("Should have returned before this");
5719 
5720   case Type::STK_Bool: // casting from bool is like casting from an integer
5721   case Type::STK_Integral:
5722     switch (DestTy->getScalarTypeKind()) {
5723     case Type::STK_CPointer:
5724     case Type::STK_ObjCObjectPointer:
5725     case Type::STK_BlockPointer:
5726       if (Src.get()->isNullPointerConstant(Context,
5727                                            Expr::NPC_ValueDependentIsNull))
5728         return CK_NullToPointer;
5729       return CK_IntegralToPointer;
5730     case Type::STK_Bool:
5731       return CK_IntegralToBoolean;
5732     case Type::STK_Integral:
5733       return CK_IntegralCast;
5734     case Type::STK_Floating:
5735       return CK_IntegralToFloating;
5736     case Type::STK_IntegralComplex:
5737       Src = ImpCastExprToType(Src.get(),
5738                       DestTy->castAs<ComplexType>()->getElementType(),
5739                       CK_IntegralCast);
5740       return CK_IntegralRealToComplex;
5741     case Type::STK_FloatingComplex:
5742       Src = ImpCastExprToType(Src.get(),
5743                       DestTy->castAs<ComplexType>()->getElementType(),
5744                       CK_IntegralToFloating);
5745       return CK_FloatingRealToComplex;
5746     case Type::STK_MemberPointer:
5747       llvm_unreachable("member pointer type in C");
5748     }
5749     llvm_unreachable("Should have returned before this");
5750 
5751   case Type::STK_Floating:
5752     switch (DestTy->getScalarTypeKind()) {
5753     case Type::STK_Floating:
5754       return CK_FloatingCast;
5755     case Type::STK_Bool:
5756       return CK_FloatingToBoolean;
5757     case Type::STK_Integral:
5758       return CK_FloatingToIntegral;
5759     case Type::STK_FloatingComplex:
5760       Src = ImpCastExprToType(Src.get(),
5761                               DestTy->castAs<ComplexType>()->getElementType(),
5762                               CK_FloatingCast);
5763       return CK_FloatingRealToComplex;
5764     case Type::STK_IntegralComplex:
5765       Src = ImpCastExprToType(Src.get(),
5766                               DestTy->castAs<ComplexType>()->getElementType(),
5767                               CK_FloatingToIntegral);
5768       return CK_IntegralRealToComplex;
5769     case Type::STK_CPointer:
5770     case Type::STK_ObjCObjectPointer:
5771     case Type::STK_BlockPointer:
5772       llvm_unreachable("valid float->pointer cast?");
5773     case Type::STK_MemberPointer:
5774       llvm_unreachable("member pointer type in C");
5775     }
5776     llvm_unreachable("Should have returned before this");
5777 
5778   case Type::STK_FloatingComplex:
5779     switch (DestTy->getScalarTypeKind()) {
5780     case Type::STK_FloatingComplex:
5781       return CK_FloatingComplexCast;
5782     case Type::STK_IntegralComplex:
5783       return CK_FloatingComplexToIntegralComplex;
5784     case Type::STK_Floating: {
5785       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5786       if (Context.hasSameType(ET, DestTy))
5787         return CK_FloatingComplexToReal;
5788       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5789       return CK_FloatingCast;
5790     }
5791     case Type::STK_Bool:
5792       return CK_FloatingComplexToBoolean;
5793     case Type::STK_Integral:
5794       Src = ImpCastExprToType(Src.get(),
5795                               SrcTy->castAs<ComplexType>()->getElementType(),
5796                               CK_FloatingComplexToReal);
5797       return CK_FloatingToIntegral;
5798     case Type::STK_CPointer:
5799     case Type::STK_ObjCObjectPointer:
5800     case Type::STK_BlockPointer:
5801       llvm_unreachable("valid complex float->pointer cast?");
5802     case Type::STK_MemberPointer:
5803       llvm_unreachable("member pointer type in C");
5804     }
5805     llvm_unreachable("Should have returned before this");
5806 
5807   case Type::STK_IntegralComplex:
5808     switch (DestTy->getScalarTypeKind()) {
5809     case Type::STK_FloatingComplex:
5810       return CK_IntegralComplexToFloatingComplex;
5811     case Type::STK_IntegralComplex:
5812       return CK_IntegralComplexCast;
5813     case Type::STK_Integral: {
5814       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5815       if (Context.hasSameType(ET, DestTy))
5816         return CK_IntegralComplexToReal;
5817       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5818       return CK_IntegralCast;
5819     }
5820     case Type::STK_Bool:
5821       return CK_IntegralComplexToBoolean;
5822     case Type::STK_Floating:
5823       Src = ImpCastExprToType(Src.get(),
5824                               SrcTy->castAs<ComplexType>()->getElementType(),
5825                               CK_IntegralComplexToReal);
5826       return CK_IntegralToFloating;
5827     case Type::STK_CPointer:
5828     case Type::STK_ObjCObjectPointer:
5829     case Type::STK_BlockPointer:
5830       llvm_unreachable("valid complex int->pointer cast?");
5831     case Type::STK_MemberPointer:
5832       llvm_unreachable("member pointer type in C");
5833     }
5834     llvm_unreachable("Should have returned before this");
5835   }
5836 
5837   llvm_unreachable("Unhandled scalar cast");
5838 }
5839 
5840 static bool breakDownVectorType(QualType type, uint64_t &len,
5841                                 QualType &eltType) {
5842   // Vectors are simple.
5843   if (const VectorType *vecType = type->getAs<VectorType>()) {
5844     len = vecType->getNumElements();
5845     eltType = vecType->getElementType();
5846     assert(eltType->isScalarType());
5847     return true;
5848   }
5849 
5850   // We allow lax conversion to and from non-vector types, but only if
5851   // they're real types (i.e. non-complex, non-pointer scalar types).
5852   if (!type->isRealType()) return false;
5853 
5854   len = 1;
5855   eltType = type;
5856   return true;
5857 }
5858 
5859 /// Are the two types lax-compatible vector types?  That is, given
5860 /// that one of them is a vector, do they have equal storage sizes,
5861 /// where the storage size is the number of elements times the element
5862 /// size?
5863 ///
5864 /// This will also return false if either of the types is neither a
5865 /// vector nor a real type.
5866 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5867   assert(destTy->isVectorType() || srcTy->isVectorType());
5868 
5869   // Disallow lax conversions between scalars and ExtVectors (these
5870   // conversions are allowed for other vector types because common headers
5871   // depend on them).  Most scalar OP ExtVector cases are handled by the
5872   // splat path anyway, which does what we want (convert, not bitcast).
5873   // What this rules out for ExtVectors is crazy things like char4*float.
5874   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5875   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5876 
5877   uint64_t srcLen, destLen;
5878   QualType srcEltTy, destEltTy;
5879   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5880   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5881 
5882   // ASTContext::getTypeSize will return the size rounded up to a
5883   // power of 2, so instead of using that, we need to use the raw
5884   // element size multiplied by the element count.
5885   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5886   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5887 
5888   return (srcLen * srcEltSize == destLen * destEltSize);
5889 }
5890 
5891 /// Is this a legal conversion between two types, one of which is
5892 /// known to be a vector type?
5893 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5894   assert(destTy->isVectorType() || srcTy->isVectorType());
5895 
5896   if (!Context.getLangOpts().LaxVectorConversions)
5897     return false;
5898   return areLaxCompatibleVectorTypes(srcTy, destTy);
5899 }
5900 
5901 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5902                            CastKind &Kind) {
5903   assert(VectorTy->isVectorType() && "Not a vector type!");
5904 
5905   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5906     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5907       return Diag(R.getBegin(),
5908                   Ty->isVectorType() ?
5909                   diag::err_invalid_conversion_between_vectors :
5910                   diag::err_invalid_conversion_between_vector_and_integer)
5911         << VectorTy << Ty << R;
5912   } else
5913     return Diag(R.getBegin(),
5914                 diag::err_invalid_conversion_between_vector_and_scalar)
5915       << VectorTy << Ty << R;
5916 
5917   Kind = CK_BitCast;
5918   return false;
5919 }
5920 
5921 ExprResult Sema::prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr) {
5922   QualType DestElemTy = VectorTy->castAs<VectorType>()->getElementType();
5923 
5924   if (DestElemTy == SplattedExpr->getType())
5925     return SplattedExpr;
5926 
5927   assert(DestElemTy->isFloatingType() ||
5928          DestElemTy->isIntegralOrEnumerationType());
5929 
5930   CastKind CK;
5931   if (VectorTy->isExtVectorType() && SplattedExpr->getType()->isBooleanType()) {
5932     // OpenCL requires that we convert `true` boolean expressions to -1, but
5933     // only when splatting vectors.
5934     if (DestElemTy->isFloatingType()) {
5935       // To avoid having to have a CK_BooleanToSignedFloating cast kind, we cast
5936       // in two steps: boolean to signed integral, then to floating.
5937       ExprResult CastExprRes = ImpCastExprToType(SplattedExpr, Context.IntTy,
5938                                                  CK_BooleanToSignedIntegral);
5939       SplattedExpr = CastExprRes.get();
5940       CK = CK_IntegralToFloating;
5941     } else {
5942       CK = CK_BooleanToSignedIntegral;
5943     }
5944   } else {
5945     ExprResult CastExprRes = SplattedExpr;
5946     CK = PrepareScalarCast(CastExprRes, DestElemTy);
5947     if (CastExprRes.isInvalid())
5948       return ExprError();
5949     SplattedExpr = CastExprRes.get();
5950   }
5951   return ImpCastExprToType(SplattedExpr, DestElemTy, CK);
5952 }
5953 
5954 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5955                                     Expr *CastExpr, CastKind &Kind) {
5956   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5957 
5958   QualType SrcTy = CastExpr->getType();
5959 
5960   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5961   // an ExtVectorType.
5962   // In OpenCL, casts between vectors of different types are not allowed.
5963   // (See OpenCL 6.2).
5964   if (SrcTy->isVectorType()) {
5965     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5966         || (getLangOpts().OpenCL &&
5967             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5968       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5969         << DestTy << SrcTy << R;
5970       return ExprError();
5971     }
5972     Kind = CK_BitCast;
5973     return CastExpr;
5974   }
5975 
5976   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5977   // conversion will take place first from scalar to elt type, and then
5978   // splat from elt type to vector.
5979   if (SrcTy->isPointerType())
5980     return Diag(R.getBegin(),
5981                 diag::err_invalid_conversion_between_vector_and_scalar)
5982       << DestTy << SrcTy << R;
5983 
5984   Kind = CK_VectorSplat;
5985   return prepareVectorSplat(DestTy, CastExpr);
5986 }
5987 
5988 ExprResult
5989 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5990                     Declarator &D, ParsedType &Ty,
5991                     SourceLocation RParenLoc, Expr *CastExpr) {
5992   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5993          "ActOnCastExpr(): missing type or expr");
5994 
5995   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5996   if (D.isInvalidType())
5997     return ExprError();
5998 
5999   if (getLangOpts().CPlusPlus) {
6000     // Check that there are no default arguments (C++ only).
6001     CheckExtraCXXDefaultArguments(D);
6002   } else {
6003     // Make sure any TypoExprs have been dealt with.
6004     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
6005     if (!Res.isUsable())
6006       return ExprError();
6007     CastExpr = Res.get();
6008   }
6009 
6010   checkUnusedDeclAttributes(D);
6011 
6012   QualType castType = castTInfo->getType();
6013   Ty = CreateParsedType(castType, castTInfo);
6014 
6015   bool isVectorLiteral = false;
6016 
6017   // Check for an altivec or OpenCL literal,
6018   // i.e. all the elements are integer constants.
6019   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
6020   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
6021   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
6022        && castType->isVectorType() && (PE || PLE)) {
6023     if (PLE && PLE->getNumExprs() == 0) {
6024       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
6025       return ExprError();
6026     }
6027     if (PE || PLE->getNumExprs() == 1) {
6028       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
6029       if (!E->getType()->isVectorType())
6030         isVectorLiteral = true;
6031     }
6032     else
6033       isVectorLiteral = true;
6034   }
6035 
6036   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
6037   // then handle it as such.
6038   if (isVectorLiteral)
6039     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
6040 
6041   // If the Expr being casted is a ParenListExpr, handle it specially.
6042   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
6043   // sequence of BinOp comma operators.
6044   if (isa<ParenListExpr>(CastExpr)) {
6045     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
6046     if (Result.isInvalid()) return ExprError();
6047     CastExpr = Result.get();
6048   }
6049 
6050   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
6051       !getSourceManager().isInSystemMacro(LParenLoc))
6052     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
6053 
6054   CheckTollFreeBridgeCast(castType, CastExpr);
6055 
6056   CheckObjCBridgeRelatedCast(castType, CastExpr);
6057 
6058   DiscardMisalignedMemberAddress(castType.getTypePtr(), CastExpr);
6059 
6060   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
6061 }
6062 
6063 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
6064                                     SourceLocation RParenLoc, Expr *E,
6065                                     TypeSourceInfo *TInfo) {
6066   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
6067          "Expected paren or paren list expression");
6068 
6069   Expr **exprs;
6070   unsigned numExprs;
6071   Expr *subExpr;
6072   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
6073   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
6074     LiteralLParenLoc = PE->getLParenLoc();
6075     LiteralRParenLoc = PE->getRParenLoc();
6076     exprs = PE->getExprs();
6077     numExprs = PE->getNumExprs();
6078   } else { // isa<ParenExpr> by assertion at function entrance
6079     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
6080     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
6081     subExpr = cast<ParenExpr>(E)->getSubExpr();
6082     exprs = &subExpr;
6083     numExprs = 1;
6084   }
6085 
6086   QualType Ty = TInfo->getType();
6087   assert(Ty->isVectorType() && "Expected vector type");
6088 
6089   SmallVector<Expr *, 8> initExprs;
6090   const VectorType *VTy = Ty->getAs<VectorType>();
6091   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
6092 
6093   // '(...)' form of vector initialization in AltiVec: the number of
6094   // initializers must be one or must match the size of the vector.
6095   // If a single value is specified in the initializer then it will be
6096   // replicated to all the components of the vector
6097   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
6098     // The number of initializers must be one or must match the size of the
6099     // vector. If a single value is specified in the initializer then it will
6100     // be replicated to all the components of the vector
6101     if (numExprs == 1) {
6102       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6103       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6104       if (Literal.isInvalid())
6105         return ExprError();
6106       Literal = ImpCastExprToType(Literal.get(), ElemTy,
6107                                   PrepareScalarCast(Literal, ElemTy));
6108       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6109     }
6110     else if (numExprs < numElems) {
6111       Diag(E->getExprLoc(),
6112            diag::err_incorrect_number_of_vector_initializers);
6113       return ExprError();
6114     }
6115     else
6116       initExprs.append(exprs, exprs + numExprs);
6117   }
6118   else {
6119     // For OpenCL, when the number of initializers is a single value,
6120     // it will be replicated to all components of the vector.
6121     if (getLangOpts().OpenCL &&
6122         VTy->getVectorKind() == VectorType::GenericVector &&
6123         numExprs == 1) {
6124         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
6125         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
6126         if (Literal.isInvalid())
6127           return ExprError();
6128         Literal = ImpCastExprToType(Literal.get(), ElemTy,
6129                                     PrepareScalarCast(Literal, ElemTy));
6130         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
6131     }
6132 
6133     initExprs.append(exprs, exprs + numExprs);
6134   }
6135   // FIXME: This means that pretty-printing the final AST will produce curly
6136   // braces instead of the original commas.
6137   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
6138                                                    initExprs, LiteralRParenLoc);
6139   initE->setType(Ty);
6140   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
6141 }
6142 
6143 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
6144 /// the ParenListExpr into a sequence of comma binary operators.
6145 ExprResult
6146 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
6147   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
6148   if (!E)
6149     return OrigExpr;
6150 
6151   ExprResult Result(E->getExpr(0));
6152 
6153   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
6154     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
6155                         E->getExpr(i));
6156 
6157   if (Result.isInvalid()) return ExprError();
6158 
6159   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
6160 }
6161 
6162 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
6163                                     SourceLocation R,
6164                                     MultiExprArg Val) {
6165   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
6166   return expr;
6167 }
6168 
6169 /// \brief Emit a specialized diagnostic when one expression is a null pointer
6170 /// constant and the other is not a pointer.  Returns true if a diagnostic is
6171 /// emitted.
6172 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
6173                                       SourceLocation QuestionLoc) {
6174   Expr *NullExpr = LHSExpr;
6175   Expr *NonPointerExpr = RHSExpr;
6176   Expr::NullPointerConstantKind NullKind =
6177       NullExpr->isNullPointerConstant(Context,
6178                                       Expr::NPC_ValueDependentIsNotNull);
6179 
6180   if (NullKind == Expr::NPCK_NotNull) {
6181     NullExpr = RHSExpr;
6182     NonPointerExpr = LHSExpr;
6183     NullKind =
6184         NullExpr->isNullPointerConstant(Context,
6185                                         Expr::NPC_ValueDependentIsNotNull);
6186   }
6187 
6188   if (NullKind == Expr::NPCK_NotNull)
6189     return false;
6190 
6191   if (NullKind == Expr::NPCK_ZeroExpression)
6192     return false;
6193 
6194   if (NullKind == Expr::NPCK_ZeroLiteral) {
6195     // In this case, check to make sure that we got here from a "NULL"
6196     // string in the source code.
6197     NullExpr = NullExpr->IgnoreParenImpCasts();
6198     SourceLocation loc = NullExpr->getExprLoc();
6199     if (!findMacroSpelling(loc, "NULL"))
6200       return false;
6201   }
6202 
6203   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
6204   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
6205       << NonPointerExpr->getType() << DiagType
6206       << NonPointerExpr->getSourceRange();
6207   return true;
6208 }
6209 
6210 /// \brief Return false if the condition expression is valid, true otherwise.
6211 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
6212   QualType CondTy = Cond->getType();
6213 
6214   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
6215   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
6216     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6217       << CondTy << Cond->getSourceRange();
6218     return true;
6219   }
6220 
6221   // C99 6.5.15p2
6222   if (CondTy->isScalarType()) return false;
6223 
6224   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
6225     << CondTy << Cond->getSourceRange();
6226   return true;
6227 }
6228 
6229 /// \brief Handle when one or both operands are void type.
6230 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
6231                                          ExprResult &RHS) {
6232     Expr *LHSExpr = LHS.get();
6233     Expr *RHSExpr = RHS.get();
6234 
6235     if (!LHSExpr->getType()->isVoidType())
6236       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6237         << RHSExpr->getSourceRange();
6238     if (!RHSExpr->getType()->isVoidType())
6239       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
6240         << LHSExpr->getSourceRange();
6241     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
6242     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
6243     return S.Context.VoidTy;
6244 }
6245 
6246 /// \brief Return false if the NullExpr can be promoted to PointerTy,
6247 /// true otherwise.
6248 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
6249                                         QualType PointerTy) {
6250   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
6251       !NullExpr.get()->isNullPointerConstant(S.Context,
6252                                             Expr::NPC_ValueDependentIsNull))
6253     return true;
6254 
6255   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
6256   return false;
6257 }
6258 
6259 /// \brief Checks compatibility between two pointers and return the resulting
6260 /// type.
6261 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
6262                                                      ExprResult &RHS,
6263                                                      SourceLocation Loc) {
6264   QualType LHSTy = LHS.get()->getType();
6265   QualType RHSTy = RHS.get()->getType();
6266 
6267   if (S.Context.hasSameType(LHSTy, RHSTy)) {
6268     // Two identical pointers types are always compatible.
6269     return LHSTy;
6270   }
6271 
6272   QualType lhptee, rhptee;
6273 
6274   // Get the pointee types.
6275   bool IsBlockPointer = false;
6276   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
6277     lhptee = LHSBTy->getPointeeType();
6278     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
6279     IsBlockPointer = true;
6280   } else {
6281     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
6282     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
6283   }
6284 
6285   // C99 6.5.15p6: If both operands are pointers to compatible types or to
6286   // differently qualified versions of compatible types, the result type is
6287   // a pointer to an appropriately qualified version of the composite
6288   // type.
6289 
6290   // Only CVR-qualifiers exist in the standard, and the differently-qualified
6291   // clause doesn't make sense for our extensions. E.g. address space 2 should
6292   // be incompatible with address space 3: they may live on different devices or
6293   // anything.
6294   Qualifiers lhQual = lhptee.getQualifiers();
6295   Qualifiers rhQual = rhptee.getQualifiers();
6296 
6297   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
6298   lhQual.removeCVRQualifiers();
6299   rhQual.removeCVRQualifiers();
6300 
6301   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
6302   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
6303 
6304   // For OpenCL:
6305   // 1. If LHS and RHS types match exactly and:
6306   //  (a) AS match => use standard C rules, no bitcast or addrspacecast
6307   //  (b) AS overlap => generate addrspacecast
6308   //  (c) AS don't overlap => give an error
6309   // 2. if LHS and RHS types don't match:
6310   //  (a) AS match => use standard C rules, generate bitcast
6311   //  (b) AS overlap => generate addrspacecast instead of bitcast
6312   //  (c) AS don't overlap => give an error
6313 
6314   // For OpenCL, non-null composite type is returned only for cases 1a and 1b.
6315   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
6316 
6317   // OpenCL cases 1c, 2a, 2b, and 2c.
6318   if (CompositeTy.isNull()) {
6319     // In this situation, we assume void* type. No especially good
6320     // reason, but this is what gcc does, and we do have to pick
6321     // to get a consistent AST.
6322     QualType incompatTy;
6323     if (S.getLangOpts().OpenCL) {
6324       // OpenCL v1.1 s6.5 - Conversion between pointers to distinct address
6325       // spaces is disallowed.
6326       unsigned ResultAddrSpace;
6327       if (lhQual.isAddressSpaceSupersetOf(rhQual)) {
6328         // Cases 2a and 2b.
6329         ResultAddrSpace = lhQual.getAddressSpace();
6330       } else if (rhQual.isAddressSpaceSupersetOf(lhQual)) {
6331         // Cases 2a and 2b.
6332         ResultAddrSpace = rhQual.getAddressSpace();
6333       } else {
6334         // Cases 1c and 2c.
6335         S.Diag(Loc,
6336                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
6337             << LHSTy << RHSTy << 2 << LHS.get()->getSourceRange()
6338             << RHS.get()->getSourceRange();
6339         return QualType();
6340       }
6341 
6342       // Continue handling cases 2a and 2b.
6343       incompatTy = S.Context.getPointerType(
6344           S.Context.getAddrSpaceQualType(S.Context.VoidTy, ResultAddrSpace));
6345       LHS = S.ImpCastExprToType(LHS.get(), incompatTy,
6346                                 (lhQual.getAddressSpace() != ResultAddrSpace)
6347                                     ? CK_AddressSpaceConversion /* 2b */
6348                                     : CK_BitCast /* 2a */);
6349       RHS = S.ImpCastExprToType(RHS.get(), incompatTy,
6350                                 (rhQual.getAddressSpace() != ResultAddrSpace)
6351                                     ? CK_AddressSpaceConversion /* 2b */
6352                                     : CK_BitCast /* 2a */);
6353     } else {
6354       S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
6355           << LHSTy << RHSTy << LHS.get()->getSourceRange()
6356           << RHS.get()->getSourceRange();
6357       incompatTy = S.Context.getPointerType(S.Context.VoidTy);
6358       LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6359       RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6360     }
6361     return incompatTy;
6362   }
6363 
6364   // The pointer types are compatible.
6365   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
6366   auto LHSCastKind = CK_BitCast, RHSCastKind = CK_BitCast;
6367   if (IsBlockPointer)
6368     ResultTy = S.Context.getBlockPointerType(ResultTy);
6369   else {
6370     // Cases 1a and 1b for OpenCL.
6371     auto ResultAddrSpace = ResultTy.getQualifiers().getAddressSpace();
6372     LHSCastKind = lhQual.getAddressSpace() == ResultAddrSpace
6373                       ? CK_BitCast /* 1a */
6374                       : CK_AddressSpaceConversion /* 1b */;
6375     RHSCastKind = rhQual.getAddressSpace() == ResultAddrSpace
6376                       ? CK_BitCast /* 1a */
6377                       : CK_AddressSpaceConversion /* 1b */;
6378     ResultTy = S.Context.getPointerType(ResultTy);
6379   }
6380 
6381   // For case 1a of OpenCL, S.ImpCastExprToType will not insert bitcast
6382   // if the target type does not change.
6383   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, LHSCastKind);
6384   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, RHSCastKind);
6385   return ResultTy;
6386 }
6387 
6388 /// \brief Return the resulting type when the operands are both block pointers.
6389 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
6390                                                           ExprResult &LHS,
6391                                                           ExprResult &RHS,
6392                                                           SourceLocation Loc) {
6393   QualType LHSTy = LHS.get()->getType();
6394   QualType RHSTy = RHS.get()->getType();
6395 
6396   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
6397     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
6398       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
6399       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6400       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6401       return destType;
6402     }
6403     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
6404       << LHSTy << RHSTy << LHS.get()->getSourceRange()
6405       << RHS.get()->getSourceRange();
6406     return QualType();
6407   }
6408 
6409   // We have 2 block pointer types.
6410   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6411 }
6412 
6413 /// \brief Return the resulting type when the operands are both pointers.
6414 static QualType
6415 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6416                                             ExprResult &RHS,
6417                                             SourceLocation Loc) {
6418   // get the pointer types
6419   QualType LHSTy = LHS.get()->getType();
6420   QualType RHSTy = RHS.get()->getType();
6421 
6422   // get the "pointed to" types
6423   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6424   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6425 
6426   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6427   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6428     // Figure out necessary qualifiers (C99 6.5.15p6)
6429     QualType destPointee
6430       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6431     QualType destType = S.Context.getPointerType(destPointee);
6432     // Add qualifiers if necessary.
6433     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6434     // Promote to void*.
6435     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6436     return destType;
6437   }
6438   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6439     QualType destPointee
6440       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6441     QualType destType = S.Context.getPointerType(destPointee);
6442     // Add qualifiers if necessary.
6443     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6444     // Promote to void*.
6445     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6446     return destType;
6447   }
6448 
6449   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6450 }
6451 
6452 /// \brief Return false if the first expression is not an integer and the second
6453 /// expression is not a pointer, true otherwise.
6454 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6455                                         Expr* PointerExpr, SourceLocation Loc,
6456                                         bool IsIntFirstExpr) {
6457   if (!PointerExpr->getType()->isPointerType() ||
6458       !Int.get()->getType()->isIntegerType())
6459     return false;
6460 
6461   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6462   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6463 
6464   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6465     << Expr1->getType() << Expr2->getType()
6466     << Expr1->getSourceRange() << Expr2->getSourceRange();
6467   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6468                             CK_IntegralToPointer);
6469   return true;
6470 }
6471 
6472 /// \brief Simple conversion between integer and floating point types.
6473 ///
6474 /// Used when handling the OpenCL conditional operator where the
6475 /// condition is a vector while the other operands are scalar.
6476 ///
6477 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6478 /// types are either integer or floating type. Between the two
6479 /// operands, the type with the higher rank is defined as the "result
6480 /// type". The other operand needs to be promoted to the same type. No
6481 /// other type promotion is allowed. We cannot use
6482 /// UsualArithmeticConversions() for this purpose, since it always
6483 /// promotes promotable types.
6484 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6485                                             ExprResult &RHS,
6486                                             SourceLocation QuestionLoc) {
6487   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6488   if (LHS.isInvalid())
6489     return QualType();
6490   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6491   if (RHS.isInvalid())
6492     return QualType();
6493 
6494   // For conversion purposes, we ignore any qualifiers.
6495   // For example, "const float" and "float" are equivalent.
6496   QualType LHSType =
6497     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6498   QualType RHSType =
6499     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6500 
6501   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6502     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6503       << LHSType << LHS.get()->getSourceRange();
6504     return QualType();
6505   }
6506 
6507   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6508     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6509       << RHSType << RHS.get()->getSourceRange();
6510     return QualType();
6511   }
6512 
6513   // If both types are identical, no conversion is needed.
6514   if (LHSType == RHSType)
6515     return LHSType;
6516 
6517   // Now handle "real" floating types (i.e. float, double, long double).
6518   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6519     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6520                                  /*IsCompAssign = */ false);
6521 
6522   // Finally, we have two differing integer types.
6523   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6524   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6525 }
6526 
6527 /// \brief Convert scalar operands to a vector that matches the
6528 ///        condition in length.
6529 ///
6530 /// Used when handling the OpenCL conditional operator where the
6531 /// condition is a vector while the other operands are scalar.
6532 ///
6533 /// We first compute the "result type" for the scalar operands
6534 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6535 /// into a vector of that type where the length matches the condition
6536 /// vector type. s6.11.6 requires that the element types of the result
6537 /// and the condition must have the same number of bits.
6538 static QualType
6539 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6540                               QualType CondTy, SourceLocation QuestionLoc) {
6541   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6542   if (ResTy.isNull()) return QualType();
6543 
6544   const VectorType *CV = CondTy->getAs<VectorType>();
6545   assert(CV);
6546 
6547   // Determine the vector result type
6548   unsigned NumElements = CV->getNumElements();
6549   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6550 
6551   // Ensure that all types have the same number of bits
6552   if (S.Context.getTypeSize(CV->getElementType())
6553       != S.Context.getTypeSize(ResTy)) {
6554     // Since VectorTy is created internally, it does not pretty print
6555     // with an OpenCL name. Instead, we just print a description.
6556     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6557     SmallString<64> Str;
6558     llvm::raw_svector_ostream OS(Str);
6559     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6560     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6561       << CondTy << OS.str();
6562     return QualType();
6563   }
6564 
6565   // Convert operands to the vector result type
6566   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6567   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6568 
6569   return VectorTy;
6570 }
6571 
6572 /// \brief Return false if this is a valid OpenCL condition vector
6573 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6574                                        SourceLocation QuestionLoc) {
6575   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6576   // integral type.
6577   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6578   assert(CondTy);
6579   QualType EleTy = CondTy->getElementType();
6580   if (EleTy->isIntegerType()) return false;
6581 
6582   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6583     << Cond->getType() << Cond->getSourceRange();
6584   return true;
6585 }
6586 
6587 /// \brief Return false if the vector condition type and the vector
6588 ///        result type are compatible.
6589 ///
6590 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6591 /// number of elements, and their element types have the same number
6592 /// of bits.
6593 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6594                               SourceLocation QuestionLoc) {
6595   const VectorType *CV = CondTy->getAs<VectorType>();
6596   const VectorType *RV = VecResTy->getAs<VectorType>();
6597   assert(CV && RV);
6598 
6599   if (CV->getNumElements() != RV->getNumElements()) {
6600     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6601       << CondTy << VecResTy;
6602     return true;
6603   }
6604 
6605   QualType CVE = CV->getElementType();
6606   QualType RVE = RV->getElementType();
6607 
6608   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6609     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6610       << CondTy << VecResTy;
6611     return true;
6612   }
6613 
6614   return false;
6615 }
6616 
6617 /// \brief Return the resulting type for the conditional operator in
6618 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6619 ///        s6.3.i) when the condition is a vector type.
6620 static QualType
6621 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6622                              ExprResult &LHS, ExprResult &RHS,
6623                              SourceLocation QuestionLoc) {
6624   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6625   if (Cond.isInvalid())
6626     return QualType();
6627   QualType CondTy = Cond.get()->getType();
6628 
6629   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6630     return QualType();
6631 
6632   // If either operand is a vector then find the vector type of the
6633   // result as specified in OpenCL v1.1 s6.3.i.
6634   if (LHS.get()->getType()->isVectorType() ||
6635       RHS.get()->getType()->isVectorType()) {
6636     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6637                                               /*isCompAssign*/false,
6638                                               /*AllowBothBool*/true,
6639                                               /*AllowBoolConversions*/false);
6640     if (VecResTy.isNull()) return QualType();
6641     // The result type must match the condition type as specified in
6642     // OpenCL v1.1 s6.11.6.
6643     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6644       return QualType();
6645     return VecResTy;
6646   }
6647 
6648   // Both operands are scalar.
6649   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6650 }
6651 
6652 /// \brief Return true if the Expr is block type
6653 static bool checkBlockType(Sema &S, const Expr *E) {
6654   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
6655     QualType Ty = CE->getCallee()->getType();
6656     if (Ty->isBlockPointerType()) {
6657       S.Diag(E->getExprLoc(), diag::err_opencl_ternary_with_block);
6658       return true;
6659     }
6660   }
6661   return false;
6662 }
6663 
6664 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6665 /// In that case, LHS = cond.
6666 /// C99 6.5.15
6667 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6668                                         ExprResult &RHS, ExprValueKind &VK,
6669                                         ExprObjectKind &OK,
6670                                         SourceLocation QuestionLoc) {
6671 
6672   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6673   if (!LHSResult.isUsable()) return QualType();
6674   LHS = LHSResult;
6675 
6676   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6677   if (!RHSResult.isUsable()) return QualType();
6678   RHS = RHSResult;
6679 
6680   // C++ is sufficiently different to merit its own checker.
6681   if (getLangOpts().CPlusPlus)
6682     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6683 
6684   VK = VK_RValue;
6685   OK = OK_Ordinary;
6686 
6687   // The OpenCL operator with a vector condition is sufficiently
6688   // different to merit its own checker.
6689   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6690     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6691 
6692   // First, check the condition.
6693   Cond = UsualUnaryConversions(Cond.get());
6694   if (Cond.isInvalid())
6695     return QualType();
6696   if (checkCondition(*this, Cond.get(), QuestionLoc))
6697     return QualType();
6698 
6699   // Now check the two expressions.
6700   if (LHS.get()->getType()->isVectorType() ||
6701       RHS.get()->getType()->isVectorType())
6702     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6703                                /*AllowBothBool*/true,
6704                                /*AllowBoolConversions*/false);
6705 
6706   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6707   if (LHS.isInvalid() || RHS.isInvalid())
6708     return QualType();
6709 
6710   QualType LHSTy = LHS.get()->getType();
6711   QualType RHSTy = RHS.get()->getType();
6712 
6713   // Diagnose attempts to convert between __float128 and long double where
6714   // such conversions currently can't be handled.
6715   if (unsupportedTypeConversion(*this, LHSTy, RHSTy)) {
6716     Diag(QuestionLoc,
6717          diag::err_typecheck_cond_incompatible_operands) << LHSTy << RHSTy
6718       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6719     return QualType();
6720   }
6721 
6722   // OpenCL v2.0 s6.12.5 - Blocks cannot be used as expressions of the ternary
6723   // selection operator (?:).
6724   if (getLangOpts().OpenCL &&
6725       (checkBlockType(*this, LHS.get()) | checkBlockType(*this, RHS.get()))) {
6726     return QualType();
6727   }
6728 
6729   // If both operands have arithmetic type, do the usual arithmetic conversions
6730   // to find a common type: C99 6.5.15p3,5.
6731   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6732     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6733     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6734 
6735     return ResTy;
6736   }
6737 
6738   // If both operands are the same structure or union type, the result is that
6739   // type.
6740   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6741     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6742       if (LHSRT->getDecl() == RHSRT->getDecl())
6743         // "If both the operands have structure or union type, the result has
6744         // that type."  This implies that CV qualifiers are dropped.
6745         return LHSTy.getUnqualifiedType();
6746     // FIXME: Type of conditional expression must be complete in C mode.
6747   }
6748 
6749   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6750   // The following || allows only one side to be void (a GCC-ism).
6751   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6752     return checkConditionalVoidType(*this, LHS, RHS);
6753   }
6754 
6755   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6756   // the type of the other operand."
6757   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6758   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6759 
6760   // All objective-c pointer type analysis is done here.
6761   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6762                                                         QuestionLoc);
6763   if (LHS.isInvalid() || RHS.isInvalid())
6764     return QualType();
6765   if (!compositeType.isNull())
6766     return compositeType;
6767 
6768 
6769   // Handle block pointer types.
6770   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6771     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6772                                                      QuestionLoc);
6773 
6774   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6775   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6776     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6777                                                        QuestionLoc);
6778 
6779   // GCC compatibility: soften pointer/integer mismatch.  Note that
6780   // null pointers have been filtered out by this point.
6781   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6782       /*isIntFirstExpr=*/true))
6783     return RHSTy;
6784   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6785       /*isIntFirstExpr=*/false))
6786     return LHSTy;
6787 
6788   // Emit a better diagnostic if one of the expressions is a null pointer
6789   // constant and the other is not a pointer type. In this case, the user most
6790   // likely forgot to take the address of the other expression.
6791   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6792     return QualType();
6793 
6794   // Otherwise, the operands are not compatible.
6795   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6796     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6797     << RHS.get()->getSourceRange();
6798   return QualType();
6799 }
6800 
6801 /// FindCompositeObjCPointerType - Helper method to find composite type of
6802 /// two objective-c pointer types of the two input expressions.
6803 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6804                                             SourceLocation QuestionLoc) {
6805   QualType LHSTy = LHS.get()->getType();
6806   QualType RHSTy = RHS.get()->getType();
6807 
6808   // Handle things like Class and struct objc_class*.  Here we case the result
6809   // to the pseudo-builtin, because that will be implicitly cast back to the
6810   // redefinition type if an attempt is made to access its fields.
6811   if (LHSTy->isObjCClassType() &&
6812       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6813     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6814     return LHSTy;
6815   }
6816   if (RHSTy->isObjCClassType() &&
6817       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6818     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6819     return RHSTy;
6820   }
6821   // And the same for struct objc_object* / id
6822   if (LHSTy->isObjCIdType() &&
6823       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6824     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6825     return LHSTy;
6826   }
6827   if (RHSTy->isObjCIdType() &&
6828       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6829     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6830     return RHSTy;
6831   }
6832   // And the same for struct objc_selector* / SEL
6833   if (Context.isObjCSelType(LHSTy) &&
6834       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6835     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6836     return LHSTy;
6837   }
6838   if (Context.isObjCSelType(RHSTy) &&
6839       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6840     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6841     return RHSTy;
6842   }
6843   // Check constraints for Objective-C object pointers types.
6844   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6845 
6846     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6847       // Two identical object pointer types are always compatible.
6848       return LHSTy;
6849     }
6850     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6851     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6852     QualType compositeType = LHSTy;
6853 
6854     // If both operands are interfaces and either operand can be
6855     // assigned to the other, use that type as the composite
6856     // type. This allows
6857     //   xxx ? (A*) a : (B*) b
6858     // where B is a subclass of A.
6859     //
6860     // Additionally, as for assignment, if either type is 'id'
6861     // allow silent coercion. Finally, if the types are
6862     // incompatible then make sure to use 'id' as the composite
6863     // type so the result is acceptable for sending messages to.
6864 
6865     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6866     // It could return the composite type.
6867     if (!(compositeType =
6868           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6869       // Nothing more to do.
6870     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6871       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6872     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6873       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6874     } else if ((LHSTy->isObjCQualifiedIdType() ||
6875                 RHSTy->isObjCQualifiedIdType()) &&
6876                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6877       // Need to handle "id<xx>" explicitly.
6878       // GCC allows qualified id and any Objective-C type to devolve to
6879       // id. Currently localizing to here until clear this should be
6880       // part of ObjCQualifiedIdTypesAreCompatible.
6881       compositeType = Context.getObjCIdType();
6882     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6883       compositeType = Context.getObjCIdType();
6884     } else {
6885       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6886       << LHSTy << RHSTy
6887       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6888       QualType incompatTy = Context.getObjCIdType();
6889       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6890       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6891       return incompatTy;
6892     }
6893     // The object pointer types are compatible.
6894     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6895     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6896     return compositeType;
6897   }
6898   // Check Objective-C object pointer types and 'void *'
6899   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6900     if (getLangOpts().ObjCAutoRefCount) {
6901       // ARC forbids the implicit conversion of object pointers to 'void *',
6902       // so these types are not compatible.
6903       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6904           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6905       LHS = RHS = true;
6906       return QualType();
6907     }
6908     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6909     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6910     QualType destPointee
6911     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6912     QualType destType = Context.getPointerType(destPointee);
6913     // Add qualifiers if necessary.
6914     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6915     // Promote to void*.
6916     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6917     return destType;
6918   }
6919   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6920     if (getLangOpts().ObjCAutoRefCount) {
6921       // ARC forbids the implicit conversion of object pointers to 'void *',
6922       // so these types are not compatible.
6923       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6924           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6925       LHS = RHS = true;
6926       return QualType();
6927     }
6928     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6929     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6930     QualType destPointee
6931     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6932     QualType destType = Context.getPointerType(destPointee);
6933     // Add qualifiers if necessary.
6934     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6935     // Promote to void*.
6936     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6937     return destType;
6938   }
6939   return QualType();
6940 }
6941 
6942 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6943 /// ParenRange in parentheses.
6944 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6945                                const PartialDiagnostic &Note,
6946                                SourceRange ParenRange) {
6947   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6948   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6949       EndLoc.isValid()) {
6950     Self.Diag(Loc, Note)
6951       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6952       << FixItHint::CreateInsertion(EndLoc, ")");
6953   } else {
6954     // We can't display the parentheses, so just show the bare note.
6955     Self.Diag(Loc, Note) << ParenRange;
6956   }
6957 }
6958 
6959 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6960   return BinaryOperator::isAdditiveOp(Opc) ||
6961          BinaryOperator::isMultiplicativeOp(Opc) ||
6962          BinaryOperator::isShiftOp(Opc);
6963 }
6964 
6965 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6966 /// expression, either using a built-in or overloaded operator,
6967 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6968 /// expression.
6969 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6970                                    Expr **RHSExprs) {
6971   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6972   E = E->IgnoreImpCasts();
6973   E = E->IgnoreConversionOperator();
6974   E = E->IgnoreImpCasts();
6975 
6976   // Built-in binary operator.
6977   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6978     if (IsArithmeticOp(OP->getOpcode())) {
6979       *Opcode = OP->getOpcode();
6980       *RHSExprs = OP->getRHS();
6981       return true;
6982     }
6983   }
6984 
6985   // Overloaded operator.
6986   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6987     if (Call->getNumArgs() != 2)
6988       return false;
6989 
6990     // Make sure this is really a binary operator that is safe to pass into
6991     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6992     OverloadedOperatorKind OO = Call->getOperator();
6993     if (OO < OO_Plus || OO > OO_Arrow ||
6994         OO == OO_PlusPlus || OO == OO_MinusMinus)
6995       return false;
6996 
6997     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6998     if (IsArithmeticOp(OpKind)) {
6999       *Opcode = OpKind;
7000       *RHSExprs = Call->getArg(1);
7001       return true;
7002     }
7003   }
7004 
7005   return false;
7006 }
7007 
7008 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
7009 /// or is a logical expression such as (x==y) which has int type, but is
7010 /// commonly interpreted as boolean.
7011 static bool ExprLooksBoolean(Expr *E) {
7012   E = E->IgnoreParenImpCasts();
7013 
7014   if (E->getType()->isBooleanType())
7015     return true;
7016   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
7017     return OP->isComparisonOp() || OP->isLogicalOp();
7018   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
7019     return OP->getOpcode() == UO_LNot;
7020   if (E->getType()->isPointerType())
7021     return true;
7022 
7023   return false;
7024 }
7025 
7026 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
7027 /// and binary operator are mixed in a way that suggests the programmer assumed
7028 /// the conditional operator has higher precedence, for example:
7029 /// "int x = a + someBinaryCondition ? 1 : 2".
7030 static void DiagnoseConditionalPrecedence(Sema &Self,
7031                                           SourceLocation OpLoc,
7032                                           Expr *Condition,
7033                                           Expr *LHSExpr,
7034                                           Expr *RHSExpr) {
7035   BinaryOperatorKind CondOpcode;
7036   Expr *CondRHS;
7037 
7038   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
7039     return;
7040   if (!ExprLooksBoolean(CondRHS))
7041     return;
7042 
7043   // The condition is an arithmetic binary expression, with a right-
7044   // hand side that looks boolean, so warn.
7045 
7046   Self.Diag(OpLoc, diag::warn_precedence_conditional)
7047       << Condition->getSourceRange()
7048       << BinaryOperator::getOpcodeStr(CondOpcode);
7049 
7050   SuggestParentheses(Self, OpLoc,
7051     Self.PDiag(diag::note_precedence_silence)
7052       << BinaryOperator::getOpcodeStr(CondOpcode),
7053     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
7054 
7055   SuggestParentheses(Self, OpLoc,
7056     Self.PDiag(diag::note_precedence_conditional_first),
7057     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
7058 }
7059 
7060 /// Compute the nullability of a conditional expression.
7061 static QualType computeConditionalNullability(QualType ResTy, bool IsBin,
7062                                               QualType LHSTy, QualType RHSTy,
7063                                               ASTContext &Ctx) {
7064   if (!ResTy->isAnyPointerType())
7065     return ResTy;
7066 
7067   auto GetNullability = [&Ctx](QualType Ty) {
7068     Optional<NullabilityKind> Kind = Ty->getNullability(Ctx);
7069     if (Kind)
7070       return *Kind;
7071     return NullabilityKind::Unspecified;
7072   };
7073 
7074   auto LHSKind = GetNullability(LHSTy), RHSKind = GetNullability(RHSTy);
7075   NullabilityKind MergedKind;
7076 
7077   // Compute nullability of a binary conditional expression.
7078   if (IsBin) {
7079     if (LHSKind == NullabilityKind::NonNull)
7080       MergedKind = NullabilityKind::NonNull;
7081     else
7082       MergedKind = RHSKind;
7083   // Compute nullability of a normal conditional expression.
7084   } else {
7085     if (LHSKind == NullabilityKind::Nullable ||
7086         RHSKind == NullabilityKind::Nullable)
7087       MergedKind = NullabilityKind::Nullable;
7088     else if (LHSKind == NullabilityKind::NonNull)
7089       MergedKind = RHSKind;
7090     else if (RHSKind == NullabilityKind::NonNull)
7091       MergedKind = LHSKind;
7092     else
7093       MergedKind = NullabilityKind::Unspecified;
7094   }
7095 
7096   // Return if ResTy already has the correct nullability.
7097   if (GetNullability(ResTy) == MergedKind)
7098     return ResTy;
7099 
7100   // Strip all nullability from ResTy.
7101   while (ResTy->getNullability(Ctx))
7102     ResTy = ResTy.getSingleStepDesugaredType(Ctx);
7103 
7104   // Create a new AttributedType with the new nullability kind.
7105   auto NewAttr = AttributedType::getNullabilityAttrKind(MergedKind);
7106   return Ctx.getAttributedType(NewAttr, ResTy, ResTy);
7107 }
7108 
7109 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
7110 /// in the case of a the GNU conditional expr extension.
7111 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
7112                                     SourceLocation ColonLoc,
7113                                     Expr *CondExpr, Expr *LHSExpr,
7114                                     Expr *RHSExpr) {
7115   if (!getLangOpts().CPlusPlus) {
7116     // C cannot handle TypoExpr nodes in the condition because it
7117     // doesn't handle dependent types properly, so make sure any TypoExprs have
7118     // been dealt with before checking the operands.
7119     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
7120     ExprResult LHSResult = CorrectDelayedTyposInExpr(LHSExpr);
7121     ExprResult RHSResult = CorrectDelayedTyposInExpr(RHSExpr);
7122 
7123     if (!CondResult.isUsable())
7124       return ExprError();
7125 
7126     if (LHSExpr) {
7127       if (!LHSResult.isUsable())
7128         return ExprError();
7129     }
7130 
7131     if (!RHSResult.isUsable())
7132       return ExprError();
7133 
7134     CondExpr = CondResult.get();
7135     LHSExpr = LHSResult.get();
7136     RHSExpr = RHSResult.get();
7137   }
7138 
7139   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
7140   // was the condition.
7141   OpaqueValueExpr *opaqueValue = nullptr;
7142   Expr *commonExpr = nullptr;
7143   if (!LHSExpr) {
7144     commonExpr = CondExpr;
7145     // Lower out placeholder types first.  This is important so that we don't
7146     // try to capture a placeholder. This happens in few cases in C++; such
7147     // as Objective-C++'s dictionary subscripting syntax.
7148     if (commonExpr->hasPlaceholderType()) {
7149       ExprResult result = CheckPlaceholderExpr(commonExpr);
7150       if (!result.isUsable()) return ExprError();
7151       commonExpr = result.get();
7152     }
7153     // We usually want to apply unary conversions *before* saving, except
7154     // in the special case of a C++ l-value conditional.
7155     if (!(getLangOpts().CPlusPlus
7156           && !commonExpr->isTypeDependent()
7157           && commonExpr->getValueKind() == RHSExpr->getValueKind()
7158           && commonExpr->isGLValue()
7159           && commonExpr->isOrdinaryOrBitFieldObject()
7160           && RHSExpr->isOrdinaryOrBitFieldObject()
7161           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
7162       ExprResult commonRes = UsualUnaryConversions(commonExpr);
7163       if (commonRes.isInvalid())
7164         return ExprError();
7165       commonExpr = commonRes.get();
7166     }
7167 
7168     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
7169                                                 commonExpr->getType(),
7170                                                 commonExpr->getValueKind(),
7171                                                 commonExpr->getObjectKind(),
7172                                                 commonExpr);
7173     LHSExpr = CondExpr = opaqueValue;
7174   }
7175 
7176   QualType LHSTy = LHSExpr->getType(), RHSTy = RHSExpr->getType();
7177   ExprValueKind VK = VK_RValue;
7178   ExprObjectKind OK = OK_Ordinary;
7179   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
7180   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
7181                                              VK, OK, QuestionLoc);
7182   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
7183       RHS.isInvalid())
7184     return ExprError();
7185 
7186   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
7187                                 RHS.get());
7188 
7189   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
7190 
7191   result = computeConditionalNullability(result, commonExpr, LHSTy, RHSTy,
7192                                          Context);
7193 
7194   if (!commonExpr)
7195     return new (Context)
7196         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
7197                             RHS.get(), result, VK, OK);
7198 
7199   return new (Context) BinaryConditionalOperator(
7200       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
7201       ColonLoc, result, VK, OK);
7202 }
7203 
7204 // checkPointerTypesForAssignment - This is a very tricky routine (despite
7205 // being closely modeled after the C99 spec:-). The odd characteristic of this
7206 // routine is it effectively iqnores the qualifiers on the top level pointee.
7207 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
7208 // FIXME: add a couple examples in this comment.
7209 static Sema::AssignConvertType
7210 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
7211   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7212   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7213 
7214   // get the "pointed to" type (ignoring qualifiers at the top level)
7215   const Type *lhptee, *rhptee;
7216   Qualifiers lhq, rhq;
7217   std::tie(lhptee, lhq) =
7218       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
7219   std::tie(rhptee, rhq) =
7220       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
7221 
7222   Sema::AssignConvertType ConvTy = Sema::Compatible;
7223 
7224   // C99 6.5.16.1p1: This following citation is common to constraints
7225   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
7226   // qualifiers of the type *pointed to* by the right;
7227 
7228   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
7229   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
7230       lhq.compatiblyIncludesObjCLifetime(rhq)) {
7231     // Ignore lifetime for further calculation.
7232     lhq.removeObjCLifetime();
7233     rhq.removeObjCLifetime();
7234   }
7235 
7236   if (!lhq.compatiblyIncludes(rhq)) {
7237     // Treat address-space mismatches as fatal.  TODO: address subspaces
7238     if (!lhq.isAddressSpaceSupersetOf(rhq))
7239       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7240 
7241     // It's okay to add or remove GC or lifetime qualifiers when converting to
7242     // and from void*.
7243     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
7244                         .compatiblyIncludes(
7245                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
7246              && (lhptee->isVoidType() || rhptee->isVoidType()))
7247       ; // keep old
7248 
7249     // Treat lifetime mismatches as fatal.
7250     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
7251       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
7252 
7253     // For GCC/MS compatibility, other qualifier mismatches are treated
7254     // as still compatible in C.
7255     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7256   }
7257 
7258   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
7259   // incomplete type and the other is a pointer to a qualified or unqualified
7260   // version of void...
7261   if (lhptee->isVoidType()) {
7262     if (rhptee->isIncompleteOrObjectType())
7263       return ConvTy;
7264 
7265     // As an extension, we allow cast to/from void* to function pointer.
7266     assert(rhptee->isFunctionType());
7267     return Sema::FunctionVoidPointer;
7268   }
7269 
7270   if (rhptee->isVoidType()) {
7271     if (lhptee->isIncompleteOrObjectType())
7272       return ConvTy;
7273 
7274     // As an extension, we allow cast to/from void* to function pointer.
7275     assert(lhptee->isFunctionType());
7276     return Sema::FunctionVoidPointer;
7277   }
7278 
7279   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
7280   // unqualified versions of compatible types, ...
7281   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
7282   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
7283     // Check if the pointee types are compatible ignoring the sign.
7284     // We explicitly check for char so that we catch "char" vs
7285     // "unsigned char" on systems where "char" is unsigned.
7286     if (lhptee->isCharType())
7287       ltrans = S.Context.UnsignedCharTy;
7288     else if (lhptee->hasSignedIntegerRepresentation())
7289       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
7290 
7291     if (rhptee->isCharType())
7292       rtrans = S.Context.UnsignedCharTy;
7293     else if (rhptee->hasSignedIntegerRepresentation())
7294       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
7295 
7296     if (ltrans == rtrans) {
7297       // Types are compatible ignoring the sign. Qualifier incompatibility
7298       // takes priority over sign incompatibility because the sign
7299       // warning can be disabled.
7300       if (ConvTy != Sema::Compatible)
7301         return ConvTy;
7302 
7303       return Sema::IncompatiblePointerSign;
7304     }
7305 
7306     // If we are a multi-level pointer, it's possible that our issue is simply
7307     // one of qualification - e.g. char ** -> const char ** is not allowed. If
7308     // the eventual target type is the same and the pointers have the same
7309     // level of indirection, this must be the issue.
7310     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
7311       do {
7312         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
7313         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
7314       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
7315 
7316       if (lhptee == rhptee)
7317         return Sema::IncompatibleNestedPointerQualifiers;
7318     }
7319 
7320     // General pointer incompatibility takes priority over qualifiers.
7321     return Sema::IncompatiblePointer;
7322   }
7323   if (!S.getLangOpts().CPlusPlus &&
7324       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
7325     return Sema::IncompatiblePointer;
7326   return ConvTy;
7327 }
7328 
7329 /// checkBlockPointerTypesForAssignment - This routine determines whether two
7330 /// block pointer types are compatible or whether a block and normal pointer
7331 /// are compatible. It is more restrict than comparing two function pointer
7332 // types.
7333 static Sema::AssignConvertType
7334 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
7335                                     QualType RHSType) {
7336   assert(LHSType.isCanonical() && "LHS not canonicalized!");
7337   assert(RHSType.isCanonical() && "RHS not canonicalized!");
7338 
7339   QualType lhptee, rhptee;
7340 
7341   // get the "pointed to" type (ignoring qualifiers at the top level)
7342   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
7343   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
7344 
7345   // In C++, the types have to match exactly.
7346   if (S.getLangOpts().CPlusPlus)
7347     return Sema::IncompatibleBlockPointer;
7348 
7349   Sema::AssignConvertType ConvTy = Sema::Compatible;
7350 
7351   // For blocks we enforce that qualifiers are identical.
7352   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
7353     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
7354 
7355   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
7356     return Sema::IncompatibleBlockPointer;
7357 
7358   return ConvTy;
7359 }
7360 
7361 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
7362 /// for assignment compatibility.
7363 static Sema::AssignConvertType
7364 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
7365                                    QualType RHSType) {
7366   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
7367   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
7368 
7369   if (LHSType->isObjCBuiltinType()) {
7370     // Class is not compatible with ObjC object pointers.
7371     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
7372         !RHSType->isObjCQualifiedClassType())
7373       return Sema::IncompatiblePointer;
7374     return Sema::Compatible;
7375   }
7376   if (RHSType->isObjCBuiltinType()) {
7377     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
7378         !LHSType->isObjCQualifiedClassType())
7379       return Sema::IncompatiblePointer;
7380     return Sema::Compatible;
7381   }
7382   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7383   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
7384 
7385   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
7386       // make an exception for id<P>
7387       !LHSType->isObjCQualifiedIdType())
7388     return Sema::CompatiblePointerDiscardsQualifiers;
7389 
7390   if (S.Context.typesAreCompatible(LHSType, RHSType))
7391     return Sema::Compatible;
7392   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
7393     return Sema::IncompatibleObjCQualifiedId;
7394   return Sema::IncompatiblePointer;
7395 }
7396 
7397 Sema::AssignConvertType
7398 Sema::CheckAssignmentConstraints(SourceLocation Loc,
7399                                  QualType LHSType, QualType RHSType) {
7400   // Fake up an opaque expression.  We don't actually care about what
7401   // cast operations are required, so if CheckAssignmentConstraints
7402   // adds casts to this they'll be wasted, but fortunately that doesn't
7403   // usually happen on valid code.
7404   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
7405   ExprResult RHSPtr = &RHSExpr;
7406   CastKind K = CK_Invalid;
7407 
7408   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
7409 }
7410 
7411 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
7412 /// has code to accommodate several GCC extensions when type checking
7413 /// pointers. Here are some objectionable examples that GCC considers warnings:
7414 ///
7415 ///  int a, *pint;
7416 ///  short *pshort;
7417 ///  struct foo *pfoo;
7418 ///
7419 ///  pint = pshort; // warning: assignment from incompatible pointer type
7420 ///  a = pint; // warning: assignment makes integer from pointer without a cast
7421 ///  pint = a; // warning: assignment makes pointer from integer without a cast
7422 ///  pint = pfoo; // warning: assignment from incompatible pointer type
7423 ///
7424 /// As a result, the code for dealing with pointers is more complex than the
7425 /// C99 spec dictates.
7426 ///
7427 /// Sets 'Kind' for any result kind except Incompatible.
7428 Sema::AssignConvertType
7429 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
7430                                  CastKind &Kind, bool ConvertRHS) {
7431   QualType RHSType = RHS.get()->getType();
7432   QualType OrigLHSType = LHSType;
7433 
7434   // Get canonical types.  We're not formatting these types, just comparing
7435   // them.
7436   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
7437   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
7438 
7439   // Common case: no conversion required.
7440   if (LHSType == RHSType) {
7441     Kind = CK_NoOp;
7442     return Compatible;
7443   }
7444 
7445   // If we have an atomic type, try a non-atomic assignment, then just add an
7446   // atomic qualification step.
7447   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
7448     Sema::AssignConvertType result =
7449       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
7450     if (result != Compatible)
7451       return result;
7452     if (Kind != CK_NoOp && ConvertRHS)
7453       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
7454     Kind = CK_NonAtomicToAtomic;
7455     return Compatible;
7456   }
7457 
7458   // If the left-hand side is a reference type, then we are in a
7459   // (rare!) case where we've allowed the use of references in C,
7460   // e.g., as a parameter type in a built-in function. In this case,
7461   // just make sure that the type referenced is compatible with the
7462   // right-hand side type. The caller is responsible for adjusting
7463   // LHSType so that the resulting expression does not have reference
7464   // type.
7465   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
7466     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
7467       Kind = CK_LValueBitCast;
7468       return Compatible;
7469     }
7470     return Incompatible;
7471   }
7472 
7473   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
7474   // to the same ExtVector type.
7475   if (LHSType->isExtVectorType()) {
7476     if (RHSType->isExtVectorType())
7477       return Incompatible;
7478     if (RHSType->isArithmeticType()) {
7479       // CK_VectorSplat does T -> vector T, so first cast to the element type.
7480       if (ConvertRHS)
7481         RHS = prepareVectorSplat(LHSType, RHS.get());
7482       Kind = CK_VectorSplat;
7483       return Compatible;
7484     }
7485   }
7486 
7487   // Conversions to or from vector type.
7488   if (LHSType->isVectorType() || RHSType->isVectorType()) {
7489     if (LHSType->isVectorType() && RHSType->isVectorType()) {
7490       // Allow assignments of an AltiVec vector type to an equivalent GCC
7491       // vector type and vice versa
7492       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7493         Kind = CK_BitCast;
7494         return Compatible;
7495       }
7496 
7497       // If we are allowing lax vector conversions, and LHS and RHS are both
7498       // vectors, the total size only needs to be the same. This is a bitcast;
7499       // no bits are changed but the result type is different.
7500       if (isLaxVectorConversion(RHSType, LHSType)) {
7501         Kind = CK_BitCast;
7502         return IncompatibleVectors;
7503       }
7504     }
7505 
7506     // When the RHS comes from another lax conversion (e.g. binops between
7507     // scalars and vectors) the result is canonicalized as a vector. When the
7508     // LHS is also a vector, the lax is allowed by the condition above. Handle
7509     // the case where LHS is a scalar.
7510     if (LHSType->isScalarType()) {
7511       const VectorType *VecType = RHSType->getAs<VectorType>();
7512       if (VecType && VecType->getNumElements() == 1 &&
7513           isLaxVectorConversion(RHSType, LHSType)) {
7514         ExprResult *VecExpr = &RHS;
7515         *VecExpr = ImpCastExprToType(VecExpr->get(), LHSType, CK_BitCast);
7516         Kind = CK_BitCast;
7517         return Compatible;
7518       }
7519     }
7520 
7521     return Incompatible;
7522   }
7523 
7524   // Diagnose attempts to convert between __float128 and long double where
7525   // such conversions currently can't be handled.
7526   if (unsupportedTypeConversion(*this, LHSType, RHSType))
7527     return Incompatible;
7528 
7529   // Arithmetic conversions.
7530   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7531       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7532     if (ConvertRHS)
7533       Kind = PrepareScalarCast(RHS, LHSType);
7534     return Compatible;
7535   }
7536 
7537   // Conversions to normal pointers.
7538   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7539     // U* -> T*
7540     if (isa<PointerType>(RHSType)) {
7541       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7542       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7543       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7544       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7545     }
7546 
7547     // int -> T*
7548     if (RHSType->isIntegerType()) {
7549       Kind = CK_IntegralToPointer; // FIXME: null?
7550       return IntToPointer;
7551     }
7552 
7553     // C pointers are not compatible with ObjC object pointers,
7554     // with two exceptions:
7555     if (isa<ObjCObjectPointerType>(RHSType)) {
7556       //  - conversions to void*
7557       if (LHSPointer->getPointeeType()->isVoidType()) {
7558         Kind = CK_BitCast;
7559         return Compatible;
7560       }
7561 
7562       //  - conversions from 'Class' to the redefinition type
7563       if (RHSType->isObjCClassType() &&
7564           Context.hasSameType(LHSType,
7565                               Context.getObjCClassRedefinitionType())) {
7566         Kind = CK_BitCast;
7567         return Compatible;
7568       }
7569 
7570       Kind = CK_BitCast;
7571       return IncompatiblePointer;
7572     }
7573 
7574     // U^ -> void*
7575     if (RHSType->getAs<BlockPointerType>()) {
7576       if (LHSPointer->getPointeeType()->isVoidType()) {
7577         Kind = CK_BitCast;
7578         return Compatible;
7579       }
7580     }
7581 
7582     return Incompatible;
7583   }
7584 
7585   // Conversions to block pointers.
7586   if (isa<BlockPointerType>(LHSType)) {
7587     // U^ -> T^
7588     if (RHSType->isBlockPointerType()) {
7589       Kind = CK_BitCast;
7590       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7591     }
7592 
7593     // int or null -> T^
7594     if (RHSType->isIntegerType()) {
7595       Kind = CK_IntegralToPointer; // FIXME: null
7596       return IntToBlockPointer;
7597     }
7598 
7599     // id -> T^
7600     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7601       Kind = CK_AnyPointerToBlockPointerCast;
7602       return Compatible;
7603     }
7604 
7605     // void* -> T^
7606     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7607       if (RHSPT->getPointeeType()->isVoidType()) {
7608         Kind = CK_AnyPointerToBlockPointerCast;
7609         return Compatible;
7610       }
7611 
7612     return Incompatible;
7613   }
7614 
7615   // Conversions to Objective-C pointers.
7616   if (isa<ObjCObjectPointerType>(LHSType)) {
7617     // A* -> B*
7618     if (RHSType->isObjCObjectPointerType()) {
7619       Kind = CK_BitCast;
7620       Sema::AssignConvertType result =
7621         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7622       if (getLangOpts().ObjCAutoRefCount &&
7623           result == Compatible &&
7624           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7625         result = IncompatibleObjCWeakRef;
7626       return result;
7627     }
7628 
7629     // int or null -> A*
7630     if (RHSType->isIntegerType()) {
7631       Kind = CK_IntegralToPointer; // FIXME: null
7632       return IntToPointer;
7633     }
7634 
7635     // In general, C pointers are not compatible with ObjC object pointers,
7636     // with two exceptions:
7637     if (isa<PointerType>(RHSType)) {
7638       Kind = CK_CPointerToObjCPointerCast;
7639 
7640       //  - conversions from 'void*'
7641       if (RHSType->isVoidPointerType()) {
7642         return Compatible;
7643       }
7644 
7645       //  - conversions to 'Class' from its redefinition type
7646       if (LHSType->isObjCClassType() &&
7647           Context.hasSameType(RHSType,
7648                               Context.getObjCClassRedefinitionType())) {
7649         return Compatible;
7650       }
7651 
7652       return IncompatiblePointer;
7653     }
7654 
7655     // Only under strict condition T^ is compatible with an Objective-C pointer.
7656     if (RHSType->isBlockPointerType() &&
7657         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7658       if (ConvertRHS)
7659         maybeExtendBlockObject(RHS);
7660       Kind = CK_BlockPointerToObjCPointerCast;
7661       return Compatible;
7662     }
7663 
7664     return Incompatible;
7665   }
7666 
7667   // Conversions from pointers that are not covered by the above.
7668   if (isa<PointerType>(RHSType)) {
7669     // T* -> _Bool
7670     if (LHSType == Context.BoolTy) {
7671       Kind = CK_PointerToBoolean;
7672       return Compatible;
7673     }
7674 
7675     // T* -> int
7676     if (LHSType->isIntegerType()) {
7677       Kind = CK_PointerToIntegral;
7678       return PointerToInt;
7679     }
7680 
7681     return Incompatible;
7682   }
7683 
7684   // Conversions from Objective-C pointers that are not covered by the above.
7685   if (isa<ObjCObjectPointerType>(RHSType)) {
7686     // T* -> _Bool
7687     if (LHSType == Context.BoolTy) {
7688       Kind = CK_PointerToBoolean;
7689       return Compatible;
7690     }
7691 
7692     // T* -> int
7693     if (LHSType->isIntegerType()) {
7694       Kind = CK_PointerToIntegral;
7695       return PointerToInt;
7696     }
7697 
7698     return Incompatible;
7699   }
7700 
7701   // struct A -> struct B
7702   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7703     if (Context.typesAreCompatible(LHSType, RHSType)) {
7704       Kind = CK_NoOp;
7705       return Compatible;
7706     }
7707   }
7708 
7709   if (LHSType->isSamplerT() && RHSType->isIntegerType()) {
7710     Kind = CK_IntToOCLSampler;
7711     return Compatible;
7712   }
7713 
7714   return Incompatible;
7715 }
7716 
7717 /// \brief Constructs a transparent union from an expression that is
7718 /// used to initialize the transparent union.
7719 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7720                                       ExprResult &EResult, QualType UnionType,
7721                                       FieldDecl *Field) {
7722   // Build an initializer list that designates the appropriate member
7723   // of the transparent union.
7724   Expr *E = EResult.get();
7725   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7726                                                    E, SourceLocation());
7727   Initializer->setType(UnionType);
7728   Initializer->setInitializedFieldInUnion(Field);
7729 
7730   // Build a compound literal constructing a value of the transparent
7731   // union type from this initializer list.
7732   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7733   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7734                                         VK_RValue, Initializer, false);
7735 }
7736 
7737 Sema::AssignConvertType
7738 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7739                                                ExprResult &RHS) {
7740   QualType RHSType = RHS.get()->getType();
7741 
7742   // If the ArgType is a Union type, we want to handle a potential
7743   // transparent_union GCC extension.
7744   const RecordType *UT = ArgType->getAsUnionType();
7745   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7746     return Incompatible;
7747 
7748   // The field to initialize within the transparent union.
7749   RecordDecl *UD = UT->getDecl();
7750   FieldDecl *InitField = nullptr;
7751   // It's compatible if the expression matches any of the fields.
7752   for (auto *it : UD->fields()) {
7753     if (it->getType()->isPointerType()) {
7754       // If the transparent union contains a pointer type, we allow:
7755       // 1) void pointer
7756       // 2) null pointer constant
7757       if (RHSType->isPointerType())
7758         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7759           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7760           InitField = it;
7761           break;
7762         }
7763 
7764       if (RHS.get()->isNullPointerConstant(Context,
7765                                            Expr::NPC_ValueDependentIsNull)) {
7766         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7767                                 CK_NullToPointer);
7768         InitField = it;
7769         break;
7770       }
7771     }
7772 
7773     CastKind Kind = CK_Invalid;
7774     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7775           == Compatible) {
7776       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7777       InitField = it;
7778       break;
7779     }
7780   }
7781 
7782   if (!InitField)
7783     return Incompatible;
7784 
7785   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7786   return Compatible;
7787 }
7788 
7789 Sema::AssignConvertType
7790 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7791                                        bool Diagnose,
7792                                        bool DiagnoseCFAudited,
7793                                        bool ConvertRHS) {
7794   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7795   // we can't avoid *all* modifications at the moment, so we need some somewhere
7796   // to put the updated value.
7797   ExprResult LocalRHS = CallerRHS;
7798   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7799 
7800   if (getLangOpts().CPlusPlus) {
7801     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7802       // C++ 5.17p3: If the left operand is not of class type, the
7803       // expression is implicitly converted (C++ 4) to the
7804       // cv-unqualified type of the left operand.
7805       ExprResult Res;
7806       if (Diagnose) {
7807         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7808                                         AA_Assigning);
7809       } else {
7810         ImplicitConversionSequence ICS =
7811             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7812                                   /*SuppressUserConversions=*/false,
7813                                   /*AllowExplicit=*/false,
7814                                   /*InOverloadResolution=*/false,
7815                                   /*CStyle=*/false,
7816                                   /*AllowObjCWritebackConversion=*/false);
7817         if (ICS.isFailure())
7818           return Incompatible;
7819         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7820                                         ICS, AA_Assigning);
7821       }
7822       if (Res.isInvalid())
7823         return Incompatible;
7824       Sema::AssignConvertType result = Compatible;
7825       if (getLangOpts().ObjCAutoRefCount &&
7826           !CheckObjCARCUnavailableWeakConversion(LHSType,
7827                                                  RHS.get()->getType()))
7828         result = IncompatibleObjCWeakRef;
7829       RHS = Res;
7830       return result;
7831     }
7832 
7833     // FIXME: Currently, we fall through and treat C++ classes like C
7834     // structures.
7835     // FIXME: We also fall through for atomics; not sure what should
7836     // happen there, though.
7837   } else if (RHS.get()->getType() == Context.OverloadTy) {
7838     // As a set of extensions to C, we support overloading on functions. These
7839     // functions need to be resolved here.
7840     DeclAccessPair DAP;
7841     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7842             RHS.get(), LHSType, /*Complain=*/false, DAP))
7843       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7844     else
7845       return Incompatible;
7846   }
7847 
7848   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7849   // a null pointer constant.
7850   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7851        LHSType->isBlockPointerType()) &&
7852       RHS.get()->isNullPointerConstant(Context,
7853                                        Expr::NPC_ValueDependentIsNull)) {
7854     if (Diagnose || ConvertRHS) {
7855       CastKind Kind;
7856       CXXCastPath Path;
7857       CheckPointerConversion(RHS.get(), LHSType, Kind, Path,
7858                              /*IgnoreBaseAccess=*/false, Diagnose);
7859       if (ConvertRHS)
7860         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7861     }
7862     return Compatible;
7863   }
7864 
7865   // This check seems unnatural, however it is necessary to ensure the proper
7866   // conversion of functions/arrays. If the conversion were done for all
7867   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7868   // expressions that suppress this implicit conversion (&, sizeof).
7869   //
7870   // Suppress this for references: C++ 8.5.3p5.
7871   if (!LHSType->isReferenceType()) {
7872     // FIXME: We potentially allocate here even if ConvertRHS is false.
7873     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7874     if (RHS.isInvalid())
7875       return Incompatible;
7876   }
7877 
7878   Expr *PRE = RHS.get()->IgnoreParenCasts();
7879   if (Diagnose && isa<ObjCProtocolExpr>(PRE)) {
7880     ObjCProtocolDecl *PDecl = cast<ObjCProtocolExpr>(PRE)->getProtocol();
7881     if (PDecl && !PDecl->hasDefinition()) {
7882       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7883       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7884     }
7885   }
7886 
7887   CastKind Kind = CK_Invalid;
7888   Sema::AssignConvertType result =
7889     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7890 
7891   // C99 6.5.16.1p2: The value of the right operand is converted to the
7892   // type of the assignment expression.
7893   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7894   // so that we can use references in built-in functions even in C.
7895   // The getNonReferenceType() call makes sure that the resulting expression
7896   // does not have reference type.
7897   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7898     QualType Ty = LHSType.getNonLValueExprType(Context);
7899     Expr *E = RHS.get();
7900 
7901     // Check for various Objective-C errors. If we are not reporting
7902     // diagnostics and just checking for errors, e.g., during overload
7903     // resolution, return Incompatible to indicate the failure.
7904     if (getLangOpts().ObjCAutoRefCount &&
7905         CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7906                                Diagnose, DiagnoseCFAudited) != ACR_okay) {
7907       if (!Diagnose)
7908         return Incompatible;
7909     }
7910     if (getLangOpts().ObjC1 &&
7911         (CheckObjCBridgeRelatedConversions(E->getLocStart(), LHSType,
7912                                            E->getType(), E, Diagnose) ||
7913          ConversionToObjCStringLiteralCheck(LHSType, E, Diagnose))) {
7914       if (!Diagnose)
7915         return Incompatible;
7916       // Replace the expression with a corrected version and continue so we
7917       // can find further errors.
7918       RHS = E;
7919       return Compatible;
7920     }
7921 
7922     if (ConvertRHS)
7923       RHS = ImpCastExprToType(E, Ty, Kind);
7924   }
7925   return result;
7926 }
7927 
7928 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7929                                ExprResult &RHS) {
7930   Diag(Loc, diag::err_typecheck_invalid_operands)
7931     << LHS.get()->getType() << RHS.get()->getType()
7932     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7933   return QualType();
7934 }
7935 
7936 /// Try to convert a value of non-vector type to a vector type by converting
7937 /// the type to the element type of the vector and then performing a splat.
7938 /// If the language is OpenCL, we only use conversions that promote scalar
7939 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7940 /// for float->int.
7941 ///
7942 /// \param scalar - if non-null, actually perform the conversions
7943 /// \return true if the operation fails (but without diagnosing the failure)
7944 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7945                                      QualType scalarTy,
7946                                      QualType vectorEltTy,
7947                                      QualType vectorTy) {
7948   // The conversion to apply to the scalar before splatting it,
7949   // if necessary.
7950   CastKind scalarCast = CK_Invalid;
7951 
7952   if (vectorEltTy->isIntegralType(S.Context)) {
7953     if (!scalarTy->isIntegralType(S.Context))
7954       return true;
7955     if (S.getLangOpts().OpenCL &&
7956         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7957       return true;
7958     scalarCast = CK_IntegralCast;
7959   } else if (vectorEltTy->isRealFloatingType()) {
7960     if (scalarTy->isRealFloatingType()) {
7961       if (S.getLangOpts().OpenCL &&
7962           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7963         return true;
7964       scalarCast = CK_FloatingCast;
7965     }
7966     else if (scalarTy->isIntegralType(S.Context))
7967       scalarCast = CK_IntegralToFloating;
7968     else
7969       return true;
7970   } else {
7971     return true;
7972   }
7973 
7974   // Adjust scalar if desired.
7975   if (scalar) {
7976     if (scalarCast != CK_Invalid)
7977       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7978     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7979   }
7980   return false;
7981 }
7982 
7983 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7984                                    SourceLocation Loc, bool IsCompAssign,
7985                                    bool AllowBothBool,
7986                                    bool AllowBoolConversions) {
7987   if (!IsCompAssign) {
7988     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7989     if (LHS.isInvalid())
7990       return QualType();
7991   }
7992   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7993   if (RHS.isInvalid())
7994     return QualType();
7995 
7996   // For conversion purposes, we ignore any qualifiers.
7997   // For example, "const float" and "float" are equivalent.
7998   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7999   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
8000 
8001   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
8002   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
8003   assert(LHSVecType || RHSVecType);
8004 
8005   // AltiVec-style "vector bool op vector bool" combinations are allowed
8006   // for some operators but not others.
8007   if (!AllowBothBool &&
8008       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8009       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8010     return InvalidOperands(Loc, LHS, RHS);
8011 
8012   // If the vector types are identical, return.
8013   if (Context.hasSameType(LHSType, RHSType))
8014     return LHSType;
8015 
8016   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
8017   if (LHSVecType && RHSVecType &&
8018       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
8019     if (isa<ExtVectorType>(LHSVecType)) {
8020       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8021       return LHSType;
8022     }
8023 
8024     if (!IsCompAssign)
8025       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8026     return RHSType;
8027   }
8028 
8029   // AllowBoolConversions says that bool and non-bool AltiVec vectors
8030   // can be mixed, with the result being the non-bool type.  The non-bool
8031   // operand must have integer element type.
8032   if (AllowBoolConversions && LHSVecType && RHSVecType &&
8033       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
8034       (Context.getTypeSize(LHSVecType->getElementType()) ==
8035        Context.getTypeSize(RHSVecType->getElementType()))) {
8036     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8037         LHSVecType->getElementType()->isIntegerType() &&
8038         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
8039       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8040       return LHSType;
8041     }
8042     if (!IsCompAssign &&
8043         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
8044         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
8045         RHSVecType->getElementType()->isIntegerType()) {
8046       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8047       return RHSType;
8048     }
8049   }
8050 
8051   // If there's an ext-vector type and a scalar, try to convert the scalar to
8052   // the vector element type and splat.
8053   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
8054     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
8055                                   LHSVecType->getElementType(), LHSType))
8056       return LHSType;
8057   }
8058   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
8059     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
8060                                   LHSType, RHSVecType->getElementType(),
8061                                   RHSType))
8062       return RHSType;
8063   }
8064 
8065   // If we're allowing lax vector conversions, only the total (data) size needs
8066   // to be the same. If one of the types is scalar, the result is always the
8067   // vector type. Don't allow this if the scalar operand is an lvalue.
8068   QualType VecType = LHSVecType ? LHSType : RHSType;
8069   QualType ScalarType = LHSVecType ? RHSType : LHSType;
8070   ExprResult *ScalarExpr = LHSVecType ? &RHS : &LHS;
8071   if (isLaxVectorConversion(ScalarType, VecType) &&
8072       !ScalarExpr->get()->isLValue()) {
8073     *ScalarExpr = ImpCastExprToType(ScalarExpr->get(), VecType, CK_BitCast);
8074     return VecType;
8075   }
8076 
8077   // Okay, the expression is invalid.
8078 
8079   // If there's a non-vector, non-real operand, diagnose that.
8080   if ((!RHSVecType && !RHSType->isRealType()) ||
8081       (!LHSVecType && !LHSType->isRealType())) {
8082     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
8083       << LHSType << RHSType
8084       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8085     return QualType();
8086   }
8087 
8088   // OpenCL V1.1 6.2.6.p1:
8089   // If the operands are of more than one vector type, then an error shall
8090   // occur. Implicit conversions between vector types are not permitted, per
8091   // section 6.2.1.
8092   if (getLangOpts().OpenCL &&
8093       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
8094       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
8095     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
8096                                                            << RHSType;
8097     return QualType();
8098   }
8099 
8100   // Otherwise, use the generic diagnostic.
8101   Diag(Loc, diag::err_typecheck_vector_not_convertable)
8102     << LHSType << RHSType
8103     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8104   return QualType();
8105 }
8106 
8107 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
8108 // expression.  These are mainly cases where the null pointer is used as an
8109 // integer instead of a pointer.
8110 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
8111                                 SourceLocation Loc, bool IsCompare) {
8112   // The canonical way to check for a GNU null is with isNullPointerConstant,
8113   // but we use a bit of a hack here for speed; this is a relatively
8114   // hot path, and isNullPointerConstant is slow.
8115   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
8116   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
8117 
8118   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
8119 
8120   // Avoid analyzing cases where the result will either be invalid (and
8121   // diagnosed as such) or entirely valid and not something to warn about.
8122   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
8123       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
8124     return;
8125 
8126   // Comparison operations would not make sense with a null pointer no matter
8127   // what the other expression is.
8128   if (!IsCompare) {
8129     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
8130         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
8131         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
8132     return;
8133   }
8134 
8135   // The rest of the operations only make sense with a null pointer
8136   // if the other expression is a pointer.
8137   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
8138       NonNullType->canDecayToPointerType())
8139     return;
8140 
8141   S.Diag(Loc, diag::warn_null_in_comparison_operation)
8142       << LHSNull /* LHS is NULL */ << NonNullType
8143       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8144 }
8145 
8146 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
8147                                                ExprResult &RHS,
8148                                                SourceLocation Loc, bool IsDiv) {
8149   // Check for division/remainder by zero.
8150   llvm::APSInt RHSValue;
8151   if (!RHS.get()->isValueDependent() &&
8152       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
8153     S.DiagRuntimeBehavior(Loc, RHS.get(),
8154                           S.PDiag(diag::warn_remainder_division_by_zero)
8155                             << IsDiv << RHS.get()->getSourceRange());
8156 }
8157 
8158 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
8159                                            SourceLocation Loc,
8160                                            bool IsCompAssign, bool IsDiv) {
8161   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8162 
8163   if (LHS.get()->getType()->isVectorType() ||
8164       RHS.get()->getType()->isVectorType())
8165     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8166                                /*AllowBothBool*/getLangOpts().AltiVec,
8167                                /*AllowBoolConversions*/false);
8168 
8169   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8170   if (LHS.isInvalid() || RHS.isInvalid())
8171     return QualType();
8172 
8173 
8174   if (compType.isNull() || !compType->isArithmeticType())
8175     return InvalidOperands(Loc, LHS, RHS);
8176   if (IsDiv)
8177     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
8178   return compType;
8179 }
8180 
8181 QualType Sema::CheckRemainderOperands(
8182   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8183   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8184 
8185   if (LHS.get()->getType()->isVectorType() ||
8186       RHS.get()->getType()->isVectorType()) {
8187     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8188         RHS.get()->getType()->hasIntegerRepresentation())
8189       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8190                                  /*AllowBothBool*/getLangOpts().AltiVec,
8191                                  /*AllowBoolConversions*/false);
8192     return InvalidOperands(Loc, LHS, RHS);
8193   }
8194 
8195   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
8196   if (LHS.isInvalid() || RHS.isInvalid())
8197     return QualType();
8198 
8199   if (compType.isNull() || !compType->isIntegerType())
8200     return InvalidOperands(Loc, LHS, RHS);
8201   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
8202   return compType;
8203 }
8204 
8205 /// \brief Diagnose invalid arithmetic on two void pointers.
8206 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
8207                                                 Expr *LHSExpr, Expr *RHSExpr) {
8208   S.Diag(Loc, S.getLangOpts().CPlusPlus
8209                 ? diag::err_typecheck_pointer_arith_void_type
8210                 : diag::ext_gnu_void_ptr)
8211     << 1 /* two pointers */ << LHSExpr->getSourceRange()
8212                             << RHSExpr->getSourceRange();
8213 }
8214 
8215 /// \brief Diagnose invalid arithmetic on a void pointer.
8216 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
8217                                             Expr *Pointer) {
8218   S.Diag(Loc, S.getLangOpts().CPlusPlus
8219                 ? diag::err_typecheck_pointer_arith_void_type
8220                 : diag::ext_gnu_void_ptr)
8221     << 0 /* one pointer */ << Pointer->getSourceRange();
8222 }
8223 
8224 /// \brief Diagnose invalid arithmetic on two function pointers.
8225 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
8226                                                     Expr *LHS, Expr *RHS) {
8227   assert(LHS->getType()->isAnyPointerType());
8228   assert(RHS->getType()->isAnyPointerType());
8229   S.Diag(Loc, S.getLangOpts().CPlusPlus
8230                 ? diag::err_typecheck_pointer_arith_function_type
8231                 : diag::ext_gnu_ptr_func_arith)
8232     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
8233     // We only show the second type if it differs from the first.
8234     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
8235                                                    RHS->getType())
8236     << RHS->getType()->getPointeeType()
8237     << LHS->getSourceRange() << RHS->getSourceRange();
8238 }
8239 
8240 /// \brief Diagnose invalid arithmetic on a function pointer.
8241 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
8242                                                 Expr *Pointer) {
8243   assert(Pointer->getType()->isAnyPointerType());
8244   S.Diag(Loc, S.getLangOpts().CPlusPlus
8245                 ? diag::err_typecheck_pointer_arith_function_type
8246                 : diag::ext_gnu_ptr_func_arith)
8247     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
8248     << 0 /* one pointer, so only one type */
8249     << Pointer->getSourceRange();
8250 }
8251 
8252 /// \brief Emit error if Operand is incomplete pointer type
8253 ///
8254 /// \returns True if pointer has incomplete type
8255 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
8256                                                  Expr *Operand) {
8257   QualType ResType = Operand->getType();
8258   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8259     ResType = ResAtomicType->getValueType();
8260 
8261   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
8262   QualType PointeeTy = ResType->getPointeeType();
8263   return S.RequireCompleteType(Loc, PointeeTy,
8264                                diag::err_typecheck_arithmetic_incomplete_type,
8265                                PointeeTy, Operand->getSourceRange());
8266 }
8267 
8268 /// \brief Check the validity of an arithmetic pointer operand.
8269 ///
8270 /// If the operand has pointer type, this code will check for pointer types
8271 /// which are invalid in arithmetic operations. These will be diagnosed
8272 /// appropriately, including whether or not the use is supported as an
8273 /// extension.
8274 ///
8275 /// \returns True when the operand is valid to use (even if as an extension).
8276 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
8277                                             Expr *Operand) {
8278   QualType ResType = Operand->getType();
8279   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8280     ResType = ResAtomicType->getValueType();
8281 
8282   if (!ResType->isAnyPointerType()) return true;
8283 
8284   QualType PointeeTy = ResType->getPointeeType();
8285   if (PointeeTy->isVoidType()) {
8286     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
8287     return !S.getLangOpts().CPlusPlus;
8288   }
8289   if (PointeeTy->isFunctionType()) {
8290     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
8291     return !S.getLangOpts().CPlusPlus;
8292   }
8293 
8294   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
8295 
8296   return true;
8297 }
8298 
8299 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
8300 /// operands.
8301 ///
8302 /// This routine will diagnose any invalid arithmetic on pointer operands much
8303 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
8304 /// for emitting a single diagnostic even for operations where both LHS and RHS
8305 /// are (potentially problematic) pointers.
8306 ///
8307 /// \returns True when the operand is valid to use (even if as an extension).
8308 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
8309                                                 Expr *LHSExpr, Expr *RHSExpr) {
8310   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
8311   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
8312   if (!isLHSPointer && !isRHSPointer) return true;
8313 
8314   QualType LHSPointeeTy, RHSPointeeTy;
8315   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
8316   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
8317 
8318   // if both are pointers check if operation is valid wrt address spaces
8319   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
8320     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
8321     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
8322     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
8323       S.Diag(Loc,
8324              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8325           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
8326           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8327       return false;
8328     }
8329   }
8330 
8331   // Check for arithmetic on pointers to incomplete types.
8332   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
8333   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
8334   if (isLHSVoidPtr || isRHSVoidPtr) {
8335     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
8336     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
8337     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
8338 
8339     return !S.getLangOpts().CPlusPlus;
8340   }
8341 
8342   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
8343   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
8344   if (isLHSFuncPtr || isRHSFuncPtr) {
8345     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
8346     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
8347                                                                 RHSExpr);
8348     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
8349 
8350     return !S.getLangOpts().CPlusPlus;
8351   }
8352 
8353   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
8354     return false;
8355   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
8356     return false;
8357 
8358   return true;
8359 }
8360 
8361 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
8362 /// literal.
8363 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
8364                                   Expr *LHSExpr, Expr *RHSExpr) {
8365   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
8366   Expr* IndexExpr = RHSExpr;
8367   if (!StrExpr) {
8368     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
8369     IndexExpr = LHSExpr;
8370   }
8371 
8372   bool IsStringPlusInt = StrExpr &&
8373       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
8374   if (!IsStringPlusInt || IndexExpr->isValueDependent())
8375     return;
8376 
8377   llvm::APSInt index;
8378   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
8379     unsigned StrLenWithNull = StrExpr->getLength() + 1;
8380     if (index.isNonNegative() &&
8381         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
8382                               index.isUnsigned()))
8383       return;
8384   }
8385 
8386   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8387   Self.Diag(OpLoc, diag::warn_string_plus_int)
8388       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
8389 
8390   // Only print a fixit for "str" + int, not for int + "str".
8391   if (IndexExpr == RHSExpr) {
8392     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8393     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8394         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8395         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8396         << FixItHint::CreateInsertion(EndLoc, "]");
8397   } else
8398     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8399 }
8400 
8401 /// \brief Emit a warning when adding a char literal to a string.
8402 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
8403                                    Expr *LHSExpr, Expr *RHSExpr) {
8404   const Expr *StringRefExpr = LHSExpr;
8405   const CharacterLiteral *CharExpr =
8406       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
8407 
8408   if (!CharExpr) {
8409     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
8410     StringRefExpr = RHSExpr;
8411   }
8412 
8413   if (!CharExpr || !StringRefExpr)
8414     return;
8415 
8416   const QualType StringType = StringRefExpr->getType();
8417 
8418   // Return if not a PointerType.
8419   if (!StringType->isAnyPointerType())
8420     return;
8421 
8422   // Return if not a CharacterType.
8423   if (!StringType->getPointeeType()->isAnyCharacterType())
8424     return;
8425 
8426   ASTContext &Ctx = Self.getASTContext();
8427   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
8428 
8429   const QualType CharType = CharExpr->getType();
8430   if (!CharType->isAnyCharacterType() &&
8431       CharType->isIntegerType() &&
8432       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
8433     Self.Diag(OpLoc, diag::warn_string_plus_char)
8434         << DiagRange << Ctx.CharTy;
8435   } else {
8436     Self.Diag(OpLoc, diag::warn_string_plus_char)
8437         << DiagRange << CharExpr->getType();
8438   }
8439 
8440   // Only print a fixit for str + char, not for char + str.
8441   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
8442     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
8443     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
8444         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
8445         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
8446         << FixItHint::CreateInsertion(EndLoc, "]");
8447   } else {
8448     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
8449   }
8450 }
8451 
8452 /// \brief Emit error when two pointers are incompatible.
8453 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
8454                                            Expr *LHSExpr, Expr *RHSExpr) {
8455   assert(LHSExpr->getType()->isAnyPointerType());
8456   assert(RHSExpr->getType()->isAnyPointerType());
8457   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
8458     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
8459     << RHSExpr->getSourceRange();
8460 }
8461 
8462 // C99 6.5.6
8463 QualType Sema::CheckAdditionOperands(ExprResult &LHS, ExprResult &RHS,
8464                                      SourceLocation Loc, BinaryOperatorKind Opc,
8465                                      QualType* CompLHSTy) {
8466   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8467 
8468   if (LHS.get()->getType()->isVectorType() ||
8469       RHS.get()->getType()->isVectorType()) {
8470     QualType compType = CheckVectorOperands(
8471         LHS, RHS, Loc, CompLHSTy,
8472         /*AllowBothBool*/getLangOpts().AltiVec,
8473         /*AllowBoolConversions*/getLangOpts().ZVector);
8474     if (CompLHSTy) *CompLHSTy = compType;
8475     return compType;
8476   }
8477 
8478   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8479   if (LHS.isInvalid() || RHS.isInvalid())
8480     return QualType();
8481 
8482   // Diagnose "string literal" '+' int and string '+' "char literal".
8483   if (Opc == BO_Add) {
8484     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
8485     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
8486   }
8487 
8488   // handle the common case first (both operands are arithmetic).
8489   if (!compType.isNull() && compType->isArithmeticType()) {
8490     if (CompLHSTy) *CompLHSTy = compType;
8491     return compType;
8492   }
8493 
8494   // Type-checking.  Ultimately the pointer's going to be in PExp;
8495   // note that we bias towards the LHS being the pointer.
8496   Expr *PExp = LHS.get(), *IExp = RHS.get();
8497 
8498   bool isObjCPointer;
8499   if (PExp->getType()->isPointerType()) {
8500     isObjCPointer = false;
8501   } else if (PExp->getType()->isObjCObjectPointerType()) {
8502     isObjCPointer = true;
8503   } else {
8504     std::swap(PExp, IExp);
8505     if (PExp->getType()->isPointerType()) {
8506       isObjCPointer = false;
8507     } else if (PExp->getType()->isObjCObjectPointerType()) {
8508       isObjCPointer = true;
8509     } else {
8510       return InvalidOperands(Loc, LHS, RHS);
8511     }
8512   }
8513   assert(PExp->getType()->isAnyPointerType());
8514 
8515   if (!IExp->getType()->isIntegerType())
8516     return InvalidOperands(Loc, LHS, RHS);
8517 
8518   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
8519     return QualType();
8520 
8521   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
8522     return QualType();
8523 
8524   // Check array bounds for pointer arithemtic
8525   CheckArrayAccess(PExp, IExp);
8526 
8527   if (CompLHSTy) {
8528     QualType LHSTy = Context.isPromotableBitField(LHS.get());
8529     if (LHSTy.isNull()) {
8530       LHSTy = LHS.get()->getType();
8531       if (LHSTy->isPromotableIntegerType())
8532         LHSTy = Context.getPromotedIntegerType(LHSTy);
8533     }
8534     *CompLHSTy = LHSTy;
8535   }
8536 
8537   return PExp->getType();
8538 }
8539 
8540 // C99 6.5.6
8541 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8542                                         SourceLocation Loc,
8543                                         QualType* CompLHSTy) {
8544   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8545 
8546   if (LHS.get()->getType()->isVectorType() ||
8547       RHS.get()->getType()->isVectorType()) {
8548     QualType compType = CheckVectorOperands(
8549         LHS, RHS, Loc, CompLHSTy,
8550         /*AllowBothBool*/getLangOpts().AltiVec,
8551         /*AllowBoolConversions*/getLangOpts().ZVector);
8552     if (CompLHSTy) *CompLHSTy = compType;
8553     return compType;
8554   }
8555 
8556   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8557   if (LHS.isInvalid() || RHS.isInvalid())
8558     return QualType();
8559 
8560   // Enforce type constraints: C99 6.5.6p3.
8561 
8562   // Handle the common case first (both operands are arithmetic).
8563   if (!compType.isNull() && compType->isArithmeticType()) {
8564     if (CompLHSTy) *CompLHSTy = compType;
8565     return compType;
8566   }
8567 
8568   // Either ptr - int   or   ptr - ptr.
8569   if (LHS.get()->getType()->isAnyPointerType()) {
8570     QualType lpointee = LHS.get()->getType()->getPointeeType();
8571 
8572     // Diagnose bad cases where we step over interface counts.
8573     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8574         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8575       return QualType();
8576 
8577     // The result type of a pointer-int computation is the pointer type.
8578     if (RHS.get()->getType()->isIntegerType()) {
8579       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8580         return QualType();
8581 
8582       // Check array bounds for pointer arithemtic
8583       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8584                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8585 
8586       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8587       return LHS.get()->getType();
8588     }
8589 
8590     // Handle pointer-pointer subtractions.
8591     if (const PointerType *RHSPTy
8592           = RHS.get()->getType()->getAs<PointerType>()) {
8593       QualType rpointee = RHSPTy->getPointeeType();
8594 
8595       if (getLangOpts().CPlusPlus) {
8596         // Pointee types must be the same: C++ [expr.add]
8597         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8598           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8599         }
8600       } else {
8601         // Pointee types must be compatible C99 6.5.6p3
8602         if (!Context.typesAreCompatible(
8603                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8604                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8605           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8606           return QualType();
8607         }
8608       }
8609 
8610       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8611                                                LHS.get(), RHS.get()))
8612         return QualType();
8613 
8614       // The pointee type may have zero size.  As an extension, a structure or
8615       // union may have zero size or an array may have zero length.  In this
8616       // case subtraction does not make sense.
8617       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8618         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8619         if (ElementSize.isZero()) {
8620           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8621             << rpointee.getUnqualifiedType()
8622             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8623         }
8624       }
8625 
8626       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8627       return Context.getPointerDiffType();
8628     }
8629   }
8630 
8631   return InvalidOperands(Loc, LHS, RHS);
8632 }
8633 
8634 static bool isScopedEnumerationType(QualType T) {
8635   if (const EnumType *ET = T->getAs<EnumType>())
8636     return ET->getDecl()->isScoped();
8637   return false;
8638 }
8639 
8640 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8641                                    SourceLocation Loc, BinaryOperatorKind Opc,
8642                                    QualType LHSType) {
8643   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8644   // so skip remaining warnings as we don't want to modify values within Sema.
8645   if (S.getLangOpts().OpenCL)
8646     return;
8647 
8648   llvm::APSInt Right;
8649   // Check right/shifter operand
8650   if (RHS.get()->isValueDependent() ||
8651       !RHS.get()->EvaluateAsInt(Right, S.Context))
8652     return;
8653 
8654   if (Right.isNegative()) {
8655     S.DiagRuntimeBehavior(Loc, RHS.get(),
8656                           S.PDiag(diag::warn_shift_negative)
8657                             << RHS.get()->getSourceRange());
8658     return;
8659   }
8660   llvm::APInt LeftBits(Right.getBitWidth(),
8661                        S.Context.getTypeSize(LHS.get()->getType()));
8662   if (Right.uge(LeftBits)) {
8663     S.DiagRuntimeBehavior(Loc, RHS.get(),
8664                           S.PDiag(diag::warn_shift_gt_typewidth)
8665                             << RHS.get()->getSourceRange());
8666     return;
8667   }
8668   if (Opc != BO_Shl)
8669     return;
8670 
8671   // When left shifting an ICE which is signed, we can check for overflow which
8672   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8673   // integers have defined behavior modulo one more than the maximum value
8674   // representable in the result type, so never warn for those.
8675   llvm::APSInt Left;
8676   if (LHS.get()->isValueDependent() ||
8677       LHSType->hasUnsignedIntegerRepresentation() ||
8678       !LHS.get()->EvaluateAsInt(Left, S.Context))
8679     return;
8680 
8681   // If LHS does not have a signed type and non-negative value
8682   // then, the behavior is undefined. Warn about it.
8683   if (Left.isNegative() && !S.getLangOpts().isSignedOverflowDefined()) {
8684     S.DiagRuntimeBehavior(Loc, LHS.get(),
8685                           S.PDiag(diag::warn_shift_lhs_negative)
8686                             << LHS.get()->getSourceRange());
8687     return;
8688   }
8689 
8690   llvm::APInt ResultBits =
8691       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8692   if (LeftBits.uge(ResultBits))
8693     return;
8694   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8695   Result = Result.shl(Right);
8696 
8697   // Print the bit representation of the signed integer as an unsigned
8698   // hexadecimal number.
8699   SmallString<40> HexResult;
8700   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8701 
8702   // If we are only missing a sign bit, this is less likely to result in actual
8703   // bugs -- if the result is cast back to an unsigned type, it will have the
8704   // expected value. Thus we place this behind a different warning that can be
8705   // turned off separately if needed.
8706   if (LeftBits == ResultBits - 1) {
8707     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8708         << HexResult << LHSType
8709         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8710     return;
8711   }
8712 
8713   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8714     << HexResult.str() << Result.getMinSignedBits() << LHSType
8715     << Left.getBitWidth() << LHS.get()->getSourceRange()
8716     << RHS.get()->getSourceRange();
8717 }
8718 
8719 /// \brief Return the resulting type when a vector is shifted
8720 ///        by a scalar or vector shift amount.
8721 static QualType checkVectorShift(Sema &S, ExprResult &LHS, ExprResult &RHS,
8722                                  SourceLocation Loc, bool IsCompAssign) {
8723   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8724   if (!LHS.get()->getType()->isVectorType()) {
8725     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8726       << RHS.get()->getType() << LHS.get()->getType()
8727       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8728     return QualType();
8729   }
8730 
8731   if (!IsCompAssign) {
8732     LHS = S.UsualUnaryConversions(LHS.get());
8733     if (LHS.isInvalid()) return QualType();
8734   }
8735 
8736   RHS = S.UsualUnaryConversions(RHS.get());
8737   if (RHS.isInvalid()) return QualType();
8738 
8739   QualType LHSType = LHS.get()->getType();
8740   const VectorType *LHSVecTy = LHSType->castAs<VectorType>();
8741   QualType LHSEleType = LHSVecTy->getElementType();
8742 
8743   // Note that RHS might not be a vector.
8744   QualType RHSType = RHS.get()->getType();
8745   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8746   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8747 
8748   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8749   if (!LHSEleType->isIntegerType()) {
8750     S.Diag(Loc, diag::err_typecheck_expect_int)
8751       << LHS.get()->getType() << LHS.get()->getSourceRange();
8752     return QualType();
8753   }
8754 
8755   if (!RHSEleType->isIntegerType()) {
8756     S.Diag(Loc, diag::err_typecheck_expect_int)
8757       << RHS.get()->getType() << RHS.get()->getSourceRange();
8758     return QualType();
8759   }
8760 
8761   if (RHSVecTy) {
8762     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8763     // are applied component-wise. So if RHS is a vector, then ensure
8764     // that the number of elements is the same as LHS...
8765     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8766       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8767         << LHS.get()->getType() << RHS.get()->getType()
8768         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8769       return QualType();
8770     }
8771   } else {
8772     // ...else expand RHS to match the number of elements in LHS.
8773     QualType VecTy =
8774       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8775     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8776   }
8777 
8778   return LHSType;
8779 }
8780 
8781 // C99 6.5.7
8782 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8783                                   SourceLocation Loc, BinaryOperatorKind Opc,
8784                                   bool IsCompAssign) {
8785   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8786 
8787   // Vector shifts promote their scalar inputs to vector type.
8788   if (LHS.get()->getType()->isVectorType() ||
8789       RHS.get()->getType()->isVectorType()) {
8790     if (LangOpts.ZVector) {
8791       // The shift operators for the z vector extensions work basically
8792       // like general shifts, except that neither the LHS nor the RHS is
8793       // allowed to be a "vector bool".
8794       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8795         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8796           return InvalidOperands(Loc, LHS, RHS);
8797       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8798         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8799           return InvalidOperands(Loc, LHS, RHS);
8800     }
8801     return checkVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8802   }
8803 
8804   // Shifts don't perform usual arithmetic conversions, they just do integer
8805   // promotions on each operand. C99 6.5.7p3
8806 
8807   // For the LHS, do usual unary conversions, but then reset them away
8808   // if this is a compound assignment.
8809   ExprResult OldLHS = LHS;
8810   LHS = UsualUnaryConversions(LHS.get());
8811   if (LHS.isInvalid())
8812     return QualType();
8813   QualType LHSType = LHS.get()->getType();
8814   if (IsCompAssign) LHS = OldLHS;
8815 
8816   // The RHS is simpler.
8817   RHS = UsualUnaryConversions(RHS.get());
8818   if (RHS.isInvalid())
8819     return QualType();
8820   QualType RHSType = RHS.get()->getType();
8821 
8822   // C99 6.5.7p2: Each of the operands shall have integer type.
8823   if (!LHSType->hasIntegerRepresentation() ||
8824       !RHSType->hasIntegerRepresentation())
8825     return InvalidOperands(Loc, LHS, RHS);
8826 
8827   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8828   // hasIntegerRepresentation() above instead of this.
8829   if (isScopedEnumerationType(LHSType) ||
8830       isScopedEnumerationType(RHSType)) {
8831     return InvalidOperands(Loc, LHS, RHS);
8832   }
8833   // Sanity-check shift operands
8834   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8835 
8836   // "The type of the result is that of the promoted left operand."
8837   return LHSType;
8838 }
8839 
8840 static bool IsWithinTemplateSpecialization(Decl *D) {
8841   if (DeclContext *DC = D->getDeclContext()) {
8842     if (isa<ClassTemplateSpecializationDecl>(DC))
8843       return true;
8844     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8845       return FD->isFunctionTemplateSpecialization();
8846   }
8847   return false;
8848 }
8849 
8850 /// If two different enums are compared, raise a warning.
8851 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8852                                 Expr *RHS) {
8853   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8854   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8855 
8856   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8857   if (!LHSEnumType)
8858     return;
8859   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8860   if (!RHSEnumType)
8861     return;
8862 
8863   // Ignore anonymous enums.
8864   if (!LHSEnumType->getDecl()->getIdentifier())
8865     return;
8866   if (!RHSEnumType->getDecl()->getIdentifier())
8867     return;
8868 
8869   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8870     return;
8871 
8872   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8873       << LHSStrippedType << RHSStrippedType
8874       << LHS->getSourceRange() << RHS->getSourceRange();
8875 }
8876 
8877 /// \brief Diagnose bad pointer comparisons.
8878 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8879                                               ExprResult &LHS, ExprResult &RHS,
8880                                               bool IsError) {
8881   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8882                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8883     << LHS.get()->getType() << RHS.get()->getType()
8884     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8885 }
8886 
8887 /// \brief Returns false if the pointers are converted to a composite type,
8888 /// true otherwise.
8889 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8890                                            ExprResult &LHS, ExprResult &RHS) {
8891   // C++ [expr.rel]p2:
8892   //   [...] Pointer conversions (4.10) and qualification
8893   //   conversions (4.4) are performed on pointer operands (or on
8894   //   a pointer operand and a null pointer constant) to bring
8895   //   them to their composite pointer type. [...]
8896   //
8897   // C++ [expr.eq]p1 uses the same notion for (in)equality
8898   // comparisons of pointers.
8899 
8900   // C++ [expr.eq]p2:
8901   //   In addition, pointers to members can be compared, or a pointer to
8902   //   member and a null pointer constant. Pointer to member conversions
8903   //   (4.11) and qualification conversions (4.4) are performed to bring
8904   //   them to a common type. If one operand is a null pointer constant,
8905   //   the common type is the type of the other operand. Otherwise, the
8906   //   common type is a pointer to member type similar (4.4) to the type
8907   //   of one of the operands, with a cv-qualification signature (4.4)
8908   //   that is the union of the cv-qualification signatures of the operand
8909   //   types.
8910 
8911   QualType LHSType = LHS.get()->getType();
8912   QualType RHSType = RHS.get()->getType();
8913   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8914          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8915 
8916   bool NonStandardCompositeType = false;
8917   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8918   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8919   if (T.isNull()) {
8920     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8921     return true;
8922   }
8923 
8924   if (NonStandardCompositeType)
8925     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8926       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8927       << RHS.get()->getSourceRange();
8928 
8929   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8930   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8931   return false;
8932 }
8933 
8934 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8935                                                     ExprResult &LHS,
8936                                                     ExprResult &RHS,
8937                                                     bool IsError) {
8938   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8939                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8940     << LHS.get()->getType() << RHS.get()->getType()
8941     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8942 }
8943 
8944 static bool isObjCObjectLiteral(ExprResult &E) {
8945   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8946   case Stmt::ObjCArrayLiteralClass:
8947   case Stmt::ObjCDictionaryLiteralClass:
8948   case Stmt::ObjCStringLiteralClass:
8949   case Stmt::ObjCBoxedExprClass:
8950     return true;
8951   default:
8952     // Note that ObjCBoolLiteral is NOT an object literal!
8953     return false;
8954   }
8955 }
8956 
8957 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8958   const ObjCObjectPointerType *Type =
8959     LHS->getType()->getAs<ObjCObjectPointerType>();
8960 
8961   // If this is not actually an Objective-C object, bail out.
8962   if (!Type)
8963     return false;
8964 
8965   // Get the LHS object's interface type.
8966   QualType InterfaceType = Type->getPointeeType();
8967 
8968   // If the RHS isn't an Objective-C object, bail out.
8969   if (!RHS->getType()->isObjCObjectPointerType())
8970     return false;
8971 
8972   // Try to find the -isEqual: method.
8973   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8974   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8975                                                       InterfaceType,
8976                                                       /*instance=*/true);
8977   if (!Method) {
8978     if (Type->isObjCIdType()) {
8979       // For 'id', just check the global pool.
8980       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8981                                                   /*receiverId=*/true);
8982     } else {
8983       // Check protocols.
8984       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8985                                              /*instance=*/true);
8986     }
8987   }
8988 
8989   if (!Method)
8990     return false;
8991 
8992   QualType T = Method->parameters()[0]->getType();
8993   if (!T->isObjCObjectPointerType())
8994     return false;
8995 
8996   QualType R = Method->getReturnType();
8997   if (!R->isScalarType())
8998     return false;
8999 
9000   return true;
9001 }
9002 
9003 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
9004   FromE = FromE->IgnoreParenImpCasts();
9005   switch (FromE->getStmtClass()) {
9006     default:
9007       break;
9008     case Stmt::ObjCStringLiteralClass:
9009       // "string literal"
9010       return LK_String;
9011     case Stmt::ObjCArrayLiteralClass:
9012       // "array literal"
9013       return LK_Array;
9014     case Stmt::ObjCDictionaryLiteralClass:
9015       // "dictionary literal"
9016       return LK_Dictionary;
9017     case Stmt::BlockExprClass:
9018       return LK_Block;
9019     case Stmt::ObjCBoxedExprClass: {
9020       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
9021       switch (Inner->getStmtClass()) {
9022         case Stmt::IntegerLiteralClass:
9023         case Stmt::FloatingLiteralClass:
9024         case Stmt::CharacterLiteralClass:
9025         case Stmt::ObjCBoolLiteralExprClass:
9026         case Stmt::CXXBoolLiteralExprClass:
9027           // "numeric literal"
9028           return LK_Numeric;
9029         case Stmt::ImplicitCastExprClass: {
9030           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
9031           // Boolean literals can be represented by implicit casts.
9032           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
9033             return LK_Numeric;
9034           break;
9035         }
9036         default:
9037           break;
9038       }
9039       return LK_Boxed;
9040     }
9041   }
9042   return LK_None;
9043 }
9044 
9045 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
9046                                           ExprResult &LHS, ExprResult &RHS,
9047                                           BinaryOperator::Opcode Opc){
9048   Expr *Literal;
9049   Expr *Other;
9050   if (isObjCObjectLiteral(LHS)) {
9051     Literal = LHS.get();
9052     Other = RHS.get();
9053   } else {
9054     Literal = RHS.get();
9055     Other = LHS.get();
9056   }
9057 
9058   // Don't warn on comparisons against nil.
9059   Other = Other->IgnoreParenCasts();
9060   if (Other->isNullPointerConstant(S.getASTContext(),
9061                                    Expr::NPC_ValueDependentIsNotNull))
9062     return;
9063 
9064   // This should be kept in sync with warn_objc_literal_comparison.
9065   // LK_String should always be after the other literals, since it has its own
9066   // warning flag.
9067   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
9068   assert(LiteralKind != Sema::LK_Block);
9069   if (LiteralKind == Sema::LK_None) {
9070     llvm_unreachable("Unknown Objective-C object literal kind");
9071   }
9072 
9073   if (LiteralKind == Sema::LK_String)
9074     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
9075       << Literal->getSourceRange();
9076   else
9077     S.Diag(Loc, diag::warn_objc_literal_comparison)
9078       << LiteralKind << Literal->getSourceRange();
9079 
9080   if (BinaryOperator::isEqualityOp(Opc) &&
9081       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
9082     SourceLocation Start = LHS.get()->getLocStart();
9083     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
9084     CharSourceRange OpRange =
9085       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
9086 
9087     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
9088       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
9089       << FixItHint::CreateReplacement(OpRange, " isEqual:")
9090       << FixItHint::CreateInsertion(End, "]");
9091   }
9092 }
9093 
9094 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
9095                                                 ExprResult &RHS,
9096                                                 SourceLocation Loc,
9097                                                 BinaryOperatorKind Opc) {
9098   // Check that left hand side is !something.
9099   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
9100   if (!UO || UO->getOpcode() != UO_LNot) return;
9101 
9102   // Only check if the right hand side is non-bool arithmetic type.
9103   if (RHS.get()->isKnownToHaveBooleanValue()) return;
9104 
9105   // Make sure that the something in !something is not bool.
9106   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
9107   if (SubExpr->isKnownToHaveBooleanValue()) return;
9108 
9109   // Emit warning.
9110   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
9111       << Loc;
9112 
9113   // First note suggest !(x < y)
9114   SourceLocation FirstOpen = SubExpr->getLocStart();
9115   SourceLocation FirstClose = RHS.get()->getLocEnd();
9116   FirstClose = S.getLocForEndOfToken(FirstClose);
9117   if (FirstClose.isInvalid())
9118     FirstOpen = SourceLocation();
9119   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
9120       << FixItHint::CreateInsertion(FirstOpen, "(")
9121       << FixItHint::CreateInsertion(FirstClose, ")");
9122 
9123   // Second note suggests (!x) < y
9124   SourceLocation SecondOpen = LHS.get()->getLocStart();
9125   SourceLocation SecondClose = LHS.get()->getLocEnd();
9126   SecondClose = S.getLocForEndOfToken(SecondClose);
9127   if (SecondClose.isInvalid())
9128     SecondOpen = SourceLocation();
9129   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
9130       << FixItHint::CreateInsertion(SecondOpen, "(")
9131       << FixItHint::CreateInsertion(SecondClose, ")");
9132 }
9133 
9134 // Get the decl for a simple expression: a reference to a variable,
9135 // an implicit C++ field reference, or an implicit ObjC ivar reference.
9136 static ValueDecl *getCompareDecl(Expr *E) {
9137   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
9138     return DR->getDecl();
9139   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
9140     if (Ivar->isFreeIvar())
9141       return Ivar->getDecl();
9142   }
9143   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
9144     if (Mem->isImplicitAccess())
9145       return Mem->getMemberDecl();
9146   }
9147   return nullptr;
9148 }
9149 
9150 // C99 6.5.8, C++ [expr.rel]
9151 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
9152                                     SourceLocation Loc, BinaryOperatorKind Opc,
9153                                     bool IsRelational) {
9154   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
9155 
9156   // Handle vector comparisons separately.
9157   if (LHS.get()->getType()->isVectorType() ||
9158       RHS.get()->getType()->isVectorType())
9159     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
9160 
9161   QualType LHSType = LHS.get()->getType();
9162   QualType RHSType = RHS.get()->getType();
9163 
9164   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
9165   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
9166 
9167   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
9168   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, Opc);
9169 
9170   if (!LHSType->hasFloatingRepresentation() &&
9171       !(LHSType->isBlockPointerType() && IsRelational) &&
9172       !LHS.get()->getLocStart().isMacroID() &&
9173       !RHS.get()->getLocStart().isMacroID() &&
9174       ActiveTemplateInstantiations.empty()) {
9175     // For non-floating point types, check for self-comparisons of the form
9176     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9177     // often indicate logic errors in the program.
9178     //
9179     // NOTE: Don't warn about comparison expressions resulting from macro
9180     // expansion. Also don't warn about comparisons which are only self
9181     // comparisons within a template specialization. The warnings should catch
9182     // obvious cases in the definition of the template anyways. The idea is to
9183     // warn when the typed comparison operator will always evaluate to the same
9184     // result.
9185     ValueDecl *DL = getCompareDecl(LHSStripped);
9186     ValueDecl *DR = getCompareDecl(RHSStripped);
9187     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
9188       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9189                           << 0 // self-
9190                           << (Opc == BO_EQ
9191                               || Opc == BO_LE
9192                               || Opc == BO_GE));
9193     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
9194                !DL->getType()->isReferenceType() &&
9195                !DR->getType()->isReferenceType()) {
9196         // what is it always going to eval to?
9197         char always_evals_to;
9198         switch(Opc) {
9199         case BO_EQ: // e.g. array1 == array2
9200           always_evals_to = 0; // false
9201           break;
9202         case BO_NE: // e.g. array1 != array2
9203           always_evals_to = 1; // true
9204           break;
9205         default:
9206           // best we can say is 'a constant'
9207           always_evals_to = 2; // e.g. array1 <= array2
9208           break;
9209         }
9210         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
9211                             << 1 // array
9212                             << always_evals_to);
9213     }
9214 
9215     if (isa<CastExpr>(LHSStripped))
9216       LHSStripped = LHSStripped->IgnoreParenCasts();
9217     if (isa<CastExpr>(RHSStripped))
9218       RHSStripped = RHSStripped->IgnoreParenCasts();
9219 
9220     // Warn about comparisons against a string constant (unless the other
9221     // operand is null), the user probably wants strcmp.
9222     Expr *literalString = nullptr;
9223     Expr *literalStringStripped = nullptr;
9224     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
9225         !RHSStripped->isNullPointerConstant(Context,
9226                                             Expr::NPC_ValueDependentIsNull)) {
9227       literalString = LHS.get();
9228       literalStringStripped = LHSStripped;
9229     } else if ((isa<StringLiteral>(RHSStripped) ||
9230                 isa<ObjCEncodeExpr>(RHSStripped)) &&
9231                !LHSStripped->isNullPointerConstant(Context,
9232                                             Expr::NPC_ValueDependentIsNull)) {
9233       literalString = RHS.get();
9234       literalStringStripped = RHSStripped;
9235     }
9236 
9237     if (literalString) {
9238       DiagRuntimeBehavior(Loc, nullptr,
9239         PDiag(diag::warn_stringcompare)
9240           << isa<ObjCEncodeExpr>(literalStringStripped)
9241           << literalString->getSourceRange());
9242     }
9243   }
9244 
9245   // C99 6.5.8p3 / C99 6.5.9p4
9246   UsualArithmeticConversions(LHS, RHS);
9247   if (LHS.isInvalid() || RHS.isInvalid())
9248     return QualType();
9249 
9250   LHSType = LHS.get()->getType();
9251   RHSType = RHS.get()->getType();
9252 
9253   // The result of comparisons is 'bool' in C++, 'int' in C.
9254   QualType ResultTy = Context.getLogicalOperationType();
9255 
9256   if (IsRelational) {
9257     if (LHSType->isRealType() && RHSType->isRealType())
9258       return ResultTy;
9259   } else {
9260     // Check for comparisons of floating point operands using != and ==.
9261     if (LHSType->hasFloatingRepresentation())
9262       CheckFloatComparison(Loc, LHS.get(), RHS.get());
9263 
9264     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
9265       return ResultTy;
9266   }
9267 
9268   const Expr::NullPointerConstantKind LHSNullKind =
9269       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9270   const Expr::NullPointerConstantKind RHSNullKind =
9271       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
9272   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
9273   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
9274 
9275   if (!IsRelational && LHSIsNull != RHSIsNull) {
9276     bool IsEquality = Opc == BO_EQ;
9277     if (RHSIsNull)
9278       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
9279                                    RHS.get()->getSourceRange());
9280     else
9281       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
9282                                    LHS.get()->getSourceRange());
9283   }
9284 
9285   // All of the following pointer-related warnings are GCC extensions, except
9286   // when handling null pointer constants.
9287   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
9288     QualType LCanPointeeTy =
9289       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9290     QualType RCanPointeeTy =
9291       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
9292 
9293     if (getLangOpts().CPlusPlus) {
9294       if (LCanPointeeTy == RCanPointeeTy)
9295         return ResultTy;
9296       if (!IsRelational &&
9297           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9298         // Valid unless comparison between non-null pointer and function pointer
9299         // This is a gcc extension compatibility comparison.
9300         // In a SFINAE context, we treat this as a hard error to maintain
9301         // conformance with the C++ standard.
9302         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9303             && !LHSIsNull && !RHSIsNull) {
9304           diagnoseFunctionPointerToVoidComparison(
9305               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
9306 
9307           if (isSFINAEContext())
9308             return QualType();
9309 
9310           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9311           return ResultTy;
9312         }
9313       }
9314 
9315       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9316         return QualType();
9317       else
9318         return ResultTy;
9319     }
9320     // C99 6.5.9p2 and C99 6.5.8p2
9321     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
9322                                    RCanPointeeTy.getUnqualifiedType())) {
9323       // Valid unless a relational comparison of function pointers
9324       if (IsRelational && LCanPointeeTy->isFunctionType()) {
9325         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
9326           << LHSType << RHSType << LHS.get()->getSourceRange()
9327           << RHS.get()->getSourceRange();
9328       }
9329     } else if (!IsRelational &&
9330                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
9331       // Valid unless comparison between non-null pointer and function pointer
9332       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
9333           && !LHSIsNull && !RHSIsNull)
9334         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
9335                                                 /*isError*/false);
9336     } else {
9337       // Invalid
9338       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
9339     }
9340     if (LCanPointeeTy != RCanPointeeTy) {
9341       // Treat NULL constant as a special case in OpenCL.
9342       if (getLangOpts().OpenCL && !LHSIsNull && !RHSIsNull) {
9343         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
9344         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
9345           Diag(Loc,
9346                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
9347               << LHSType << RHSType << 0 /* comparison */
9348               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
9349         }
9350       }
9351       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
9352       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
9353       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
9354                                                : CK_BitCast;
9355       if (LHSIsNull && !RHSIsNull)
9356         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
9357       else
9358         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
9359     }
9360     return ResultTy;
9361   }
9362 
9363   if (getLangOpts().CPlusPlus) {
9364     // Comparison of nullptr_t with itself.
9365     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
9366       return ResultTy;
9367 
9368     // Comparison of pointers with null pointer constants and equality
9369     // comparisons of member pointers to null pointer constants.
9370     if (RHSIsNull &&
9371         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
9372          (!IsRelational &&
9373           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
9374       RHS = ImpCastExprToType(RHS.get(), LHSType,
9375                         LHSType->isMemberPointerType()
9376                           ? CK_NullToMemberPointer
9377                           : CK_NullToPointer);
9378       return ResultTy;
9379     }
9380     if (LHSIsNull &&
9381         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
9382          (!IsRelational &&
9383           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
9384       LHS = ImpCastExprToType(LHS.get(), RHSType,
9385                         RHSType->isMemberPointerType()
9386                           ? CK_NullToMemberPointer
9387                           : CK_NullToPointer);
9388       return ResultTy;
9389     }
9390 
9391     // Comparison of member pointers.
9392     if (!IsRelational &&
9393         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
9394       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
9395         return QualType();
9396       else
9397         return ResultTy;
9398     }
9399 
9400     // Handle scoped enumeration types specifically, since they don't promote
9401     // to integers.
9402     if (LHS.get()->getType()->isEnumeralType() &&
9403         Context.hasSameUnqualifiedType(LHS.get()->getType(),
9404                                        RHS.get()->getType()))
9405       return ResultTy;
9406   }
9407 
9408   // Handle block pointer types.
9409   if (!IsRelational && LHSType->isBlockPointerType() &&
9410       RHSType->isBlockPointerType()) {
9411     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
9412     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
9413 
9414     if (!LHSIsNull && !RHSIsNull &&
9415         !Context.typesAreCompatible(lpointee, rpointee)) {
9416       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9417         << LHSType << RHSType << LHS.get()->getSourceRange()
9418         << RHS.get()->getSourceRange();
9419     }
9420     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9421     return ResultTy;
9422   }
9423 
9424   // Allow block pointers to be compared with null pointer constants.
9425   if (!IsRelational
9426       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
9427           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
9428     if (!LHSIsNull && !RHSIsNull) {
9429       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
9430              ->getPointeeType()->isVoidType())
9431             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
9432                 ->getPointeeType()->isVoidType())))
9433         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
9434           << LHSType << RHSType << LHS.get()->getSourceRange()
9435           << RHS.get()->getSourceRange();
9436     }
9437     if (LHSIsNull && !RHSIsNull)
9438       LHS = ImpCastExprToType(LHS.get(), RHSType,
9439                               RHSType->isPointerType() ? CK_BitCast
9440                                 : CK_AnyPointerToBlockPointerCast);
9441     else
9442       RHS = ImpCastExprToType(RHS.get(), LHSType,
9443                               LHSType->isPointerType() ? CK_BitCast
9444                                 : CK_AnyPointerToBlockPointerCast);
9445     return ResultTy;
9446   }
9447 
9448   if (LHSType->isObjCObjectPointerType() ||
9449       RHSType->isObjCObjectPointerType()) {
9450     const PointerType *LPT = LHSType->getAs<PointerType>();
9451     const PointerType *RPT = RHSType->getAs<PointerType>();
9452     if (LPT || RPT) {
9453       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
9454       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
9455 
9456       if (!LPtrToVoid && !RPtrToVoid &&
9457           !Context.typesAreCompatible(LHSType, RHSType)) {
9458         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9459                                           /*isError*/false);
9460       }
9461       if (LHSIsNull && !RHSIsNull) {
9462         Expr *E = LHS.get();
9463         if (getLangOpts().ObjCAutoRefCount)
9464           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
9465         LHS = ImpCastExprToType(E, RHSType,
9466                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9467       }
9468       else {
9469         Expr *E = RHS.get();
9470         if (getLangOpts().ObjCAutoRefCount)
9471           CheckObjCARCConversion(SourceRange(), LHSType, E,
9472                                  CCK_ImplicitConversion, /*Diagnose=*/true,
9473                                  /*DiagnoseCFAudited=*/false, Opc);
9474         RHS = ImpCastExprToType(E, LHSType,
9475                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
9476       }
9477       return ResultTy;
9478     }
9479     if (LHSType->isObjCObjectPointerType() &&
9480         RHSType->isObjCObjectPointerType()) {
9481       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
9482         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
9483                                           /*isError*/false);
9484       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
9485         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
9486 
9487       if (LHSIsNull && !RHSIsNull)
9488         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
9489       else
9490         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
9491       return ResultTy;
9492     }
9493   }
9494   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
9495       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
9496     unsigned DiagID = 0;
9497     bool isError = false;
9498     if (LangOpts.DebuggerSupport) {
9499       // Under a debugger, allow the comparison of pointers to integers,
9500       // since users tend to want to compare addresses.
9501     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
9502         (RHSIsNull && RHSType->isIntegerType())) {
9503       if (IsRelational && !getLangOpts().CPlusPlus)
9504         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
9505     } else if (IsRelational && !getLangOpts().CPlusPlus)
9506       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
9507     else if (getLangOpts().CPlusPlus) {
9508       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
9509       isError = true;
9510     } else
9511       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
9512 
9513     if (DiagID) {
9514       Diag(Loc, DiagID)
9515         << LHSType << RHSType << LHS.get()->getSourceRange()
9516         << RHS.get()->getSourceRange();
9517       if (isError)
9518         return QualType();
9519     }
9520 
9521     if (LHSType->isIntegerType())
9522       LHS = ImpCastExprToType(LHS.get(), RHSType,
9523                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9524     else
9525       RHS = ImpCastExprToType(RHS.get(), LHSType,
9526                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
9527     return ResultTy;
9528   }
9529 
9530   // Handle block pointers.
9531   if (!IsRelational && RHSIsNull
9532       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9533     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9534     return ResultTy;
9535   }
9536   if (!IsRelational && LHSIsNull
9537       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9538     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9539     return ResultTy;
9540   }
9541 
9542   return InvalidOperands(Loc, LHS, RHS);
9543 }
9544 
9545 
9546 // Return a signed type that is of identical size and number of elements.
9547 // For floating point vectors, return an integer type of identical size
9548 // and number of elements.
9549 QualType Sema::GetSignedVectorType(QualType V) {
9550   const VectorType *VTy = V->getAs<VectorType>();
9551   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9552   if (TypeSize == Context.getTypeSize(Context.CharTy))
9553     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9554   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9555     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9556   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9557     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9558   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9559     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9560   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9561          "Unhandled vector element size in vector compare");
9562   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9563 }
9564 
9565 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9566 /// operates on extended vector types.  Instead of producing an IntTy result,
9567 /// like a scalar comparison, a vector comparison produces a vector of integer
9568 /// types.
9569 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9570                                           SourceLocation Loc,
9571                                           bool IsRelational) {
9572   // Check to make sure we're operating on vectors of the same type and width,
9573   // Allowing one side to be a scalar of element type.
9574   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9575                               /*AllowBothBool*/true,
9576                               /*AllowBoolConversions*/getLangOpts().ZVector);
9577   if (vType.isNull())
9578     return vType;
9579 
9580   QualType LHSType = LHS.get()->getType();
9581 
9582   // If AltiVec, the comparison results in a numeric type, i.e.
9583   // bool for C++, int for C
9584   if (getLangOpts().AltiVec &&
9585       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9586     return Context.getLogicalOperationType();
9587 
9588   // For non-floating point types, check for self-comparisons of the form
9589   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9590   // often indicate logic errors in the program.
9591   if (!LHSType->hasFloatingRepresentation() &&
9592       ActiveTemplateInstantiations.empty()) {
9593     if (DeclRefExpr* DRL
9594           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9595       if (DeclRefExpr* DRR
9596             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9597         if (DRL->getDecl() == DRR->getDecl())
9598           DiagRuntimeBehavior(Loc, nullptr,
9599                               PDiag(diag::warn_comparison_always)
9600                                 << 0 // self-
9601                                 << 2 // "a constant"
9602                               );
9603   }
9604 
9605   // Check for comparisons of floating point operands using != and ==.
9606   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9607     assert (RHS.get()->getType()->hasFloatingRepresentation());
9608     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9609   }
9610 
9611   // Return a signed type for the vector.
9612   return GetSignedVectorType(vType);
9613 }
9614 
9615 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9616                                           SourceLocation Loc) {
9617   // Ensure that either both operands are of the same vector type, or
9618   // one operand is of a vector type and the other is of its element type.
9619   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9620                                        /*AllowBothBool*/true,
9621                                        /*AllowBoolConversions*/false);
9622   if (vType.isNull())
9623     return InvalidOperands(Loc, LHS, RHS);
9624   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9625       vType->hasFloatingRepresentation())
9626     return InvalidOperands(Loc, LHS, RHS);
9627 
9628   return GetSignedVectorType(LHS.get()->getType());
9629 }
9630 
9631 inline QualType Sema::CheckBitwiseOperands(
9632   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9633   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9634 
9635   if (LHS.get()->getType()->isVectorType() ||
9636       RHS.get()->getType()->isVectorType()) {
9637     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9638         RHS.get()->getType()->hasIntegerRepresentation())
9639       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9640                         /*AllowBothBool*/true,
9641                         /*AllowBoolConversions*/getLangOpts().ZVector);
9642     return InvalidOperands(Loc, LHS, RHS);
9643   }
9644 
9645   ExprResult LHSResult = LHS, RHSResult = RHS;
9646   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9647                                                  IsCompAssign);
9648   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9649     return QualType();
9650   LHS = LHSResult.get();
9651   RHS = RHSResult.get();
9652 
9653   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9654     return compType;
9655   return InvalidOperands(Loc, LHS, RHS);
9656 }
9657 
9658 // C99 6.5.[13,14]
9659 inline QualType Sema::CheckLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9660                                            SourceLocation Loc,
9661                                            BinaryOperatorKind Opc) {
9662   // Check vector operands differently.
9663   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9664     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9665 
9666   // Diagnose cases where the user write a logical and/or but probably meant a
9667   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9668   // is a constant.
9669   if (LHS.get()->getType()->isIntegerType() &&
9670       !LHS.get()->getType()->isBooleanType() &&
9671       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9672       // Don't warn in macros or template instantiations.
9673       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9674     // If the RHS can be constant folded, and if it constant folds to something
9675     // that isn't 0 or 1 (which indicate a potential logical operation that
9676     // happened to fold to true/false) then warn.
9677     // Parens on the RHS are ignored.
9678     llvm::APSInt Result;
9679     if (RHS.get()->EvaluateAsInt(Result, Context))
9680       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9681            !RHS.get()->getExprLoc().isMacroID()) ||
9682           (Result != 0 && Result != 1)) {
9683         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9684           << RHS.get()->getSourceRange()
9685           << (Opc == BO_LAnd ? "&&" : "||");
9686         // Suggest replacing the logical operator with the bitwise version
9687         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9688             << (Opc == BO_LAnd ? "&" : "|")
9689             << FixItHint::CreateReplacement(SourceRange(
9690                                                  Loc, getLocForEndOfToken(Loc)),
9691                                             Opc == BO_LAnd ? "&" : "|");
9692         if (Opc == BO_LAnd)
9693           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9694           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9695               << FixItHint::CreateRemoval(
9696                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9697                               RHS.get()->getLocEnd()));
9698       }
9699   }
9700 
9701   if (!Context.getLangOpts().CPlusPlus) {
9702     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9703     // not operate on the built-in scalar and vector float types.
9704     if (Context.getLangOpts().OpenCL &&
9705         Context.getLangOpts().OpenCLVersion < 120) {
9706       if (LHS.get()->getType()->isFloatingType() ||
9707           RHS.get()->getType()->isFloatingType())
9708         return InvalidOperands(Loc, LHS, RHS);
9709     }
9710 
9711     LHS = UsualUnaryConversions(LHS.get());
9712     if (LHS.isInvalid())
9713       return QualType();
9714 
9715     RHS = UsualUnaryConversions(RHS.get());
9716     if (RHS.isInvalid())
9717       return QualType();
9718 
9719     if (!LHS.get()->getType()->isScalarType() ||
9720         !RHS.get()->getType()->isScalarType())
9721       return InvalidOperands(Loc, LHS, RHS);
9722 
9723     return Context.IntTy;
9724   }
9725 
9726   // The following is safe because we only use this method for
9727   // non-overloadable operands.
9728 
9729   // C++ [expr.log.and]p1
9730   // C++ [expr.log.or]p1
9731   // The operands are both contextually converted to type bool.
9732   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9733   if (LHSRes.isInvalid())
9734     return InvalidOperands(Loc, LHS, RHS);
9735   LHS = LHSRes;
9736 
9737   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9738   if (RHSRes.isInvalid())
9739     return InvalidOperands(Loc, LHS, RHS);
9740   RHS = RHSRes;
9741 
9742   // C++ [expr.log.and]p2
9743   // C++ [expr.log.or]p2
9744   // The result is a bool.
9745   return Context.BoolTy;
9746 }
9747 
9748 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9749   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9750   if (!ME) return false;
9751   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9752   ObjCMessageExpr *Base =
9753     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9754   if (!Base) return false;
9755   return Base->getMethodDecl() != nullptr;
9756 }
9757 
9758 /// Is the given expression (which must be 'const') a reference to a
9759 /// variable which was originally non-const, but which has become
9760 /// 'const' due to being captured within a block?
9761 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9762 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9763   assert(E->isLValue() && E->getType().isConstQualified());
9764   E = E->IgnoreParens();
9765 
9766   // Must be a reference to a declaration from an enclosing scope.
9767   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9768   if (!DRE) return NCCK_None;
9769   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9770 
9771   // The declaration must be a variable which is not declared 'const'.
9772   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9773   if (!var) return NCCK_None;
9774   if (var->getType().isConstQualified()) return NCCK_None;
9775   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9776 
9777   // Decide whether the first capture was for a block or a lambda.
9778   DeclContext *DC = S.CurContext, *Prev = nullptr;
9779   // Decide whether the first capture was for a block or a lambda.
9780   while (DC) {
9781     // For init-capture, it is possible that the variable belongs to the
9782     // template pattern of the current context.
9783     if (auto *FD = dyn_cast<FunctionDecl>(DC))
9784       if (var->isInitCapture() &&
9785           FD->getTemplateInstantiationPattern() == var->getDeclContext())
9786         break;
9787     if (DC == var->getDeclContext())
9788       break;
9789     Prev = DC;
9790     DC = DC->getParent();
9791   }
9792   // Unless we have an init-capture, we've gone one step too far.
9793   if (!var->isInitCapture())
9794     DC = Prev;
9795   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9796 }
9797 
9798 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9799   Ty = Ty.getNonReferenceType();
9800   if (IsDereference && Ty->isPointerType())
9801     Ty = Ty->getPointeeType();
9802   return !Ty.isConstQualified();
9803 }
9804 
9805 /// Emit the "read-only variable not assignable" error and print notes to give
9806 /// more information about why the variable is not assignable, such as pointing
9807 /// to the declaration of a const variable, showing that a method is const, or
9808 /// that the function is returning a const reference.
9809 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9810                                     SourceLocation Loc) {
9811   // Update err_typecheck_assign_const and note_typecheck_assign_const
9812   // when this enum is changed.
9813   enum {
9814     ConstFunction,
9815     ConstVariable,
9816     ConstMember,
9817     ConstMethod,
9818     ConstUnknown,  // Keep as last element
9819   };
9820 
9821   SourceRange ExprRange = E->getSourceRange();
9822 
9823   // Only emit one error on the first const found.  All other consts will emit
9824   // a note to the error.
9825   bool DiagnosticEmitted = false;
9826 
9827   // Track if the current expression is the result of a derefence, and if the
9828   // next checked expression is the result of a derefence.
9829   bool IsDereference = false;
9830   bool NextIsDereference = false;
9831 
9832   // Loop to process MemberExpr chains.
9833   while (true) {
9834     IsDereference = NextIsDereference;
9835     NextIsDereference = false;
9836 
9837     E = E->IgnoreParenImpCasts();
9838     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9839       NextIsDereference = ME->isArrow();
9840       const ValueDecl *VD = ME->getMemberDecl();
9841       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9842         // Mutable fields can be modified even if the class is const.
9843         if (Field->isMutable()) {
9844           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9845           break;
9846         }
9847 
9848         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9849           if (!DiagnosticEmitted) {
9850             S.Diag(Loc, diag::err_typecheck_assign_const)
9851                 << ExprRange << ConstMember << false /*static*/ << Field
9852                 << Field->getType();
9853             DiagnosticEmitted = true;
9854           }
9855           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9856               << ConstMember << false /*static*/ << Field << Field->getType()
9857               << Field->getSourceRange();
9858         }
9859         E = ME->getBase();
9860         continue;
9861       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9862         if (VDecl->getType().isConstQualified()) {
9863           if (!DiagnosticEmitted) {
9864             S.Diag(Loc, diag::err_typecheck_assign_const)
9865                 << ExprRange << ConstMember << true /*static*/ << VDecl
9866                 << VDecl->getType();
9867             DiagnosticEmitted = true;
9868           }
9869           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9870               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9871               << VDecl->getSourceRange();
9872         }
9873         // Static fields do not inherit constness from parents.
9874         break;
9875       }
9876       break;
9877     } // End MemberExpr
9878     break;
9879   }
9880 
9881   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9882     // Function calls
9883     const FunctionDecl *FD = CE->getDirectCallee();
9884     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9885       if (!DiagnosticEmitted) {
9886         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9887                                                       << ConstFunction << FD;
9888         DiagnosticEmitted = true;
9889       }
9890       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9891              diag::note_typecheck_assign_const)
9892           << ConstFunction << FD << FD->getReturnType()
9893           << FD->getReturnTypeSourceRange();
9894     }
9895   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9896     // Point to variable declaration.
9897     if (const ValueDecl *VD = DRE->getDecl()) {
9898       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9899         if (!DiagnosticEmitted) {
9900           S.Diag(Loc, diag::err_typecheck_assign_const)
9901               << ExprRange << ConstVariable << VD << VD->getType();
9902           DiagnosticEmitted = true;
9903         }
9904         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9905             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9906       }
9907     }
9908   } else if (isa<CXXThisExpr>(E)) {
9909     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9910       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9911         if (MD->isConst()) {
9912           if (!DiagnosticEmitted) {
9913             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9914                                                           << ConstMethod << MD;
9915             DiagnosticEmitted = true;
9916           }
9917           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9918               << ConstMethod << MD << MD->getSourceRange();
9919         }
9920       }
9921     }
9922   }
9923 
9924   if (DiagnosticEmitted)
9925     return;
9926 
9927   // Can't determine a more specific message, so display the generic error.
9928   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9929 }
9930 
9931 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9932 /// emit an error and return true.  If so, return false.
9933 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9934   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9935 
9936   S.CheckShadowingDeclModification(E, Loc);
9937 
9938   SourceLocation OrigLoc = Loc;
9939   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9940                                                               &Loc);
9941   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9942     IsLV = Expr::MLV_InvalidMessageExpression;
9943   if (IsLV == Expr::MLV_Valid)
9944     return false;
9945 
9946   unsigned DiagID = 0;
9947   bool NeedType = false;
9948   switch (IsLV) { // C99 6.5.16p2
9949   case Expr::MLV_ConstQualified:
9950     // Use a specialized diagnostic when we're assigning to an object
9951     // from an enclosing function or block.
9952     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9953       if (NCCK == NCCK_Block)
9954         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9955       else
9956         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9957       break;
9958     }
9959 
9960     // In ARC, use some specialized diagnostics for occasions where we
9961     // infer 'const'.  These are always pseudo-strong variables.
9962     if (S.getLangOpts().ObjCAutoRefCount) {
9963       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9964       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9965         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9966 
9967         // Use the normal diagnostic if it's pseudo-__strong but the
9968         // user actually wrote 'const'.
9969         if (var->isARCPseudoStrong() &&
9970             (!var->getTypeSourceInfo() ||
9971              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9972           // There are two pseudo-strong cases:
9973           //  - self
9974           ObjCMethodDecl *method = S.getCurMethodDecl();
9975           if (method && var == method->getSelfDecl())
9976             DiagID = method->isClassMethod()
9977               ? diag::err_typecheck_arc_assign_self_class_method
9978               : diag::err_typecheck_arc_assign_self;
9979 
9980           //  - fast enumeration variables
9981           else
9982             DiagID = diag::err_typecheck_arr_assign_enumeration;
9983 
9984           SourceRange Assign;
9985           if (Loc != OrigLoc)
9986             Assign = SourceRange(OrigLoc, OrigLoc);
9987           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9988           // We need to preserve the AST regardless, so migration tool
9989           // can do its job.
9990           return false;
9991         }
9992       }
9993     }
9994 
9995     // If none of the special cases above are triggered, then this is a
9996     // simple const assignment.
9997     if (DiagID == 0) {
9998       DiagnoseConstAssignment(S, E, Loc);
9999       return true;
10000     }
10001 
10002     break;
10003   case Expr::MLV_ConstAddrSpace:
10004     DiagnoseConstAssignment(S, E, Loc);
10005     return true;
10006   case Expr::MLV_ArrayType:
10007   case Expr::MLV_ArrayTemporary:
10008     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
10009     NeedType = true;
10010     break;
10011   case Expr::MLV_NotObjectType:
10012     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
10013     NeedType = true;
10014     break;
10015   case Expr::MLV_LValueCast:
10016     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
10017     break;
10018   case Expr::MLV_Valid:
10019     llvm_unreachable("did not take early return for MLV_Valid");
10020   case Expr::MLV_InvalidExpression:
10021   case Expr::MLV_MemberFunction:
10022   case Expr::MLV_ClassTemporary:
10023     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
10024     break;
10025   case Expr::MLV_IncompleteType:
10026   case Expr::MLV_IncompleteVoidType:
10027     return S.RequireCompleteType(Loc, E->getType(),
10028              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
10029   case Expr::MLV_DuplicateVectorComponents:
10030     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
10031     break;
10032   case Expr::MLV_NoSetterProperty:
10033     llvm_unreachable("readonly properties should be processed differently");
10034   case Expr::MLV_InvalidMessageExpression:
10035     DiagID = diag::error_readonly_message_assignment;
10036     break;
10037   case Expr::MLV_SubObjCPropertySetting:
10038     DiagID = diag::error_no_subobject_property_setting;
10039     break;
10040   }
10041 
10042   SourceRange Assign;
10043   if (Loc != OrigLoc)
10044     Assign = SourceRange(OrigLoc, OrigLoc);
10045   if (NeedType)
10046     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
10047   else
10048     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
10049   return true;
10050 }
10051 
10052 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
10053                                          SourceLocation Loc,
10054                                          Sema &Sema) {
10055   // C / C++ fields
10056   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
10057   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
10058   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
10059     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
10060       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
10061   }
10062 
10063   // Objective-C instance variables
10064   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
10065   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
10066   if (OL && OR && OL->getDecl() == OR->getDecl()) {
10067     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
10068     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
10069     if (RL && RR && RL->getDecl() == RR->getDecl())
10070       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
10071   }
10072 }
10073 
10074 // C99 6.5.16.1
10075 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
10076                                        SourceLocation Loc,
10077                                        QualType CompoundType) {
10078   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
10079 
10080   // Verify that LHS is a modifiable lvalue, and emit error if not.
10081   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
10082     return QualType();
10083 
10084   QualType LHSType = LHSExpr->getType();
10085   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
10086                                              CompoundType;
10087   AssignConvertType ConvTy;
10088   if (CompoundType.isNull()) {
10089     Expr *RHSCheck = RHS.get();
10090 
10091     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
10092 
10093     QualType LHSTy(LHSType);
10094     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
10095     if (RHS.isInvalid())
10096       return QualType();
10097     // Special case of NSObject attributes on c-style pointer types.
10098     if (ConvTy == IncompatiblePointer &&
10099         ((Context.isObjCNSObjectType(LHSType) &&
10100           RHSType->isObjCObjectPointerType()) ||
10101          (Context.isObjCNSObjectType(RHSType) &&
10102           LHSType->isObjCObjectPointerType())))
10103       ConvTy = Compatible;
10104 
10105     if (ConvTy == Compatible &&
10106         LHSType->isObjCObjectType())
10107         Diag(Loc, diag::err_objc_object_assignment)
10108           << LHSType;
10109 
10110     // If the RHS is a unary plus or minus, check to see if they = and + are
10111     // right next to each other.  If so, the user may have typo'd "x =+ 4"
10112     // instead of "x += 4".
10113     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
10114       RHSCheck = ICE->getSubExpr();
10115     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
10116       if ((UO->getOpcode() == UO_Plus ||
10117            UO->getOpcode() == UO_Minus) &&
10118           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
10119           // Only if the two operators are exactly adjacent.
10120           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
10121           // And there is a space or other character before the subexpr of the
10122           // unary +/-.  We don't want to warn on "x=-1".
10123           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
10124           UO->getSubExpr()->getLocStart().isFileID()) {
10125         Diag(Loc, diag::warn_not_compound_assign)
10126           << (UO->getOpcode() == UO_Plus ? "+" : "-")
10127           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
10128       }
10129     }
10130 
10131     if (ConvTy == Compatible) {
10132       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
10133         // Warn about retain cycles where a block captures the LHS, but
10134         // not if the LHS is a simple variable into which the block is
10135         // being stored...unless that variable can be captured by reference!
10136         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
10137         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
10138         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
10139           checkRetainCycles(LHSExpr, RHS.get());
10140 
10141         // It is safe to assign a weak reference into a strong variable.
10142         // Although this code can still have problems:
10143         //   id x = self.weakProp;
10144         //   id y = self.weakProp;
10145         // we do not warn to warn spuriously when 'x' and 'y' are on separate
10146         // paths through the function. This should be revisited if
10147         // -Wrepeated-use-of-weak is made flow-sensitive.
10148         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10149                              RHS.get()->getLocStart()))
10150           getCurFunction()->markSafeWeakUse(RHS.get());
10151 
10152       } else if (getLangOpts().ObjCAutoRefCount) {
10153         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
10154       }
10155     }
10156   } else {
10157     // Compound assignment "x += y"
10158     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
10159   }
10160 
10161   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
10162                                RHS.get(), AA_Assigning))
10163     return QualType();
10164 
10165   CheckForNullPointerDereference(*this, LHSExpr);
10166 
10167   // C99 6.5.16p3: The type of an assignment expression is the type of the
10168   // left operand unless the left operand has qualified type, in which case
10169   // it is the unqualified version of the type of the left operand.
10170   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
10171   // is converted to the type of the assignment expression (above).
10172   // C++ 5.17p1: the type of the assignment expression is that of its left
10173   // operand.
10174   return (getLangOpts().CPlusPlus
10175           ? LHSType : LHSType.getUnqualifiedType());
10176 }
10177 
10178 // Only ignore explicit casts to void.
10179 static bool IgnoreCommaOperand(const Expr *E) {
10180   E = E->IgnoreParens();
10181 
10182   if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
10183     if (CE->getCastKind() == CK_ToVoid) {
10184       return true;
10185     }
10186   }
10187 
10188   return false;
10189 }
10190 
10191 // Look for instances where it is likely the comma operator is confused with
10192 // another operator.  There is a whitelist of acceptable expressions for the
10193 // left hand side of the comma operator, otherwise emit a warning.
10194 void Sema::DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc) {
10195   // No warnings in macros
10196   if (Loc.isMacroID())
10197     return;
10198 
10199   // Don't warn in template instantiations.
10200   if (!ActiveTemplateInstantiations.empty())
10201     return;
10202 
10203   // Scope isn't fine-grained enough to whitelist the specific cases, so
10204   // instead, skip more than needed, then call back into here with the
10205   // CommaVisitor in SemaStmt.cpp.
10206   // The whitelisted locations are the initialization and increment portions
10207   // of a for loop.  The additional checks are on the condition of
10208   // if statements, do/while loops, and for loops.
10209   const unsigned ForIncrementFlags =
10210       Scope::ControlScope | Scope::ContinueScope | Scope::BreakScope;
10211   const unsigned ForInitFlags = Scope::ControlScope | Scope::DeclScope;
10212   const unsigned ScopeFlags = getCurScope()->getFlags();
10213   if ((ScopeFlags & ForIncrementFlags) == ForIncrementFlags ||
10214       (ScopeFlags & ForInitFlags) == ForInitFlags)
10215     return;
10216 
10217   // If there are multiple comma operators used together, get the RHS of the
10218   // of the comma operator as the LHS.
10219   while (const BinaryOperator *BO = dyn_cast<BinaryOperator>(LHS)) {
10220     if (BO->getOpcode() != BO_Comma)
10221       break;
10222     LHS = BO->getRHS();
10223   }
10224 
10225   // Only allow some expressions on LHS to not warn.
10226   if (IgnoreCommaOperand(LHS))
10227     return;
10228 
10229   Diag(Loc, diag::warn_comma_operator);
10230   Diag(LHS->getLocStart(), diag::note_cast_to_void)
10231       << LHS->getSourceRange()
10232       << FixItHint::CreateInsertion(LHS->getLocStart(),
10233                                     LangOpts.CPlusPlus ? "static_cast<void>("
10234                                                        : "(void)(")
10235       << FixItHint::CreateInsertion(PP.getLocForEndOfToken(LHS->getLocEnd()),
10236                                     ")");
10237 }
10238 
10239 // C99 6.5.17
10240 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
10241                                    SourceLocation Loc) {
10242   LHS = S.CheckPlaceholderExpr(LHS.get());
10243   RHS = S.CheckPlaceholderExpr(RHS.get());
10244   if (LHS.isInvalid() || RHS.isInvalid())
10245     return QualType();
10246 
10247   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
10248   // operands, but not unary promotions.
10249   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
10250 
10251   // So we treat the LHS as a ignored value, and in C++ we allow the
10252   // containing site to determine what should be done with the RHS.
10253   LHS = S.IgnoredValueConversions(LHS.get());
10254   if (LHS.isInvalid())
10255     return QualType();
10256 
10257   S.DiagnoseUnusedExprResult(LHS.get());
10258 
10259   if (!S.getLangOpts().CPlusPlus) {
10260     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
10261     if (RHS.isInvalid())
10262       return QualType();
10263     if (!RHS.get()->getType()->isVoidType())
10264       S.RequireCompleteType(Loc, RHS.get()->getType(),
10265                             diag::err_incomplete_type);
10266   }
10267 
10268   if (!S.getDiagnostics().isIgnored(diag::warn_comma_operator, Loc))
10269     S.DiagnoseCommaOperator(LHS.get(), Loc);
10270 
10271   return RHS.get()->getType();
10272 }
10273 
10274 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
10275 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
10276 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
10277                                                ExprValueKind &VK,
10278                                                ExprObjectKind &OK,
10279                                                SourceLocation OpLoc,
10280                                                bool IsInc, bool IsPrefix) {
10281   if (Op->isTypeDependent())
10282     return S.Context.DependentTy;
10283 
10284   QualType ResType = Op->getType();
10285   // Atomic types can be used for increment / decrement where the non-atomic
10286   // versions can, so ignore the _Atomic() specifier for the purpose of
10287   // checking.
10288   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
10289     ResType = ResAtomicType->getValueType();
10290 
10291   assert(!ResType.isNull() && "no type for increment/decrement expression");
10292 
10293   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
10294     // Decrement of bool is not allowed.
10295     if (!IsInc) {
10296       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
10297       return QualType();
10298     }
10299     // Increment of bool sets it to true, but is deprecated.
10300     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
10301                                               : diag::warn_increment_bool)
10302       << Op->getSourceRange();
10303   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
10304     // Error on enum increments and decrements in C++ mode
10305     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
10306     return QualType();
10307   } else if (ResType->isRealType()) {
10308     // OK!
10309   } else if (ResType->isPointerType()) {
10310     // C99 6.5.2.4p2, 6.5.6p2
10311     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
10312       return QualType();
10313   } else if (ResType->isObjCObjectPointerType()) {
10314     // On modern runtimes, ObjC pointer arithmetic is forbidden.
10315     // Otherwise, we just need a complete type.
10316     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
10317         checkArithmeticOnObjCPointer(S, OpLoc, Op))
10318       return QualType();
10319   } else if (ResType->isAnyComplexType()) {
10320     // C99 does not support ++/-- on complex types, we allow as an extension.
10321     S.Diag(OpLoc, diag::ext_integer_increment_complex)
10322       << ResType << Op->getSourceRange();
10323   } else if (ResType->isPlaceholderType()) {
10324     ExprResult PR = S.CheckPlaceholderExpr(Op);
10325     if (PR.isInvalid()) return QualType();
10326     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
10327                                           IsInc, IsPrefix);
10328   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
10329     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
10330   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
10331              (ResType->getAs<VectorType>()->getVectorKind() !=
10332               VectorType::AltiVecBool)) {
10333     // The z vector extensions allow ++ and -- for non-bool vectors.
10334   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
10335             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
10336     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
10337   } else {
10338     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
10339       << ResType << int(IsInc) << Op->getSourceRange();
10340     return QualType();
10341   }
10342   // At this point, we know we have a real, complex or pointer type.
10343   // Now make sure the operand is a modifiable lvalue.
10344   if (CheckForModifiableLvalue(Op, OpLoc, S))
10345     return QualType();
10346   // In C++, a prefix increment is the same type as the operand. Otherwise
10347   // (in C or with postfix), the increment is the unqualified type of the
10348   // operand.
10349   if (IsPrefix && S.getLangOpts().CPlusPlus) {
10350     VK = VK_LValue;
10351     OK = Op->getObjectKind();
10352     return ResType;
10353   } else {
10354     VK = VK_RValue;
10355     return ResType.getUnqualifiedType();
10356   }
10357 }
10358 
10359 
10360 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
10361 /// This routine allows us to typecheck complex/recursive expressions
10362 /// where the declaration is needed for type checking. We only need to
10363 /// handle cases when the expression references a function designator
10364 /// or is an lvalue. Here are some examples:
10365 ///  - &(x) => x
10366 ///  - &*****f => f for f a function designator.
10367 ///  - &s.xx => s
10368 ///  - &s.zz[1].yy -> s, if zz is an array
10369 ///  - *(x + 1) -> x, if x is an array
10370 ///  - &"123"[2] -> 0
10371 ///  - & __real__ x -> x
10372 static ValueDecl *getPrimaryDecl(Expr *E) {
10373   switch (E->getStmtClass()) {
10374   case Stmt::DeclRefExprClass:
10375     return cast<DeclRefExpr>(E)->getDecl();
10376   case Stmt::MemberExprClass:
10377     // If this is an arrow operator, the address is an offset from
10378     // the base's value, so the object the base refers to is
10379     // irrelevant.
10380     if (cast<MemberExpr>(E)->isArrow())
10381       return nullptr;
10382     // Otherwise, the expression refers to a part of the base
10383     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
10384   case Stmt::ArraySubscriptExprClass: {
10385     // FIXME: This code shouldn't be necessary!  We should catch the implicit
10386     // promotion of register arrays earlier.
10387     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
10388     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
10389       if (ICE->getSubExpr()->getType()->isArrayType())
10390         return getPrimaryDecl(ICE->getSubExpr());
10391     }
10392     return nullptr;
10393   }
10394   case Stmt::UnaryOperatorClass: {
10395     UnaryOperator *UO = cast<UnaryOperator>(E);
10396 
10397     switch(UO->getOpcode()) {
10398     case UO_Real:
10399     case UO_Imag:
10400     case UO_Extension:
10401       return getPrimaryDecl(UO->getSubExpr());
10402     default:
10403       return nullptr;
10404     }
10405   }
10406   case Stmt::ParenExprClass:
10407     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
10408   case Stmt::ImplicitCastExprClass:
10409     // If the result of an implicit cast is an l-value, we care about
10410     // the sub-expression; otherwise, the result here doesn't matter.
10411     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
10412   default:
10413     return nullptr;
10414   }
10415 }
10416 
10417 namespace {
10418   enum {
10419     AO_Bit_Field = 0,
10420     AO_Vector_Element = 1,
10421     AO_Property_Expansion = 2,
10422     AO_Register_Variable = 3,
10423     AO_No_Error = 4
10424   };
10425 }
10426 /// \brief Diagnose invalid operand for address of operations.
10427 ///
10428 /// \param Type The type of operand which cannot have its address taken.
10429 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
10430                                          Expr *E, unsigned Type) {
10431   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
10432 }
10433 
10434 /// CheckAddressOfOperand - The operand of & must be either a function
10435 /// designator or an lvalue designating an object. If it is an lvalue, the
10436 /// object cannot be declared with storage class register or be a bit field.
10437 /// Note: The usual conversions are *not* applied to the operand of the &
10438 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
10439 /// In C++, the operand might be an overloaded function name, in which case
10440 /// we allow the '&' but retain the overloaded-function type.
10441 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
10442   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
10443     if (PTy->getKind() == BuiltinType::Overload) {
10444       Expr *E = OrigOp.get()->IgnoreParens();
10445       if (!isa<OverloadExpr>(E)) {
10446         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
10447         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
10448           << OrigOp.get()->getSourceRange();
10449         return QualType();
10450       }
10451 
10452       OverloadExpr *Ovl = cast<OverloadExpr>(E);
10453       if (isa<UnresolvedMemberExpr>(Ovl))
10454         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
10455           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10456             << OrigOp.get()->getSourceRange();
10457           return QualType();
10458         }
10459 
10460       return Context.OverloadTy;
10461     }
10462 
10463     if (PTy->getKind() == BuiltinType::UnknownAny)
10464       return Context.UnknownAnyTy;
10465 
10466     if (PTy->getKind() == BuiltinType::BoundMember) {
10467       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10468         << OrigOp.get()->getSourceRange();
10469       return QualType();
10470     }
10471 
10472     OrigOp = CheckPlaceholderExpr(OrigOp.get());
10473     if (OrigOp.isInvalid()) return QualType();
10474   }
10475 
10476   if (OrigOp.get()->isTypeDependent())
10477     return Context.DependentTy;
10478 
10479   assert(!OrigOp.get()->getType()->isPlaceholderType());
10480 
10481   // Make sure to ignore parentheses in subsequent checks
10482   Expr *op = OrigOp.get()->IgnoreParens();
10483 
10484   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
10485   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
10486     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
10487     return QualType();
10488   }
10489 
10490   if (getLangOpts().C99) {
10491     // Implement C99-only parts of addressof rules.
10492     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
10493       if (uOp->getOpcode() == UO_Deref)
10494         // Per C99 6.5.3.2, the address of a deref always returns a valid result
10495         // (assuming the deref expression is valid).
10496         return uOp->getSubExpr()->getType();
10497     }
10498     // Technically, there should be a check for array subscript
10499     // expressions here, but the result of one is always an lvalue anyway.
10500   }
10501   ValueDecl *dcl = getPrimaryDecl(op);
10502 
10503   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
10504     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
10505                                            op->getLocStart()))
10506       return QualType();
10507 
10508   Expr::LValueClassification lval = op->ClassifyLValue(Context);
10509   unsigned AddressOfError = AO_No_Error;
10510 
10511   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
10512     bool sfinae = (bool)isSFINAEContext();
10513     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
10514                                   : diag::ext_typecheck_addrof_temporary)
10515       << op->getType() << op->getSourceRange();
10516     if (sfinae)
10517       return QualType();
10518     // Materialize the temporary as an lvalue so that we can take its address.
10519     OrigOp = op =
10520         CreateMaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
10521   } else if (isa<ObjCSelectorExpr>(op)) {
10522     return Context.getPointerType(op->getType());
10523   } else if (lval == Expr::LV_MemberFunction) {
10524     // If it's an instance method, make a member pointer.
10525     // The expression must have exactly the form &A::foo.
10526 
10527     // If the underlying expression isn't a decl ref, give up.
10528     if (!isa<DeclRefExpr>(op)) {
10529       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
10530         << OrigOp.get()->getSourceRange();
10531       return QualType();
10532     }
10533     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
10534     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
10535 
10536     // The id-expression was parenthesized.
10537     if (OrigOp.get() != DRE) {
10538       Diag(OpLoc, diag::err_parens_pointer_member_function)
10539         << OrigOp.get()->getSourceRange();
10540 
10541     // The method was named without a qualifier.
10542     } else if (!DRE->getQualifier()) {
10543       if (MD->getParent()->getName().empty())
10544         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10545           << op->getSourceRange();
10546       else {
10547         SmallString<32> Str;
10548         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
10549         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
10550           << op->getSourceRange()
10551           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
10552       }
10553     }
10554 
10555     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
10556     if (isa<CXXDestructorDecl>(MD))
10557       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
10558 
10559     QualType MPTy = Context.getMemberPointerType(
10560         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
10561     // Under the MS ABI, lock down the inheritance model now.
10562     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10563       (void)isCompleteType(OpLoc, MPTy);
10564     return MPTy;
10565   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
10566     // C99 6.5.3.2p1
10567     // The operand must be either an l-value or a function designator
10568     if (!op->getType()->isFunctionType()) {
10569       // Use a special diagnostic for loads from property references.
10570       if (isa<PseudoObjectExpr>(op)) {
10571         AddressOfError = AO_Property_Expansion;
10572       } else {
10573         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
10574           << op->getType() << op->getSourceRange();
10575         return QualType();
10576       }
10577     }
10578   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
10579     // The operand cannot be a bit-field
10580     AddressOfError = AO_Bit_Field;
10581   } else if (op->getObjectKind() == OK_VectorComponent) {
10582     // The operand cannot be an element of a vector
10583     AddressOfError = AO_Vector_Element;
10584   } else if (dcl) { // C99 6.5.3.2p1
10585     // We have an lvalue with a decl. Make sure the decl is not declared
10586     // with the register storage-class specifier.
10587     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
10588       // in C++ it is not error to take address of a register
10589       // variable (c++03 7.1.1P3)
10590       if (vd->getStorageClass() == SC_Register &&
10591           !getLangOpts().CPlusPlus) {
10592         AddressOfError = AO_Register_Variable;
10593       }
10594     } else if (isa<MSPropertyDecl>(dcl)) {
10595       AddressOfError = AO_Property_Expansion;
10596     } else if (isa<FunctionTemplateDecl>(dcl)) {
10597       return Context.OverloadTy;
10598     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
10599       // Okay: we can take the address of a field.
10600       // Could be a pointer to member, though, if there is an explicit
10601       // scope qualifier for the class.
10602       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
10603         DeclContext *Ctx = dcl->getDeclContext();
10604         if (Ctx && Ctx->isRecord()) {
10605           if (dcl->getType()->isReferenceType()) {
10606             Diag(OpLoc,
10607                  diag::err_cannot_form_pointer_to_member_of_reference_type)
10608               << dcl->getDeclName() << dcl->getType();
10609             return QualType();
10610           }
10611 
10612           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10613             Ctx = Ctx->getParent();
10614 
10615           QualType MPTy = Context.getMemberPointerType(
10616               op->getType(),
10617               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10618           // Under the MS ABI, lock down the inheritance model now.
10619           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10620             (void)isCompleteType(OpLoc, MPTy);
10621           return MPTy;
10622         }
10623       }
10624     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl) &&
10625                !isa<BindingDecl>(dcl))
10626       llvm_unreachable("Unknown/unexpected decl type");
10627   }
10628 
10629   if (AddressOfError != AO_No_Error) {
10630     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10631     return QualType();
10632   }
10633 
10634   if (lval == Expr::LV_IncompleteVoidType) {
10635     // Taking the address of a void variable is technically illegal, but we
10636     // allow it in cases which are otherwise valid.
10637     // Example: "extern void x; void* y = &x;".
10638     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10639   }
10640 
10641   // If the operand has type "type", the result has type "pointer to type".
10642   if (op->getType()->isObjCObjectType())
10643     return Context.getObjCObjectPointerType(op->getType());
10644 
10645   CheckAddressOfPackedMember(op);
10646 
10647   return Context.getPointerType(op->getType());
10648 }
10649 
10650 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10651   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10652   if (!DRE)
10653     return;
10654   const Decl *D = DRE->getDecl();
10655   if (!D)
10656     return;
10657   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10658   if (!Param)
10659     return;
10660   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10661     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10662       return;
10663   if (FunctionScopeInfo *FD = S.getCurFunction())
10664     if (!FD->ModifiedNonNullParams.count(Param))
10665       FD->ModifiedNonNullParams.insert(Param);
10666 }
10667 
10668 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10669 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10670                                         SourceLocation OpLoc) {
10671   if (Op->isTypeDependent())
10672     return S.Context.DependentTy;
10673 
10674   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10675   if (ConvResult.isInvalid())
10676     return QualType();
10677   Op = ConvResult.get();
10678   QualType OpTy = Op->getType();
10679   QualType Result;
10680 
10681   if (isa<CXXReinterpretCastExpr>(Op)) {
10682     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10683     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10684                                      Op->getSourceRange());
10685   }
10686 
10687   if (const PointerType *PT = OpTy->getAs<PointerType>())
10688   {
10689     Result = PT->getPointeeType();
10690   }
10691   else if (const ObjCObjectPointerType *OPT =
10692              OpTy->getAs<ObjCObjectPointerType>())
10693     Result = OPT->getPointeeType();
10694   else {
10695     ExprResult PR = S.CheckPlaceholderExpr(Op);
10696     if (PR.isInvalid()) return QualType();
10697     if (PR.get() != Op)
10698       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10699   }
10700 
10701   if (Result.isNull()) {
10702     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10703       << OpTy << Op->getSourceRange();
10704     return QualType();
10705   }
10706 
10707   // Note that per both C89 and C99, indirection is always legal, even if Result
10708   // is an incomplete type or void.  It would be possible to warn about
10709   // dereferencing a void pointer, but it's completely well-defined, and such a
10710   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10711   // for pointers to 'void' but is fine for any other pointer type:
10712   //
10713   // C++ [expr.unary.op]p1:
10714   //   [...] the expression to which [the unary * operator] is applied shall
10715   //   be a pointer to an object type, or a pointer to a function type
10716   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10717     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10718       << OpTy << Op->getSourceRange();
10719 
10720   // Dereferences are usually l-values...
10721   VK = VK_LValue;
10722 
10723   // ...except that certain expressions are never l-values in C.
10724   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10725     VK = VK_RValue;
10726 
10727   return Result;
10728 }
10729 
10730 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10731   BinaryOperatorKind Opc;
10732   switch (Kind) {
10733   default: llvm_unreachable("Unknown binop!");
10734   case tok::periodstar:           Opc = BO_PtrMemD; break;
10735   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10736   case tok::star:                 Opc = BO_Mul; break;
10737   case tok::slash:                Opc = BO_Div; break;
10738   case tok::percent:              Opc = BO_Rem; break;
10739   case tok::plus:                 Opc = BO_Add; break;
10740   case tok::minus:                Opc = BO_Sub; break;
10741   case tok::lessless:             Opc = BO_Shl; break;
10742   case tok::greatergreater:       Opc = BO_Shr; break;
10743   case tok::lessequal:            Opc = BO_LE; break;
10744   case tok::less:                 Opc = BO_LT; break;
10745   case tok::greaterequal:         Opc = BO_GE; break;
10746   case tok::greater:              Opc = BO_GT; break;
10747   case tok::exclaimequal:         Opc = BO_NE; break;
10748   case tok::equalequal:           Opc = BO_EQ; break;
10749   case tok::amp:                  Opc = BO_And; break;
10750   case tok::caret:                Opc = BO_Xor; break;
10751   case tok::pipe:                 Opc = BO_Or; break;
10752   case tok::ampamp:               Opc = BO_LAnd; break;
10753   case tok::pipepipe:             Opc = BO_LOr; break;
10754   case tok::equal:                Opc = BO_Assign; break;
10755   case tok::starequal:            Opc = BO_MulAssign; break;
10756   case tok::slashequal:           Opc = BO_DivAssign; break;
10757   case tok::percentequal:         Opc = BO_RemAssign; break;
10758   case tok::plusequal:            Opc = BO_AddAssign; break;
10759   case tok::minusequal:           Opc = BO_SubAssign; break;
10760   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10761   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10762   case tok::ampequal:             Opc = BO_AndAssign; break;
10763   case tok::caretequal:           Opc = BO_XorAssign; break;
10764   case tok::pipeequal:            Opc = BO_OrAssign; break;
10765   case tok::comma:                Opc = BO_Comma; break;
10766   }
10767   return Opc;
10768 }
10769 
10770 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10771   tok::TokenKind Kind) {
10772   UnaryOperatorKind Opc;
10773   switch (Kind) {
10774   default: llvm_unreachable("Unknown unary op!");
10775   case tok::plusplus:     Opc = UO_PreInc; break;
10776   case tok::minusminus:   Opc = UO_PreDec; break;
10777   case tok::amp:          Opc = UO_AddrOf; break;
10778   case tok::star:         Opc = UO_Deref; break;
10779   case tok::plus:         Opc = UO_Plus; break;
10780   case tok::minus:        Opc = UO_Minus; break;
10781   case tok::tilde:        Opc = UO_Not; break;
10782   case tok::exclaim:      Opc = UO_LNot; break;
10783   case tok::kw___real:    Opc = UO_Real; break;
10784   case tok::kw___imag:    Opc = UO_Imag; break;
10785   case tok::kw___extension__: Opc = UO_Extension; break;
10786   }
10787   return Opc;
10788 }
10789 
10790 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10791 /// This warning is only emitted for builtin assignment operations. It is also
10792 /// suppressed in the event of macro expansions.
10793 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10794                                    SourceLocation OpLoc) {
10795   if (!S.ActiveTemplateInstantiations.empty())
10796     return;
10797   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10798     return;
10799   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10800   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10801   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10802   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10803   if (!LHSDeclRef || !RHSDeclRef ||
10804       LHSDeclRef->getLocation().isMacroID() ||
10805       RHSDeclRef->getLocation().isMacroID())
10806     return;
10807   const ValueDecl *LHSDecl =
10808     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10809   const ValueDecl *RHSDecl =
10810     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10811   if (LHSDecl != RHSDecl)
10812     return;
10813   if (LHSDecl->getType().isVolatileQualified())
10814     return;
10815   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10816     if (RefTy->getPointeeType().isVolatileQualified())
10817       return;
10818 
10819   S.Diag(OpLoc, diag::warn_self_assignment)
10820       << LHSDeclRef->getType()
10821       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10822 }
10823 
10824 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10825 /// is usually indicative of introspection within the Objective-C pointer.
10826 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10827                                           SourceLocation OpLoc) {
10828   if (!S.getLangOpts().ObjC1)
10829     return;
10830 
10831   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10832   const Expr *LHS = L.get();
10833   const Expr *RHS = R.get();
10834 
10835   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10836     ObjCPointerExpr = LHS;
10837     OtherExpr = RHS;
10838   }
10839   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10840     ObjCPointerExpr = RHS;
10841     OtherExpr = LHS;
10842   }
10843 
10844   // This warning is deliberately made very specific to reduce false
10845   // positives with logic that uses '&' for hashing.  This logic mainly
10846   // looks for code trying to introspect into tagged pointers, which
10847   // code should generally never do.
10848   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10849     unsigned Diag = diag::warn_objc_pointer_masking;
10850     // Determine if we are introspecting the result of performSelectorXXX.
10851     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10852     // Special case messages to -performSelector and friends, which
10853     // can return non-pointer values boxed in a pointer value.
10854     // Some clients may wish to silence warnings in this subcase.
10855     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10856       Selector S = ME->getSelector();
10857       StringRef SelArg0 = S.getNameForSlot(0);
10858       if (SelArg0.startswith("performSelector"))
10859         Diag = diag::warn_objc_pointer_masking_performSelector;
10860     }
10861 
10862     S.Diag(OpLoc, Diag)
10863       << ObjCPointerExpr->getSourceRange();
10864   }
10865 }
10866 
10867 static NamedDecl *getDeclFromExpr(Expr *E) {
10868   if (!E)
10869     return nullptr;
10870   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10871     return DRE->getDecl();
10872   if (auto *ME = dyn_cast<MemberExpr>(E))
10873     return ME->getMemberDecl();
10874   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10875     return IRE->getDecl();
10876   return nullptr;
10877 }
10878 
10879 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10880 /// operator @p Opc at location @c TokLoc. This routine only supports
10881 /// built-in operations; ActOnBinOp handles overloaded operators.
10882 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10883                                     BinaryOperatorKind Opc,
10884                                     Expr *LHSExpr, Expr *RHSExpr) {
10885   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10886     // The syntax only allows initializer lists on the RHS of assignment,
10887     // so we don't need to worry about accepting invalid code for
10888     // non-assignment operators.
10889     // C++11 5.17p9:
10890     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10891     //   of x = {} is x = T().
10892     InitializationKind Kind =
10893         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10894     InitializedEntity Entity =
10895         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10896     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10897     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10898     if (Init.isInvalid())
10899       return Init;
10900     RHSExpr = Init.get();
10901   }
10902 
10903   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10904   QualType ResultTy;     // Result type of the binary operator.
10905   // The following two variables are used for compound assignment operators
10906   QualType CompLHSTy;    // Type of LHS after promotions for computation
10907   QualType CompResultTy; // Type of computation result
10908   ExprValueKind VK = VK_RValue;
10909   ExprObjectKind OK = OK_Ordinary;
10910 
10911   if (!getLangOpts().CPlusPlus) {
10912     // C cannot handle TypoExpr nodes on either side of a binop because it
10913     // doesn't handle dependent types properly, so make sure any TypoExprs have
10914     // been dealt with before checking the operands.
10915     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10916     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10917       if (Opc != BO_Assign)
10918         return ExprResult(E);
10919       // Avoid correcting the RHS to the same Expr as the LHS.
10920       Decl *D = getDeclFromExpr(E);
10921       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10922     });
10923     if (!LHS.isUsable() || !RHS.isUsable())
10924       return ExprError();
10925   }
10926 
10927   if (getLangOpts().OpenCL) {
10928     QualType LHSTy = LHSExpr->getType();
10929     QualType RHSTy = RHSExpr->getType();
10930     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10931     // the ATOMIC_VAR_INIT macro.
10932     if (LHSTy->isAtomicType() || RHSTy->isAtomicType()) {
10933       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10934       if (BO_Assign == Opc)
10935         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10936       else
10937         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10938       return ExprError();
10939     }
10940 
10941     // OpenCL special types - image, sampler, pipe, and blocks are to be used
10942     // only with a builtin functions and therefore should be disallowed here.
10943     if (LHSTy->isImageType() || RHSTy->isImageType() ||
10944         LHSTy->isSamplerT() || RHSTy->isSamplerT() ||
10945         LHSTy->isPipeType() || RHSTy->isPipeType() ||
10946         LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
10947       ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10948       return ExprError();
10949     }
10950   }
10951 
10952   switch (Opc) {
10953   case BO_Assign:
10954     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10955     if (getLangOpts().CPlusPlus &&
10956         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10957       VK = LHS.get()->getValueKind();
10958       OK = LHS.get()->getObjectKind();
10959     }
10960     if (!ResultTy.isNull()) {
10961       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10962       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10963     }
10964     RecordModifiableNonNullParam(*this, LHS.get());
10965     break;
10966   case BO_PtrMemD:
10967   case BO_PtrMemI:
10968     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10969                                             Opc == BO_PtrMemI);
10970     break;
10971   case BO_Mul:
10972   case BO_Div:
10973     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10974                                            Opc == BO_Div);
10975     break;
10976   case BO_Rem:
10977     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10978     break;
10979   case BO_Add:
10980     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10981     break;
10982   case BO_Sub:
10983     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10984     break;
10985   case BO_Shl:
10986   case BO_Shr:
10987     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10988     break;
10989   case BO_LE:
10990   case BO_LT:
10991   case BO_GE:
10992   case BO_GT:
10993     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10994     break;
10995   case BO_EQ:
10996   case BO_NE:
10997     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10998     break;
10999   case BO_And:
11000     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
11001   case BO_Xor:
11002   case BO_Or:
11003     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
11004     break;
11005   case BO_LAnd:
11006   case BO_LOr:
11007     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
11008     break;
11009   case BO_MulAssign:
11010   case BO_DivAssign:
11011     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
11012                                                Opc == BO_DivAssign);
11013     CompLHSTy = CompResultTy;
11014     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11015       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11016     break;
11017   case BO_RemAssign:
11018     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
11019     CompLHSTy = CompResultTy;
11020     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11021       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11022     break;
11023   case BO_AddAssign:
11024     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
11025     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11026       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11027     break;
11028   case BO_SubAssign:
11029     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
11030     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11031       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11032     break;
11033   case BO_ShlAssign:
11034   case BO_ShrAssign:
11035     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
11036     CompLHSTy = CompResultTy;
11037     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11038       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11039     break;
11040   case BO_AndAssign:
11041   case BO_OrAssign: // fallthrough
11042     DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
11043   case BO_XorAssign:
11044     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
11045     CompLHSTy = CompResultTy;
11046     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
11047       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
11048     break;
11049   case BO_Comma:
11050     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
11051     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
11052       VK = RHS.get()->getValueKind();
11053       OK = RHS.get()->getObjectKind();
11054     }
11055     break;
11056   }
11057   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
11058     return ExprError();
11059 
11060   // Check for array bounds violations for both sides of the BinaryOperator
11061   CheckArrayAccess(LHS.get());
11062   CheckArrayAccess(RHS.get());
11063 
11064   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
11065     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
11066                                                  &Context.Idents.get("object_setClass"),
11067                                                  SourceLocation(), LookupOrdinaryName);
11068     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
11069       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
11070       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
11071       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
11072       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
11073       FixItHint::CreateInsertion(RHSLocEnd, ")");
11074     }
11075     else
11076       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
11077   }
11078   else if (const ObjCIvarRefExpr *OIRE =
11079            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
11080     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
11081 
11082   if (CompResultTy.isNull())
11083     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
11084                                         OK, OpLoc, FPFeatures.fp_contract);
11085   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
11086       OK_ObjCProperty) {
11087     VK = VK_LValue;
11088     OK = LHS.get()->getObjectKind();
11089   }
11090   return new (Context) CompoundAssignOperator(
11091       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
11092       OpLoc, FPFeatures.fp_contract);
11093 }
11094 
11095 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
11096 /// operators are mixed in a way that suggests that the programmer forgot that
11097 /// comparison operators have higher precedence. The most typical example of
11098 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
11099 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
11100                                       SourceLocation OpLoc, Expr *LHSExpr,
11101                                       Expr *RHSExpr) {
11102   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
11103   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
11104 
11105   // Check that one of the sides is a comparison operator and the other isn't.
11106   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
11107   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
11108   if (isLeftComp == isRightComp)
11109     return;
11110 
11111   // Bitwise operations are sometimes used as eager logical ops.
11112   // Don't diagnose this.
11113   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
11114   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
11115   if (isLeftBitwise || isRightBitwise)
11116     return;
11117 
11118   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
11119                                                    OpLoc)
11120                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
11121   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
11122   SourceRange ParensRange = isLeftComp ?
11123       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
11124     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
11125 
11126   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
11127     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
11128   SuggestParentheses(Self, OpLoc,
11129     Self.PDiag(diag::note_precedence_silence) << OpStr,
11130     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
11131   SuggestParentheses(Self, OpLoc,
11132     Self.PDiag(diag::note_precedence_bitwise_first)
11133       << BinaryOperator::getOpcodeStr(Opc),
11134     ParensRange);
11135 }
11136 
11137 /// \brief It accepts a '&&' expr that is inside a '||' one.
11138 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
11139 /// in parentheses.
11140 static void
11141 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
11142                                        BinaryOperator *Bop) {
11143   assert(Bop->getOpcode() == BO_LAnd);
11144   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
11145       << Bop->getSourceRange() << OpLoc;
11146   SuggestParentheses(Self, Bop->getOperatorLoc(),
11147     Self.PDiag(diag::note_precedence_silence)
11148       << Bop->getOpcodeStr(),
11149     Bop->getSourceRange());
11150 }
11151 
11152 /// \brief Returns true if the given expression can be evaluated as a constant
11153 /// 'true'.
11154 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
11155   bool Res;
11156   return !E->isValueDependent() &&
11157          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
11158 }
11159 
11160 /// \brief Returns true if the given expression can be evaluated as a constant
11161 /// 'false'.
11162 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
11163   bool Res;
11164   return !E->isValueDependent() &&
11165          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
11166 }
11167 
11168 /// \brief Look for '&&' in the left hand of a '||' expr.
11169 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
11170                                              Expr *LHSExpr, Expr *RHSExpr) {
11171   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
11172     if (Bop->getOpcode() == BO_LAnd) {
11173       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
11174       if (EvaluatesAsFalse(S, RHSExpr))
11175         return;
11176       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
11177       if (!EvaluatesAsTrue(S, Bop->getLHS()))
11178         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11179     } else if (Bop->getOpcode() == BO_LOr) {
11180       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
11181         // If it's "a || b && 1 || c" we didn't warn earlier for
11182         // "a || b && 1", but warn now.
11183         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
11184           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
11185       }
11186     }
11187   }
11188 }
11189 
11190 /// \brief Look for '&&' in the right hand of a '||' expr.
11191 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
11192                                              Expr *LHSExpr, Expr *RHSExpr) {
11193   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
11194     if (Bop->getOpcode() == BO_LAnd) {
11195       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
11196       if (EvaluatesAsFalse(S, LHSExpr))
11197         return;
11198       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
11199       if (!EvaluatesAsTrue(S, Bop->getRHS()))
11200         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
11201     }
11202   }
11203 }
11204 
11205 /// \brief Look for bitwise op in the left or right hand of a bitwise op with
11206 /// lower precedence and emit a diagnostic together with a fixit hint that wraps
11207 /// the '&' expression in parentheses.
11208 static void DiagnoseBitwiseOpInBitwiseOp(Sema &S, BinaryOperatorKind Opc,
11209                                          SourceLocation OpLoc, Expr *SubExpr) {
11210   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11211     if (Bop->isBitwiseOp() && Bop->getOpcode() < Opc) {
11212       S.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_op_in_bitwise_op)
11213         << Bop->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc)
11214         << Bop->getSourceRange() << OpLoc;
11215       SuggestParentheses(S, Bop->getOperatorLoc(),
11216         S.PDiag(diag::note_precedence_silence)
11217           << Bop->getOpcodeStr(),
11218         Bop->getSourceRange());
11219     }
11220   }
11221 }
11222 
11223 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
11224                                     Expr *SubExpr, StringRef Shift) {
11225   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
11226     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
11227       StringRef Op = Bop->getOpcodeStr();
11228       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
11229           << Bop->getSourceRange() << OpLoc << Shift << Op;
11230       SuggestParentheses(S, Bop->getOperatorLoc(),
11231           S.PDiag(diag::note_precedence_silence) << Op,
11232           Bop->getSourceRange());
11233     }
11234   }
11235 }
11236 
11237 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
11238                                  Expr *LHSExpr, Expr *RHSExpr) {
11239   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
11240   if (!OCE)
11241     return;
11242 
11243   FunctionDecl *FD = OCE->getDirectCallee();
11244   if (!FD || !FD->isOverloadedOperator())
11245     return;
11246 
11247   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
11248   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
11249     return;
11250 
11251   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
11252       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
11253       << (Kind == OO_LessLess);
11254   SuggestParentheses(S, OCE->getOperatorLoc(),
11255                      S.PDiag(diag::note_precedence_silence)
11256                          << (Kind == OO_LessLess ? "<<" : ">>"),
11257                      OCE->getSourceRange());
11258   SuggestParentheses(S, OpLoc,
11259                      S.PDiag(diag::note_evaluate_comparison_first),
11260                      SourceRange(OCE->getArg(1)->getLocStart(),
11261                                  RHSExpr->getLocEnd()));
11262 }
11263 
11264 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
11265 /// precedence.
11266 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
11267                                     SourceLocation OpLoc, Expr *LHSExpr,
11268                                     Expr *RHSExpr){
11269   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
11270   if (BinaryOperator::isBitwiseOp(Opc))
11271     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
11272 
11273   // Diagnose "arg1 & arg2 | arg3"
11274   if ((Opc == BO_Or || Opc == BO_Xor) &&
11275       !OpLoc.isMacroID()/* Don't warn in macros. */) {
11276     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, LHSExpr);
11277     DiagnoseBitwiseOpInBitwiseOp(Self, Opc, OpLoc, RHSExpr);
11278   }
11279 
11280   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
11281   // We don't warn for 'assert(a || b && "bad")' since this is safe.
11282   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
11283     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
11284     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
11285   }
11286 
11287   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
11288       || Opc == BO_Shr) {
11289     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
11290     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
11291     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
11292   }
11293 
11294   // Warn on overloaded shift operators and comparisons, such as:
11295   // cout << 5 == 4;
11296   if (BinaryOperator::isComparisonOp(Opc))
11297     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
11298 }
11299 
11300 // Binary Operators.  'Tok' is the token for the operator.
11301 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
11302                             tok::TokenKind Kind,
11303                             Expr *LHSExpr, Expr *RHSExpr) {
11304   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
11305   assert(LHSExpr && "ActOnBinOp(): missing left expression");
11306   assert(RHSExpr && "ActOnBinOp(): missing right expression");
11307 
11308   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
11309   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
11310 
11311   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
11312 }
11313 
11314 /// Build an overloaded binary operator expression in the given scope.
11315 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
11316                                        BinaryOperatorKind Opc,
11317                                        Expr *LHS, Expr *RHS) {
11318   // Find all of the overloaded operators visible from this
11319   // point. We perform both an operator-name lookup from the local
11320   // scope and an argument-dependent lookup based on the types of
11321   // the arguments.
11322   UnresolvedSet<16> Functions;
11323   OverloadedOperatorKind OverOp
11324     = BinaryOperator::getOverloadedOperator(Opc);
11325   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
11326     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
11327                                    RHS->getType(), Functions);
11328 
11329   // Build the (potentially-overloaded, potentially-dependent)
11330   // binary operation.
11331   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
11332 }
11333 
11334 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
11335                             BinaryOperatorKind Opc,
11336                             Expr *LHSExpr, Expr *RHSExpr) {
11337   // We want to end up calling one of checkPseudoObjectAssignment
11338   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
11339   // both expressions are overloadable or either is type-dependent),
11340   // or CreateBuiltinBinOp (in any other case).  We also want to get
11341   // any placeholder types out of the way.
11342 
11343   // Handle pseudo-objects in the LHS.
11344   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
11345     // Assignments with a pseudo-object l-value need special analysis.
11346     if (pty->getKind() == BuiltinType::PseudoObject &&
11347         BinaryOperator::isAssignmentOp(Opc))
11348       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
11349 
11350     // Don't resolve overloads if the other type is overloadable.
11351     if (pty->getKind() == BuiltinType::Overload) {
11352       // We can't actually test that if we still have a placeholder,
11353       // though.  Fortunately, none of the exceptions we see in that
11354       // code below are valid when the LHS is an overload set.  Note
11355       // that an overload set can be dependently-typed, but it never
11356       // instantiates to having an overloadable type.
11357       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11358       if (resolvedRHS.isInvalid()) return ExprError();
11359       RHSExpr = resolvedRHS.get();
11360 
11361       if (RHSExpr->isTypeDependent() ||
11362           RHSExpr->getType()->isOverloadableType())
11363         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11364     }
11365 
11366     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
11367     if (LHS.isInvalid()) return ExprError();
11368     LHSExpr = LHS.get();
11369   }
11370 
11371   // Handle pseudo-objects in the RHS.
11372   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
11373     // An overload in the RHS can potentially be resolved by the type
11374     // being assigned to.
11375     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
11376       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11377         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11378 
11379       if (LHSExpr->getType()->isOverloadableType())
11380         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11381 
11382       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11383     }
11384 
11385     // Don't resolve overloads if the other type is overloadable.
11386     if (pty->getKind() == BuiltinType::Overload &&
11387         LHSExpr->getType()->isOverloadableType())
11388       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11389 
11390     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
11391     if (!resolvedRHS.isUsable()) return ExprError();
11392     RHSExpr = resolvedRHS.get();
11393   }
11394 
11395   if (getLangOpts().CPlusPlus) {
11396     // If either expression is type-dependent, always build an
11397     // overloaded op.
11398     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
11399       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11400 
11401     // Otherwise, build an overloaded op if either expression has an
11402     // overloadable type.
11403     if (LHSExpr->getType()->isOverloadableType() ||
11404         RHSExpr->getType()->isOverloadableType())
11405       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
11406   }
11407 
11408   // Build a built-in binary operation.
11409   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
11410 }
11411 
11412 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
11413                                       UnaryOperatorKind Opc,
11414                                       Expr *InputExpr) {
11415   ExprResult Input = InputExpr;
11416   ExprValueKind VK = VK_RValue;
11417   ExprObjectKind OK = OK_Ordinary;
11418   QualType resultType;
11419   if (getLangOpts().OpenCL) {
11420     QualType Ty = InputExpr->getType();
11421     // The only legal unary operation for atomics is '&'.
11422     if ((Opc != UO_AddrOf && Ty->isAtomicType()) ||
11423     // OpenCL special types - image, sampler, pipe, and blocks are to be used
11424     // only with a builtin functions and therefore should be disallowed here.
11425         (Ty->isImageType() || Ty->isSamplerT() || Ty->isPipeType()
11426         || Ty->isBlockPointerType())) {
11427       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11428                        << InputExpr->getType()
11429                        << Input.get()->getSourceRange());
11430     }
11431   }
11432   switch (Opc) {
11433   case UO_PreInc:
11434   case UO_PreDec:
11435   case UO_PostInc:
11436   case UO_PostDec:
11437     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
11438                                                 OpLoc,
11439                                                 Opc == UO_PreInc ||
11440                                                 Opc == UO_PostInc,
11441                                                 Opc == UO_PreInc ||
11442                                                 Opc == UO_PreDec);
11443     break;
11444   case UO_AddrOf:
11445     resultType = CheckAddressOfOperand(Input, OpLoc);
11446     RecordModifiableNonNullParam(*this, InputExpr);
11447     break;
11448   case UO_Deref: {
11449     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11450     if (Input.isInvalid()) return ExprError();
11451     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
11452     break;
11453   }
11454   case UO_Plus:
11455   case UO_Minus:
11456     Input = UsualUnaryConversions(Input.get());
11457     if (Input.isInvalid()) return ExprError();
11458     resultType = Input.get()->getType();
11459     if (resultType->isDependentType())
11460       break;
11461     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
11462       break;
11463     else if (resultType->isVectorType() &&
11464              // The z vector extensions don't allow + or - with bool vectors.
11465              (!Context.getLangOpts().ZVector ||
11466               resultType->getAs<VectorType>()->getVectorKind() !=
11467               VectorType::AltiVecBool))
11468       break;
11469     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
11470              Opc == UO_Plus &&
11471              resultType->isPointerType())
11472       break;
11473 
11474     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11475       << resultType << Input.get()->getSourceRange());
11476 
11477   case UO_Not: // bitwise complement
11478     Input = UsualUnaryConversions(Input.get());
11479     if (Input.isInvalid())
11480       return ExprError();
11481     resultType = Input.get()->getType();
11482     if (resultType->isDependentType())
11483       break;
11484     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
11485     if (resultType->isComplexType() || resultType->isComplexIntegerType())
11486       // C99 does not support '~' for complex conjugation.
11487       Diag(OpLoc, diag::ext_integer_complement_complex)
11488           << resultType << Input.get()->getSourceRange();
11489     else if (resultType->hasIntegerRepresentation())
11490       break;
11491     else if (resultType->isExtVectorType()) {
11492       if (Context.getLangOpts().OpenCL) {
11493         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
11494         // on vector float types.
11495         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11496         if (!T->isIntegerType())
11497           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11498                            << resultType << Input.get()->getSourceRange());
11499       }
11500       break;
11501     } else {
11502       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11503                        << resultType << Input.get()->getSourceRange());
11504     }
11505     break;
11506 
11507   case UO_LNot: // logical negation
11508     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
11509     Input = DefaultFunctionArrayLvalueConversion(Input.get());
11510     if (Input.isInvalid()) return ExprError();
11511     resultType = Input.get()->getType();
11512 
11513     // Though we still have to promote half FP to float...
11514     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
11515       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
11516       resultType = Context.FloatTy;
11517     }
11518 
11519     if (resultType->isDependentType())
11520       break;
11521     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
11522       // C99 6.5.3.3p1: ok, fallthrough;
11523       if (Context.getLangOpts().CPlusPlus) {
11524         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
11525         // operand contextually converted to bool.
11526         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
11527                                   ScalarTypeToBooleanCastKind(resultType));
11528       } else if (Context.getLangOpts().OpenCL &&
11529                  Context.getLangOpts().OpenCLVersion < 120) {
11530         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11531         // operate on scalar float types.
11532         if (!resultType->isIntegerType())
11533           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11534                            << resultType << Input.get()->getSourceRange());
11535       }
11536     } else if (resultType->isExtVectorType()) {
11537       if (Context.getLangOpts().OpenCL &&
11538           Context.getLangOpts().OpenCLVersion < 120) {
11539         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
11540         // operate on vector float types.
11541         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
11542         if (!T->isIntegerType())
11543           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11544                            << resultType << Input.get()->getSourceRange());
11545       }
11546       // Vector logical not returns the signed variant of the operand type.
11547       resultType = GetSignedVectorType(resultType);
11548       break;
11549     } else {
11550       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
11551         << resultType << Input.get()->getSourceRange());
11552     }
11553 
11554     // LNot always has type int. C99 6.5.3.3p5.
11555     // In C++, it's bool. C++ 5.3.1p8
11556     resultType = Context.getLogicalOperationType();
11557     break;
11558   case UO_Real:
11559   case UO_Imag:
11560     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
11561     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
11562     // complex l-values to ordinary l-values and all other values to r-values.
11563     if (Input.isInvalid()) return ExprError();
11564     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
11565       if (Input.get()->getValueKind() != VK_RValue &&
11566           Input.get()->getObjectKind() == OK_Ordinary)
11567         VK = Input.get()->getValueKind();
11568     } else if (!getLangOpts().CPlusPlus) {
11569       // In C, a volatile scalar is read by __imag. In C++, it is not.
11570       Input = DefaultLvalueConversion(Input.get());
11571     }
11572     break;
11573   case UO_Extension:
11574   case UO_Coawait:
11575     resultType = Input.get()->getType();
11576     VK = Input.get()->getValueKind();
11577     OK = Input.get()->getObjectKind();
11578     break;
11579   }
11580   if (resultType.isNull() || Input.isInvalid())
11581     return ExprError();
11582 
11583   // Check for array bounds violations in the operand of the UnaryOperator,
11584   // except for the '*' and '&' operators that have to be handled specially
11585   // by CheckArrayAccess (as there are special cases like &array[arraysize]
11586   // that are explicitly defined as valid by the standard).
11587   if (Opc != UO_AddrOf && Opc != UO_Deref)
11588     CheckArrayAccess(Input.get());
11589 
11590   return new (Context)
11591       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
11592 }
11593 
11594 /// \brief Determine whether the given expression is a qualified member
11595 /// access expression, of a form that could be turned into a pointer to member
11596 /// with the address-of operator.
11597 static bool isQualifiedMemberAccess(Expr *E) {
11598   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
11599     if (!DRE->getQualifier())
11600       return false;
11601 
11602     ValueDecl *VD = DRE->getDecl();
11603     if (!VD->isCXXClassMember())
11604       return false;
11605 
11606     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
11607       return true;
11608     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
11609       return Method->isInstance();
11610 
11611     return false;
11612   }
11613 
11614   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
11615     if (!ULE->getQualifier())
11616       return false;
11617 
11618     for (NamedDecl *D : ULE->decls()) {
11619       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
11620         if (Method->isInstance())
11621           return true;
11622       } else {
11623         // Overload set does not contain methods.
11624         break;
11625       }
11626     }
11627 
11628     return false;
11629   }
11630 
11631   return false;
11632 }
11633 
11634 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11635                               UnaryOperatorKind Opc, Expr *Input) {
11636   // First things first: handle placeholders so that the
11637   // overloaded-operator check considers the right type.
11638   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11639     // Increment and decrement of pseudo-object references.
11640     if (pty->getKind() == BuiltinType::PseudoObject &&
11641         UnaryOperator::isIncrementDecrementOp(Opc))
11642       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11643 
11644     // extension is always a builtin operator.
11645     if (Opc == UO_Extension)
11646       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11647 
11648     // & gets special logic for several kinds of placeholder.
11649     // The builtin code knows what to do.
11650     if (Opc == UO_AddrOf &&
11651         (pty->getKind() == BuiltinType::Overload ||
11652          pty->getKind() == BuiltinType::UnknownAny ||
11653          pty->getKind() == BuiltinType::BoundMember))
11654       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11655 
11656     // Anything else needs to be handled now.
11657     ExprResult Result = CheckPlaceholderExpr(Input);
11658     if (Result.isInvalid()) return ExprError();
11659     Input = Result.get();
11660   }
11661 
11662   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11663       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11664       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11665     // Find all of the overloaded operators visible from this
11666     // point. We perform both an operator-name lookup from the local
11667     // scope and an argument-dependent lookup based on the types of
11668     // the arguments.
11669     UnresolvedSet<16> Functions;
11670     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11671     if (S && OverOp != OO_None)
11672       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11673                                    Functions);
11674 
11675     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11676   }
11677 
11678   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11679 }
11680 
11681 // Unary Operators.  'Tok' is the token for the operator.
11682 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11683                               tok::TokenKind Op, Expr *Input) {
11684   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11685 }
11686 
11687 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11688 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11689                                 LabelDecl *TheDecl) {
11690   TheDecl->markUsed(Context);
11691   // Create the AST node.  The address of a label always has type 'void*'.
11692   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11693                                      Context.getPointerType(Context.VoidTy));
11694 }
11695 
11696 /// Given the last statement in a statement-expression, check whether
11697 /// the result is a producing expression (like a call to an
11698 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11699 /// release out of the full-expression.  Otherwise, return null.
11700 /// Cannot fail.
11701 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11702   // Should always be wrapped with one of these.
11703   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11704   if (!cleanups) return nullptr;
11705 
11706   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11707   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11708     return nullptr;
11709 
11710   // Splice out the cast.  This shouldn't modify any interesting
11711   // features of the statement.
11712   Expr *producer = cast->getSubExpr();
11713   assert(producer->getType() == cast->getType());
11714   assert(producer->getValueKind() == cast->getValueKind());
11715   cleanups->setSubExpr(producer);
11716   return cleanups;
11717 }
11718 
11719 void Sema::ActOnStartStmtExpr() {
11720   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11721 }
11722 
11723 void Sema::ActOnStmtExprError() {
11724   // Note that function is also called by TreeTransform when leaving a
11725   // StmtExpr scope without rebuilding anything.
11726 
11727   DiscardCleanupsInEvaluationContext();
11728   PopExpressionEvaluationContext();
11729 }
11730 
11731 ExprResult
11732 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11733                     SourceLocation RPLoc) { // "({..})"
11734   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11735   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11736 
11737   if (hasAnyUnrecoverableErrorsInThisFunction())
11738     DiscardCleanupsInEvaluationContext();
11739   assert(!Cleanup.exprNeedsCleanups() &&
11740          "cleanups within StmtExpr not correctly bound!");
11741   PopExpressionEvaluationContext();
11742 
11743   // FIXME: there are a variety of strange constraints to enforce here, for
11744   // example, it is not possible to goto into a stmt expression apparently.
11745   // More semantic analysis is needed.
11746 
11747   // If there are sub-stmts in the compound stmt, take the type of the last one
11748   // as the type of the stmtexpr.
11749   QualType Ty = Context.VoidTy;
11750   bool StmtExprMayBindToTemp = false;
11751   if (!Compound->body_empty()) {
11752     Stmt *LastStmt = Compound->body_back();
11753     LabelStmt *LastLabelStmt = nullptr;
11754     // If LastStmt is a label, skip down through into the body.
11755     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11756       LastLabelStmt = Label;
11757       LastStmt = Label->getSubStmt();
11758     }
11759 
11760     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11761       // Do function/array conversion on the last expression, but not
11762       // lvalue-to-rvalue.  However, initialize an unqualified type.
11763       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11764       if (LastExpr.isInvalid())
11765         return ExprError();
11766       Ty = LastExpr.get()->getType().getUnqualifiedType();
11767 
11768       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11769         // In ARC, if the final expression ends in a consume, splice
11770         // the consume out and bind it later.  In the alternate case
11771         // (when dealing with a retainable type), the result
11772         // initialization will create a produce.  In both cases the
11773         // result will be +1, and we'll need to balance that out with
11774         // a bind.
11775         if (Expr *rebuiltLastStmt
11776               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11777           LastExpr = rebuiltLastStmt;
11778         } else {
11779           LastExpr = PerformCopyInitialization(
11780                             InitializedEntity::InitializeResult(LPLoc,
11781                                                                 Ty,
11782                                                                 false),
11783                                                    SourceLocation(),
11784                                                LastExpr);
11785         }
11786 
11787         if (LastExpr.isInvalid())
11788           return ExprError();
11789         if (LastExpr.get() != nullptr) {
11790           if (!LastLabelStmt)
11791             Compound->setLastStmt(LastExpr.get());
11792           else
11793             LastLabelStmt->setSubStmt(LastExpr.get());
11794           StmtExprMayBindToTemp = true;
11795         }
11796       }
11797     }
11798   }
11799 
11800   // FIXME: Check that expression type is complete/non-abstract; statement
11801   // expressions are not lvalues.
11802   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11803   if (StmtExprMayBindToTemp)
11804     return MaybeBindToTemporary(ResStmtExpr);
11805   return ResStmtExpr;
11806 }
11807 
11808 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11809                                       TypeSourceInfo *TInfo,
11810                                       ArrayRef<OffsetOfComponent> Components,
11811                                       SourceLocation RParenLoc) {
11812   QualType ArgTy = TInfo->getType();
11813   bool Dependent = ArgTy->isDependentType();
11814   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11815 
11816   // We must have at least one component that refers to the type, and the first
11817   // one is known to be a field designator.  Verify that the ArgTy represents
11818   // a struct/union/class.
11819   if (!Dependent && !ArgTy->isRecordType())
11820     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11821                        << ArgTy << TypeRange);
11822 
11823   // Type must be complete per C99 7.17p3 because a declaring a variable
11824   // with an incomplete type would be ill-formed.
11825   if (!Dependent
11826       && RequireCompleteType(BuiltinLoc, ArgTy,
11827                              diag::err_offsetof_incomplete_type, TypeRange))
11828     return ExprError();
11829 
11830   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11831   // GCC extension, diagnose them.
11832   // FIXME: This diagnostic isn't actually visible because the location is in
11833   // a system header!
11834   if (Components.size() != 1)
11835     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11836       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11837 
11838   bool DidWarnAboutNonPOD = false;
11839   QualType CurrentType = ArgTy;
11840   SmallVector<OffsetOfNode, 4> Comps;
11841   SmallVector<Expr*, 4> Exprs;
11842   for (const OffsetOfComponent &OC : Components) {
11843     if (OC.isBrackets) {
11844       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11845       if (!CurrentType->isDependentType()) {
11846         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11847         if(!AT)
11848           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11849                            << CurrentType);
11850         CurrentType = AT->getElementType();
11851       } else
11852         CurrentType = Context.DependentTy;
11853 
11854       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11855       if (IdxRval.isInvalid())
11856         return ExprError();
11857       Expr *Idx = IdxRval.get();
11858 
11859       // The expression must be an integral expression.
11860       // FIXME: An integral constant expression?
11861       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11862           !Idx->getType()->isIntegerType())
11863         return ExprError(Diag(Idx->getLocStart(),
11864                               diag::err_typecheck_subscript_not_integer)
11865                          << Idx->getSourceRange());
11866 
11867       // Record this array index.
11868       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11869       Exprs.push_back(Idx);
11870       continue;
11871     }
11872 
11873     // Offset of a field.
11874     if (CurrentType->isDependentType()) {
11875       // We have the offset of a field, but we can't look into the dependent
11876       // type. Just record the identifier of the field.
11877       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11878       CurrentType = Context.DependentTy;
11879       continue;
11880     }
11881 
11882     // We need to have a complete type to look into.
11883     if (RequireCompleteType(OC.LocStart, CurrentType,
11884                             diag::err_offsetof_incomplete_type))
11885       return ExprError();
11886 
11887     // Look for the designated field.
11888     const RecordType *RC = CurrentType->getAs<RecordType>();
11889     if (!RC)
11890       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11891                        << CurrentType);
11892     RecordDecl *RD = RC->getDecl();
11893 
11894     // C++ [lib.support.types]p5:
11895     //   The macro offsetof accepts a restricted set of type arguments in this
11896     //   International Standard. type shall be a POD structure or a POD union
11897     //   (clause 9).
11898     // C++11 [support.types]p4:
11899     //   If type is not a standard-layout class (Clause 9), the results are
11900     //   undefined.
11901     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11902       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11903       unsigned DiagID =
11904         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11905                             : diag::ext_offsetof_non_pod_type;
11906 
11907       if (!IsSafe && !DidWarnAboutNonPOD &&
11908           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11909                               PDiag(DiagID)
11910                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11911                               << CurrentType))
11912         DidWarnAboutNonPOD = true;
11913     }
11914 
11915     // Look for the field.
11916     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11917     LookupQualifiedName(R, RD);
11918     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11919     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11920     if (!MemberDecl) {
11921       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11922         MemberDecl = IndirectMemberDecl->getAnonField();
11923     }
11924 
11925     if (!MemberDecl)
11926       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11927                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11928                                                               OC.LocEnd));
11929 
11930     // C99 7.17p3:
11931     //   (If the specified member is a bit-field, the behavior is undefined.)
11932     //
11933     // We diagnose this as an error.
11934     if (MemberDecl->isBitField()) {
11935       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11936         << MemberDecl->getDeclName()
11937         << SourceRange(BuiltinLoc, RParenLoc);
11938       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11939       return ExprError();
11940     }
11941 
11942     RecordDecl *Parent = MemberDecl->getParent();
11943     if (IndirectMemberDecl)
11944       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11945 
11946     // If the member was found in a base class, introduce OffsetOfNodes for
11947     // the base class indirections.
11948     CXXBasePaths Paths;
11949     if (IsDerivedFrom(OC.LocStart, CurrentType, Context.getTypeDeclType(Parent),
11950                       Paths)) {
11951       if (Paths.getDetectedVirtual()) {
11952         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11953           << MemberDecl->getDeclName()
11954           << SourceRange(BuiltinLoc, RParenLoc);
11955         return ExprError();
11956       }
11957 
11958       CXXBasePath &Path = Paths.front();
11959       for (const CXXBasePathElement &B : Path)
11960         Comps.push_back(OffsetOfNode(B.Base));
11961     }
11962 
11963     if (IndirectMemberDecl) {
11964       for (auto *FI : IndirectMemberDecl->chain()) {
11965         assert(isa<FieldDecl>(FI));
11966         Comps.push_back(OffsetOfNode(OC.LocStart,
11967                                      cast<FieldDecl>(FI), OC.LocEnd));
11968       }
11969     } else
11970       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11971 
11972     CurrentType = MemberDecl->getType().getNonReferenceType();
11973   }
11974 
11975   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11976                               Comps, Exprs, RParenLoc);
11977 }
11978 
11979 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11980                                       SourceLocation BuiltinLoc,
11981                                       SourceLocation TypeLoc,
11982                                       ParsedType ParsedArgTy,
11983                                       ArrayRef<OffsetOfComponent> Components,
11984                                       SourceLocation RParenLoc) {
11985 
11986   TypeSourceInfo *ArgTInfo;
11987   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11988   if (ArgTy.isNull())
11989     return ExprError();
11990 
11991   if (!ArgTInfo)
11992     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11993 
11994   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11995 }
11996 
11997 
11998 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11999                                  Expr *CondExpr,
12000                                  Expr *LHSExpr, Expr *RHSExpr,
12001                                  SourceLocation RPLoc) {
12002   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
12003 
12004   ExprValueKind VK = VK_RValue;
12005   ExprObjectKind OK = OK_Ordinary;
12006   QualType resType;
12007   bool ValueDependent = false;
12008   bool CondIsTrue = false;
12009   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
12010     resType = Context.DependentTy;
12011     ValueDependent = true;
12012   } else {
12013     // The conditional expression is required to be a constant expression.
12014     llvm::APSInt condEval(32);
12015     ExprResult CondICE
12016       = VerifyIntegerConstantExpression(CondExpr, &condEval,
12017           diag::err_typecheck_choose_expr_requires_constant, false);
12018     if (CondICE.isInvalid())
12019       return ExprError();
12020     CondExpr = CondICE.get();
12021     CondIsTrue = condEval.getZExtValue();
12022 
12023     // If the condition is > zero, then the AST type is the same as the LSHExpr.
12024     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
12025 
12026     resType = ActiveExpr->getType();
12027     ValueDependent = ActiveExpr->isValueDependent();
12028     VK = ActiveExpr->getValueKind();
12029     OK = ActiveExpr->getObjectKind();
12030   }
12031 
12032   return new (Context)
12033       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
12034                  CondIsTrue, resType->isDependentType(), ValueDependent);
12035 }
12036 
12037 //===----------------------------------------------------------------------===//
12038 // Clang Extensions.
12039 //===----------------------------------------------------------------------===//
12040 
12041 /// ActOnBlockStart - This callback is invoked when a block literal is started.
12042 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
12043   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
12044 
12045   if (LangOpts.CPlusPlus) {
12046     Decl *ManglingContextDecl;
12047     if (MangleNumberingContext *MCtx =
12048             getCurrentMangleNumberContext(Block->getDeclContext(),
12049                                           ManglingContextDecl)) {
12050       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
12051       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
12052     }
12053   }
12054 
12055   PushBlockScope(CurScope, Block);
12056   CurContext->addDecl(Block);
12057   if (CurScope)
12058     PushDeclContext(CurScope, Block);
12059   else
12060     CurContext = Block;
12061 
12062   getCurBlock()->HasImplicitReturnType = true;
12063 
12064   // Enter a new evaluation context to insulate the block from any
12065   // cleanups from the enclosing full-expression.
12066   PushExpressionEvaluationContext(PotentiallyEvaluated);
12067 }
12068 
12069 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
12070                                Scope *CurScope) {
12071   assert(ParamInfo.getIdentifier() == nullptr &&
12072          "block-id should have no identifier!");
12073   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
12074   BlockScopeInfo *CurBlock = getCurBlock();
12075 
12076   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
12077   QualType T = Sig->getType();
12078 
12079   // FIXME: We should allow unexpanded parameter packs here, but that would,
12080   // in turn, make the block expression contain unexpanded parameter packs.
12081   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
12082     // Drop the parameters.
12083     FunctionProtoType::ExtProtoInfo EPI;
12084     EPI.HasTrailingReturn = false;
12085     EPI.TypeQuals |= DeclSpec::TQ_const;
12086     T = Context.getFunctionType(Context.DependentTy, None, EPI);
12087     Sig = Context.getTrivialTypeSourceInfo(T);
12088   }
12089 
12090   // GetTypeForDeclarator always produces a function type for a block
12091   // literal signature.  Furthermore, it is always a FunctionProtoType
12092   // unless the function was written with a typedef.
12093   assert(T->isFunctionType() &&
12094          "GetTypeForDeclarator made a non-function block signature");
12095 
12096   // Look for an explicit signature in that function type.
12097   FunctionProtoTypeLoc ExplicitSignature;
12098 
12099   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
12100   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
12101 
12102     // Check whether that explicit signature was synthesized by
12103     // GetTypeForDeclarator.  If so, don't save that as part of the
12104     // written signature.
12105     if (ExplicitSignature.getLocalRangeBegin() ==
12106         ExplicitSignature.getLocalRangeEnd()) {
12107       // This would be much cheaper if we stored TypeLocs instead of
12108       // TypeSourceInfos.
12109       TypeLoc Result = ExplicitSignature.getReturnLoc();
12110       unsigned Size = Result.getFullDataSize();
12111       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
12112       Sig->getTypeLoc().initializeFullCopy(Result, Size);
12113 
12114       ExplicitSignature = FunctionProtoTypeLoc();
12115     }
12116   }
12117 
12118   CurBlock->TheDecl->setSignatureAsWritten(Sig);
12119   CurBlock->FunctionType = T;
12120 
12121   const FunctionType *Fn = T->getAs<FunctionType>();
12122   QualType RetTy = Fn->getReturnType();
12123   bool isVariadic =
12124     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
12125 
12126   CurBlock->TheDecl->setIsVariadic(isVariadic);
12127 
12128   // Context.DependentTy is used as a placeholder for a missing block
12129   // return type.  TODO:  what should we do with declarators like:
12130   //   ^ * { ... }
12131   // If the answer is "apply template argument deduction"....
12132   if (RetTy != Context.DependentTy) {
12133     CurBlock->ReturnType = RetTy;
12134     CurBlock->TheDecl->setBlockMissingReturnType(false);
12135     CurBlock->HasImplicitReturnType = false;
12136   }
12137 
12138   // Push block parameters from the declarator if we had them.
12139   SmallVector<ParmVarDecl*, 8> Params;
12140   if (ExplicitSignature) {
12141     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
12142       ParmVarDecl *Param = ExplicitSignature.getParam(I);
12143       if (Param->getIdentifier() == nullptr &&
12144           !Param->isImplicit() &&
12145           !Param->isInvalidDecl() &&
12146           !getLangOpts().CPlusPlus)
12147         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
12148       Params.push_back(Param);
12149     }
12150 
12151   // Fake up parameter variables if we have a typedef, like
12152   //   ^ fntype { ... }
12153   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
12154     for (const auto &I : Fn->param_types()) {
12155       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
12156           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
12157       Params.push_back(Param);
12158     }
12159   }
12160 
12161   // Set the parameters on the block decl.
12162   if (!Params.empty()) {
12163     CurBlock->TheDecl->setParams(Params);
12164     CheckParmsForFunctionDef(CurBlock->TheDecl->parameters(),
12165                              /*CheckParameterNames=*/false);
12166   }
12167 
12168   // Finally we can process decl attributes.
12169   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
12170 
12171   // Put the parameter variables in scope.
12172   for (auto AI : CurBlock->TheDecl->parameters()) {
12173     AI->setOwningFunction(CurBlock->TheDecl);
12174 
12175     // If this has an identifier, add it to the scope stack.
12176     if (AI->getIdentifier()) {
12177       CheckShadow(CurBlock->TheScope, AI);
12178 
12179       PushOnScopeChains(AI, CurBlock->TheScope);
12180     }
12181   }
12182 }
12183 
12184 /// ActOnBlockError - If there is an error parsing a block, this callback
12185 /// is invoked to pop the information about the block from the action impl.
12186 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
12187   // Leave the expression-evaluation context.
12188   DiscardCleanupsInEvaluationContext();
12189   PopExpressionEvaluationContext();
12190 
12191   // Pop off CurBlock, handle nested blocks.
12192   PopDeclContext();
12193   PopFunctionScopeInfo();
12194 }
12195 
12196 /// ActOnBlockStmtExpr - This is called when the body of a block statement
12197 /// literal was successfully completed.  ^(int x){...}
12198 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
12199                                     Stmt *Body, Scope *CurScope) {
12200   // If blocks are disabled, emit an error.
12201   if (!LangOpts.Blocks)
12202     Diag(CaretLoc, diag::err_blocks_disable) << LangOpts.OpenCL;
12203 
12204   // Leave the expression-evaluation context.
12205   if (hasAnyUnrecoverableErrorsInThisFunction())
12206     DiscardCleanupsInEvaluationContext();
12207   assert(!Cleanup.exprNeedsCleanups() &&
12208          "cleanups within block not correctly bound!");
12209   PopExpressionEvaluationContext();
12210 
12211   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
12212 
12213   if (BSI->HasImplicitReturnType)
12214     deduceClosureReturnType(*BSI);
12215 
12216   PopDeclContext();
12217 
12218   QualType RetTy = Context.VoidTy;
12219   if (!BSI->ReturnType.isNull())
12220     RetTy = BSI->ReturnType;
12221 
12222   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
12223   QualType BlockTy;
12224 
12225   // Set the captured variables on the block.
12226   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
12227   SmallVector<BlockDecl::Capture, 4> Captures;
12228   for (CapturingScopeInfo::Capture &Cap : BSI->Captures) {
12229     if (Cap.isThisCapture())
12230       continue;
12231     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
12232                               Cap.isNested(), Cap.getInitExpr());
12233     Captures.push_back(NewCap);
12234   }
12235   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
12236 
12237   // If the user wrote a function type in some form, try to use that.
12238   if (!BSI->FunctionType.isNull()) {
12239     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
12240 
12241     FunctionType::ExtInfo Ext = FTy->getExtInfo();
12242     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
12243 
12244     // Turn protoless block types into nullary block types.
12245     if (isa<FunctionNoProtoType>(FTy)) {
12246       FunctionProtoType::ExtProtoInfo EPI;
12247       EPI.ExtInfo = Ext;
12248       BlockTy = Context.getFunctionType(RetTy, None, EPI);
12249 
12250     // Otherwise, if we don't need to change anything about the function type,
12251     // preserve its sugar structure.
12252     } else if (FTy->getReturnType() == RetTy &&
12253                (!NoReturn || FTy->getNoReturnAttr())) {
12254       BlockTy = BSI->FunctionType;
12255 
12256     // Otherwise, make the minimal modifications to the function type.
12257     } else {
12258       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
12259       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
12260       EPI.TypeQuals = 0; // FIXME: silently?
12261       EPI.ExtInfo = Ext;
12262       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
12263     }
12264 
12265   // If we don't have a function type, just build one from nothing.
12266   } else {
12267     FunctionProtoType::ExtProtoInfo EPI;
12268     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
12269     BlockTy = Context.getFunctionType(RetTy, None, EPI);
12270   }
12271 
12272   DiagnoseUnusedParameters(BSI->TheDecl->parameters());
12273   BlockTy = Context.getBlockPointerType(BlockTy);
12274 
12275   // If needed, diagnose invalid gotos and switches in the block.
12276   if (getCurFunction()->NeedsScopeChecking() &&
12277       !PP.isCodeCompletionEnabled())
12278     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
12279 
12280   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
12281 
12282   // Try to apply the named return value optimization. We have to check again
12283   // if we can do this, though, because blocks keep return statements around
12284   // to deduce an implicit return type.
12285   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
12286       !BSI->TheDecl->isDependentContext())
12287     computeNRVO(Body, BSI);
12288 
12289   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
12290   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12291   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
12292 
12293   // If the block isn't obviously global, i.e. it captures anything at
12294   // all, then we need to do a few things in the surrounding context:
12295   if (Result->getBlockDecl()->hasCaptures()) {
12296     // First, this expression has a new cleanup object.
12297     ExprCleanupObjects.push_back(Result->getBlockDecl());
12298     Cleanup.setExprNeedsCleanups(true);
12299 
12300     // It also gets a branch-protected scope if any of the captured
12301     // variables needs destruction.
12302     for (const auto &CI : Result->getBlockDecl()->captures()) {
12303       const VarDecl *var = CI.getVariable();
12304       if (var->getType().isDestructedType() != QualType::DK_none) {
12305         getCurFunction()->setHasBranchProtectedScope();
12306         break;
12307       }
12308     }
12309   }
12310 
12311   return Result;
12312 }
12313 
12314 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty,
12315                             SourceLocation RPLoc) {
12316   TypeSourceInfo *TInfo;
12317   GetTypeFromParser(Ty, &TInfo);
12318   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
12319 }
12320 
12321 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
12322                                 Expr *E, TypeSourceInfo *TInfo,
12323                                 SourceLocation RPLoc) {
12324   Expr *OrigExpr = E;
12325   bool IsMS = false;
12326 
12327   // CUDA device code does not support varargs.
12328   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
12329     if (const FunctionDecl *F = dyn_cast<FunctionDecl>(CurContext)) {
12330       CUDAFunctionTarget T = IdentifyCUDATarget(F);
12331       if (T == CFT_Global || T == CFT_Device || T == CFT_HostDevice)
12332         return ExprError(Diag(E->getLocStart(), diag::err_va_arg_in_device));
12333     }
12334   }
12335 
12336   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
12337   // as Microsoft ABI on an actual Microsoft platform, where
12338   // __builtin_ms_va_list and __builtin_va_list are the same.)
12339   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
12340       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
12341     QualType MSVaListType = Context.getBuiltinMSVaListType();
12342     if (Context.hasSameType(MSVaListType, E->getType())) {
12343       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
12344         return ExprError();
12345       IsMS = true;
12346     }
12347   }
12348 
12349   // Get the va_list type
12350   QualType VaListType = Context.getBuiltinVaListType();
12351   if (!IsMS) {
12352     if (VaListType->isArrayType()) {
12353       // Deal with implicit array decay; for example, on x86-64,
12354       // va_list is an array, but it's supposed to decay to
12355       // a pointer for va_arg.
12356       VaListType = Context.getArrayDecayedType(VaListType);
12357       // Make sure the input expression also decays appropriately.
12358       ExprResult Result = UsualUnaryConversions(E);
12359       if (Result.isInvalid())
12360         return ExprError();
12361       E = Result.get();
12362     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
12363       // If va_list is a record type and we are compiling in C++ mode,
12364       // check the argument using reference binding.
12365       InitializedEntity Entity = InitializedEntity::InitializeParameter(
12366           Context, Context.getLValueReferenceType(VaListType), false);
12367       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
12368       if (Init.isInvalid())
12369         return ExprError();
12370       E = Init.getAs<Expr>();
12371     } else {
12372       // Otherwise, the va_list argument must be an l-value because
12373       // it is modified by va_arg.
12374       if (!E->isTypeDependent() &&
12375           CheckForModifiableLvalue(E, BuiltinLoc, *this))
12376         return ExprError();
12377     }
12378   }
12379 
12380   if (!IsMS && !E->isTypeDependent() &&
12381       !Context.hasSameType(VaListType, E->getType()))
12382     return ExprError(Diag(E->getLocStart(),
12383                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
12384       << OrigExpr->getType() << E->getSourceRange());
12385 
12386   if (!TInfo->getType()->isDependentType()) {
12387     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
12388                             diag::err_second_parameter_to_va_arg_incomplete,
12389                             TInfo->getTypeLoc()))
12390       return ExprError();
12391 
12392     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
12393                                TInfo->getType(),
12394                                diag::err_second_parameter_to_va_arg_abstract,
12395                                TInfo->getTypeLoc()))
12396       return ExprError();
12397 
12398     if (!TInfo->getType().isPODType(Context)) {
12399       Diag(TInfo->getTypeLoc().getBeginLoc(),
12400            TInfo->getType()->isObjCLifetimeType()
12401              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
12402              : diag::warn_second_parameter_to_va_arg_not_pod)
12403         << TInfo->getType()
12404         << TInfo->getTypeLoc().getSourceRange();
12405     }
12406 
12407     // Check for va_arg where arguments of the given type will be promoted
12408     // (i.e. this va_arg is guaranteed to have undefined behavior).
12409     QualType PromoteType;
12410     if (TInfo->getType()->isPromotableIntegerType()) {
12411       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
12412       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
12413         PromoteType = QualType();
12414     }
12415     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
12416       PromoteType = Context.DoubleTy;
12417     if (!PromoteType.isNull())
12418       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
12419                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
12420                           << TInfo->getType()
12421                           << PromoteType
12422                           << TInfo->getTypeLoc().getSourceRange());
12423   }
12424 
12425   QualType T = TInfo->getType().getNonLValueExprType(Context);
12426   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
12427 }
12428 
12429 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
12430   // The type of __null will be int or long, depending on the size of
12431   // pointers on the target.
12432   QualType Ty;
12433   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
12434   if (pw == Context.getTargetInfo().getIntWidth())
12435     Ty = Context.IntTy;
12436   else if (pw == Context.getTargetInfo().getLongWidth())
12437     Ty = Context.LongTy;
12438   else if (pw == Context.getTargetInfo().getLongLongWidth())
12439     Ty = Context.LongLongTy;
12440   else {
12441     llvm_unreachable("I don't know size of pointer!");
12442   }
12443 
12444   return new (Context) GNUNullExpr(Ty, TokenLoc);
12445 }
12446 
12447 bool Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp,
12448                                               bool Diagnose) {
12449   if (!getLangOpts().ObjC1)
12450     return false;
12451 
12452   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
12453   if (!PT)
12454     return false;
12455 
12456   if (!PT->isObjCIdType()) {
12457     // Check if the destination is the 'NSString' interface.
12458     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
12459     if (!ID || !ID->getIdentifier()->isStr("NSString"))
12460       return false;
12461   }
12462 
12463   // Ignore any parens, implicit casts (should only be
12464   // array-to-pointer decays), and not-so-opaque values.  The last is
12465   // important for making this trigger for property assignments.
12466   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
12467   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
12468     if (OV->getSourceExpr())
12469       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
12470 
12471   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
12472   if (!SL || !SL->isAscii())
12473     return false;
12474   if (Diagnose) {
12475     Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
12476       << FixItHint::CreateInsertion(SL->getLocStart(), "@");
12477     Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
12478   }
12479   return true;
12480 }
12481 
12482 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
12483                                               const Expr *SrcExpr) {
12484   if (!DstType->isFunctionPointerType() ||
12485       !SrcExpr->getType()->isFunctionType())
12486     return false;
12487 
12488   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
12489   if (!DRE)
12490     return false;
12491 
12492   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12493   if (!FD)
12494     return false;
12495 
12496   return !S.checkAddressOfFunctionIsAvailable(FD,
12497                                               /*Complain=*/true,
12498                                               SrcExpr->getLocStart());
12499 }
12500 
12501 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
12502                                     SourceLocation Loc,
12503                                     QualType DstType, QualType SrcType,
12504                                     Expr *SrcExpr, AssignmentAction Action,
12505                                     bool *Complained) {
12506   if (Complained)
12507     *Complained = false;
12508 
12509   // Decode the result (notice that AST's are still created for extensions).
12510   bool CheckInferredResultType = false;
12511   bool isInvalid = false;
12512   unsigned DiagKind = 0;
12513   FixItHint Hint;
12514   ConversionFixItGenerator ConvHints;
12515   bool MayHaveConvFixit = false;
12516   bool MayHaveFunctionDiff = false;
12517   const ObjCInterfaceDecl *IFace = nullptr;
12518   const ObjCProtocolDecl *PDecl = nullptr;
12519 
12520   switch (ConvTy) {
12521   case Compatible:
12522       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
12523       return false;
12524 
12525   case PointerToInt:
12526     DiagKind = diag::ext_typecheck_convert_pointer_int;
12527     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12528     MayHaveConvFixit = true;
12529     break;
12530   case IntToPointer:
12531     DiagKind = diag::ext_typecheck_convert_int_pointer;
12532     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12533     MayHaveConvFixit = true;
12534     break;
12535   case IncompatiblePointer:
12536     if (Action == AA_Passing_CFAudited)
12537       DiagKind = diag::err_arc_typecheck_convert_incompatible_pointer;
12538     else if (SrcType->isFunctionPointerType() &&
12539              DstType->isFunctionPointerType())
12540       DiagKind = diag::ext_typecheck_convert_incompatible_function_pointer;
12541     else
12542       DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
12543 
12544     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
12545       SrcType->isObjCObjectPointerType();
12546     if (Hint.isNull() && !CheckInferredResultType) {
12547       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12548     }
12549     else if (CheckInferredResultType) {
12550       SrcType = SrcType.getUnqualifiedType();
12551       DstType = DstType.getUnqualifiedType();
12552     }
12553     MayHaveConvFixit = true;
12554     break;
12555   case IncompatiblePointerSign:
12556     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
12557     break;
12558   case FunctionVoidPointer:
12559     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
12560     break;
12561   case IncompatiblePointerDiscardsQualifiers: {
12562     // Perform array-to-pointer decay if necessary.
12563     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
12564 
12565     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
12566     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
12567     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
12568       DiagKind = diag::err_typecheck_incompatible_address_space;
12569       break;
12570 
12571 
12572     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
12573       DiagKind = diag::err_typecheck_incompatible_ownership;
12574       break;
12575     }
12576 
12577     llvm_unreachable("unknown error case for discarding qualifiers!");
12578     // fallthrough
12579   }
12580   case CompatiblePointerDiscardsQualifiers:
12581     // If the qualifiers lost were because we were applying the
12582     // (deprecated) C++ conversion from a string literal to a char*
12583     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
12584     // Ideally, this check would be performed in
12585     // checkPointerTypesForAssignment. However, that would require a
12586     // bit of refactoring (so that the second argument is an
12587     // expression, rather than a type), which should be done as part
12588     // of a larger effort to fix checkPointerTypesForAssignment for
12589     // C++ semantics.
12590     if (getLangOpts().CPlusPlus &&
12591         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
12592       return false;
12593     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
12594     break;
12595   case IncompatibleNestedPointerQualifiers:
12596     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
12597     break;
12598   case IntToBlockPointer:
12599     DiagKind = diag::err_int_to_block_pointer;
12600     break;
12601   case IncompatibleBlockPointer:
12602     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
12603     break;
12604   case IncompatibleObjCQualifiedId: {
12605     if (SrcType->isObjCQualifiedIdType()) {
12606       const ObjCObjectPointerType *srcOPT =
12607                 SrcType->getAs<ObjCObjectPointerType>();
12608       for (auto *srcProto : srcOPT->quals()) {
12609         PDecl = srcProto;
12610         break;
12611       }
12612       if (const ObjCInterfaceType *IFaceT =
12613             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12614         IFace = IFaceT->getDecl();
12615     }
12616     else if (DstType->isObjCQualifiedIdType()) {
12617       const ObjCObjectPointerType *dstOPT =
12618         DstType->getAs<ObjCObjectPointerType>();
12619       for (auto *dstProto : dstOPT->quals()) {
12620         PDecl = dstProto;
12621         break;
12622       }
12623       if (const ObjCInterfaceType *IFaceT =
12624             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
12625         IFace = IFaceT->getDecl();
12626     }
12627     DiagKind = diag::warn_incompatible_qualified_id;
12628     break;
12629   }
12630   case IncompatibleVectors:
12631     DiagKind = diag::warn_incompatible_vectors;
12632     break;
12633   case IncompatibleObjCWeakRef:
12634     DiagKind = diag::err_arc_weak_unavailable_assign;
12635     break;
12636   case Incompatible:
12637     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
12638       if (Complained)
12639         *Complained = true;
12640       return true;
12641     }
12642 
12643     DiagKind = diag::err_typecheck_convert_incompatible;
12644     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12645     MayHaveConvFixit = true;
12646     isInvalid = true;
12647     MayHaveFunctionDiff = true;
12648     break;
12649   }
12650 
12651   QualType FirstType, SecondType;
12652   switch (Action) {
12653   case AA_Assigning:
12654   case AA_Initializing:
12655     // The destination type comes first.
12656     FirstType = DstType;
12657     SecondType = SrcType;
12658     break;
12659 
12660   case AA_Returning:
12661   case AA_Passing:
12662   case AA_Passing_CFAudited:
12663   case AA_Converting:
12664   case AA_Sending:
12665   case AA_Casting:
12666     // The source type comes first.
12667     FirstType = SrcType;
12668     SecondType = DstType;
12669     break;
12670   }
12671 
12672   PartialDiagnostic FDiag = PDiag(DiagKind);
12673   if (Action == AA_Passing_CFAudited)
12674     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12675   else
12676     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12677 
12678   // If we can fix the conversion, suggest the FixIts.
12679   assert(ConvHints.isNull() || Hint.isNull());
12680   if (!ConvHints.isNull()) {
12681     for (FixItHint &H : ConvHints.Hints)
12682       FDiag << H;
12683   } else {
12684     FDiag << Hint;
12685   }
12686   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12687 
12688   if (MayHaveFunctionDiff)
12689     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12690 
12691   Diag(Loc, FDiag);
12692   if (DiagKind == diag::warn_incompatible_qualified_id &&
12693       PDecl && IFace && !IFace->hasDefinition())
12694       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12695         << IFace->getName() << PDecl->getName();
12696 
12697   if (SecondType == Context.OverloadTy)
12698     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12699                               FirstType, /*TakingAddress=*/true);
12700 
12701   if (CheckInferredResultType)
12702     EmitRelatedResultTypeNote(SrcExpr);
12703 
12704   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12705     EmitRelatedResultTypeNoteForReturn(DstType);
12706 
12707   if (Complained)
12708     *Complained = true;
12709   return isInvalid;
12710 }
12711 
12712 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12713                                                  llvm::APSInt *Result) {
12714   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12715   public:
12716     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12717       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12718     }
12719   } Diagnoser;
12720 
12721   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12722 }
12723 
12724 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12725                                                  llvm::APSInt *Result,
12726                                                  unsigned DiagID,
12727                                                  bool AllowFold) {
12728   class IDDiagnoser : public VerifyICEDiagnoser {
12729     unsigned DiagID;
12730 
12731   public:
12732     IDDiagnoser(unsigned DiagID)
12733       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12734 
12735     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12736       S.Diag(Loc, DiagID) << SR;
12737     }
12738   } Diagnoser(DiagID);
12739 
12740   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12741 }
12742 
12743 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12744                                             SourceRange SR) {
12745   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12746 }
12747 
12748 ExprResult
12749 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12750                                       VerifyICEDiagnoser &Diagnoser,
12751                                       bool AllowFold) {
12752   SourceLocation DiagLoc = E->getLocStart();
12753 
12754   if (getLangOpts().CPlusPlus11) {
12755     // C++11 [expr.const]p5:
12756     //   If an expression of literal class type is used in a context where an
12757     //   integral constant expression is required, then that class type shall
12758     //   have a single non-explicit conversion function to an integral or
12759     //   unscoped enumeration type
12760     ExprResult Converted;
12761     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12762     public:
12763       CXX11ConvertDiagnoser(bool Silent)
12764           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12765                                 Silent, true) {}
12766 
12767       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12768                                            QualType T) override {
12769         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12770       }
12771 
12772       SemaDiagnosticBuilder diagnoseIncomplete(
12773           Sema &S, SourceLocation Loc, QualType T) override {
12774         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12775       }
12776 
12777       SemaDiagnosticBuilder diagnoseExplicitConv(
12778           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12779         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12780       }
12781 
12782       SemaDiagnosticBuilder noteExplicitConv(
12783           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12784         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12785                  << ConvTy->isEnumeralType() << ConvTy;
12786       }
12787 
12788       SemaDiagnosticBuilder diagnoseAmbiguous(
12789           Sema &S, SourceLocation Loc, QualType T) override {
12790         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12791       }
12792 
12793       SemaDiagnosticBuilder noteAmbiguous(
12794           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12795         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12796                  << ConvTy->isEnumeralType() << ConvTy;
12797       }
12798 
12799       SemaDiagnosticBuilder diagnoseConversion(
12800           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12801         llvm_unreachable("conversion functions are permitted");
12802       }
12803     } ConvertDiagnoser(Diagnoser.Suppress);
12804 
12805     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12806                                                     ConvertDiagnoser);
12807     if (Converted.isInvalid())
12808       return Converted;
12809     E = Converted.get();
12810     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12811       return ExprError();
12812   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12813     // An ICE must be of integral or unscoped enumeration type.
12814     if (!Diagnoser.Suppress)
12815       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12816     return ExprError();
12817   }
12818 
12819   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12820   // in the non-ICE case.
12821   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12822     if (Result)
12823       *Result = E->EvaluateKnownConstInt(Context);
12824     return E;
12825   }
12826 
12827   Expr::EvalResult EvalResult;
12828   SmallVector<PartialDiagnosticAt, 8> Notes;
12829   EvalResult.Diag = &Notes;
12830 
12831   // Try to evaluate the expression, and produce diagnostics explaining why it's
12832   // not a constant expression as a side-effect.
12833   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12834                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12835 
12836   // In C++11, we can rely on diagnostics being produced for any expression
12837   // which is not a constant expression. If no diagnostics were produced, then
12838   // this is a constant expression.
12839   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12840     if (Result)
12841       *Result = EvalResult.Val.getInt();
12842     return E;
12843   }
12844 
12845   // If our only note is the usual "invalid subexpression" note, just point
12846   // the caret at its location rather than producing an essentially
12847   // redundant note.
12848   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12849         diag::note_invalid_subexpr_in_const_expr) {
12850     DiagLoc = Notes[0].first;
12851     Notes.clear();
12852   }
12853 
12854   if (!Folded || !AllowFold) {
12855     if (!Diagnoser.Suppress) {
12856       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12857       for (const PartialDiagnosticAt &Note : Notes)
12858         Diag(Note.first, Note.second);
12859     }
12860 
12861     return ExprError();
12862   }
12863 
12864   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12865   for (const PartialDiagnosticAt &Note : Notes)
12866     Diag(Note.first, Note.second);
12867 
12868   if (Result)
12869     *Result = EvalResult.Val.getInt();
12870   return E;
12871 }
12872 
12873 namespace {
12874   // Handle the case where we conclude a expression which we speculatively
12875   // considered to be unevaluated is actually evaluated.
12876   class TransformToPE : public TreeTransform<TransformToPE> {
12877     typedef TreeTransform<TransformToPE> BaseTransform;
12878 
12879   public:
12880     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12881 
12882     // Make sure we redo semantic analysis
12883     bool AlwaysRebuild() { return true; }
12884 
12885     // Make sure we handle LabelStmts correctly.
12886     // FIXME: This does the right thing, but maybe we need a more general
12887     // fix to TreeTransform?
12888     StmtResult TransformLabelStmt(LabelStmt *S) {
12889       S->getDecl()->setStmt(nullptr);
12890       return BaseTransform::TransformLabelStmt(S);
12891     }
12892 
12893     // We need to special-case DeclRefExprs referring to FieldDecls which
12894     // are not part of a member pointer formation; normal TreeTransforming
12895     // doesn't catch this case because of the way we represent them in the AST.
12896     // FIXME: This is a bit ugly; is it really the best way to handle this
12897     // case?
12898     //
12899     // Error on DeclRefExprs referring to FieldDecls.
12900     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12901       if (isa<FieldDecl>(E->getDecl()) &&
12902           !SemaRef.isUnevaluatedContext())
12903         return SemaRef.Diag(E->getLocation(),
12904                             diag::err_invalid_non_static_member_use)
12905             << E->getDecl() << E->getSourceRange();
12906 
12907       return BaseTransform::TransformDeclRefExpr(E);
12908     }
12909 
12910     // Exception: filter out member pointer formation
12911     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12912       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12913         return E;
12914 
12915       return BaseTransform::TransformUnaryOperator(E);
12916     }
12917 
12918     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12919       // Lambdas never need to be transformed.
12920       return E;
12921     }
12922   };
12923 }
12924 
12925 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12926   assert(isUnevaluatedContext() &&
12927          "Should only transform unevaluated expressions");
12928   ExprEvalContexts.back().Context =
12929       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12930   if (isUnevaluatedContext())
12931     return E;
12932   return TransformToPE(*this).TransformExpr(E);
12933 }
12934 
12935 void
12936 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12937                                       Decl *LambdaContextDecl,
12938                                       bool IsDecltype) {
12939   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(), Cleanup,
12940                                 LambdaContextDecl, IsDecltype);
12941   Cleanup.reset();
12942   if (!MaybeODRUseExprs.empty())
12943     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12944 }
12945 
12946 void
12947 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12948                                       ReuseLambdaContextDecl_t,
12949                                       bool IsDecltype) {
12950   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12951   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12952 }
12953 
12954 void Sema::PopExpressionEvaluationContext() {
12955   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12956   unsigned NumTypos = Rec.NumTypos;
12957 
12958   if (!Rec.Lambdas.empty()) {
12959     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12960       unsigned D;
12961       if (Rec.isUnevaluated()) {
12962         // C++11 [expr.prim.lambda]p2:
12963         //   A lambda-expression shall not appear in an unevaluated operand
12964         //   (Clause 5).
12965         D = diag::err_lambda_unevaluated_operand;
12966       } else {
12967         // C++1y [expr.const]p2:
12968         //   A conditional-expression e is a core constant expression unless the
12969         //   evaluation of e, following the rules of the abstract machine, would
12970         //   evaluate [...] a lambda-expression.
12971         D = diag::err_lambda_in_constant_expression;
12972       }
12973       for (const auto *L : Rec.Lambdas)
12974         Diag(L->getLocStart(), D);
12975     } else {
12976       // Mark the capture expressions odr-used. This was deferred
12977       // during lambda expression creation.
12978       for (auto *Lambda : Rec.Lambdas) {
12979         for (auto *C : Lambda->capture_inits())
12980           MarkDeclarationsReferencedInExpr(C);
12981       }
12982     }
12983   }
12984 
12985   // When are coming out of an unevaluated context, clear out any
12986   // temporaries that we may have created as part of the evaluation of
12987   // the expression in that context: they aren't relevant because they
12988   // will never be constructed.
12989   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12990     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12991                              ExprCleanupObjects.end());
12992     Cleanup = Rec.ParentCleanup;
12993     CleanupVarDeclMarking();
12994     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12995   // Otherwise, merge the contexts together.
12996   } else {
12997     Cleanup.mergeFrom(Rec.ParentCleanup);
12998     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12999                             Rec.SavedMaybeODRUseExprs.end());
13000   }
13001 
13002   // Pop the current expression evaluation context off the stack.
13003   ExprEvalContexts.pop_back();
13004 
13005   if (!ExprEvalContexts.empty())
13006     ExprEvalContexts.back().NumTypos += NumTypos;
13007   else
13008     assert(NumTypos == 0 && "There are outstanding typos after popping the "
13009                             "last ExpressionEvaluationContextRecord");
13010 }
13011 
13012 void Sema::DiscardCleanupsInEvaluationContext() {
13013   ExprCleanupObjects.erase(
13014          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
13015          ExprCleanupObjects.end());
13016   Cleanup.reset();
13017   MaybeODRUseExprs.clear();
13018 }
13019 
13020 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
13021   if (!E->getType()->isVariablyModifiedType())
13022     return E;
13023   return TransformToPotentiallyEvaluated(E);
13024 }
13025 
13026 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
13027   // Do not mark anything as "used" within a dependent context; wait for
13028   // an instantiation.
13029   if (SemaRef.CurContext->isDependentContext())
13030     return false;
13031 
13032   switch (SemaRef.ExprEvalContexts.back().Context) {
13033     case Sema::Unevaluated:
13034     case Sema::UnevaluatedAbstract:
13035       // We are in an expression that is not potentially evaluated; do nothing.
13036       // (Depending on how you read the standard, we actually do need to do
13037       // something here for null pointer constants, but the standard's
13038       // definition of a null pointer constant is completely crazy.)
13039       return false;
13040 
13041     case Sema::DiscardedStatement:
13042       // These are technically a potentially evaluated but they have the effect
13043       // of suppressing use marking.
13044       return false;
13045 
13046     case Sema::ConstantEvaluated:
13047     case Sema::PotentiallyEvaluated:
13048       // We are in a potentially evaluated expression (or a constant-expression
13049       // in C++03); we need to do implicit template instantiation, implicitly
13050       // define class members, and mark most declarations as used.
13051       return true;
13052 
13053     case Sema::PotentiallyEvaluatedIfUsed:
13054       // Referenced declarations will only be used if the construct in the
13055       // containing expression is used.
13056       return false;
13057   }
13058   llvm_unreachable("Invalid context");
13059 }
13060 
13061 /// \brief Mark a function referenced, and check whether it is odr-used
13062 /// (C++ [basic.def.odr]p2, C99 6.9p3)
13063 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
13064                                   bool MightBeOdrUse) {
13065   assert(Func && "No function?");
13066 
13067   Func->setReferenced();
13068 
13069   // C++11 [basic.def.odr]p3:
13070   //   A function whose name appears as a potentially-evaluated expression is
13071   //   odr-used if it is the unique lookup result or the selected member of a
13072   //   set of overloaded functions [...].
13073   //
13074   // We (incorrectly) mark overload resolution as an unevaluated context, so we
13075   // can just check that here.
13076   bool OdrUse = MightBeOdrUse && IsPotentiallyEvaluatedContext(*this);
13077 
13078   // Determine whether we require a function definition to exist, per
13079   // C++11 [temp.inst]p3:
13080   //   Unless a function template specialization has been explicitly
13081   //   instantiated or explicitly specialized, the function template
13082   //   specialization is implicitly instantiated when the specialization is
13083   //   referenced in a context that requires a function definition to exist.
13084   //
13085   // We consider constexpr function templates to be referenced in a context
13086   // that requires a definition to exist whenever they are referenced.
13087   //
13088   // FIXME: This instantiates constexpr functions too frequently. If this is
13089   // really an unevaluated context (and we're not just in the definition of a
13090   // function template or overload resolution or other cases which we
13091   // incorrectly consider to be unevaluated contexts), and we're not in a
13092   // subexpression which we actually need to evaluate (for instance, a
13093   // template argument, array bound or an expression in a braced-init-list),
13094   // we are not permitted to instantiate this constexpr function definition.
13095   //
13096   // FIXME: This also implicitly defines special members too frequently. They
13097   // are only supposed to be implicitly defined if they are odr-used, but they
13098   // are not odr-used from constant expressions in unevaluated contexts.
13099   // However, they cannot be referenced if they are deleted, and they are
13100   // deleted whenever the implicit definition of the special member would
13101   // fail (with very few exceptions).
13102   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
13103   bool NeedDefinition =
13104       OdrUse || (Func->isConstexpr() && (Func->isImplicitlyInstantiable() ||
13105                                          (MD && !MD->isUserProvided())));
13106 
13107   // C++14 [temp.expl.spec]p6:
13108   //   If a template [...] is explicitly specialized then that specialization
13109   //   shall be declared before the first use of that specialization that would
13110   //   cause an implicit instantiation to take place, in every translation unit
13111   //   in which such a use occurs
13112   if (NeedDefinition &&
13113       (Func->getTemplateSpecializationKind() != TSK_Undeclared ||
13114        Func->getMemberSpecializationInfo()))
13115     checkSpecializationVisibility(Loc, Func);
13116 
13117   // If we don't need to mark the function as used, and we don't need to
13118   // try to provide a definition, there's nothing more to do.
13119   if ((Func->isUsed(/*CheckUsedAttr=*/false) || !OdrUse) &&
13120       (!NeedDefinition || Func->getBody()))
13121     return;
13122 
13123   // Note that this declaration has been used.
13124   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
13125     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
13126     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
13127       if (Constructor->isDefaultConstructor()) {
13128         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
13129           return;
13130         DefineImplicitDefaultConstructor(Loc, Constructor);
13131       } else if (Constructor->isCopyConstructor()) {
13132         DefineImplicitCopyConstructor(Loc, Constructor);
13133       } else if (Constructor->isMoveConstructor()) {
13134         DefineImplicitMoveConstructor(Loc, Constructor);
13135       }
13136     } else if (Constructor->getInheritedConstructor()) {
13137       DefineInheritingConstructor(Loc, Constructor);
13138     }
13139   } else if (CXXDestructorDecl *Destructor =
13140                  dyn_cast<CXXDestructorDecl>(Func)) {
13141     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
13142     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
13143       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
13144         return;
13145       DefineImplicitDestructor(Loc, Destructor);
13146     }
13147     if (Destructor->isVirtual() && getLangOpts().AppleKext)
13148       MarkVTableUsed(Loc, Destructor->getParent());
13149   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
13150     if (MethodDecl->isOverloadedOperator() &&
13151         MethodDecl->getOverloadedOperator() == OO_Equal) {
13152       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
13153       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
13154         if (MethodDecl->isCopyAssignmentOperator())
13155           DefineImplicitCopyAssignment(Loc, MethodDecl);
13156         else if (MethodDecl->isMoveAssignmentOperator())
13157           DefineImplicitMoveAssignment(Loc, MethodDecl);
13158       }
13159     } else if (isa<CXXConversionDecl>(MethodDecl) &&
13160                MethodDecl->getParent()->isLambda()) {
13161       CXXConversionDecl *Conversion =
13162           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
13163       if (Conversion->isLambdaToBlockPointerConversion())
13164         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
13165       else
13166         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
13167     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
13168       MarkVTableUsed(Loc, MethodDecl->getParent());
13169   }
13170 
13171   // Recursive functions should be marked when used from another function.
13172   // FIXME: Is this really right?
13173   if (CurContext == Func) return;
13174 
13175   // Resolve the exception specification for any function which is
13176   // used: CodeGen will need it.
13177   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
13178   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
13179     ResolveExceptionSpec(Loc, FPT);
13180 
13181   // Implicit instantiation of function templates and member functions of
13182   // class templates.
13183   if (Func->isImplicitlyInstantiable()) {
13184     bool AlreadyInstantiated = false;
13185     SourceLocation PointOfInstantiation = Loc;
13186     if (FunctionTemplateSpecializationInfo *SpecInfo
13187                               = Func->getTemplateSpecializationInfo()) {
13188       if (SpecInfo->getPointOfInstantiation().isInvalid())
13189         SpecInfo->setPointOfInstantiation(Loc);
13190       else if (SpecInfo->getTemplateSpecializationKind()
13191                  == TSK_ImplicitInstantiation) {
13192         AlreadyInstantiated = true;
13193         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
13194       }
13195     } else if (MemberSpecializationInfo *MSInfo
13196                                 = Func->getMemberSpecializationInfo()) {
13197       if (MSInfo->getPointOfInstantiation().isInvalid())
13198         MSInfo->setPointOfInstantiation(Loc);
13199       else if (MSInfo->getTemplateSpecializationKind()
13200                  == TSK_ImplicitInstantiation) {
13201         AlreadyInstantiated = true;
13202         PointOfInstantiation = MSInfo->getPointOfInstantiation();
13203       }
13204     }
13205 
13206     if (!AlreadyInstantiated || Func->isConstexpr()) {
13207       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
13208           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
13209           ActiveTemplateInstantiations.size())
13210         PendingLocalImplicitInstantiations.push_back(
13211             std::make_pair(Func, PointOfInstantiation));
13212       else if (Func->isConstexpr())
13213         // Do not defer instantiations of constexpr functions, to avoid the
13214         // expression evaluator needing to call back into Sema if it sees a
13215         // call to such a function.
13216         InstantiateFunctionDefinition(PointOfInstantiation, Func);
13217       else {
13218         PendingInstantiations.push_back(std::make_pair(Func,
13219                                                        PointOfInstantiation));
13220         // Notify the consumer that a function was implicitly instantiated.
13221         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
13222       }
13223     }
13224   } else {
13225     // Walk redefinitions, as some of them may be instantiable.
13226     for (auto i : Func->redecls()) {
13227       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
13228         MarkFunctionReferenced(Loc, i, OdrUse);
13229     }
13230   }
13231 
13232   if (!OdrUse) return;
13233 
13234   // Keep track of used but undefined functions.
13235   if (!Func->isDefined()) {
13236     if (mightHaveNonExternalLinkage(Func))
13237       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13238     else if (Func->getMostRecentDecl()->isInlined() &&
13239              !LangOpts.GNUInline &&
13240              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
13241       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
13242   }
13243 
13244   Func->markUsed(Context);
13245 }
13246 
13247 static void
13248 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
13249                                    ValueDecl *var, DeclContext *DC) {
13250   DeclContext *VarDC = var->getDeclContext();
13251 
13252   //  If the parameter still belongs to the translation unit, then
13253   //  we're actually just using one parameter in the declaration of
13254   //  the next.
13255   if (isa<ParmVarDecl>(var) &&
13256       isa<TranslationUnitDecl>(VarDC))
13257     return;
13258 
13259   // For C code, don't diagnose about capture if we're not actually in code
13260   // right now; it's impossible to write a non-constant expression outside of
13261   // function context, so we'll get other (more useful) diagnostics later.
13262   //
13263   // For C++, things get a bit more nasty... it would be nice to suppress this
13264   // diagnostic for certain cases like using a local variable in an array bound
13265   // for a member of a local class, but the correct predicate is not obvious.
13266   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
13267     return;
13268 
13269   unsigned ValueKind = isa<BindingDecl>(var) ? 1 : 0;
13270   unsigned ContextKind = 3; // unknown
13271   if (isa<CXXMethodDecl>(VarDC) &&
13272       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
13273     ContextKind = 2;
13274   } else if (isa<FunctionDecl>(VarDC)) {
13275     ContextKind = 0;
13276   } else if (isa<BlockDecl>(VarDC)) {
13277     ContextKind = 1;
13278   }
13279 
13280   S.Diag(loc, diag::err_reference_to_local_in_enclosing_context)
13281     << var << ValueKind << ContextKind << VarDC;
13282   S.Diag(var->getLocation(), diag::note_entity_declared_at)
13283       << var;
13284 
13285   // FIXME: Add additional diagnostic info about class etc. which prevents
13286   // capture.
13287 }
13288 
13289 
13290 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
13291                                       bool &SubCapturesAreNested,
13292                                       QualType &CaptureType,
13293                                       QualType &DeclRefType) {
13294    // Check whether we've already captured it.
13295   if (CSI->CaptureMap.count(Var)) {
13296     // If we found a capture, any subcaptures are nested.
13297     SubCapturesAreNested = true;
13298 
13299     // Retrieve the capture type for this variable.
13300     CaptureType = CSI->getCapture(Var).getCaptureType();
13301 
13302     // Compute the type of an expression that refers to this variable.
13303     DeclRefType = CaptureType.getNonReferenceType();
13304 
13305     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
13306     // are mutable in the sense that user can change their value - they are
13307     // private instances of the captured declarations.
13308     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
13309     if (Cap.isCopyCapture() &&
13310         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
13311         !(isa<CapturedRegionScopeInfo>(CSI) &&
13312           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
13313       DeclRefType.addConst();
13314     return true;
13315   }
13316   return false;
13317 }
13318 
13319 // Only block literals, captured statements, and lambda expressions can
13320 // capture; other scopes don't work.
13321 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
13322                                  SourceLocation Loc,
13323                                  const bool Diagnose, Sema &S) {
13324   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
13325     return getLambdaAwareParentOfDeclContext(DC);
13326   else if (Var->hasLocalStorage()) {
13327     if (Diagnose)
13328        diagnoseUncapturableValueReference(S, Loc, Var, DC);
13329   }
13330   return nullptr;
13331 }
13332 
13333 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13334 // certain types of variables (unnamed, variably modified types etc.)
13335 // so check for eligibility.
13336 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
13337                                  SourceLocation Loc,
13338                                  const bool Diagnose, Sema &S) {
13339 
13340   bool IsBlock = isa<BlockScopeInfo>(CSI);
13341   bool IsLambda = isa<LambdaScopeInfo>(CSI);
13342 
13343   // Lambdas are not allowed to capture unnamed variables
13344   // (e.g. anonymous unions).
13345   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
13346   // assuming that's the intent.
13347   if (IsLambda && !Var->getDeclName()) {
13348     if (Diagnose) {
13349       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
13350       S.Diag(Var->getLocation(), diag::note_declared_at);
13351     }
13352     return false;
13353   }
13354 
13355   // Prohibit variably-modified types in blocks; they're difficult to deal with.
13356   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
13357     if (Diagnose) {
13358       S.Diag(Loc, diag::err_ref_vm_type);
13359       S.Diag(Var->getLocation(), diag::note_previous_decl)
13360         << Var->getDeclName();
13361     }
13362     return false;
13363   }
13364   // Prohibit structs with flexible array members too.
13365   // We cannot capture what is in the tail end of the struct.
13366   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
13367     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
13368       if (Diagnose) {
13369         if (IsBlock)
13370           S.Diag(Loc, diag::err_ref_flexarray_type);
13371         else
13372           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
13373             << Var->getDeclName();
13374         S.Diag(Var->getLocation(), diag::note_previous_decl)
13375           << Var->getDeclName();
13376       }
13377       return false;
13378     }
13379   }
13380   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13381   // Lambdas and captured statements are not allowed to capture __block
13382   // variables; they don't support the expected semantics.
13383   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
13384     if (Diagnose) {
13385       S.Diag(Loc, diag::err_capture_block_variable)
13386         << Var->getDeclName() << !IsLambda;
13387       S.Diag(Var->getLocation(), diag::note_previous_decl)
13388         << Var->getDeclName();
13389     }
13390     return false;
13391   }
13392 
13393   return true;
13394 }
13395 
13396 // Returns true if the capture by block was successful.
13397 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
13398                                  SourceLocation Loc,
13399                                  const bool BuildAndDiagnose,
13400                                  QualType &CaptureType,
13401                                  QualType &DeclRefType,
13402                                  const bool Nested,
13403                                  Sema &S) {
13404   Expr *CopyExpr = nullptr;
13405   bool ByRef = false;
13406 
13407   // Blocks are not allowed to capture arrays.
13408   if (CaptureType->isArrayType()) {
13409     if (BuildAndDiagnose) {
13410       S.Diag(Loc, diag::err_ref_array_type);
13411       S.Diag(Var->getLocation(), diag::note_previous_decl)
13412       << Var->getDeclName();
13413     }
13414     return false;
13415   }
13416 
13417   // Forbid the block-capture of autoreleasing variables.
13418   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13419     if (BuildAndDiagnose) {
13420       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
13421         << /*block*/ 0;
13422       S.Diag(Var->getLocation(), diag::note_previous_decl)
13423         << Var->getDeclName();
13424     }
13425     return false;
13426   }
13427   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
13428   if (HasBlocksAttr || CaptureType->isReferenceType() ||
13429       (S.getLangOpts().OpenMP && S.IsOpenMPCapturedDecl(Var))) {
13430     // Block capture by reference does not change the capture or
13431     // declaration reference types.
13432     ByRef = true;
13433   } else {
13434     // Block capture by copy introduces 'const'.
13435     CaptureType = CaptureType.getNonReferenceType().withConst();
13436     DeclRefType = CaptureType;
13437 
13438     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
13439       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
13440         // The capture logic needs the destructor, so make sure we mark it.
13441         // Usually this is unnecessary because most local variables have
13442         // their destructors marked at declaration time, but parameters are
13443         // an exception because it's technically only the call site that
13444         // actually requires the destructor.
13445         if (isa<ParmVarDecl>(Var))
13446           S.FinalizeVarWithDestructor(Var, Record);
13447 
13448         // Enter a new evaluation context to insulate the copy
13449         // full-expression.
13450         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
13451 
13452         // According to the blocks spec, the capture of a variable from
13453         // the stack requires a const copy constructor.  This is not true
13454         // of the copy/move done to move a __block variable to the heap.
13455         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
13456                                                   DeclRefType.withConst(),
13457                                                   VK_LValue, Loc);
13458 
13459         ExprResult Result
13460           = S.PerformCopyInitialization(
13461               InitializedEntity::InitializeBlock(Var->getLocation(),
13462                                                   CaptureType, false),
13463               Loc, DeclRef);
13464 
13465         // Build a full-expression copy expression if initialization
13466         // succeeded and used a non-trivial constructor.  Recover from
13467         // errors by pretending that the copy isn't necessary.
13468         if (!Result.isInvalid() &&
13469             !cast<CXXConstructExpr>(Result.get())->getConstructor()
13470                 ->isTrivial()) {
13471           Result = S.MaybeCreateExprWithCleanups(Result);
13472           CopyExpr = Result.get();
13473         }
13474       }
13475     }
13476   }
13477 
13478   // Actually capture the variable.
13479   if (BuildAndDiagnose)
13480     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
13481                     SourceLocation(), CaptureType, CopyExpr);
13482 
13483   return true;
13484 
13485 }
13486 
13487 
13488 /// \brief Capture the given variable in the captured region.
13489 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
13490                                     VarDecl *Var,
13491                                     SourceLocation Loc,
13492                                     const bool BuildAndDiagnose,
13493                                     QualType &CaptureType,
13494                                     QualType &DeclRefType,
13495                                     const bool RefersToCapturedVariable,
13496                                     Sema &S) {
13497   // By default, capture variables by reference.
13498   bool ByRef = true;
13499   // Using an LValue reference type is consistent with Lambdas (see below).
13500   if (S.getLangOpts().OpenMP && RSI->CapRegionKind == CR_OpenMP) {
13501     if (S.IsOpenMPCapturedDecl(Var))
13502       DeclRefType = DeclRefType.getUnqualifiedType();
13503     ByRef = S.IsOpenMPCapturedByRef(Var, RSI->OpenMPLevel);
13504   }
13505 
13506   if (ByRef)
13507     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13508   else
13509     CaptureType = DeclRefType;
13510 
13511   Expr *CopyExpr = nullptr;
13512   if (BuildAndDiagnose) {
13513     // The current implementation assumes that all variables are captured
13514     // by references. Since there is no capture by copy, no expression
13515     // evaluation will be needed.
13516     RecordDecl *RD = RSI->TheRecordDecl;
13517 
13518     FieldDecl *Field
13519       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
13520                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
13521                           nullptr, false, ICIS_NoInit);
13522     Field->setImplicit(true);
13523     Field->setAccess(AS_private);
13524     RD->addDecl(Field);
13525 
13526     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
13527                                             DeclRefType, VK_LValue, Loc);
13528     Var->setReferenced(true);
13529     Var->markUsed(S.Context);
13530   }
13531 
13532   // Actually capture the variable.
13533   if (BuildAndDiagnose)
13534     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
13535                     SourceLocation(), CaptureType, CopyExpr);
13536 
13537 
13538   return true;
13539 }
13540 
13541 /// \brief Create a field within the lambda class for the variable
13542 /// being captured.
13543 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI,
13544                                     QualType FieldType, QualType DeclRefType,
13545                                     SourceLocation Loc,
13546                                     bool RefersToCapturedVariable) {
13547   CXXRecordDecl *Lambda = LSI->Lambda;
13548 
13549   // Build the non-static data member.
13550   FieldDecl *Field
13551     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
13552                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
13553                         nullptr, false, ICIS_NoInit);
13554   Field->setImplicit(true);
13555   Field->setAccess(AS_private);
13556   Lambda->addDecl(Field);
13557 }
13558 
13559 /// \brief Capture the given variable in the lambda.
13560 static bool captureInLambda(LambdaScopeInfo *LSI,
13561                             VarDecl *Var,
13562                             SourceLocation Loc,
13563                             const bool BuildAndDiagnose,
13564                             QualType &CaptureType,
13565                             QualType &DeclRefType,
13566                             const bool RefersToCapturedVariable,
13567                             const Sema::TryCaptureKind Kind,
13568                             SourceLocation EllipsisLoc,
13569                             const bool IsTopScope,
13570                             Sema &S) {
13571 
13572   // Determine whether we are capturing by reference or by value.
13573   bool ByRef = false;
13574   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
13575     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
13576   } else {
13577     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
13578   }
13579 
13580   // Compute the type of the field that will capture this variable.
13581   if (ByRef) {
13582     // C++11 [expr.prim.lambda]p15:
13583     //   An entity is captured by reference if it is implicitly or
13584     //   explicitly captured but not captured by copy. It is
13585     //   unspecified whether additional unnamed non-static data
13586     //   members are declared in the closure type for entities
13587     //   captured by reference.
13588     //
13589     // FIXME: It is not clear whether we want to build an lvalue reference
13590     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
13591     // to do the former, while EDG does the latter. Core issue 1249 will
13592     // clarify, but for now we follow GCC because it's a more permissive and
13593     // easily defensible position.
13594     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
13595   } else {
13596     // C++11 [expr.prim.lambda]p14:
13597     //   For each entity captured by copy, an unnamed non-static
13598     //   data member is declared in the closure type. The
13599     //   declaration order of these members is unspecified. The type
13600     //   of such a data member is the type of the corresponding
13601     //   captured entity if the entity is not a reference to an
13602     //   object, or the referenced type otherwise. [Note: If the
13603     //   captured entity is a reference to a function, the
13604     //   corresponding data member is also a reference to a
13605     //   function. - end note ]
13606     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
13607       if (!RefType->getPointeeType()->isFunctionType())
13608         CaptureType = RefType->getPointeeType();
13609     }
13610 
13611     // Forbid the lambda copy-capture of autoreleasing variables.
13612     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
13613       if (BuildAndDiagnose) {
13614         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
13615         S.Diag(Var->getLocation(), diag::note_previous_decl)
13616           << Var->getDeclName();
13617       }
13618       return false;
13619     }
13620 
13621     // Make sure that by-copy captures are of a complete and non-abstract type.
13622     if (BuildAndDiagnose) {
13623       if (!CaptureType->isDependentType() &&
13624           S.RequireCompleteType(Loc, CaptureType,
13625                                 diag::err_capture_of_incomplete_type,
13626                                 Var->getDeclName()))
13627         return false;
13628 
13629       if (S.RequireNonAbstractType(Loc, CaptureType,
13630                                    diag::err_capture_of_abstract_type))
13631         return false;
13632     }
13633   }
13634 
13635   // Capture this variable in the lambda.
13636   if (BuildAndDiagnose)
13637     addAsFieldToClosureType(S, LSI, CaptureType, DeclRefType, Loc,
13638                             RefersToCapturedVariable);
13639 
13640   // Compute the type of a reference to this captured variable.
13641   if (ByRef)
13642     DeclRefType = CaptureType.getNonReferenceType();
13643   else {
13644     // C++ [expr.prim.lambda]p5:
13645     //   The closure type for a lambda-expression has a public inline
13646     //   function call operator [...]. This function call operator is
13647     //   declared const (9.3.1) if and only if the lambda-expression’s
13648     //   parameter-declaration-clause is not followed by mutable.
13649     DeclRefType = CaptureType.getNonReferenceType();
13650     if (!LSI->Mutable && !CaptureType->isReferenceType())
13651       DeclRefType.addConst();
13652   }
13653 
13654   // Add the capture.
13655   if (BuildAndDiagnose)
13656     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13657                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13658 
13659   return true;
13660 }
13661 
13662 bool Sema::tryCaptureVariable(
13663     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13664     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13665     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13666   // An init-capture is notionally from the context surrounding its
13667   // declaration, but its parent DC is the lambda class.
13668   DeclContext *VarDC = Var->getDeclContext();
13669   if (Var->isInitCapture())
13670     VarDC = VarDC->getParent();
13671 
13672   DeclContext *DC = CurContext;
13673   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13674       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13675   // We need to sync up the Declaration Context with the
13676   // FunctionScopeIndexToStopAt
13677   if (FunctionScopeIndexToStopAt) {
13678     unsigned FSIndex = FunctionScopes.size() - 1;
13679     while (FSIndex != MaxFunctionScopesIndex) {
13680       DC = getLambdaAwareParentOfDeclContext(DC);
13681       --FSIndex;
13682     }
13683   }
13684 
13685 
13686   // If the variable is declared in the current context, there is no need to
13687   // capture it.
13688   if (VarDC == DC) return true;
13689 
13690   // Capture global variables if it is required to use private copy of this
13691   // variable.
13692   bool IsGlobal = !Var->hasLocalStorage();
13693   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedDecl(Var)))
13694     return true;
13695 
13696   // Walk up the stack to determine whether we can capture the variable,
13697   // performing the "simple" checks that don't depend on type. We stop when
13698   // we've either hit the declared scope of the variable or find an existing
13699   // capture of that variable.  We start from the innermost capturing-entity
13700   // (the DC) and ensure that all intervening capturing-entities
13701   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13702   // declcontext can either capture the variable or have already captured
13703   // the variable.
13704   CaptureType = Var->getType();
13705   DeclRefType = CaptureType.getNonReferenceType();
13706   bool Nested = false;
13707   bool Explicit = (Kind != TryCapture_Implicit);
13708   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13709   do {
13710     // Only block literals, captured statements, and lambda expressions can
13711     // capture; other scopes don't work.
13712     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13713                                                               ExprLoc,
13714                                                               BuildAndDiagnose,
13715                                                               *this);
13716     // We need to check for the parent *first* because, if we *have*
13717     // private-captured a global variable, we need to recursively capture it in
13718     // intermediate blocks, lambdas, etc.
13719     if (!ParentDC) {
13720       if (IsGlobal) {
13721         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13722         break;
13723       }
13724       return true;
13725     }
13726 
13727     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13728     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13729 
13730 
13731     // Check whether we've already captured it.
13732     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13733                                              DeclRefType))
13734       break;
13735     // If we are instantiating a generic lambda call operator body,
13736     // we do not want to capture new variables.  What was captured
13737     // during either a lambdas transformation or initial parsing
13738     // should be used.
13739     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13740       if (BuildAndDiagnose) {
13741         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13742         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13743           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13744           Diag(Var->getLocation(), diag::note_previous_decl)
13745              << Var->getDeclName();
13746           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13747         } else
13748           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13749       }
13750       return true;
13751     }
13752     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13753     // certain types of variables (unnamed, variably modified types etc.)
13754     // so check for eligibility.
13755     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13756        return true;
13757 
13758     // Try to capture variable-length arrays types.
13759     if (Var->getType()->isVariablyModifiedType()) {
13760       // We're going to walk down into the type and look for VLA
13761       // expressions.
13762       QualType QTy = Var->getType();
13763       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13764         QTy = PVD->getOriginalType();
13765       captureVariablyModifiedType(Context, QTy, CSI);
13766     }
13767 
13768     if (getLangOpts().OpenMP) {
13769       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13770         // OpenMP private variables should not be captured in outer scope, so
13771         // just break here. Similarly, global variables that are captured in a
13772         // target region should not be captured outside the scope of the region.
13773         if (RSI->CapRegionKind == CR_OpenMP) {
13774           auto IsTargetCap = isOpenMPTargetCapturedDecl(Var, RSI->OpenMPLevel);
13775           // When we detect target captures we are looking from inside the
13776           // target region, therefore we need to propagate the capture from the
13777           // enclosing region. Therefore, the capture is not initially nested.
13778           if (IsTargetCap)
13779             FunctionScopesIndex--;
13780 
13781           if (IsTargetCap || isOpenMPPrivateDecl(Var, RSI->OpenMPLevel)) {
13782             Nested = !IsTargetCap;
13783             DeclRefType = DeclRefType.getUnqualifiedType();
13784             CaptureType = Context.getLValueReferenceType(DeclRefType);
13785             break;
13786           }
13787         }
13788       }
13789     }
13790     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13791       // No capture-default, and this is not an explicit capture
13792       // so cannot capture this variable.
13793       if (BuildAndDiagnose) {
13794         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13795         Diag(Var->getLocation(), diag::note_previous_decl)
13796           << Var->getDeclName();
13797         if (cast<LambdaScopeInfo>(CSI)->Lambda)
13798           Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13799                diag::note_lambda_decl);
13800         // FIXME: If we error out because an outer lambda can not implicitly
13801         // capture a variable that an inner lambda explicitly captures, we
13802         // should have the inner lambda do the explicit capture - because
13803         // it makes for cleaner diagnostics later.  This would purely be done
13804         // so that the diagnostic does not misleadingly claim that a variable
13805         // can not be captured by a lambda implicitly even though it is captured
13806         // explicitly.  Suggestion:
13807         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13808         //    at the function head
13809         //  - cache the StartingDeclContext - this must be a lambda
13810         //  - captureInLambda in the innermost lambda the variable.
13811       }
13812       return true;
13813     }
13814 
13815     FunctionScopesIndex--;
13816     DC = ParentDC;
13817     Explicit = false;
13818   } while (!VarDC->Equals(DC));
13819 
13820   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13821   // computing the type of the capture at each step, checking type-specific
13822   // requirements, and adding captures if requested.
13823   // If the variable had already been captured previously, we start capturing
13824   // at the lambda nested within that one.
13825   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13826        ++I) {
13827     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13828 
13829     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13830       if (!captureInBlock(BSI, Var, ExprLoc,
13831                           BuildAndDiagnose, CaptureType,
13832                           DeclRefType, Nested, *this))
13833         return true;
13834       Nested = true;
13835     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13836       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13837                                    BuildAndDiagnose, CaptureType,
13838                                    DeclRefType, Nested, *this))
13839         return true;
13840       Nested = true;
13841     } else {
13842       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13843       if (!captureInLambda(LSI, Var, ExprLoc,
13844                            BuildAndDiagnose, CaptureType,
13845                            DeclRefType, Nested, Kind, EllipsisLoc,
13846                             /*IsTopScope*/I == N - 1, *this))
13847         return true;
13848       Nested = true;
13849     }
13850   }
13851   return false;
13852 }
13853 
13854 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13855                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13856   QualType CaptureType;
13857   QualType DeclRefType;
13858   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13859                             /*BuildAndDiagnose=*/true, CaptureType,
13860                             DeclRefType, nullptr);
13861 }
13862 
13863 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13864   QualType CaptureType;
13865   QualType DeclRefType;
13866   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13867                              /*BuildAndDiagnose=*/false, CaptureType,
13868                              DeclRefType, nullptr);
13869 }
13870 
13871 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13872   QualType CaptureType;
13873   QualType DeclRefType;
13874 
13875   // Determine whether we can capture this variable.
13876   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13877                          /*BuildAndDiagnose=*/false, CaptureType,
13878                          DeclRefType, nullptr))
13879     return QualType();
13880 
13881   return DeclRefType;
13882 }
13883 
13884 
13885 
13886 // If either the type of the variable or the initializer is dependent,
13887 // return false. Otherwise, determine whether the variable is a constant
13888 // expression. Use this if you need to know if a variable that might or
13889 // might not be dependent is truly a constant expression.
13890 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13891     ASTContext &Context) {
13892 
13893   if (Var->getType()->isDependentType())
13894     return false;
13895   const VarDecl *DefVD = nullptr;
13896   Var->getAnyInitializer(DefVD);
13897   if (!DefVD)
13898     return false;
13899   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13900   Expr *Init = cast<Expr>(Eval->Value);
13901   if (Init->isValueDependent())
13902     return false;
13903   return IsVariableAConstantExpression(Var, Context);
13904 }
13905 
13906 
13907 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13908   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13909   // an object that satisfies the requirements for appearing in a
13910   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13911   // is immediately applied."  This function handles the lvalue-to-rvalue
13912   // conversion part.
13913   MaybeODRUseExprs.erase(E->IgnoreParens());
13914 
13915   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13916   // to a variable that is a constant expression, and if so, identify it as
13917   // a reference to a variable that does not involve an odr-use of that
13918   // variable.
13919   if (LambdaScopeInfo *LSI = getCurLambda()) {
13920     Expr *SansParensExpr = E->IgnoreParens();
13921     VarDecl *Var = nullptr;
13922     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13923       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13924     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13925       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13926 
13927     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13928       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13929   }
13930 }
13931 
13932 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13933   Res = CorrectDelayedTyposInExpr(Res);
13934 
13935   if (!Res.isUsable())
13936     return Res;
13937 
13938   // If a constant-expression is a reference to a variable where we delay
13939   // deciding whether it is an odr-use, just assume we will apply the
13940   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13941   // (a non-type template argument), we have special handling anyway.
13942   UpdateMarkingForLValueToRValue(Res.get());
13943   return Res;
13944 }
13945 
13946 void Sema::CleanupVarDeclMarking() {
13947   for (Expr *E : MaybeODRUseExprs) {
13948     VarDecl *Var;
13949     SourceLocation Loc;
13950     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13951       Var = cast<VarDecl>(DRE->getDecl());
13952       Loc = DRE->getLocation();
13953     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13954       Var = cast<VarDecl>(ME->getMemberDecl());
13955       Loc = ME->getMemberLoc();
13956     } else {
13957       llvm_unreachable("Unexpected expression");
13958     }
13959 
13960     MarkVarDeclODRUsed(Var, Loc, *this,
13961                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13962   }
13963 
13964   MaybeODRUseExprs.clear();
13965 }
13966 
13967 
13968 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13969                                     VarDecl *Var, Expr *E) {
13970   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13971          "Invalid Expr argument to DoMarkVarDeclReferenced");
13972   Var->setReferenced();
13973 
13974   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13975   bool MarkODRUsed = true;
13976 
13977   // If the context is not potentially evaluated, this is not an odr-use and
13978   // does not trigger instantiation.
13979   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13980     if (SemaRef.isUnevaluatedContext())
13981       return;
13982 
13983     // If we don't yet know whether this context is going to end up being an
13984     // evaluated context, and we're referencing a variable from an enclosing
13985     // scope, add a potential capture.
13986     //
13987     // FIXME: Is this necessary? These contexts are only used for default
13988     // arguments, where local variables can't be used.
13989     const bool RefersToEnclosingScope =
13990         (SemaRef.CurContext != Var->getDeclContext() &&
13991          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13992     if (RefersToEnclosingScope) {
13993       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13994         // If a variable could potentially be odr-used, defer marking it so
13995         // until we finish analyzing the full expression for any
13996         // lvalue-to-rvalue
13997         // or discarded value conversions that would obviate odr-use.
13998         // Add it to the list of potential captures that will be analyzed
13999         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
14000         // unless the variable is a reference that was initialized by a constant
14001         // expression (this will never need to be captured or odr-used).
14002         assert(E && "Capture variable should be used in an expression.");
14003         if (!Var->getType()->isReferenceType() ||
14004             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
14005           LSI->addPotentialCapture(E->IgnoreParens());
14006       }
14007     }
14008 
14009     if (!isTemplateInstantiation(TSK))
14010       return;
14011 
14012     // Instantiate, but do not mark as odr-used, variable templates.
14013     MarkODRUsed = false;
14014   }
14015 
14016   VarTemplateSpecializationDecl *VarSpec =
14017       dyn_cast<VarTemplateSpecializationDecl>(Var);
14018   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
14019          "Can't instantiate a partial template specialization.");
14020 
14021   // If this might be a member specialization of a static data member, check
14022   // the specialization is visible. We already did the checks for variable
14023   // template specializations when we created them.
14024   if (TSK != TSK_Undeclared && !isa<VarTemplateSpecializationDecl>(Var))
14025     SemaRef.checkSpecializationVisibility(Loc, Var);
14026 
14027   // Perform implicit instantiation of static data members, static data member
14028   // templates of class templates, and variable template specializations. Delay
14029   // instantiations of variable templates, except for those that could be used
14030   // in a constant expression.
14031   if (isTemplateInstantiation(TSK)) {
14032     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
14033 
14034     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
14035       if (Var->getPointOfInstantiation().isInvalid()) {
14036         // This is a modification of an existing AST node. Notify listeners.
14037         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
14038           L->StaticDataMemberInstantiated(Var);
14039       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
14040         // Don't bother trying to instantiate it again, unless we might need
14041         // its initializer before we get to the end of the TU.
14042         TryInstantiating = false;
14043     }
14044 
14045     if (Var->getPointOfInstantiation().isInvalid())
14046       Var->setTemplateSpecializationKind(TSK, Loc);
14047 
14048     if (TryInstantiating) {
14049       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
14050       bool InstantiationDependent = false;
14051       bool IsNonDependent =
14052           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
14053                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
14054                   : true;
14055 
14056       // Do not instantiate specializations that are still type-dependent.
14057       if (IsNonDependent) {
14058         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
14059           // Do not defer instantiations of variables which could be used in a
14060           // constant expression.
14061           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
14062         } else {
14063           SemaRef.PendingInstantiations
14064               .push_back(std::make_pair(Var, PointOfInstantiation));
14065         }
14066       }
14067     }
14068   }
14069 
14070   if (!MarkODRUsed)
14071     return;
14072 
14073   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
14074   // the requirements for appearing in a constant expression (5.19) and, if
14075   // it is an object, the lvalue-to-rvalue conversion (4.1)
14076   // is immediately applied."  We check the first part here, and
14077   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
14078   // Note that we use the C++11 definition everywhere because nothing in
14079   // C++03 depends on whether we get the C++03 version correct. The second
14080   // part does not apply to references, since they are not objects.
14081   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
14082     // A reference initialized by a constant expression can never be
14083     // odr-used, so simply ignore it.
14084     if (!Var->getType()->isReferenceType())
14085       SemaRef.MaybeODRUseExprs.insert(E);
14086   } else
14087     MarkVarDeclODRUsed(Var, Loc, SemaRef,
14088                        /*MaxFunctionScopeIndex ptr*/ nullptr);
14089 }
14090 
14091 /// \brief Mark a variable referenced, and check whether it is odr-used
14092 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
14093 /// used directly for normal expressions referring to VarDecl.
14094 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
14095   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
14096 }
14097 
14098 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
14099                                Decl *D, Expr *E, bool MightBeOdrUse) {
14100   if (SemaRef.isInOpenMPDeclareTargetContext())
14101     SemaRef.checkDeclIsAllowedInOpenMPTarget(E, D);
14102 
14103   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
14104     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
14105     return;
14106   }
14107 
14108   SemaRef.MarkAnyDeclReferenced(Loc, D, MightBeOdrUse);
14109 
14110   // If this is a call to a method via a cast, also mark the method in the
14111   // derived class used in case codegen can devirtualize the call.
14112   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
14113   if (!ME)
14114     return;
14115   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
14116   if (!MD)
14117     return;
14118   // Only attempt to devirtualize if this is truly a virtual call.
14119   bool IsVirtualCall = MD->isVirtual() &&
14120                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
14121   if (!IsVirtualCall)
14122     return;
14123   const Expr *Base = ME->getBase();
14124   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
14125   if (!MostDerivedClassDecl)
14126     return;
14127   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
14128   if (!DM || DM->isPure())
14129     return;
14130   SemaRef.MarkAnyDeclReferenced(Loc, DM, MightBeOdrUse);
14131 }
14132 
14133 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
14134 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
14135   // TODO: update this with DR# once a defect report is filed.
14136   // C++11 defect. The address of a pure member should not be an ODR use, even
14137   // if it's a qualified reference.
14138   bool OdrUse = true;
14139   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
14140     if (Method->isVirtual())
14141       OdrUse = false;
14142   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
14143 }
14144 
14145 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
14146 void Sema::MarkMemberReferenced(MemberExpr *E) {
14147   // C++11 [basic.def.odr]p2:
14148   //   A non-overloaded function whose name appears as a potentially-evaluated
14149   //   expression or a member of a set of candidate functions, if selected by
14150   //   overload resolution when referred to from a potentially-evaluated
14151   //   expression, is odr-used, unless it is a pure virtual function and its
14152   //   name is not explicitly qualified.
14153   bool MightBeOdrUse = true;
14154   if (E->performsVirtualDispatch(getLangOpts())) {
14155     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
14156       if (Method->isPure())
14157         MightBeOdrUse = false;
14158   }
14159   SourceLocation Loc = E->getMemberLoc().isValid() ?
14160                             E->getMemberLoc() : E->getLocStart();
14161   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, MightBeOdrUse);
14162 }
14163 
14164 /// \brief Perform marking for a reference to an arbitrary declaration.  It
14165 /// marks the declaration referenced, and performs odr-use checking for
14166 /// functions and variables. This method should not be used when building a
14167 /// normal expression which refers to a variable.
14168 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D,
14169                                  bool MightBeOdrUse) {
14170   if (MightBeOdrUse) {
14171     if (auto *VD = dyn_cast<VarDecl>(D)) {
14172       MarkVariableReferenced(Loc, VD);
14173       return;
14174     }
14175   }
14176   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
14177     MarkFunctionReferenced(Loc, FD, MightBeOdrUse);
14178     return;
14179   }
14180   D->setReferenced();
14181 }
14182 
14183 namespace {
14184   // Mark all of the declarations referenced
14185   // FIXME: Not fully implemented yet! We need to have a better understanding
14186   // of when we're entering
14187   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
14188     Sema &S;
14189     SourceLocation Loc;
14190 
14191   public:
14192     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
14193 
14194     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
14195 
14196     bool TraverseTemplateArgument(const TemplateArgument &Arg);
14197     bool TraverseRecordType(RecordType *T);
14198   };
14199 }
14200 
14201 bool MarkReferencedDecls::TraverseTemplateArgument(
14202     const TemplateArgument &Arg) {
14203   if (Arg.getKind() == TemplateArgument::Declaration) {
14204     if (Decl *D = Arg.getAsDecl())
14205       S.MarkAnyDeclReferenced(Loc, D, true);
14206   }
14207 
14208   return Inherited::TraverseTemplateArgument(Arg);
14209 }
14210 
14211 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
14212   if (ClassTemplateSpecializationDecl *Spec
14213                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
14214     const TemplateArgumentList &Args = Spec->getTemplateArgs();
14215     return TraverseTemplateArguments(Args.data(), Args.size());
14216   }
14217 
14218   return true;
14219 }
14220 
14221 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
14222   MarkReferencedDecls Marker(*this, Loc);
14223   Marker.TraverseType(Context.getCanonicalType(T));
14224 }
14225 
14226 namespace {
14227   /// \brief Helper class that marks all of the declarations referenced by
14228   /// potentially-evaluated subexpressions as "referenced".
14229   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
14230     Sema &S;
14231     bool SkipLocalVariables;
14232 
14233   public:
14234     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
14235 
14236     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
14237       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
14238 
14239     void VisitDeclRefExpr(DeclRefExpr *E) {
14240       // If we were asked not to visit local variables, don't.
14241       if (SkipLocalVariables) {
14242         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
14243           if (VD->hasLocalStorage())
14244             return;
14245       }
14246 
14247       S.MarkDeclRefReferenced(E);
14248     }
14249 
14250     void VisitMemberExpr(MemberExpr *E) {
14251       S.MarkMemberReferenced(E);
14252       Inherited::VisitMemberExpr(E);
14253     }
14254 
14255     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
14256       S.MarkFunctionReferenced(E->getLocStart(),
14257             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
14258       Visit(E->getSubExpr());
14259     }
14260 
14261     void VisitCXXNewExpr(CXXNewExpr *E) {
14262       if (E->getOperatorNew())
14263         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
14264       if (E->getOperatorDelete())
14265         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14266       Inherited::VisitCXXNewExpr(E);
14267     }
14268 
14269     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
14270       if (E->getOperatorDelete())
14271         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
14272       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
14273       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
14274         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
14275         S.MarkFunctionReferenced(E->getLocStart(),
14276                                     S.LookupDestructor(Record));
14277       }
14278 
14279       Inherited::VisitCXXDeleteExpr(E);
14280     }
14281 
14282     void VisitCXXConstructExpr(CXXConstructExpr *E) {
14283       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
14284       Inherited::VisitCXXConstructExpr(E);
14285     }
14286 
14287     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
14288       Visit(E->getExpr());
14289     }
14290 
14291     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
14292       Inherited::VisitImplicitCastExpr(E);
14293 
14294       if (E->getCastKind() == CK_LValueToRValue)
14295         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
14296     }
14297   };
14298 }
14299 
14300 /// \brief Mark any declarations that appear within this expression or any
14301 /// potentially-evaluated subexpressions as "referenced".
14302 ///
14303 /// \param SkipLocalVariables If true, don't mark local variables as
14304 /// 'referenced'.
14305 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
14306                                             bool SkipLocalVariables) {
14307   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
14308 }
14309 
14310 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
14311 /// of the program being compiled.
14312 ///
14313 /// This routine emits the given diagnostic when the code currently being
14314 /// type-checked is "potentially evaluated", meaning that there is a
14315 /// possibility that the code will actually be executable. Code in sizeof()
14316 /// expressions, code used only during overload resolution, etc., are not
14317 /// potentially evaluated. This routine will suppress such diagnostics or,
14318 /// in the absolutely nutty case of potentially potentially evaluated
14319 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
14320 /// later.
14321 ///
14322 /// This routine should be used for all diagnostics that describe the run-time
14323 /// behavior of a program, such as passing a non-POD value through an ellipsis.
14324 /// Failure to do so will likely result in spurious diagnostics or failures
14325 /// during overload resolution or within sizeof/alignof/typeof/typeid.
14326 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
14327                                const PartialDiagnostic &PD) {
14328   switch (ExprEvalContexts.back().Context) {
14329   case Unevaluated:
14330   case UnevaluatedAbstract:
14331   case DiscardedStatement:
14332     // The argument will never be evaluated, so don't complain.
14333     break;
14334 
14335   case ConstantEvaluated:
14336     // Relevant diagnostics should be produced by constant evaluation.
14337     break;
14338 
14339   case PotentiallyEvaluated:
14340   case PotentiallyEvaluatedIfUsed:
14341     if (Statement && getCurFunctionOrMethodDecl()) {
14342       FunctionScopes.back()->PossiblyUnreachableDiags.
14343         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
14344     }
14345     else
14346       Diag(Loc, PD);
14347 
14348     return true;
14349   }
14350 
14351   return false;
14352 }
14353 
14354 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
14355                                CallExpr *CE, FunctionDecl *FD) {
14356   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
14357     return false;
14358 
14359   // If we're inside a decltype's expression, don't check for a valid return
14360   // type or construct temporaries until we know whether this is the last call.
14361   if (ExprEvalContexts.back().IsDecltype) {
14362     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
14363     return false;
14364   }
14365 
14366   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
14367     FunctionDecl *FD;
14368     CallExpr *CE;
14369 
14370   public:
14371     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
14372       : FD(FD), CE(CE) { }
14373 
14374     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
14375       if (!FD) {
14376         S.Diag(Loc, diag::err_call_incomplete_return)
14377           << T << CE->getSourceRange();
14378         return;
14379       }
14380 
14381       S.Diag(Loc, diag::err_call_function_incomplete_return)
14382         << CE->getSourceRange() << FD->getDeclName() << T;
14383       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
14384           << FD->getDeclName();
14385     }
14386   } Diagnoser(FD, CE);
14387 
14388   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
14389     return true;
14390 
14391   return false;
14392 }
14393 
14394 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
14395 // will prevent this condition from triggering, which is what we want.
14396 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
14397   SourceLocation Loc;
14398 
14399   unsigned diagnostic = diag::warn_condition_is_assignment;
14400   bool IsOrAssign = false;
14401 
14402   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
14403     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
14404       return;
14405 
14406     IsOrAssign = Op->getOpcode() == BO_OrAssign;
14407 
14408     // Greylist some idioms by putting them into a warning subcategory.
14409     if (ObjCMessageExpr *ME
14410           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
14411       Selector Sel = ME->getSelector();
14412 
14413       // self = [<foo> init...]
14414       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
14415         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14416 
14417       // <foo> = [<bar> nextObject]
14418       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
14419         diagnostic = diag::warn_condition_is_idiomatic_assignment;
14420     }
14421 
14422     Loc = Op->getOperatorLoc();
14423   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
14424     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
14425       return;
14426 
14427     IsOrAssign = Op->getOperator() == OO_PipeEqual;
14428     Loc = Op->getOperatorLoc();
14429   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
14430     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
14431   else {
14432     // Not an assignment.
14433     return;
14434   }
14435 
14436   Diag(Loc, diagnostic) << E->getSourceRange();
14437 
14438   SourceLocation Open = E->getLocStart();
14439   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
14440   Diag(Loc, diag::note_condition_assign_silence)
14441         << FixItHint::CreateInsertion(Open, "(")
14442         << FixItHint::CreateInsertion(Close, ")");
14443 
14444   if (IsOrAssign)
14445     Diag(Loc, diag::note_condition_or_assign_to_comparison)
14446       << FixItHint::CreateReplacement(Loc, "!=");
14447   else
14448     Diag(Loc, diag::note_condition_assign_to_comparison)
14449       << FixItHint::CreateReplacement(Loc, "==");
14450 }
14451 
14452 /// \brief Redundant parentheses over an equality comparison can indicate
14453 /// that the user intended an assignment used as condition.
14454 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
14455   // Don't warn if the parens came from a macro.
14456   SourceLocation parenLoc = ParenE->getLocStart();
14457   if (parenLoc.isInvalid() || parenLoc.isMacroID())
14458     return;
14459   // Don't warn for dependent expressions.
14460   if (ParenE->isTypeDependent())
14461     return;
14462 
14463   Expr *E = ParenE->IgnoreParens();
14464 
14465   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
14466     if (opE->getOpcode() == BO_EQ &&
14467         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
14468                                                            == Expr::MLV_Valid) {
14469       SourceLocation Loc = opE->getOperatorLoc();
14470 
14471       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
14472       SourceRange ParenERange = ParenE->getSourceRange();
14473       Diag(Loc, diag::note_equality_comparison_silence)
14474         << FixItHint::CreateRemoval(ParenERange.getBegin())
14475         << FixItHint::CreateRemoval(ParenERange.getEnd());
14476       Diag(Loc, diag::note_equality_comparison_to_assign)
14477         << FixItHint::CreateReplacement(Loc, "=");
14478     }
14479 }
14480 
14481 ExprResult Sema::CheckBooleanCondition(SourceLocation Loc, Expr *E,
14482                                        bool IsConstexpr) {
14483   DiagnoseAssignmentAsCondition(E);
14484   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
14485     DiagnoseEqualityWithExtraParens(parenE);
14486 
14487   ExprResult result = CheckPlaceholderExpr(E);
14488   if (result.isInvalid()) return ExprError();
14489   E = result.get();
14490 
14491   if (!E->isTypeDependent()) {
14492     if (getLangOpts().CPlusPlus)
14493       return CheckCXXBooleanCondition(E, IsConstexpr); // C++ 6.4p4
14494 
14495     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
14496     if (ERes.isInvalid())
14497       return ExprError();
14498     E = ERes.get();
14499 
14500     QualType T = E->getType();
14501     if (!T->isScalarType()) { // C99 6.8.4.1p1
14502       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
14503         << T << E->getSourceRange();
14504       return ExprError();
14505     }
14506     CheckBoolLikeConversion(E, Loc);
14507   }
14508 
14509   return E;
14510 }
14511 
14512 Sema::ConditionResult Sema::ActOnCondition(Scope *S, SourceLocation Loc,
14513                                            Expr *SubExpr, ConditionKind CK) {
14514   // Empty conditions are valid in for-statements.
14515   if (!SubExpr)
14516     return ConditionResult();
14517 
14518   ExprResult Cond;
14519   switch (CK) {
14520   case ConditionKind::Boolean:
14521     Cond = CheckBooleanCondition(Loc, SubExpr);
14522     break;
14523 
14524   case ConditionKind::ConstexprIf:
14525     Cond = CheckBooleanCondition(Loc, SubExpr, true);
14526     break;
14527 
14528   case ConditionKind::Switch:
14529     Cond = CheckSwitchCondition(Loc, SubExpr);
14530     break;
14531   }
14532   if (Cond.isInvalid())
14533     return ConditionError();
14534 
14535   // FIXME: FullExprArg doesn't have an invalid bit, so check nullness instead.
14536   FullExprArg FullExpr = MakeFullExpr(Cond.get(), Loc);
14537   if (!FullExpr.get())
14538     return ConditionError();
14539 
14540   return ConditionResult(*this, nullptr, FullExpr,
14541                          CK == ConditionKind::ConstexprIf);
14542 }
14543 
14544 namespace {
14545   /// A visitor for rebuilding a call to an __unknown_any expression
14546   /// to have an appropriate type.
14547   struct RebuildUnknownAnyFunction
14548     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
14549 
14550     Sema &S;
14551 
14552     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
14553 
14554     ExprResult VisitStmt(Stmt *S) {
14555       llvm_unreachable("unexpected statement!");
14556     }
14557 
14558     ExprResult VisitExpr(Expr *E) {
14559       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
14560         << E->getSourceRange();
14561       return ExprError();
14562     }
14563 
14564     /// Rebuild an expression which simply semantically wraps another
14565     /// expression which it shares the type and value kind of.
14566     template <class T> ExprResult rebuildSugarExpr(T *E) {
14567       ExprResult SubResult = Visit(E->getSubExpr());
14568       if (SubResult.isInvalid()) return ExprError();
14569 
14570       Expr *SubExpr = SubResult.get();
14571       E->setSubExpr(SubExpr);
14572       E->setType(SubExpr->getType());
14573       E->setValueKind(SubExpr->getValueKind());
14574       assert(E->getObjectKind() == OK_Ordinary);
14575       return E;
14576     }
14577 
14578     ExprResult VisitParenExpr(ParenExpr *E) {
14579       return rebuildSugarExpr(E);
14580     }
14581 
14582     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14583       return rebuildSugarExpr(E);
14584     }
14585 
14586     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14587       ExprResult SubResult = Visit(E->getSubExpr());
14588       if (SubResult.isInvalid()) return ExprError();
14589 
14590       Expr *SubExpr = SubResult.get();
14591       E->setSubExpr(SubExpr);
14592       E->setType(S.Context.getPointerType(SubExpr->getType()));
14593       assert(E->getValueKind() == VK_RValue);
14594       assert(E->getObjectKind() == OK_Ordinary);
14595       return E;
14596     }
14597 
14598     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14599       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14600 
14601       E->setType(VD->getType());
14602 
14603       assert(E->getValueKind() == VK_RValue);
14604       if (S.getLangOpts().CPlusPlus &&
14605           !(isa<CXXMethodDecl>(VD) &&
14606             cast<CXXMethodDecl>(VD)->isInstance()))
14607         E->setValueKind(VK_LValue);
14608 
14609       return E;
14610     }
14611 
14612     ExprResult VisitMemberExpr(MemberExpr *E) {
14613       return resolveDecl(E, E->getMemberDecl());
14614     }
14615 
14616     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14617       return resolveDecl(E, E->getDecl());
14618     }
14619   };
14620 }
14621 
14622 /// Given a function expression of unknown-any type, try to rebuild it
14623 /// to have a function type.
14624 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14625   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14626   if (Result.isInvalid()) return ExprError();
14627   return S.DefaultFunctionArrayConversion(Result.get());
14628 }
14629 
14630 namespace {
14631   /// A visitor for rebuilding an expression of type __unknown_anytype
14632   /// into one which resolves the type directly on the referring
14633   /// expression.  Strict preservation of the original source
14634   /// structure is not a goal.
14635   struct RebuildUnknownAnyExpr
14636     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14637 
14638     Sema &S;
14639 
14640     /// The current destination type.
14641     QualType DestType;
14642 
14643     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14644       : S(S), DestType(CastType) {}
14645 
14646     ExprResult VisitStmt(Stmt *S) {
14647       llvm_unreachable("unexpected statement!");
14648     }
14649 
14650     ExprResult VisitExpr(Expr *E) {
14651       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14652         << E->getSourceRange();
14653       return ExprError();
14654     }
14655 
14656     ExprResult VisitCallExpr(CallExpr *E);
14657     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14658 
14659     /// Rebuild an expression which simply semantically wraps another
14660     /// expression which it shares the type and value kind of.
14661     template <class T> ExprResult rebuildSugarExpr(T *E) {
14662       ExprResult SubResult = Visit(E->getSubExpr());
14663       if (SubResult.isInvalid()) return ExprError();
14664       Expr *SubExpr = SubResult.get();
14665       E->setSubExpr(SubExpr);
14666       E->setType(SubExpr->getType());
14667       E->setValueKind(SubExpr->getValueKind());
14668       assert(E->getObjectKind() == OK_Ordinary);
14669       return E;
14670     }
14671 
14672     ExprResult VisitParenExpr(ParenExpr *E) {
14673       return rebuildSugarExpr(E);
14674     }
14675 
14676     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14677       return rebuildSugarExpr(E);
14678     }
14679 
14680     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14681       const PointerType *Ptr = DestType->getAs<PointerType>();
14682       if (!Ptr) {
14683         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14684           << E->getSourceRange();
14685         return ExprError();
14686       }
14687       assert(E->getValueKind() == VK_RValue);
14688       assert(E->getObjectKind() == OK_Ordinary);
14689       E->setType(DestType);
14690 
14691       // Build the sub-expression as if it were an object of the pointee type.
14692       DestType = Ptr->getPointeeType();
14693       ExprResult SubResult = Visit(E->getSubExpr());
14694       if (SubResult.isInvalid()) return ExprError();
14695       E->setSubExpr(SubResult.get());
14696       return E;
14697     }
14698 
14699     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14700 
14701     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14702 
14703     ExprResult VisitMemberExpr(MemberExpr *E) {
14704       return resolveDecl(E, E->getMemberDecl());
14705     }
14706 
14707     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14708       return resolveDecl(E, E->getDecl());
14709     }
14710   };
14711 }
14712 
14713 /// Rebuilds a call expression which yielded __unknown_anytype.
14714 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14715   Expr *CalleeExpr = E->getCallee();
14716 
14717   enum FnKind {
14718     FK_MemberFunction,
14719     FK_FunctionPointer,
14720     FK_BlockPointer
14721   };
14722 
14723   FnKind Kind;
14724   QualType CalleeType = CalleeExpr->getType();
14725   if (CalleeType == S.Context.BoundMemberTy) {
14726     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14727     Kind = FK_MemberFunction;
14728     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14729   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14730     CalleeType = Ptr->getPointeeType();
14731     Kind = FK_FunctionPointer;
14732   } else {
14733     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14734     Kind = FK_BlockPointer;
14735   }
14736   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14737 
14738   // Verify that this is a legal result type of a function.
14739   if (DestType->isArrayType() || DestType->isFunctionType()) {
14740     unsigned diagID = diag::err_func_returning_array_function;
14741     if (Kind == FK_BlockPointer)
14742       diagID = diag::err_block_returning_array_function;
14743 
14744     S.Diag(E->getExprLoc(), diagID)
14745       << DestType->isFunctionType() << DestType;
14746     return ExprError();
14747   }
14748 
14749   // Otherwise, go ahead and set DestType as the call's result.
14750   E->setType(DestType.getNonLValueExprType(S.Context));
14751   E->setValueKind(Expr::getValueKindForType(DestType));
14752   assert(E->getObjectKind() == OK_Ordinary);
14753 
14754   // Rebuild the function type, replacing the result type with DestType.
14755   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14756   if (Proto) {
14757     // __unknown_anytype(...) is a special case used by the debugger when
14758     // it has no idea what a function's signature is.
14759     //
14760     // We want to build this call essentially under the K&R
14761     // unprototyped rules, but making a FunctionNoProtoType in C++
14762     // would foul up all sorts of assumptions.  However, we cannot
14763     // simply pass all arguments as variadic arguments, nor can we
14764     // portably just call the function under a non-variadic type; see
14765     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14766     // However, it turns out that in practice it is generally safe to
14767     // call a function declared as "A foo(B,C,D);" under the prototype
14768     // "A foo(B,C,D,...);".  The only known exception is with the
14769     // Windows ABI, where any variadic function is implicitly cdecl
14770     // regardless of its normal CC.  Therefore we change the parameter
14771     // types to match the types of the arguments.
14772     //
14773     // This is a hack, but it is far superior to moving the
14774     // corresponding target-specific code from IR-gen to Sema/AST.
14775 
14776     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14777     SmallVector<QualType, 8> ArgTypes;
14778     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14779       ArgTypes.reserve(E->getNumArgs());
14780       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14781         Expr *Arg = E->getArg(i);
14782         QualType ArgType = Arg->getType();
14783         if (E->isLValue()) {
14784           ArgType = S.Context.getLValueReferenceType(ArgType);
14785         } else if (E->isXValue()) {
14786           ArgType = S.Context.getRValueReferenceType(ArgType);
14787         }
14788         ArgTypes.push_back(ArgType);
14789       }
14790       ParamTypes = ArgTypes;
14791     }
14792     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14793                                          Proto->getExtProtoInfo());
14794   } else {
14795     DestType = S.Context.getFunctionNoProtoType(DestType,
14796                                                 FnType->getExtInfo());
14797   }
14798 
14799   // Rebuild the appropriate pointer-to-function type.
14800   switch (Kind) {
14801   case FK_MemberFunction:
14802     // Nothing to do.
14803     break;
14804 
14805   case FK_FunctionPointer:
14806     DestType = S.Context.getPointerType(DestType);
14807     break;
14808 
14809   case FK_BlockPointer:
14810     DestType = S.Context.getBlockPointerType(DestType);
14811     break;
14812   }
14813 
14814   // Finally, we can recurse.
14815   ExprResult CalleeResult = Visit(CalleeExpr);
14816   if (!CalleeResult.isUsable()) return ExprError();
14817   E->setCallee(CalleeResult.get());
14818 
14819   // Bind a temporary if necessary.
14820   return S.MaybeBindToTemporary(E);
14821 }
14822 
14823 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14824   // Verify that this is a legal result type of a call.
14825   if (DestType->isArrayType() || DestType->isFunctionType()) {
14826     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14827       << DestType->isFunctionType() << DestType;
14828     return ExprError();
14829   }
14830 
14831   // Rewrite the method result type if available.
14832   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14833     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14834     Method->setReturnType(DestType);
14835   }
14836 
14837   // Change the type of the message.
14838   E->setType(DestType.getNonReferenceType());
14839   E->setValueKind(Expr::getValueKindForType(DestType));
14840 
14841   return S.MaybeBindToTemporary(E);
14842 }
14843 
14844 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14845   // The only case we should ever see here is a function-to-pointer decay.
14846   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14847     assert(E->getValueKind() == VK_RValue);
14848     assert(E->getObjectKind() == OK_Ordinary);
14849 
14850     E->setType(DestType);
14851 
14852     // Rebuild the sub-expression as the pointee (function) type.
14853     DestType = DestType->castAs<PointerType>()->getPointeeType();
14854 
14855     ExprResult Result = Visit(E->getSubExpr());
14856     if (!Result.isUsable()) return ExprError();
14857 
14858     E->setSubExpr(Result.get());
14859     return E;
14860   } else if (E->getCastKind() == CK_LValueToRValue) {
14861     assert(E->getValueKind() == VK_RValue);
14862     assert(E->getObjectKind() == OK_Ordinary);
14863 
14864     assert(isa<BlockPointerType>(E->getType()));
14865 
14866     E->setType(DestType);
14867 
14868     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14869     DestType = S.Context.getLValueReferenceType(DestType);
14870 
14871     ExprResult Result = Visit(E->getSubExpr());
14872     if (!Result.isUsable()) return ExprError();
14873 
14874     E->setSubExpr(Result.get());
14875     return E;
14876   } else {
14877     llvm_unreachable("Unhandled cast type!");
14878   }
14879 }
14880 
14881 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14882   ExprValueKind ValueKind = VK_LValue;
14883   QualType Type = DestType;
14884 
14885   // We know how to make this work for certain kinds of decls:
14886 
14887   //  - functions
14888   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14889     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14890       DestType = Ptr->getPointeeType();
14891       ExprResult Result = resolveDecl(E, VD);
14892       if (Result.isInvalid()) return ExprError();
14893       return S.ImpCastExprToType(Result.get(), Type,
14894                                  CK_FunctionToPointerDecay, VK_RValue);
14895     }
14896 
14897     if (!Type->isFunctionType()) {
14898       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14899         << VD << E->getSourceRange();
14900       return ExprError();
14901     }
14902     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14903       // We must match the FunctionDecl's type to the hack introduced in
14904       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14905       // type. See the lengthy commentary in that routine.
14906       QualType FDT = FD->getType();
14907       const FunctionType *FnType = FDT->castAs<FunctionType>();
14908       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14909       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14910       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14911         SourceLocation Loc = FD->getLocation();
14912         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14913                                       FD->getDeclContext(),
14914                                       Loc, Loc, FD->getNameInfo().getName(),
14915                                       DestType, FD->getTypeSourceInfo(),
14916                                       SC_None, false/*isInlineSpecified*/,
14917                                       FD->hasPrototype(),
14918                                       false/*isConstexprSpecified*/);
14919 
14920         if (FD->getQualifier())
14921           NewFD->setQualifierInfo(FD->getQualifierLoc());
14922 
14923         SmallVector<ParmVarDecl*, 16> Params;
14924         for (const auto &AI : FT->param_types()) {
14925           ParmVarDecl *Param =
14926             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14927           Param->setScopeInfo(0, Params.size());
14928           Params.push_back(Param);
14929         }
14930         NewFD->setParams(Params);
14931         DRE->setDecl(NewFD);
14932         VD = DRE->getDecl();
14933       }
14934     }
14935 
14936     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14937       if (MD->isInstance()) {
14938         ValueKind = VK_RValue;
14939         Type = S.Context.BoundMemberTy;
14940       }
14941 
14942     // Function references aren't l-values in C.
14943     if (!S.getLangOpts().CPlusPlus)
14944       ValueKind = VK_RValue;
14945 
14946   //  - variables
14947   } else if (isa<VarDecl>(VD)) {
14948     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14949       Type = RefTy->getPointeeType();
14950     } else if (Type->isFunctionType()) {
14951       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14952         << VD << E->getSourceRange();
14953       return ExprError();
14954     }
14955 
14956   //  - nothing else
14957   } else {
14958     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14959       << VD << E->getSourceRange();
14960     return ExprError();
14961   }
14962 
14963   // Modifying the declaration like this is friendly to IR-gen but
14964   // also really dangerous.
14965   VD->setType(DestType);
14966   E->setType(Type);
14967   E->setValueKind(ValueKind);
14968   return E;
14969 }
14970 
14971 /// Check a cast of an unknown-any type.  We intentionally only
14972 /// trigger this for C-style casts.
14973 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14974                                      Expr *CastExpr, CastKind &CastKind,
14975                                      ExprValueKind &VK, CXXCastPath &Path) {
14976   // The type we're casting to must be either void or complete.
14977   if (!CastType->isVoidType() &&
14978       RequireCompleteType(TypeRange.getBegin(), CastType,
14979                           diag::err_typecheck_cast_to_incomplete))
14980     return ExprError();
14981 
14982   // Rewrite the casted expression from scratch.
14983   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14984   if (!result.isUsable()) return ExprError();
14985 
14986   CastExpr = result.get();
14987   VK = CastExpr->getValueKind();
14988   CastKind = CK_NoOp;
14989 
14990   return CastExpr;
14991 }
14992 
14993 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14994   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14995 }
14996 
14997 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14998                                     Expr *arg, QualType &paramType) {
14999   // If the syntactic form of the argument is not an explicit cast of
15000   // any sort, just do default argument promotion.
15001   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
15002   if (!castArg) {
15003     ExprResult result = DefaultArgumentPromotion(arg);
15004     if (result.isInvalid()) return ExprError();
15005     paramType = result.get()->getType();
15006     return result;
15007   }
15008 
15009   // Otherwise, use the type that was written in the explicit cast.
15010   assert(!arg->hasPlaceholderType());
15011   paramType = castArg->getTypeAsWritten();
15012 
15013   // Copy-initialize a parameter of that type.
15014   InitializedEntity entity =
15015     InitializedEntity::InitializeParameter(Context, paramType,
15016                                            /*consumed*/ false);
15017   return PerformCopyInitialization(entity, callLoc, arg);
15018 }
15019 
15020 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
15021   Expr *orig = E;
15022   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
15023   while (true) {
15024     E = E->IgnoreParenImpCasts();
15025     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
15026       E = call->getCallee();
15027       diagID = diag::err_uncasted_call_of_unknown_any;
15028     } else {
15029       break;
15030     }
15031   }
15032 
15033   SourceLocation loc;
15034   NamedDecl *d;
15035   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
15036     loc = ref->getLocation();
15037     d = ref->getDecl();
15038   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
15039     loc = mem->getMemberLoc();
15040     d = mem->getMemberDecl();
15041   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
15042     diagID = diag::err_uncasted_call_of_unknown_any;
15043     loc = msg->getSelectorStartLoc();
15044     d = msg->getMethodDecl();
15045     if (!d) {
15046       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
15047         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
15048         << orig->getSourceRange();
15049       return ExprError();
15050     }
15051   } else {
15052     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
15053       << E->getSourceRange();
15054     return ExprError();
15055   }
15056 
15057   S.Diag(loc, diagID) << d << orig->getSourceRange();
15058 
15059   // Never recoverable.
15060   return ExprError();
15061 }
15062 
15063 /// Check for operands with placeholder types and complain if found.
15064 /// Returns true if there was an error and no recovery was possible.
15065 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
15066   if (!getLangOpts().CPlusPlus) {
15067     // C cannot handle TypoExpr nodes on either side of a binop because it
15068     // doesn't handle dependent types properly, so make sure any TypoExprs have
15069     // been dealt with before checking the operands.
15070     ExprResult Result = CorrectDelayedTyposInExpr(E);
15071     if (!Result.isUsable()) return ExprError();
15072     E = Result.get();
15073   }
15074 
15075   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
15076   if (!placeholderType) return E;
15077 
15078   switch (placeholderType->getKind()) {
15079 
15080   // Overloaded expressions.
15081   case BuiltinType::Overload: {
15082     // Try to resolve a single function template specialization.
15083     // This is obligatory.
15084     ExprResult Result = E;
15085     if (ResolveAndFixSingleFunctionTemplateSpecialization(Result, false))
15086       return Result;
15087 
15088     // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
15089     // leaves Result unchanged on failure.
15090     Result = E;
15091     if (resolveAndFixAddressOfOnlyViableOverloadCandidate(Result))
15092       return Result;
15093 
15094     // If that failed, try to recover with a call.
15095     tryToRecoverWithCall(Result, PDiag(diag::err_ovl_unresolvable),
15096                          /*complain*/ true);
15097     return Result;
15098   }
15099 
15100   // Bound member functions.
15101   case BuiltinType::BoundMember: {
15102     ExprResult result = E;
15103     const Expr *BME = E->IgnoreParens();
15104     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
15105     // Try to give a nicer diagnostic if it is a bound member that we recognize.
15106     if (isa<CXXPseudoDestructorExpr>(BME)) {
15107       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
15108     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
15109       if (ME->getMemberNameInfo().getName().getNameKind() ==
15110           DeclarationName::CXXDestructorName)
15111         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
15112     }
15113     tryToRecoverWithCall(result, PD,
15114                          /*complain*/ true);
15115     return result;
15116   }
15117 
15118   // ARC unbridged casts.
15119   case BuiltinType::ARCUnbridgedCast: {
15120     Expr *realCast = stripARCUnbridgedCast(E);
15121     diagnoseARCUnbridgedCast(realCast);
15122     return realCast;
15123   }
15124 
15125   // Expressions of unknown type.
15126   case BuiltinType::UnknownAny:
15127     return diagnoseUnknownAnyExpr(*this, E);
15128 
15129   // Pseudo-objects.
15130   case BuiltinType::PseudoObject:
15131     return checkPseudoObjectRValue(E);
15132 
15133   case BuiltinType::BuiltinFn: {
15134     // Accept __noop without parens by implicitly converting it to a call expr.
15135     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
15136     if (DRE) {
15137       auto *FD = cast<FunctionDecl>(DRE->getDecl());
15138       if (FD->getBuiltinID() == Builtin::BI__noop) {
15139         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
15140                               CK_BuiltinFnToFnPtr).get();
15141         return new (Context) CallExpr(Context, E, None, Context.IntTy,
15142                                       VK_RValue, SourceLocation());
15143       }
15144     }
15145 
15146     Diag(E->getLocStart(), diag::err_builtin_fn_use);
15147     return ExprError();
15148   }
15149 
15150   // Expressions of unknown type.
15151   case BuiltinType::OMPArraySection:
15152     Diag(E->getLocStart(), diag::err_omp_array_section_use);
15153     return ExprError();
15154 
15155   // Everything else should be impossible.
15156 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
15157   case BuiltinType::Id:
15158 #include "clang/Basic/OpenCLImageTypes.def"
15159 #define BUILTIN_TYPE(Id, SingletonId) case BuiltinType::Id:
15160 #define PLACEHOLDER_TYPE(Id, SingletonId)
15161 #include "clang/AST/BuiltinTypes.def"
15162     break;
15163   }
15164 
15165   llvm_unreachable("invalid placeholder type!");
15166 }
15167 
15168 bool Sema::CheckCaseExpression(Expr *E) {
15169   if (E->isTypeDependent())
15170     return true;
15171   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
15172     return E->getType()->isIntegralOrEnumerationType();
15173   return false;
15174 }
15175 
15176 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
15177 ExprResult
15178 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
15179   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
15180          "Unknown Objective-C Boolean value!");
15181   QualType BoolT = Context.ObjCBuiltinBoolTy;
15182   if (!Context.getBOOLDecl()) {
15183     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
15184                         Sema::LookupOrdinaryName);
15185     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
15186       NamedDecl *ND = Result.getFoundDecl();
15187       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
15188         Context.setBOOLDecl(TD);
15189     }
15190   }
15191   if (Context.getBOOLDecl())
15192     BoolT = Context.getBOOLType();
15193   return new (Context)
15194       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
15195 }
15196 
15197 ExprResult Sema::ActOnObjCAvailabilityCheckExpr(
15198     llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc,
15199     SourceLocation RParen) {
15200 
15201   StringRef Platform = getASTContext().getTargetInfo().getPlatformName();
15202 
15203   auto Spec = std::find_if(AvailSpecs.begin(), AvailSpecs.end(),
15204                            [&](const AvailabilitySpec &Spec) {
15205                              return Spec.getPlatform() == Platform;
15206                            });
15207 
15208   VersionTuple Version;
15209   if (Spec != AvailSpecs.end())
15210     Version = Spec->getVersion();
15211 
15212   return new (Context)
15213       ObjCAvailabilityCheckExpr(Version, AtLoc, RParen, Context.BoolTy);
15214 }
15215