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 "clang/Sema/SemaInternal.h"
15 #include "TreeTransform.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/ExprOpenMP.h"
28 #include "clang/AST/RecursiveASTVisitor.h"
29 #include "clang/AST/TypeLoc.h"
30 #include "clang/Basic/PartialDiagnostic.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/LiteralSupport.h"
34 #include "clang/Lex/Preprocessor.h"
35 #include "clang/Sema/AnalysisBasedWarnings.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
44 #include "clang/Sema/SemaFixItUtils.h"
45 #include "clang/Sema/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) {
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 (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 (D->hasAttr<UnusedAttr>()) {
80     const Decl *DC = cast_or_null<Decl>(S.getCurObjCLexicalContext());
81     if (DC && !DC->hasAttr<UnusedAttr>())
82       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
83   }
84 }
85 
86 static bool HasRedeclarationWithoutAvailabilityInCategory(const Decl *D) {
87   const auto *OMD = dyn_cast<ObjCMethodDecl>(D);
88   if (!OMD)
89     return false;
90   const ObjCInterfaceDecl *OID = OMD->getClassInterface();
91   if (!OID)
92     return false;
93 
94   for (const ObjCCategoryDecl *Cat : OID->visible_categories())
95     if (ObjCMethodDecl *CatMeth =
96             Cat->getMethod(OMD->getSelector(), OMD->isInstanceMethod()))
97       if (!CatMeth->hasAttr<AvailabilityAttr>())
98         return true;
99   return false;
100 }
101 
102 static AvailabilityResult
103 DiagnoseAvailabilityOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc,
104                            const ObjCInterfaceDecl *UnknownObjCClass,
105                            bool ObjCPropertyAccess) {
106   // See if this declaration is unavailable or deprecated.
107   std::string Message;
108   AvailabilityResult Result = D->getAvailability(&Message);
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);
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);
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);
136     }
137 
138   const ObjCPropertyDecl *ObjCPDecl = nullptr;
139   if (Result == AR_Deprecated || Result == AR_Unavailable ||
140       AR_NotYetIntroduced) {
141     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
142       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
143         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
144         if (PDeclResult == Result)
145           ObjCPDecl = PD;
146       }
147     }
148   }
149 
150   switch (Result) {
151     case AR_Available:
152       break;
153 
154     case AR_Deprecated:
155       if (S.getCurContextAvailability() != AR_Deprecated)
156         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
157                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
158                                   ObjCPropertyAccess);
159       break;
160 
161     case AR_NotYetIntroduced: {
162       // Don't do this for enums, they can't be redeclared.
163       if (isa<EnumConstantDecl>(D) || isa<EnumDecl>(D))
164         break;
165 
166       bool Warn = !D->getAttr<AvailabilityAttr>()->isInherited();
167       // Objective-C method declarations in categories are not modelled as
168       // redeclarations, so manually look for a redeclaration in a category
169       // if necessary.
170       if (Warn && HasRedeclarationWithoutAvailabilityInCategory(D))
171         Warn = false;
172       // In general, D will point to the most recent redeclaration. However,
173       // for `@class A;` decls, this isn't true -- manually go through the
174       // redecl chain in that case.
175       if (Warn && isa<ObjCInterfaceDecl>(D))
176         for (Decl *Redecl = D->getMostRecentDecl(); Redecl && Warn;
177              Redecl = Redecl->getPreviousDecl())
178           if (!Redecl->hasAttr<AvailabilityAttr>() ||
179               Redecl->getAttr<AvailabilityAttr>()->isInherited())
180             Warn = false;
181 
182       if (Warn)
183         S.EmitAvailabilityWarning(Sema::AD_Partial, D, Message, Loc,
184                                   UnknownObjCClass, ObjCPDecl,
185                                   ObjCPropertyAccess);
186       break;
187     }
188 
189     case AR_Unavailable:
190       if (S.getCurContextAvailability() != AR_Unavailable)
191         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
192                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl,
193                                   ObjCPropertyAccess);
194       break;
195 
196     }
197     return Result;
198 }
199 
200 /// \brief Emit a note explaining that this function is deleted.
201 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
202   assert(Decl->isDeleted());
203 
204   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
205 
206   if (Method && Method->isDeleted() && Method->isDefaulted()) {
207     // If the method was explicitly defaulted, point at that declaration.
208     if (!Method->isImplicit())
209       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
210 
211     // Try to diagnose why this special member function was implicitly
212     // deleted. This might fail, if that reason no longer applies.
213     CXXSpecialMember CSM = getSpecialMember(Method);
214     if (CSM != CXXInvalid)
215       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
216 
217     return;
218   }
219 
220   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
221     if (CXXConstructorDecl *BaseCD =
222             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
223       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
224       if (BaseCD->isDeleted()) {
225         NoteDeletedFunction(BaseCD);
226       } else {
227         // FIXME: An explanation of why exactly it can't be inherited
228         // would be nice.
229         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
230       }
231       return;
232     }
233   }
234 
235   Diag(Decl->getLocation(), diag::note_availability_specified_here)
236     << Decl << true;
237 }
238 
239 /// \brief Determine whether a FunctionDecl was ever declared with an
240 /// explicit storage class.
241 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
242   for (auto I : D->redecls()) {
243     if (I->getStorageClass() != SC_None)
244       return true;
245   }
246   return false;
247 }
248 
249 /// \brief Check whether we're in an extern inline function and referring to a
250 /// variable or function with internal linkage (C11 6.7.4p3).
251 ///
252 /// This is only a warning because we used to silently accept this code, but
253 /// in many cases it will not behave correctly. This is not enabled in C++ mode
254 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
255 /// and so while there may still be user mistakes, most of the time we can't
256 /// prove that there are errors.
257 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
258                                                       const NamedDecl *D,
259                                                       SourceLocation Loc) {
260   // This is disabled under C++; there are too many ways for this to fire in
261   // contexts where the warning is a false positive, or where it is technically
262   // correct but benign.
263   if (S.getLangOpts().CPlusPlus)
264     return;
265 
266   // Check if this is an inlined function or method.
267   FunctionDecl *Current = S.getCurFunctionDecl();
268   if (!Current)
269     return;
270   if (!Current->isInlined())
271     return;
272   if (!Current->isExternallyVisible())
273     return;
274 
275   // Check if the decl has internal linkage.
276   if (D->getFormalLinkage() != InternalLinkage)
277     return;
278 
279   // Downgrade from ExtWarn to Extension if
280   //  (1) the supposedly external inline function is in the main file,
281   //      and probably won't be included anywhere else.
282   //  (2) the thing we're referencing is a pure function.
283   //  (3) the thing we're referencing is another inline function.
284   // This last can give us false negatives, but it's better than warning on
285   // wrappers for simple C library functions.
286   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
287   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
288   if (!DowngradeWarning && UsedFn)
289     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
290 
291   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline_quiet
292                                : diag::ext_internal_in_extern_inline)
293     << /*IsVar=*/!UsedFn << D;
294 
295   S.MaybeSuggestAddingStaticToDecl(Current);
296 
297   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
298       << D;
299 }
300 
301 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
302   const FunctionDecl *First = Cur->getFirstDecl();
303 
304   // Suggest "static" on the function, if possible.
305   if (!hasAnyExplicitStorageClass(First)) {
306     SourceLocation DeclBegin = First->getSourceRange().getBegin();
307     Diag(DeclBegin, diag::note_convert_inline_to_static)
308       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
309   }
310 }
311 
312 /// \brief Determine whether the use of this declaration is valid, and
313 /// emit any corresponding diagnostics.
314 ///
315 /// This routine diagnoses various problems with referencing
316 /// declarations that can occur when using a declaration. For example,
317 /// it might warn if a deprecated or unavailable declaration is being
318 /// used, or produce an error (and return true) if a C++0x deleted
319 /// function is being used.
320 ///
321 /// \returns true if there was an error (this declaration cannot be
322 /// referenced), false otherwise.
323 ///
324 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
325                              const ObjCInterfaceDecl *UnknownObjCClass,
326                              bool ObjCPropertyAccess) {
327   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
328     // If there were any diagnostics suppressed by template argument deduction,
329     // emit them now.
330     SuppressedDiagnosticsMap::iterator
331       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
332     if (Pos != SuppressedDiagnostics.end()) {
333       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
334       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
335         Diag(Suppressed[I].first, Suppressed[I].second);
336 
337       // Clear out the list of suppressed diagnostics, so that we don't emit
338       // them again for this specialization. However, we don't obsolete this
339       // entry from the table, because we want to avoid ever emitting these
340       // diagnostics again.
341       Suppressed.clear();
342     }
343 
344     // C++ [basic.start.main]p3:
345     //   The function 'main' shall not be used within a program.
346     if (cast<FunctionDecl>(D)->isMain())
347       Diag(Loc, diag::ext_main_used);
348   }
349 
350   // See if this is an auto-typed variable whose initializer we are parsing.
351   if (ParsingInitForAutoVars.count(D)) {
352     const AutoType *AT = cast<VarDecl>(D)->getType()->getContainedAutoType();
353 
354     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
355       << D->getDeclName() << (unsigned)AT->getKeyword();
356     return true;
357   }
358 
359   // See if this is a deleted function.
360   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
361     if (FD->isDeleted()) {
362       Diag(Loc, diag::err_deleted_function_use);
363       NoteDeletedFunction(FD);
364       return true;
365     }
366 
367     // If the function has a deduced return type, and we can't deduce it,
368     // then we can't use it either.
369     if (getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
370         DeduceReturnType(FD, Loc))
371       return true;
372   }
373   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass,
374                              ObjCPropertyAccess);
375 
376   DiagnoseUnusedOfDecl(*this, D, Loc);
377 
378   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
379 
380   return false;
381 }
382 
383 /// \brief Retrieve the message suffix that should be added to a
384 /// diagnostic complaining about the given function being deleted or
385 /// unavailable.
386 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
387   std::string Message;
388   if (FD->getAvailability(&Message))
389     return ": " + Message;
390 
391   return std::string();
392 }
393 
394 /// DiagnoseSentinelCalls - This routine checks whether a call or
395 /// message-send is to a declaration with the sentinel attribute, and
396 /// if so, it checks that the requirements of the sentinel are
397 /// satisfied.
398 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
399                                  ArrayRef<Expr *> Args) {
400   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
401   if (!attr)
402     return;
403 
404   // The number of formal parameters of the declaration.
405   unsigned numFormalParams;
406 
407   // The kind of declaration.  This is also an index into a %select in
408   // the diagnostic.
409   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
410 
411   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
412     numFormalParams = MD->param_size();
413     calleeType = CT_Method;
414   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
415     numFormalParams = FD->param_size();
416     calleeType = CT_Function;
417   } else if (isa<VarDecl>(D)) {
418     QualType type = cast<ValueDecl>(D)->getType();
419     const FunctionType *fn = nullptr;
420     if (const PointerType *ptr = type->getAs<PointerType>()) {
421       fn = ptr->getPointeeType()->getAs<FunctionType>();
422       if (!fn) return;
423       calleeType = CT_Function;
424     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
425       fn = ptr->getPointeeType()->castAs<FunctionType>();
426       calleeType = CT_Block;
427     } else {
428       return;
429     }
430 
431     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
432       numFormalParams = proto->getNumParams();
433     } else {
434       numFormalParams = 0;
435     }
436   } else {
437     return;
438   }
439 
440   // "nullPos" is the number of formal parameters at the end which
441   // effectively count as part of the variadic arguments.  This is
442   // useful if you would prefer to not have *any* formal parameters,
443   // but the language forces you to have at least one.
444   unsigned nullPos = attr->getNullPos();
445   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
446   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
447 
448   // The number of arguments which should follow the sentinel.
449   unsigned numArgsAfterSentinel = attr->getSentinel();
450 
451   // If there aren't enough arguments for all the formal parameters,
452   // the sentinel, and the args after the sentinel, complain.
453   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
454     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
455     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
456     return;
457   }
458 
459   // Otherwise, find the sentinel expression.
460   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
461   if (!sentinelExpr) return;
462   if (sentinelExpr->isValueDependent()) return;
463   if (Context.isSentinelNullExpr(sentinelExpr)) return;
464 
465   // Pick a reasonable string to insert.  Optimistically use 'nil', 'nullptr',
466   // or 'NULL' if those are actually defined in the context.  Only use
467   // 'nil' for ObjC methods, where it's much more likely that the
468   // variadic arguments form a list of object pointers.
469   SourceLocation MissingNilLoc
470     = getLocForEndOfToken(sentinelExpr->getLocEnd());
471   std::string NullValue;
472   if (calleeType == CT_Method && PP.isMacroDefined("nil"))
473     NullValue = "nil";
474   else if (getLangOpts().CPlusPlus11)
475     NullValue = "nullptr";
476   else if (PP.isMacroDefined("NULL"))
477     NullValue = "NULL";
478   else
479     NullValue = "(void*) 0";
480 
481   if (MissingNilLoc.isInvalid())
482     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
483   else
484     Diag(MissingNilLoc, diag::warn_missing_sentinel)
485       << int(calleeType)
486       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
487   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
488 }
489 
490 SourceRange Sema::getExprRange(Expr *E) const {
491   return E ? E->getSourceRange() : SourceRange();
492 }
493 
494 //===----------------------------------------------------------------------===//
495 //  Standard Promotions and Conversions
496 //===----------------------------------------------------------------------===//
497 
498 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
499 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E, bool Diagnose) {
500   // Handle any placeholder expressions which made it here.
501   if (E->getType()->isPlaceholderType()) {
502     ExprResult result = CheckPlaceholderExpr(E);
503     if (result.isInvalid()) return ExprError();
504     E = result.get();
505   }
506 
507   QualType Ty = E->getType();
508   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
509 
510   if (Ty->isFunctionType()) {
511     // If we are here, we are not calling a function but taking
512     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
513     if (getLangOpts().OpenCL) {
514       if (Diagnose)
515         Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
516       return ExprError();
517     }
518 
519     if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts()))
520       if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
521         if (!checkAddressOfFunctionIsAvailable(FD, Diagnose, E->getExprLoc()))
522           return ExprError();
523 
524     E = ImpCastExprToType(E, Context.getPointerType(Ty),
525                           CK_FunctionToPointerDecay).get();
526   } else if (Ty->isArrayType()) {
527     // In C90 mode, arrays only promote to pointers if the array expression is
528     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
529     // type 'array of type' is converted to an expression that has type 'pointer
530     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
531     // that has type 'array of type' ...".  The relevant change is "an lvalue"
532     // (C90) to "an expression" (C99).
533     //
534     // C++ 4.2p1:
535     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
536     // T" can be converted to an rvalue of type "pointer to T".
537     //
538     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
539       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
540                             CK_ArrayToPointerDecay).get();
541   }
542   return E;
543 }
544 
545 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
546   // Check to see if we are dereferencing a null pointer.  If so,
547   // and if not volatile-qualified, this is undefined behavior that the
548   // optimizer will delete, so warn about it.  People sometimes try to use this
549   // to get a deterministic trap and are surprised by clang's behavior.  This
550   // only handles the pattern "*null", which is a very syntactic check.
551   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
552     if (UO->getOpcode() == UO_Deref &&
553         UO->getSubExpr()->IgnoreParenCasts()->
554           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
555         !UO->getType().isVolatileQualified()) {
556     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
557                           S.PDiag(diag::warn_indirection_through_null)
558                             << UO->getSubExpr()->getSourceRange());
559     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
560                         S.PDiag(diag::note_indirection_through_null));
561   }
562 }
563 
564 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
565                                     SourceLocation AssignLoc,
566                                     const Expr* RHS) {
567   const ObjCIvarDecl *IV = OIRE->getDecl();
568   if (!IV)
569     return;
570 
571   DeclarationName MemberName = IV->getDeclName();
572   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
573   if (!Member || !Member->isStr("isa"))
574     return;
575 
576   const Expr *Base = OIRE->getBase();
577   QualType BaseType = Base->getType();
578   if (OIRE->isArrow())
579     BaseType = BaseType->getPointeeType();
580   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
581     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
582       ObjCInterfaceDecl *ClassDeclared = nullptr;
583       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
584       if (!ClassDeclared->getSuperClass()
585           && (*ClassDeclared->ivar_begin()) == IV) {
586         if (RHS) {
587           NamedDecl *ObjectSetClass =
588             S.LookupSingleName(S.TUScope,
589                                &S.Context.Idents.get("object_setClass"),
590                                SourceLocation(), S.LookupOrdinaryName);
591           if (ObjectSetClass) {
592             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
593             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
594             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
595             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
596                                                      AssignLoc), ",") <<
597             FixItHint::CreateInsertion(RHSLocEnd, ")");
598           }
599           else
600             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
601         } else {
602           NamedDecl *ObjectGetClass =
603             S.LookupSingleName(S.TUScope,
604                                &S.Context.Idents.get("object_getClass"),
605                                SourceLocation(), S.LookupOrdinaryName);
606           if (ObjectGetClass)
607             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
608             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
609             FixItHint::CreateReplacement(
610                                          SourceRange(OIRE->getOpLoc(),
611                                                      OIRE->getLocEnd()), ")");
612           else
613             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
614         }
615         S.Diag(IV->getLocation(), diag::note_ivar_decl);
616       }
617     }
618 }
619 
620 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
621   // Handle any placeholder expressions which made it here.
622   if (E->getType()->isPlaceholderType()) {
623     ExprResult result = CheckPlaceholderExpr(E);
624     if (result.isInvalid()) return ExprError();
625     E = result.get();
626   }
627 
628   // C++ [conv.lval]p1:
629   //   A glvalue of a non-function, non-array type T can be
630   //   converted to a prvalue.
631   if (!E->isGLValue()) return E;
632 
633   QualType T = E->getType();
634   assert(!T.isNull() && "r-value conversion on typeless expression?");
635 
636   // We don't want to throw lvalue-to-rvalue casts on top of
637   // expressions of certain types in C++.
638   if (getLangOpts().CPlusPlus &&
639       (E->getType() == Context.OverloadTy ||
640        T->isDependentType() ||
641        T->isRecordType()))
642     return E;
643 
644   // The C standard is actually really unclear on this point, and
645   // DR106 tells us what the result should be but not why.  It's
646   // generally best to say that void types just doesn't undergo
647   // lvalue-to-rvalue at all.  Note that expressions of unqualified
648   // 'void' type are never l-values, but qualified void can be.
649   if (T->isVoidType())
650     return E;
651 
652   // OpenCL usually rejects direct accesses to values of 'half' type.
653   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
654       T->isHalfType()) {
655     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
656       << 0 << T;
657     return ExprError();
658   }
659 
660   CheckForNullPointerDereference(*this, E);
661   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
662     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
663                                      &Context.Idents.get("object_getClass"),
664                                      SourceLocation(), LookupOrdinaryName);
665     if (ObjectGetClass)
666       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
667         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
668         FixItHint::CreateReplacement(
669                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
670     else
671       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
672   }
673   else if (const ObjCIvarRefExpr *OIRE =
674             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
675     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
676 
677   // C++ [conv.lval]p1:
678   //   [...] If T is a non-class type, the type of the prvalue is the
679   //   cv-unqualified version of T. Otherwise, the type of the
680   //   rvalue is T.
681   //
682   // C99 6.3.2.1p2:
683   //   If the lvalue has qualified type, the value has the unqualified
684   //   version of the type of the lvalue; otherwise, the value has the
685   //   type of the lvalue.
686   if (T.hasQualifiers())
687     T = T.getUnqualifiedType();
688 
689   if (T->isMemberPointerType() &&
690       Context.getTargetInfo().getCXXABI().isMicrosoft())
691     RequireCompleteType(E->getExprLoc(), T, 0);
692 
693   UpdateMarkingForLValueToRValue(E);
694 
695   // Loading a __weak object implicitly retains the value, so we need a cleanup to
696   // balance that.
697   if (getLangOpts().ObjCAutoRefCount &&
698       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
699     ExprNeedsCleanups = true;
700 
701   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
702                                             nullptr, VK_RValue);
703 
704   // C11 6.3.2.1p2:
705   //   ... if the lvalue has atomic type, the value has the non-atomic version
706   //   of the type of the lvalue ...
707   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
708     T = Atomic->getValueType().getUnqualifiedType();
709     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
710                                    nullptr, VK_RValue);
711   }
712 
713   return Res;
714 }
715 
716 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose) {
717   ExprResult Res = DefaultFunctionArrayConversion(E, Diagnose);
718   if (Res.isInvalid())
719     return ExprError();
720   Res = DefaultLvalueConversion(Res.get());
721   if (Res.isInvalid())
722     return ExprError();
723   return Res;
724 }
725 
726 /// CallExprUnaryConversions - a special case of an unary conversion
727 /// performed on a function designator of a call expression.
728 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
729   QualType Ty = E->getType();
730   ExprResult Res = E;
731   // Only do implicit cast for a function type, but not for a pointer
732   // to function type.
733   if (Ty->isFunctionType()) {
734     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
735                             CK_FunctionToPointerDecay).get();
736     if (Res.isInvalid())
737       return ExprError();
738   }
739   Res = DefaultLvalueConversion(Res.get());
740   if (Res.isInvalid())
741     return ExprError();
742   return Res.get();
743 }
744 
745 /// UsualUnaryConversions - Performs various conversions that are common to most
746 /// operators (C99 6.3). The conversions of array and function types are
747 /// sometimes suppressed. For example, the array->pointer conversion doesn't
748 /// apply if the array is an argument to the sizeof or address (&) operators.
749 /// In these instances, this routine should *not* be called.
750 ExprResult Sema::UsualUnaryConversions(Expr *E) {
751   // First, convert to an r-value.
752   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
753   if (Res.isInvalid())
754     return ExprError();
755   E = Res.get();
756 
757   QualType Ty = E->getType();
758   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
759 
760   // Half FP have to be promoted to float unless it is natively supported
761   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
762     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
763 
764   // Try to perform integral promotions if the object has a theoretically
765   // promotable type.
766   if (Ty->isIntegralOrUnscopedEnumerationType()) {
767     // C99 6.3.1.1p2:
768     //
769     //   The following may be used in an expression wherever an int or
770     //   unsigned int may be used:
771     //     - an object or expression with an integer type whose integer
772     //       conversion rank is less than or equal to the rank of int
773     //       and unsigned int.
774     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
775     //
776     //   If an int can represent all values of the original type, the
777     //   value is converted to an int; otherwise, it is converted to an
778     //   unsigned int. These are called the integer promotions. All
779     //   other types are unchanged by the integer promotions.
780 
781     QualType PTy = Context.isPromotableBitField(E);
782     if (!PTy.isNull()) {
783       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
784       return E;
785     }
786     if (Ty->isPromotableIntegerType()) {
787       QualType PT = Context.getPromotedIntegerType(Ty);
788       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
789       return E;
790     }
791   }
792   return E;
793 }
794 
795 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
796 /// do not have a prototype. Arguments that have type float or __fp16
797 /// are promoted to double. All other argument types are converted by
798 /// UsualUnaryConversions().
799 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
800   QualType Ty = E->getType();
801   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
802 
803   ExprResult Res = UsualUnaryConversions(E);
804   if (Res.isInvalid())
805     return ExprError();
806   E = Res.get();
807 
808   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
809   // double.
810   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
811   if (BTy && (BTy->getKind() == BuiltinType::Half ||
812               BTy->getKind() == BuiltinType::Float))
813     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
814 
815   // C++ performs lvalue-to-rvalue conversion as a default argument
816   // promotion, even on class types, but note:
817   //   C++11 [conv.lval]p2:
818   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
819   //     operand or a subexpression thereof the value contained in the
820   //     referenced object is not accessed. Otherwise, if the glvalue
821   //     has a class type, the conversion copy-initializes a temporary
822   //     of type T from the glvalue and the result of the conversion
823   //     is a prvalue for the temporary.
824   // FIXME: add some way to gate this entire thing for correctness in
825   // potentially potentially evaluated contexts.
826   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
827     ExprResult Temp = PerformCopyInitialization(
828                        InitializedEntity::InitializeTemporary(E->getType()),
829                                                 E->getExprLoc(), E);
830     if (Temp.isInvalid())
831       return ExprError();
832     E = Temp.get();
833   }
834 
835   return E;
836 }
837 
838 /// Determine the degree of POD-ness for an expression.
839 /// Incomplete types are considered POD, since this check can be performed
840 /// when we're in an unevaluated context.
841 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
842   if (Ty->isIncompleteType()) {
843     // C++11 [expr.call]p7:
844     //   After these conversions, if the argument does not have arithmetic,
845     //   enumeration, pointer, pointer to member, or class type, the program
846     //   is ill-formed.
847     //
848     // Since we've already performed array-to-pointer and function-to-pointer
849     // decay, the only such type in C++ is cv void. This also handles
850     // initializer lists as variadic arguments.
851     if (Ty->isVoidType())
852       return VAK_Invalid;
853 
854     if (Ty->isObjCObjectType())
855       return VAK_Invalid;
856     return VAK_Valid;
857   }
858 
859   if (Ty.isCXX98PODType(Context))
860     return VAK_Valid;
861 
862   // C++11 [expr.call]p7:
863   //   Passing a potentially-evaluated argument of class type (Clause 9)
864   //   having a non-trivial copy constructor, a non-trivial move constructor,
865   //   or a non-trivial destructor, with no corresponding parameter,
866   //   is conditionally-supported with implementation-defined semantics.
867   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
868     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
869       if (!Record->hasNonTrivialCopyConstructor() &&
870           !Record->hasNonTrivialMoveConstructor() &&
871           !Record->hasNonTrivialDestructor())
872         return VAK_ValidInCXX11;
873 
874   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
875     return VAK_Valid;
876 
877   if (Ty->isObjCObjectType())
878     return VAK_Invalid;
879 
880   if (getLangOpts().MSVCCompat)
881     return VAK_MSVCUndefined;
882 
883   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
884   // permitted to reject them. We should consider doing so.
885   return VAK_Undefined;
886 }
887 
888 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
889   // Don't allow one to pass an Objective-C interface to a vararg.
890   const QualType &Ty = E->getType();
891   VarArgKind VAK = isValidVarArgType(Ty);
892 
893   // Complain about passing non-POD types through varargs.
894   switch (VAK) {
895   case VAK_ValidInCXX11:
896     DiagRuntimeBehavior(
897         E->getLocStart(), nullptr,
898         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
899           << Ty << CT);
900     // Fall through.
901   case VAK_Valid:
902     if (Ty->isRecordType()) {
903       // This is unlikely to be what the user intended. If the class has a
904       // 'c_str' member function, the user probably meant to call that.
905       DiagRuntimeBehavior(E->getLocStart(), nullptr,
906                           PDiag(diag::warn_pass_class_arg_to_vararg)
907                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
908     }
909     break;
910 
911   case VAK_Undefined:
912   case VAK_MSVCUndefined:
913     DiagRuntimeBehavior(
914         E->getLocStart(), nullptr,
915         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
916           << getLangOpts().CPlusPlus11 << Ty << CT);
917     break;
918 
919   case VAK_Invalid:
920     if (Ty->isObjCObjectType())
921       DiagRuntimeBehavior(
922           E->getLocStart(), nullptr,
923           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
924             << Ty << CT);
925     else
926       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
927         << isa<InitListExpr>(E) << Ty << CT;
928     break;
929   }
930 }
931 
932 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
933 /// will create a trap if the resulting type is not a POD type.
934 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
935                                                   FunctionDecl *FDecl) {
936   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
937     // Strip the unbridged-cast placeholder expression off, if applicable.
938     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
939         (CT == VariadicMethod ||
940          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
941       E = stripARCUnbridgedCast(E);
942 
943     // Otherwise, do normal placeholder checking.
944     } else {
945       ExprResult ExprRes = CheckPlaceholderExpr(E);
946       if (ExprRes.isInvalid())
947         return ExprError();
948       E = ExprRes.get();
949     }
950   }
951 
952   ExprResult ExprRes = DefaultArgumentPromotion(E);
953   if (ExprRes.isInvalid())
954     return ExprError();
955   E = ExprRes.get();
956 
957   // Diagnostics regarding non-POD argument types are
958   // emitted along with format string checking in Sema::CheckFunctionCall().
959   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
960     // Turn this into a trap.
961     CXXScopeSpec SS;
962     SourceLocation TemplateKWLoc;
963     UnqualifiedId Name;
964     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
965                        E->getLocStart());
966     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
967                                           Name, true, false);
968     if (TrapFn.isInvalid())
969       return ExprError();
970 
971     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
972                                     E->getLocStart(), None,
973                                     E->getLocEnd());
974     if (Call.isInvalid())
975       return ExprError();
976 
977     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
978                                   Call.get(), E);
979     if (Comma.isInvalid())
980       return ExprError();
981     return Comma.get();
982   }
983 
984   if (!getLangOpts().CPlusPlus &&
985       RequireCompleteType(E->getExprLoc(), E->getType(),
986                           diag::err_call_incomplete_argument))
987     return ExprError();
988 
989   return E;
990 }
991 
992 /// \brief Converts an integer to complex float type.  Helper function of
993 /// UsualArithmeticConversions()
994 ///
995 /// \return false if the integer expression is an integer type and is
996 /// successfully converted to the complex type.
997 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
998                                                   ExprResult &ComplexExpr,
999                                                   QualType IntTy,
1000                                                   QualType ComplexTy,
1001                                                   bool SkipCast) {
1002   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
1003   if (SkipCast) return false;
1004   if (IntTy->isIntegerType()) {
1005     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
1006     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1007     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1008                                   CK_FloatingRealToComplex);
1009   } else {
1010     assert(IntTy->isComplexIntegerType());
1011     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1012                                   CK_IntegralComplexToFloatingComplex);
1013   }
1014   return false;
1015 }
1016 
1017 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1018 /// UsualArithmeticConversions()
1019 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1020                                              ExprResult &RHS, QualType LHSType,
1021                                              QualType RHSType,
1022                                              bool IsCompAssign) {
1023   // if we have an integer operand, the result is the complex type.
1024   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1025                                              /*skipCast*/false))
1026     return LHSType;
1027   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1028                                              /*skipCast*/IsCompAssign))
1029     return RHSType;
1030 
1031   // This handles complex/complex, complex/float, or float/complex.
1032   // When both operands are complex, the shorter operand is converted to the
1033   // type of the longer, and that is the type of the result. This corresponds
1034   // to what is done when combining two real floating-point operands.
1035   // The fun begins when size promotion occur across type domains.
1036   // From H&S 6.3.4: When one operand is complex and the other is a real
1037   // floating-point type, the less precise type is converted, within it's
1038   // real or complex domain, to the precision of the other type. For example,
1039   // when combining a "long double" with a "double _Complex", the
1040   // "double _Complex" is promoted to "long double _Complex".
1041 
1042   // Compute the rank of the two types, regardless of whether they are complex.
1043   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1044 
1045   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1046   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1047   QualType LHSElementType =
1048       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1049   QualType RHSElementType =
1050       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1051 
1052   QualType ResultType = S.Context.getComplexType(LHSElementType);
1053   if (Order < 0) {
1054     // Promote the precision of the LHS if not an assignment.
1055     ResultType = S.Context.getComplexType(RHSElementType);
1056     if (!IsCompAssign) {
1057       if (LHSComplexType)
1058         LHS =
1059             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1060       else
1061         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1062     }
1063   } else if (Order > 0) {
1064     // Promote the precision of the RHS.
1065     if (RHSComplexType)
1066       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1067     else
1068       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1069   }
1070   return ResultType;
1071 }
1072 
1073 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1074 /// of UsualArithmeticConversions()
1075 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1076                                            ExprResult &IntExpr,
1077                                            QualType FloatTy, QualType IntTy,
1078                                            bool ConvertFloat, bool ConvertInt) {
1079   if (IntTy->isIntegerType()) {
1080     if (ConvertInt)
1081       // Convert intExpr to the lhs floating point type.
1082       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1083                                     CK_IntegralToFloating);
1084     return FloatTy;
1085   }
1086 
1087   // Convert both sides to the appropriate complex float.
1088   assert(IntTy->isComplexIntegerType());
1089   QualType result = S.Context.getComplexType(FloatTy);
1090 
1091   // _Complex int -> _Complex float
1092   if (ConvertInt)
1093     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1094                                   CK_IntegralComplexToFloatingComplex);
1095 
1096   // float -> _Complex float
1097   if (ConvertFloat)
1098     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1099                                     CK_FloatingRealToComplex);
1100 
1101   return result;
1102 }
1103 
1104 /// \brief Handle arithmethic conversion with floating point types.  Helper
1105 /// function of UsualArithmeticConversions()
1106 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1107                                       ExprResult &RHS, QualType LHSType,
1108                                       QualType RHSType, bool IsCompAssign) {
1109   bool LHSFloat = LHSType->isRealFloatingType();
1110   bool RHSFloat = RHSType->isRealFloatingType();
1111 
1112   // If we have two real floating types, convert the smaller operand
1113   // to the bigger result.
1114   if (LHSFloat && RHSFloat) {
1115     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1116     if (order > 0) {
1117       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1118       return LHSType;
1119     }
1120 
1121     assert(order < 0 && "illegal float comparison");
1122     if (!IsCompAssign)
1123       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1124     return RHSType;
1125   }
1126 
1127   if (LHSFloat) {
1128     // Half FP has to be promoted to float unless it is natively supported
1129     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1130       LHSType = S.Context.FloatTy;
1131 
1132     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1133                                       /*convertFloat=*/!IsCompAssign,
1134                                       /*convertInt=*/ true);
1135   }
1136   assert(RHSFloat);
1137   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1138                                     /*convertInt=*/ true,
1139                                     /*convertFloat=*/!IsCompAssign);
1140 }
1141 
1142 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1143 
1144 namespace {
1145 /// These helper callbacks are placed in an anonymous namespace to
1146 /// permit their use as function template parameters.
1147 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1148   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1149 }
1150 
1151 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1152   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1153                              CK_IntegralComplexCast);
1154 }
1155 }
1156 
1157 /// \brief Handle integer arithmetic conversions.  Helper function of
1158 /// UsualArithmeticConversions()
1159 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1160 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1161                                         ExprResult &RHS, QualType LHSType,
1162                                         QualType RHSType, bool IsCompAssign) {
1163   // The rules for this case are in C99 6.3.1.8
1164   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1165   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1166   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1167   if (LHSSigned == RHSSigned) {
1168     // Same signedness; use the higher-ranked type
1169     if (order >= 0) {
1170       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1171       return LHSType;
1172     } else if (!IsCompAssign)
1173       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1174     return RHSType;
1175   } else if (order != (LHSSigned ? 1 : -1)) {
1176     // The unsigned type has greater than or equal rank to the
1177     // signed type, so use the unsigned type
1178     if (RHSSigned) {
1179       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1180       return LHSType;
1181     } else if (!IsCompAssign)
1182       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1183     return RHSType;
1184   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1185     // The two types are different widths; if we are here, that
1186     // means the signed type is larger than the unsigned type, so
1187     // use the signed type.
1188     if (LHSSigned) {
1189       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1190       return LHSType;
1191     } else if (!IsCompAssign)
1192       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1193     return RHSType;
1194   } else {
1195     // The signed type is higher-ranked than the unsigned type,
1196     // but isn't actually any bigger (like unsigned int and long
1197     // on most 32-bit systems).  Use the unsigned type corresponding
1198     // to the signed type.
1199     QualType result =
1200       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1201     RHS = (*doRHSCast)(S, RHS.get(), result);
1202     if (!IsCompAssign)
1203       LHS = (*doLHSCast)(S, LHS.get(), result);
1204     return result;
1205   }
1206 }
1207 
1208 /// \brief Handle conversions with GCC complex int extension.  Helper function
1209 /// of UsualArithmeticConversions()
1210 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1211                                            ExprResult &RHS, QualType LHSType,
1212                                            QualType RHSType,
1213                                            bool IsCompAssign) {
1214   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1215   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1216 
1217   if (LHSComplexInt && RHSComplexInt) {
1218     QualType LHSEltType = LHSComplexInt->getElementType();
1219     QualType RHSEltType = RHSComplexInt->getElementType();
1220     QualType ScalarType =
1221       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1222         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1223 
1224     return S.Context.getComplexType(ScalarType);
1225   }
1226 
1227   if (LHSComplexInt) {
1228     QualType LHSEltType = LHSComplexInt->getElementType();
1229     QualType ScalarType =
1230       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1231         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1232     QualType ComplexType = S.Context.getComplexType(ScalarType);
1233     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1234                               CK_IntegralRealToComplex);
1235 
1236     return ComplexType;
1237   }
1238 
1239   assert(RHSComplexInt);
1240 
1241   QualType RHSEltType = RHSComplexInt->getElementType();
1242   QualType ScalarType =
1243     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1244       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1245   QualType ComplexType = S.Context.getComplexType(ScalarType);
1246 
1247   if (!IsCompAssign)
1248     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1249                               CK_IntegralRealToComplex);
1250   return ComplexType;
1251 }
1252 
1253 /// UsualArithmeticConversions - Performs various conversions that are common to
1254 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1255 /// routine returns the first non-arithmetic type found. The client is
1256 /// responsible for emitting appropriate error diagnostics.
1257 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1258                                           bool IsCompAssign) {
1259   if (!IsCompAssign) {
1260     LHS = UsualUnaryConversions(LHS.get());
1261     if (LHS.isInvalid())
1262       return QualType();
1263   }
1264 
1265   RHS = UsualUnaryConversions(RHS.get());
1266   if (RHS.isInvalid())
1267     return QualType();
1268 
1269   // For conversion purposes, we ignore any qualifiers.
1270   // For example, "const float" and "float" are equivalent.
1271   QualType LHSType =
1272     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1273   QualType RHSType =
1274     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1275 
1276   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1277   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1278     LHSType = AtomicLHS->getValueType();
1279 
1280   // If both types are identical, no conversion is needed.
1281   if (LHSType == RHSType)
1282     return LHSType;
1283 
1284   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1285   // The caller can deal with this (e.g. pointer + int).
1286   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1287     return QualType();
1288 
1289   // Apply unary and bitfield promotions to the LHS's type.
1290   QualType LHSUnpromotedType = LHSType;
1291   if (LHSType->isPromotableIntegerType())
1292     LHSType = Context.getPromotedIntegerType(LHSType);
1293   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1294   if (!LHSBitfieldPromoteTy.isNull())
1295     LHSType = LHSBitfieldPromoteTy;
1296   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1297     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1298 
1299   // If both types are identical, no conversion is needed.
1300   if (LHSType == RHSType)
1301     return LHSType;
1302 
1303   // At this point, we have two different arithmetic types.
1304 
1305   // Handle complex types first (C99 6.3.1.8p1).
1306   if (LHSType->isComplexType() || RHSType->isComplexType())
1307     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1308                                         IsCompAssign);
1309 
1310   // Now handle "real" floating types (i.e. float, double, long double).
1311   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1312     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1313                                  IsCompAssign);
1314 
1315   // Handle GCC complex int extension.
1316   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1317     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1318                                       IsCompAssign);
1319 
1320   // Finally, we have two differing integer types.
1321   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1322            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1323 }
1324 
1325 
1326 //===----------------------------------------------------------------------===//
1327 //  Semantic Analysis for various Expression Types
1328 //===----------------------------------------------------------------------===//
1329 
1330 
1331 ExprResult
1332 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1333                                 SourceLocation DefaultLoc,
1334                                 SourceLocation RParenLoc,
1335                                 Expr *ControllingExpr,
1336                                 ArrayRef<ParsedType> ArgTypes,
1337                                 ArrayRef<Expr *> ArgExprs) {
1338   unsigned NumAssocs = ArgTypes.size();
1339   assert(NumAssocs == ArgExprs.size());
1340 
1341   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1342   for (unsigned i = 0; i < NumAssocs; ++i) {
1343     if (ArgTypes[i])
1344       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1345     else
1346       Types[i] = nullptr;
1347   }
1348 
1349   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1350                                              ControllingExpr,
1351                                              llvm::makeArrayRef(Types, NumAssocs),
1352                                              ArgExprs);
1353   delete [] Types;
1354   return ER;
1355 }
1356 
1357 ExprResult
1358 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1359                                  SourceLocation DefaultLoc,
1360                                  SourceLocation RParenLoc,
1361                                  Expr *ControllingExpr,
1362                                  ArrayRef<TypeSourceInfo *> Types,
1363                                  ArrayRef<Expr *> Exprs) {
1364   unsigned NumAssocs = Types.size();
1365   assert(NumAssocs == Exprs.size());
1366 
1367   // Decay and strip qualifiers for the controlling expression type, and handle
1368   // placeholder type replacement. See committee discussion from WG14 DR423.
1369   ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1370   if (R.isInvalid())
1371     return ExprError();
1372   ControllingExpr = R.get();
1373 
1374   // The controlling expression is an unevaluated operand, so side effects are
1375   // likely unintended.
1376   if (ActiveTemplateInstantiations.empty() &&
1377       ControllingExpr->HasSideEffects(Context, false))
1378     Diag(ControllingExpr->getExprLoc(),
1379          diag::warn_side_effects_unevaluated_context);
1380 
1381   bool TypeErrorFound = false,
1382        IsResultDependent = ControllingExpr->isTypeDependent(),
1383        ContainsUnexpandedParameterPack
1384          = ControllingExpr->containsUnexpandedParameterPack();
1385 
1386   for (unsigned i = 0; i < NumAssocs; ++i) {
1387     if (Exprs[i]->containsUnexpandedParameterPack())
1388       ContainsUnexpandedParameterPack = true;
1389 
1390     if (Types[i]) {
1391       if (Types[i]->getType()->containsUnexpandedParameterPack())
1392         ContainsUnexpandedParameterPack = true;
1393 
1394       if (Types[i]->getType()->isDependentType()) {
1395         IsResultDependent = true;
1396       } else {
1397         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1398         // complete object type other than a variably modified type."
1399         unsigned D = 0;
1400         if (Types[i]->getType()->isIncompleteType())
1401           D = diag::err_assoc_type_incomplete;
1402         else if (!Types[i]->getType()->isObjectType())
1403           D = diag::err_assoc_type_nonobject;
1404         else if (Types[i]->getType()->isVariablyModifiedType())
1405           D = diag::err_assoc_type_variably_modified;
1406 
1407         if (D != 0) {
1408           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1409             << Types[i]->getTypeLoc().getSourceRange()
1410             << Types[i]->getType();
1411           TypeErrorFound = true;
1412         }
1413 
1414         // C11 6.5.1.1p2 "No two generic associations in the same generic
1415         // selection shall specify compatible types."
1416         for (unsigned j = i+1; j < NumAssocs; ++j)
1417           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1418               Context.typesAreCompatible(Types[i]->getType(),
1419                                          Types[j]->getType())) {
1420             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1421                  diag::err_assoc_compatible_types)
1422               << Types[j]->getTypeLoc().getSourceRange()
1423               << Types[j]->getType()
1424               << Types[i]->getType();
1425             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1426                  diag::note_compat_assoc)
1427               << Types[i]->getTypeLoc().getSourceRange()
1428               << Types[i]->getType();
1429             TypeErrorFound = true;
1430           }
1431       }
1432     }
1433   }
1434   if (TypeErrorFound)
1435     return ExprError();
1436 
1437   // If we determined that the generic selection is result-dependent, don't
1438   // try to compute the result expression.
1439   if (IsResultDependent)
1440     return new (Context) GenericSelectionExpr(
1441         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1442         ContainsUnexpandedParameterPack);
1443 
1444   SmallVector<unsigned, 1> CompatIndices;
1445   unsigned DefaultIndex = -1U;
1446   for (unsigned i = 0; i < NumAssocs; ++i) {
1447     if (!Types[i])
1448       DefaultIndex = i;
1449     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1450                                         Types[i]->getType()))
1451       CompatIndices.push_back(i);
1452   }
1453 
1454   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1455   // type compatible with at most one of the types named in its generic
1456   // association list."
1457   if (CompatIndices.size() > 1) {
1458     // We strip parens here because the controlling expression is typically
1459     // parenthesized in macro definitions.
1460     ControllingExpr = ControllingExpr->IgnoreParens();
1461     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1462       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1463       << (unsigned) CompatIndices.size();
1464     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1465          E = CompatIndices.end(); I != E; ++I) {
1466       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1467            diag::note_compat_assoc)
1468         << Types[*I]->getTypeLoc().getSourceRange()
1469         << Types[*I]->getType();
1470     }
1471     return ExprError();
1472   }
1473 
1474   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1475   // its controlling expression shall have type compatible with exactly one of
1476   // the types named in its generic association list."
1477   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1478     // We strip parens here because the controlling expression is typically
1479     // parenthesized in macro definitions.
1480     ControllingExpr = ControllingExpr->IgnoreParens();
1481     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1482       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1483     return ExprError();
1484   }
1485 
1486   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1487   // type name that is compatible with the type of the controlling expression,
1488   // then the result expression of the generic selection is the expression
1489   // in that generic association. Otherwise, the result expression of the
1490   // generic selection is the expression in the default generic association."
1491   unsigned ResultIndex =
1492     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1493 
1494   return new (Context) GenericSelectionExpr(
1495       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1496       ContainsUnexpandedParameterPack, ResultIndex);
1497 }
1498 
1499 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1500 /// location of the token and the offset of the ud-suffix within it.
1501 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1502                                      unsigned Offset) {
1503   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1504                                         S.getLangOpts());
1505 }
1506 
1507 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1508 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1509 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1510                                                  IdentifierInfo *UDSuffix,
1511                                                  SourceLocation UDSuffixLoc,
1512                                                  ArrayRef<Expr*> Args,
1513                                                  SourceLocation LitEndLoc) {
1514   assert(Args.size() <= 2 && "too many arguments for literal operator");
1515 
1516   QualType ArgTy[2];
1517   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1518     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1519     if (ArgTy[ArgIdx]->isArrayType())
1520       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1521   }
1522 
1523   DeclarationName OpName =
1524     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1525   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1526   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1527 
1528   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1529   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1530                               /*AllowRaw*/false, /*AllowTemplate*/false,
1531                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1532     return ExprError();
1533 
1534   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1535 }
1536 
1537 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1538 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1539 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1540 /// multiple tokens.  However, the common case is that StringToks points to one
1541 /// string.
1542 ///
1543 ExprResult
1544 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1545   assert(!StringToks.empty() && "Must have at least one string!");
1546 
1547   StringLiteralParser Literal(StringToks, PP);
1548   if (Literal.hadError)
1549     return ExprError();
1550 
1551   SmallVector<SourceLocation, 4> StringTokLocs;
1552   for (unsigned i = 0; i != StringToks.size(); ++i)
1553     StringTokLocs.push_back(StringToks[i].getLocation());
1554 
1555   QualType CharTy = Context.CharTy;
1556   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1557   if (Literal.isWide()) {
1558     CharTy = Context.getWideCharType();
1559     Kind = StringLiteral::Wide;
1560   } else if (Literal.isUTF8()) {
1561     Kind = StringLiteral::UTF8;
1562   } else if (Literal.isUTF16()) {
1563     CharTy = Context.Char16Ty;
1564     Kind = StringLiteral::UTF16;
1565   } else if (Literal.isUTF32()) {
1566     CharTy = Context.Char32Ty;
1567     Kind = StringLiteral::UTF32;
1568   } else if (Literal.isPascal()) {
1569     CharTy = Context.UnsignedCharTy;
1570   }
1571 
1572   QualType CharTyConst = CharTy;
1573   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1574   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1575     CharTyConst.addConst();
1576 
1577   // Get an array type for the string, according to C99 6.4.5.  This includes
1578   // the nul terminator character as well as the string length for pascal
1579   // strings.
1580   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1581                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1582                                  ArrayType::Normal, 0);
1583 
1584   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1585   if (getLangOpts().OpenCL) {
1586     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1587   }
1588 
1589   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1590   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1591                                              Kind, Literal.Pascal, StrTy,
1592                                              &StringTokLocs[0],
1593                                              StringTokLocs.size());
1594   if (Literal.getUDSuffix().empty())
1595     return Lit;
1596 
1597   // We're building a user-defined literal.
1598   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1599   SourceLocation UDSuffixLoc =
1600     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1601                    Literal.getUDSuffixOffset());
1602 
1603   // Make sure we're allowed user-defined literals here.
1604   if (!UDLScope)
1605     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1606 
1607   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1608   //   operator "" X (str, len)
1609   QualType SizeType = Context.getSizeType();
1610 
1611   DeclarationName OpName =
1612     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1613   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1614   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1615 
1616   QualType ArgTy[] = {
1617     Context.getArrayDecayedType(StrTy), SizeType
1618   };
1619 
1620   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1621   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1622                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1623                                 /*AllowStringTemplate*/true)) {
1624 
1625   case LOLR_Cooked: {
1626     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1627     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1628                                                     StringTokLocs[0]);
1629     Expr *Args[] = { Lit, LenArg };
1630 
1631     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1632   }
1633 
1634   case LOLR_StringTemplate: {
1635     TemplateArgumentListInfo ExplicitArgs;
1636 
1637     unsigned CharBits = Context.getIntWidth(CharTy);
1638     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1639     llvm::APSInt Value(CharBits, CharIsUnsigned);
1640 
1641     TemplateArgument TypeArg(CharTy);
1642     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1643     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1644 
1645     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1646       Value = Lit->getCodeUnit(I);
1647       TemplateArgument Arg(Context, Value, CharTy);
1648       TemplateArgumentLocInfo ArgInfo;
1649       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1650     }
1651     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1652                                     &ExplicitArgs);
1653   }
1654   case LOLR_Raw:
1655   case LOLR_Template:
1656     llvm_unreachable("unexpected literal operator lookup result");
1657   case LOLR_Error:
1658     return ExprError();
1659   }
1660   llvm_unreachable("unexpected literal operator lookup result");
1661 }
1662 
1663 ExprResult
1664 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1665                        SourceLocation Loc,
1666                        const CXXScopeSpec *SS) {
1667   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1668   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1669 }
1670 
1671 /// BuildDeclRefExpr - Build an expression that references a
1672 /// declaration that does not require a closure capture.
1673 ExprResult
1674 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1675                        const DeclarationNameInfo &NameInfo,
1676                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1677                        const TemplateArgumentListInfo *TemplateArgs) {
1678   if (getLangOpts().CUDA)
1679     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1680       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1681         if (CheckCUDATarget(Caller, Callee)) {
1682           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1683             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1684             << IdentifyCUDATarget(Caller);
1685           Diag(D->getLocation(), diag::note_previous_decl)
1686             << D->getIdentifier();
1687           return ExprError();
1688         }
1689       }
1690 
1691   bool RefersToCapturedVariable =
1692       isa<VarDecl>(D) &&
1693       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1694 
1695   DeclRefExpr *E;
1696   if (isa<VarTemplateSpecializationDecl>(D)) {
1697     VarTemplateSpecializationDecl *VarSpec =
1698         cast<VarTemplateSpecializationDecl>(D);
1699 
1700     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1701                                         : NestedNameSpecifierLoc(),
1702                             VarSpec->getTemplateKeywordLoc(), D,
1703                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1704                             FoundD, TemplateArgs);
1705   } else {
1706     assert(!TemplateArgs && "No template arguments for non-variable"
1707                             " template specialization references");
1708     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1709                                         : NestedNameSpecifierLoc(),
1710                             SourceLocation(), D, RefersToCapturedVariable,
1711                             NameInfo, Ty, VK, FoundD);
1712   }
1713 
1714   MarkDeclRefReferenced(E);
1715 
1716   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1717       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1718       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1719       recordUseOfEvaluatedWeak(E);
1720 
1721   // Just in case we're building an illegal pointer-to-member.
1722   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1723   if (FD && FD->isBitField())
1724     E->setObjectKind(OK_BitField);
1725 
1726   return E;
1727 }
1728 
1729 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1730 /// possibly a list of template arguments.
1731 ///
1732 /// If this produces template arguments, it is permitted to call
1733 /// DecomposeTemplateName.
1734 ///
1735 /// This actually loses a lot of source location information for
1736 /// non-standard name kinds; we should consider preserving that in
1737 /// some way.
1738 void
1739 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1740                              TemplateArgumentListInfo &Buffer,
1741                              DeclarationNameInfo &NameInfo,
1742                              const TemplateArgumentListInfo *&TemplateArgs) {
1743   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1744     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1745     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1746 
1747     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1748                                        Id.TemplateId->NumArgs);
1749     translateTemplateArguments(TemplateArgsPtr, Buffer);
1750 
1751     TemplateName TName = Id.TemplateId->Template.get();
1752     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1753     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1754     TemplateArgs = &Buffer;
1755   } else {
1756     NameInfo = GetNameFromUnqualifiedId(Id);
1757     TemplateArgs = nullptr;
1758   }
1759 }
1760 
1761 static void emitEmptyLookupTypoDiagnostic(
1762     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1763     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1764     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1765   DeclContext *Ctx =
1766       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1767   if (!TC) {
1768     // Emit a special diagnostic for failed member lookups.
1769     // FIXME: computing the declaration context might fail here (?)
1770     if (Ctx)
1771       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1772                                                  << SS.getRange();
1773     else
1774       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1775     return;
1776   }
1777 
1778   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1779   bool DroppedSpecifier =
1780       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1781   unsigned NoteID =
1782       (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1783           ? diag::note_implicit_param_decl
1784           : diag::note_previous_decl;
1785   if (!Ctx)
1786     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1787                          SemaRef.PDiag(NoteID));
1788   else
1789     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1790                                  << Typo << Ctx << DroppedSpecifier
1791                                  << SS.getRange(),
1792                          SemaRef.PDiag(NoteID));
1793 }
1794 
1795 /// Diagnose an empty lookup.
1796 ///
1797 /// \return false if new lookup candidates were found
1798 bool
1799 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1800                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1801                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1802                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1803   DeclarationName Name = R.getLookupName();
1804 
1805   unsigned diagnostic = diag::err_undeclared_var_use;
1806   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1807   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1808       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1809       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1810     diagnostic = diag::err_undeclared_use;
1811     diagnostic_suggest = diag::err_undeclared_use_suggest;
1812   }
1813 
1814   // If the original lookup was an unqualified lookup, fake an
1815   // unqualified lookup.  This is useful when (for example) the
1816   // original lookup would not have found something because it was a
1817   // dependent name.
1818   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1819   while (DC) {
1820     if (isa<CXXRecordDecl>(DC)) {
1821       LookupQualifiedName(R, DC);
1822 
1823       if (!R.empty()) {
1824         // Don't give errors about ambiguities in this lookup.
1825         R.suppressDiagnostics();
1826 
1827         // During a default argument instantiation the CurContext points
1828         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1829         // function parameter list, hence add an explicit check.
1830         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1831                               ActiveTemplateInstantiations.back().Kind ==
1832             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1833         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1834         bool isInstance = CurMethod &&
1835                           CurMethod->isInstance() &&
1836                           DC == CurMethod->getParent() && !isDefaultArgument;
1837 
1838         // Give a code modification hint to insert 'this->'.
1839         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1840         // Actually quite difficult!
1841         if (getLangOpts().MSVCCompat)
1842           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1843         if (isInstance) {
1844           Diag(R.getNameLoc(), diagnostic) << Name
1845             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1846           CheckCXXThisCapture(R.getNameLoc());
1847         } else {
1848           Diag(R.getNameLoc(), diagnostic) << Name;
1849         }
1850 
1851         // Do we really want to note all of these?
1852         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1853           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1854 
1855         // Return true if we are inside a default argument instantiation
1856         // and the found name refers to an instance member function, otherwise
1857         // the function calling DiagnoseEmptyLookup will try to create an
1858         // implicit member call and this is wrong for default argument.
1859         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1860           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1861           return true;
1862         }
1863 
1864         // Tell the callee to try to recover.
1865         return false;
1866       }
1867 
1868       R.clear();
1869     }
1870 
1871     // In Microsoft mode, if we are performing lookup from within a friend
1872     // function definition declared at class scope then we must set
1873     // DC to the lexical parent to be able to search into the parent
1874     // class.
1875     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1876         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1877         DC->getLexicalParent()->isRecord())
1878       DC = DC->getLexicalParent();
1879     else
1880       DC = DC->getParent();
1881   }
1882 
1883   // We didn't find anything, so try to correct for a typo.
1884   TypoCorrection Corrected;
1885   if (S && Out) {
1886     SourceLocation TypoLoc = R.getNameLoc();
1887     assert(!ExplicitTemplateArgs &&
1888            "Diagnosing an empty lookup with explicit template args!");
1889     *Out = CorrectTypoDelayed(
1890         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1891         [=](const TypoCorrection &TC) {
1892           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1893                                         diagnostic, diagnostic_suggest);
1894         },
1895         nullptr, CTK_ErrorRecovery);
1896     if (*Out)
1897       return true;
1898   } else if (S && (Corrected =
1899                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1900                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1901     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1902     bool DroppedSpecifier =
1903         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1904     R.setLookupName(Corrected.getCorrection());
1905 
1906     bool AcceptableWithRecovery = false;
1907     bool AcceptableWithoutRecovery = false;
1908     NamedDecl *ND = Corrected.getCorrectionDecl();
1909     if (ND) {
1910       if (Corrected.isOverloaded()) {
1911         OverloadCandidateSet OCS(R.getNameLoc(),
1912                                  OverloadCandidateSet::CSK_Normal);
1913         OverloadCandidateSet::iterator Best;
1914         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1915                                         CDEnd = Corrected.end();
1916              CD != CDEnd; ++CD) {
1917           if (FunctionTemplateDecl *FTD =
1918                    dyn_cast<FunctionTemplateDecl>(*CD))
1919             AddTemplateOverloadCandidate(
1920                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1921                 Args, OCS);
1922           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1923             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1924               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1925                                    Args, OCS);
1926         }
1927         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1928         case OR_Success:
1929           ND = Best->Function;
1930           Corrected.setCorrectionDecl(ND);
1931           break;
1932         default:
1933           // FIXME: Arbitrarily pick the first declaration for the note.
1934           Corrected.setCorrectionDecl(ND);
1935           break;
1936         }
1937       }
1938       R.addDecl(ND);
1939       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1940         CXXRecordDecl *Record = nullptr;
1941         if (Corrected.getCorrectionSpecifier()) {
1942           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1943           Record = Ty->getAsCXXRecordDecl();
1944         }
1945         if (!Record)
1946           Record = cast<CXXRecordDecl>(
1947               ND->getDeclContext()->getRedeclContext());
1948         R.setNamingClass(Record);
1949       }
1950 
1951       AcceptableWithRecovery =
1952           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1953       // FIXME: If we ended up with a typo for a type name or
1954       // Objective-C class name, we're in trouble because the parser
1955       // is in the wrong place to recover. Suggest the typo
1956       // correction, but don't make it a fix-it since we're not going
1957       // to recover well anyway.
1958       AcceptableWithoutRecovery =
1959           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1960     } else {
1961       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1962       // because we aren't able to recover.
1963       AcceptableWithoutRecovery = true;
1964     }
1965 
1966     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1967       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1968                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1969                             ? diag::note_implicit_param_decl
1970                             : diag::note_previous_decl;
1971       if (SS.isEmpty())
1972         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1973                      PDiag(NoteID), AcceptableWithRecovery);
1974       else
1975         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1976                                   << Name << computeDeclContext(SS, false)
1977                                   << DroppedSpecifier << SS.getRange(),
1978                      PDiag(NoteID), AcceptableWithRecovery);
1979 
1980       // Tell the callee whether to try to recover.
1981       return !AcceptableWithRecovery;
1982     }
1983   }
1984   R.clear();
1985 
1986   // Emit a special diagnostic for failed member lookups.
1987   // FIXME: computing the declaration context might fail here (?)
1988   if (!SS.isEmpty()) {
1989     Diag(R.getNameLoc(), diag::err_no_member)
1990       << Name << computeDeclContext(SS, false)
1991       << SS.getRange();
1992     return true;
1993   }
1994 
1995   // Give up, we can't recover.
1996   Diag(R.getNameLoc(), diagnostic) << Name;
1997   return true;
1998 }
1999 
2000 /// In Microsoft mode, if we are inside a template class whose parent class has
2001 /// dependent base classes, and we can't resolve an unqualified identifier, then
2002 /// assume the identifier is a member of a dependent base class.  We can only
2003 /// recover successfully in static methods, instance methods, and other contexts
2004 /// where 'this' is available.  This doesn't precisely match MSVC's
2005 /// instantiation model, but it's close enough.
2006 static Expr *
2007 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2008                                DeclarationNameInfo &NameInfo,
2009                                SourceLocation TemplateKWLoc,
2010                                const TemplateArgumentListInfo *TemplateArgs) {
2011   // Only try to recover from lookup into dependent bases in static methods or
2012   // contexts where 'this' is available.
2013   QualType ThisType = S.getCurrentThisType();
2014   const CXXRecordDecl *RD = nullptr;
2015   if (!ThisType.isNull())
2016     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2017   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2018     RD = MD->getParent();
2019   if (!RD || !RD->hasAnyDependentBases())
2020     return nullptr;
2021 
2022   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2023   // is available, suggest inserting 'this->' as a fixit.
2024   SourceLocation Loc = NameInfo.getLoc();
2025   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2026   DB << NameInfo.getName() << RD;
2027 
2028   if (!ThisType.isNull()) {
2029     DB << FixItHint::CreateInsertion(Loc, "this->");
2030     return CXXDependentScopeMemberExpr::Create(
2031         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2032         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2033         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2034   }
2035 
2036   // Synthesize a fake NNS that points to the derived class.  This will
2037   // perform name lookup during template instantiation.
2038   CXXScopeSpec SS;
2039   auto *NNS =
2040       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2041   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2042   return DependentScopeDeclRefExpr::Create(
2043       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2044       TemplateArgs);
2045 }
2046 
2047 ExprResult
2048 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2049                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2050                         bool HasTrailingLParen, bool IsAddressOfOperand,
2051                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2052                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2053   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2054          "cannot be direct & operand and have a trailing lparen");
2055   if (SS.isInvalid())
2056     return ExprError();
2057 
2058   TemplateArgumentListInfo TemplateArgsBuffer;
2059 
2060   // Decompose the UnqualifiedId into the following data.
2061   DeclarationNameInfo NameInfo;
2062   const TemplateArgumentListInfo *TemplateArgs;
2063   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2064 
2065   DeclarationName Name = NameInfo.getName();
2066   IdentifierInfo *II = Name.getAsIdentifierInfo();
2067   SourceLocation NameLoc = NameInfo.getLoc();
2068 
2069   // C++ [temp.dep.expr]p3:
2070   //   An id-expression is type-dependent if it contains:
2071   //     -- an identifier that was declared with a dependent type,
2072   //        (note: handled after lookup)
2073   //     -- a template-id that is dependent,
2074   //        (note: handled in BuildTemplateIdExpr)
2075   //     -- a conversion-function-id that specifies a dependent type,
2076   //     -- a nested-name-specifier that contains a class-name that
2077   //        names a dependent type.
2078   // Determine whether this is a member of an unknown specialization;
2079   // we need to handle these differently.
2080   bool DependentID = false;
2081   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2082       Name.getCXXNameType()->isDependentType()) {
2083     DependentID = true;
2084   } else if (SS.isSet()) {
2085     if (DeclContext *DC = computeDeclContext(SS, false)) {
2086       if (RequireCompleteDeclContext(SS, DC))
2087         return ExprError();
2088     } else {
2089       DependentID = true;
2090     }
2091   }
2092 
2093   if (DependentID)
2094     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2095                                       IsAddressOfOperand, TemplateArgs);
2096 
2097   // Perform the required lookup.
2098   LookupResult R(*this, NameInfo,
2099                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2100                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2101   if (TemplateArgs) {
2102     // Lookup the template name again to correctly establish the context in
2103     // which it was found. This is really unfortunate as we already did the
2104     // lookup to determine that it was a template name in the first place. If
2105     // this becomes a performance hit, we can work harder to preserve those
2106     // results until we get here but it's likely not worth it.
2107     bool MemberOfUnknownSpecialization;
2108     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2109                        MemberOfUnknownSpecialization);
2110 
2111     if (MemberOfUnknownSpecialization ||
2112         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2113       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2114                                         IsAddressOfOperand, TemplateArgs);
2115   } else {
2116     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2117     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2118 
2119     // If the result might be in a dependent base class, this is a dependent
2120     // id-expression.
2121     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2122       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2123                                         IsAddressOfOperand, TemplateArgs);
2124 
2125     // If this reference is in an Objective-C method, then we need to do
2126     // some special Objective-C lookup, too.
2127     if (IvarLookupFollowUp) {
2128       ExprResult E(LookupInObjCMethod(R, S, II, true));
2129       if (E.isInvalid())
2130         return ExprError();
2131 
2132       if (Expr *Ex = E.getAs<Expr>())
2133         return Ex;
2134     }
2135   }
2136 
2137   if (R.isAmbiguous())
2138     return ExprError();
2139 
2140   // This could be an implicitly declared function reference (legal in C90,
2141   // extension in C99, forbidden in C++).
2142   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2143     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2144     if (D) R.addDecl(D);
2145   }
2146 
2147   // Determine whether this name might be a candidate for
2148   // argument-dependent lookup.
2149   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2150 
2151   if (R.empty() && !ADL) {
2152     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2153       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2154                                                    TemplateKWLoc, TemplateArgs))
2155         return E;
2156     }
2157 
2158     // Don't diagnose an empty lookup for inline assembly.
2159     if (IsInlineAsmIdentifier)
2160       return ExprError();
2161 
2162     // If this name wasn't predeclared and if this is not a function
2163     // call, diagnose the problem.
2164     TypoExpr *TE = nullptr;
2165     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2166         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2167     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2168     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2169            "Typo correction callback misconfigured");
2170     if (CCC) {
2171       // Make sure the callback knows what the typo being diagnosed is.
2172       CCC->setTypoName(II);
2173       if (SS.isValid())
2174         CCC->setTypoNNS(SS.getScopeRep());
2175     }
2176     if (DiagnoseEmptyLookup(S, SS, R,
2177                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2178                             nullptr, None, &TE)) {
2179       if (TE && KeywordReplacement) {
2180         auto &State = getTypoExprState(TE);
2181         auto BestTC = State.Consumer->getNextCorrection();
2182         if (BestTC.isKeyword()) {
2183           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2184           if (State.DiagHandler)
2185             State.DiagHandler(BestTC);
2186           KeywordReplacement->startToken();
2187           KeywordReplacement->setKind(II->getTokenID());
2188           KeywordReplacement->setIdentifierInfo(II);
2189           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2190           // Clean up the state associated with the TypoExpr, since it has
2191           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2192           clearDelayedTypo(TE);
2193           // Signal that a correction to a keyword was performed by returning a
2194           // valid-but-null ExprResult.
2195           return (Expr*)nullptr;
2196         }
2197         State.Consumer->resetCorrectionStream();
2198       }
2199       return TE ? TE : ExprError();
2200     }
2201 
2202     assert(!R.empty() &&
2203            "DiagnoseEmptyLookup returned false but added no results");
2204 
2205     // If we found an Objective-C instance variable, let
2206     // LookupInObjCMethod build the appropriate expression to
2207     // reference the ivar.
2208     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2209       R.clear();
2210       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2211       // In a hopelessly buggy code, Objective-C instance variable
2212       // lookup fails and no expression will be built to reference it.
2213       if (!E.isInvalid() && !E.get())
2214         return ExprError();
2215       return E;
2216     }
2217   }
2218 
2219   // This is guaranteed from this point on.
2220   assert(!R.empty() || ADL);
2221 
2222   // Check whether this might be a C++ implicit instance member access.
2223   // C++ [class.mfct.non-static]p3:
2224   //   When an id-expression that is not part of a class member access
2225   //   syntax and not used to form a pointer to member is used in the
2226   //   body of a non-static member function of class X, if name lookup
2227   //   resolves the name in the id-expression to a non-static non-type
2228   //   member of some class C, the id-expression is transformed into a
2229   //   class member access expression using (*this) as the
2230   //   postfix-expression to the left of the . operator.
2231   //
2232   // But we don't actually need to do this for '&' operands if R
2233   // resolved to a function or overloaded function set, because the
2234   // expression is ill-formed if it actually works out to be a
2235   // non-static member function:
2236   //
2237   // C++ [expr.ref]p4:
2238   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2239   //   [t]he expression can be used only as the left-hand operand of a
2240   //   member function call.
2241   //
2242   // There are other safeguards against such uses, but it's important
2243   // to get this right here so that we don't end up making a
2244   // spuriously dependent expression if we're inside a dependent
2245   // instance method.
2246   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2247     bool MightBeImplicitMember;
2248     if (!IsAddressOfOperand)
2249       MightBeImplicitMember = true;
2250     else if (!SS.isEmpty())
2251       MightBeImplicitMember = false;
2252     else if (R.isOverloadedResult())
2253       MightBeImplicitMember = false;
2254     else if (R.isUnresolvableResult())
2255       MightBeImplicitMember = true;
2256     else
2257       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2258                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2259                               isa<MSPropertyDecl>(R.getFoundDecl());
2260 
2261     if (MightBeImplicitMember)
2262       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2263                                              R, TemplateArgs, S);
2264   }
2265 
2266   if (TemplateArgs || TemplateKWLoc.isValid()) {
2267 
2268     // In C++1y, if this is a variable template id, then check it
2269     // in BuildTemplateIdExpr().
2270     // The single lookup result must be a variable template declaration.
2271     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2272         Id.TemplateId->Kind == TNK_Var_template) {
2273       assert(R.getAsSingle<VarTemplateDecl>() &&
2274              "There should only be one declaration found.");
2275     }
2276 
2277     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2278   }
2279 
2280   return BuildDeclarationNameExpr(SS, R, ADL);
2281 }
2282 
2283 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2284 /// declaration name, generally during template instantiation.
2285 /// There's a large number of things which don't need to be done along
2286 /// this path.
2287 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2288     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2289     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2290   DeclContext *DC = computeDeclContext(SS, false);
2291   if (!DC)
2292     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2293                                      NameInfo, /*TemplateArgs=*/nullptr);
2294 
2295   if (RequireCompleteDeclContext(SS, DC))
2296     return ExprError();
2297 
2298   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2299   LookupQualifiedName(R, DC);
2300 
2301   if (R.isAmbiguous())
2302     return ExprError();
2303 
2304   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2305     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2306                                      NameInfo, /*TemplateArgs=*/nullptr);
2307 
2308   if (R.empty()) {
2309     Diag(NameInfo.getLoc(), diag::err_no_member)
2310       << NameInfo.getName() << DC << SS.getRange();
2311     return ExprError();
2312   }
2313 
2314   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2315     // Diagnose a missing typename if this resolved unambiguously to a type in
2316     // a dependent context.  If we can recover with a type, downgrade this to
2317     // a warning in Microsoft compatibility mode.
2318     unsigned DiagID = diag::err_typename_missing;
2319     if (RecoveryTSI && getLangOpts().MSVCCompat)
2320       DiagID = diag::ext_typename_missing;
2321     SourceLocation Loc = SS.getBeginLoc();
2322     auto D = Diag(Loc, DiagID);
2323     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2324       << SourceRange(Loc, NameInfo.getEndLoc());
2325 
2326     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2327     // context.
2328     if (!RecoveryTSI)
2329       return ExprError();
2330 
2331     // Only issue the fixit if we're prepared to recover.
2332     D << FixItHint::CreateInsertion(Loc, "typename ");
2333 
2334     // Recover by pretending this was an elaborated type.
2335     QualType Ty = Context.getTypeDeclType(TD);
2336     TypeLocBuilder TLB;
2337     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2338 
2339     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2340     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2341     QTL.setElaboratedKeywordLoc(SourceLocation());
2342     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2343 
2344     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2345 
2346     return ExprEmpty();
2347   }
2348 
2349   // Defend against this resolving to an implicit member access. We usually
2350   // won't get here if this might be a legitimate a class member (we end up in
2351   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2352   // a pointer-to-member or in an unevaluated context in C++11.
2353   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2354     return BuildPossibleImplicitMemberExpr(SS,
2355                                            /*TemplateKWLoc=*/SourceLocation(),
2356                                            R, /*TemplateArgs=*/nullptr, S);
2357 
2358   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2359 }
2360 
2361 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2362 /// detected that we're currently inside an ObjC method.  Perform some
2363 /// additional lookup.
2364 ///
2365 /// Ideally, most of this would be done by lookup, but there's
2366 /// actually quite a lot of extra work involved.
2367 ///
2368 /// Returns a null sentinel to indicate trivial success.
2369 ExprResult
2370 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2371                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2372   SourceLocation Loc = Lookup.getNameLoc();
2373   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2374 
2375   // Check for error condition which is already reported.
2376   if (!CurMethod)
2377     return ExprError();
2378 
2379   // There are two cases to handle here.  1) scoped lookup could have failed,
2380   // in which case we should look for an ivar.  2) scoped lookup could have
2381   // found a decl, but that decl is outside the current instance method (i.e.
2382   // a global variable).  In these two cases, we do a lookup for an ivar with
2383   // this name, if the lookup sucedes, we replace it our current decl.
2384 
2385   // If we're in a class method, we don't normally want to look for
2386   // ivars.  But if we don't find anything else, and there's an
2387   // ivar, that's an error.
2388   bool IsClassMethod = CurMethod->isClassMethod();
2389 
2390   bool LookForIvars;
2391   if (Lookup.empty())
2392     LookForIvars = true;
2393   else if (IsClassMethod)
2394     LookForIvars = false;
2395   else
2396     LookForIvars = (Lookup.isSingleResult() &&
2397                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2398   ObjCInterfaceDecl *IFace = nullptr;
2399   if (LookForIvars) {
2400     IFace = CurMethod->getClassInterface();
2401     ObjCInterfaceDecl *ClassDeclared;
2402     ObjCIvarDecl *IV = nullptr;
2403     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2404       // Diagnose using an ivar in a class method.
2405       if (IsClassMethod)
2406         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2407                          << IV->getDeclName());
2408 
2409       // If we're referencing an invalid decl, just return this as a silent
2410       // error node.  The error diagnostic was already emitted on the decl.
2411       if (IV->isInvalidDecl())
2412         return ExprError();
2413 
2414       // Check if referencing a field with __attribute__((deprecated)).
2415       if (DiagnoseUseOfDecl(IV, Loc))
2416         return ExprError();
2417 
2418       // Diagnose the use of an ivar outside of the declaring class.
2419       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2420           !declaresSameEntity(ClassDeclared, IFace) &&
2421           !getLangOpts().DebuggerSupport)
2422         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2423 
2424       // FIXME: This should use a new expr for a direct reference, don't
2425       // turn this into Self->ivar, just return a BareIVarExpr or something.
2426       IdentifierInfo &II = Context.Idents.get("self");
2427       UnqualifiedId SelfName;
2428       SelfName.setIdentifier(&II, SourceLocation());
2429       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2430       CXXScopeSpec SelfScopeSpec;
2431       SourceLocation TemplateKWLoc;
2432       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2433                                               SelfName, false, false);
2434       if (SelfExpr.isInvalid())
2435         return ExprError();
2436 
2437       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2438       if (SelfExpr.isInvalid())
2439         return ExprError();
2440 
2441       MarkAnyDeclReferenced(Loc, IV, true);
2442 
2443       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2444       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2445           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2446         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2447 
2448       ObjCIvarRefExpr *Result = new (Context)
2449           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2450                           IV->getLocation(), SelfExpr.get(), true, true);
2451 
2452       if (getLangOpts().ObjCAutoRefCount) {
2453         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2454           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2455             recordUseOfEvaluatedWeak(Result);
2456         }
2457         if (CurContext->isClosure())
2458           Diag(Loc, diag::warn_implicitly_retains_self)
2459             << FixItHint::CreateInsertion(Loc, "self->");
2460       }
2461 
2462       return Result;
2463     }
2464   } else if (CurMethod->isInstanceMethod()) {
2465     // We should warn if a local variable hides an ivar.
2466     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2467       ObjCInterfaceDecl *ClassDeclared;
2468       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2469         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2470             declaresSameEntity(IFace, ClassDeclared))
2471           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2472       }
2473     }
2474   } else if (Lookup.isSingleResult() &&
2475              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2476     // If accessing a stand-alone ivar in a class method, this is an error.
2477     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2478       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2479                        << IV->getDeclName());
2480   }
2481 
2482   if (Lookup.empty() && II && AllowBuiltinCreation) {
2483     // FIXME. Consolidate this with similar code in LookupName.
2484     if (unsigned BuiltinID = II->getBuiltinID()) {
2485       if (!(getLangOpts().CPlusPlus &&
2486             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2487         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2488                                            S, Lookup.isForRedeclaration(),
2489                                            Lookup.getNameLoc());
2490         if (D) Lookup.addDecl(D);
2491       }
2492     }
2493   }
2494   // Sentinel value saying that we didn't do anything special.
2495   return ExprResult((Expr *)nullptr);
2496 }
2497 
2498 /// \brief Cast a base object to a member's actual type.
2499 ///
2500 /// Logically this happens in three phases:
2501 ///
2502 /// * First we cast from the base type to the naming class.
2503 ///   The naming class is the class into which we were looking
2504 ///   when we found the member;  it's the qualifier type if a
2505 ///   qualifier was provided, and otherwise it's the base type.
2506 ///
2507 /// * Next we cast from the naming class to the declaring class.
2508 ///   If the member we found was brought into a class's scope by
2509 ///   a using declaration, this is that class;  otherwise it's
2510 ///   the class declaring the member.
2511 ///
2512 /// * Finally we cast from the declaring class to the "true"
2513 ///   declaring class of the member.  This conversion does not
2514 ///   obey access control.
2515 ExprResult
2516 Sema::PerformObjectMemberConversion(Expr *From,
2517                                     NestedNameSpecifier *Qualifier,
2518                                     NamedDecl *FoundDecl,
2519                                     NamedDecl *Member) {
2520   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2521   if (!RD)
2522     return From;
2523 
2524   QualType DestRecordType;
2525   QualType DestType;
2526   QualType FromRecordType;
2527   QualType FromType = From->getType();
2528   bool PointerConversions = false;
2529   if (isa<FieldDecl>(Member)) {
2530     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2531 
2532     if (FromType->getAs<PointerType>()) {
2533       DestType = Context.getPointerType(DestRecordType);
2534       FromRecordType = FromType->getPointeeType();
2535       PointerConversions = true;
2536     } else {
2537       DestType = DestRecordType;
2538       FromRecordType = FromType;
2539     }
2540   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2541     if (Method->isStatic())
2542       return From;
2543 
2544     DestType = Method->getThisType(Context);
2545     DestRecordType = DestType->getPointeeType();
2546 
2547     if (FromType->getAs<PointerType>()) {
2548       FromRecordType = FromType->getPointeeType();
2549       PointerConversions = true;
2550     } else {
2551       FromRecordType = FromType;
2552       DestType = DestRecordType;
2553     }
2554   } else {
2555     // No conversion necessary.
2556     return From;
2557   }
2558 
2559   if (DestType->isDependentType() || FromType->isDependentType())
2560     return From;
2561 
2562   // If the unqualified types are the same, no conversion is necessary.
2563   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2564     return From;
2565 
2566   SourceRange FromRange = From->getSourceRange();
2567   SourceLocation FromLoc = FromRange.getBegin();
2568 
2569   ExprValueKind VK = From->getValueKind();
2570 
2571   // C++ [class.member.lookup]p8:
2572   //   [...] Ambiguities can often be resolved by qualifying a name with its
2573   //   class name.
2574   //
2575   // If the member was a qualified name and the qualified referred to a
2576   // specific base subobject type, we'll cast to that intermediate type
2577   // first and then to the object in which the member is declared. That allows
2578   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2579   //
2580   //   class Base { public: int x; };
2581   //   class Derived1 : public Base { };
2582   //   class Derived2 : public Base { };
2583   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2584   //
2585   //   void VeryDerived::f() {
2586   //     x = 17; // error: ambiguous base subobjects
2587   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2588   //   }
2589   if (Qualifier && Qualifier->getAsType()) {
2590     QualType QType = QualType(Qualifier->getAsType(), 0);
2591     assert(QType->isRecordType() && "lookup done with non-record type");
2592 
2593     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2594 
2595     // In C++98, the qualifier type doesn't actually have to be a base
2596     // type of the object type, in which case we just ignore it.
2597     // Otherwise build the appropriate casts.
2598     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2599       CXXCastPath BasePath;
2600       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2601                                        FromLoc, FromRange, &BasePath))
2602         return ExprError();
2603 
2604       if (PointerConversions)
2605         QType = Context.getPointerType(QType);
2606       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2607                                VK, &BasePath).get();
2608 
2609       FromType = QType;
2610       FromRecordType = QRecordType;
2611 
2612       // If the qualifier type was the same as the destination type,
2613       // we're done.
2614       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2615         return From;
2616     }
2617   }
2618 
2619   bool IgnoreAccess = false;
2620 
2621   // If we actually found the member through a using declaration, cast
2622   // down to the using declaration's type.
2623   //
2624   // Pointer equality is fine here because only one declaration of a
2625   // class ever has member declarations.
2626   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2627     assert(isa<UsingShadowDecl>(FoundDecl));
2628     QualType URecordType = Context.getTypeDeclType(
2629                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2630 
2631     // We only need to do this if the naming-class to declaring-class
2632     // conversion is non-trivial.
2633     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2634       assert(IsDerivedFrom(FromRecordType, URecordType));
2635       CXXCastPath BasePath;
2636       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2637                                        FromLoc, FromRange, &BasePath))
2638         return ExprError();
2639 
2640       QualType UType = URecordType;
2641       if (PointerConversions)
2642         UType = Context.getPointerType(UType);
2643       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2644                                VK, &BasePath).get();
2645       FromType = UType;
2646       FromRecordType = URecordType;
2647     }
2648 
2649     // We don't do access control for the conversion from the
2650     // declaring class to the true declaring class.
2651     IgnoreAccess = true;
2652   }
2653 
2654   CXXCastPath BasePath;
2655   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2656                                    FromLoc, FromRange, &BasePath,
2657                                    IgnoreAccess))
2658     return ExprError();
2659 
2660   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2661                            VK, &BasePath);
2662 }
2663 
2664 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2665                                       const LookupResult &R,
2666                                       bool HasTrailingLParen) {
2667   // Only when used directly as the postfix-expression of a call.
2668   if (!HasTrailingLParen)
2669     return false;
2670 
2671   // Never if a scope specifier was provided.
2672   if (SS.isSet())
2673     return false;
2674 
2675   // Only in C++ or ObjC++.
2676   if (!getLangOpts().CPlusPlus)
2677     return false;
2678 
2679   // Turn off ADL when we find certain kinds of declarations during
2680   // normal lookup:
2681   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2682     NamedDecl *D = *I;
2683 
2684     // C++0x [basic.lookup.argdep]p3:
2685     //     -- a declaration of a class member
2686     // Since using decls preserve this property, we check this on the
2687     // original decl.
2688     if (D->isCXXClassMember())
2689       return false;
2690 
2691     // C++0x [basic.lookup.argdep]p3:
2692     //     -- a block-scope function declaration that is not a
2693     //        using-declaration
2694     // NOTE: we also trigger this for function templates (in fact, we
2695     // don't check the decl type at all, since all other decl types
2696     // turn off ADL anyway).
2697     if (isa<UsingShadowDecl>(D))
2698       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2699     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2700       return false;
2701 
2702     // C++0x [basic.lookup.argdep]p3:
2703     //     -- a declaration that is neither a function or a function
2704     //        template
2705     // And also for builtin functions.
2706     if (isa<FunctionDecl>(D)) {
2707       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2708 
2709       // But also builtin functions.
2710       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2711         return false;
2712     } else if (!isa<FunctionTemplateDecl>(D))
2713       return false;
2714   }
2715 
2716   return true;
2717 }
2718 
2719 
2720 /// Diagnoses obvious problems with the use of the given declaration
2721 /// as an expression.  This is only actually called for lookups that
2722 /// were not overloaded, and it doesn't promise that the declaration
2723 /// will in fact be used.
2724 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2725   if (isa<TypedefNameDecl>(D)) {
2726     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2727     return true;
2728   }
2729 
2730   if (isa<ObjCInterfaceDecl>(D)) {
2731     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2732     return true;
2733   }
2734 
2735   if (isa<NamespaceDecl>(D)) {
2736     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2737     return true;
2738   }
2739 
2740   return false;
2741 }
2742 
2743 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2744                                           LookupResult &R, bool NeedsADL,
2745                                           bool AcceptInvalidDecl) {
2746   // If this is a single, fully-resolved result and we don't need ADL,
2747   // just build an ordinary singleton decl ref.
2748   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2749     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2750                                     R.getRepresentativeDecl(), nullptr,
2751                                     AcceptInvalidDecl);
2752 
2753   // We only need to check the declaration if there's exactly one
2754   // result, because in the overloaded case the results can only be
2755   // functions and function templates.
2756   if (R.isSingleResult() &&
2757       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2758     return ExprError();
2759 
2760   // Otherwise, just build an unresolved lookup expression.  Suppress
2761   // any lookup-related diagnostics; we'll hash these out later, when
2762   // we've picked a target.
2763   R.suppressDiagnostics();
2764 
2765   UnresolvedLookupExpr *ULE
2766     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2767                                    SS.getWithLocInContext(Context),
2768                                    R.getLookupNameInfo(),
2769                                    NeedsADL, R.isOverloadedResult(),
2770                                    R.begin(), R.end());
2771 
2772   return ULE;
2773 }
2774 
2775 /// \brief Complete semantic analysis for a reference to the given declaration.
2776 ExprResult Sema::BuildDeclarationNameExpr(
2777     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2778     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2779     bool AcceptInvalidDecl) {
2780   assert(D && "Cannot refer to a NULL declaration");
2781   assert(!isa<FunctionTemplateDecl>(D) &&
2782          "Cannot refer unambiguously to a function template");
2783 
2784   SourceLocation Loc = NameInfo.getLoc();
2785   if (CheckDeclInExpr(*this, Loc, D))
2786     return ExprError();
2787 
2788   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2789     // Specifically diagnose references to class templates that are missing
2790     // a template argument list.
2791     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2792                                            << Template << SS.getRange();
2793     Diag(Template->getLocation(), diag::note_template_decl_here);
2794     return ExprError();
2795   }
2796 
2797   // Make sure that we're referring to a value.
2798   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2799   if (!VD) {
2800     Diag(Loc, diag::err_ref_non_value)
2801       << D << SS.getRange();
2802     Diag(D->getLocation(), diag::note_declared_at);
2803     return ExprError();
2804   }
2805 
2806   // Check whether this declaration can be used. Note that we suppress
2807   // this check when we're going to perform argument-dependent lookup
2808   // on this function name, because this might not be the function
2809   // that overload resolution actually selects.
2810   if (DiagnoseUseOfDecl(VD, Loc))
2811     return ExprError();
2812 
2813   // Only create DeclRefExpr's for valid Decl's.
2814   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2815     return ExprError();
2816 
2817   // Handle members of anonymous structs and unions.  If we got here,
2818   // and the reference is to a class member indirect field, then this
2819   // must be the subject of a pointer-to-member expression.
2820   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2821     if (!indirectField->isCXXClassMember())
2822       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2823                                                       indirectField);
2824 
2825   {
2826     QualType type = VD->getType();
2827     ExprValueKind valueKind = VK_RValue;
2828 
2829     switch (D->getKind()) {
2830     // Ignore all the non-ValueDecl kinds.
2831 #define ABSTRACT_DECL(kind)
2832 #define VALUE(type, base)
2833 #define DECL(type, base) \
2834     case Decl::type:
2835 #include "clang/AST/DeclNodes.inc"
2836       llvm_unreachable("invalid value decl kind");
2837 
2838     // These shouldn't make it here.
2839     case Decl::ObjCAtDefsField:
2840     case Decl::ObjCIvar:
2841       llvm_unreachable("forming non-member reference to ivar?");
2842 
2843     // Enum constants are always r-values and never references.
2844     // Unresolved using declarations are dependent.
2845     case Decl::EnumConstant:
2846     case Decl::UnresolvedUsingValue:
2847       valueKind = VK_RValue;
2848       break;
2849 
2850     // Fields and indirect fields that got here must be for
2851     // pointer-to-member expressions; we just call them l-values for
2852     // internal consistency, because this subexpression doesn't really
2853     // exist in the high-level semantics.
2854     case Decl::Field:
2855     case Decl::IndirectField:
2856       assert(getLangOpts().CPlusPlus &&
2857              "building reference to field in C?");
2858 
2859       // These can't have reference type in well-formed programs, but
2860       // for internal consistency we do this anyway.
2861       type = type.getNonReferenceType();
2862       valueKind = VK_LValue;
2863       break;
2864 
2865     // Non-type template parameters are either l-values or r-values
2866     // depending on the type.
2867     case Decl::NonTypeTemplateParm: {
2868       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2869         type = reftype->getPointeeType();
2870         valueKind = VK_LValue; // even if the parameter is an r-value reference
2871         break;
2872       }
2873 
2874       // For non-references, we need to strip qualifiers just in case
2875       // the template parameter was declared as 'const int' or whatever.
2876       valueKind = VK_RValue;
2877       type = type.getUnqualifiedType();
2878       break;
2879     }
2880 
2881     case Decl::Var:
2882     case Decl::VarTemplateSpecialization:
2883     case Decl::VarTemplatePartialSpecialization:
2884       // In C, "extern void blah;" is valid and is an r-value.
2885       if (!getLangOpts().CPlusPlus &&
2886           !type.hasQualifiers() &&
2887           type->isVoidType()) {
2888         valueKind = VK_RValue;
2889         break;
2890       }
2891       // fallthrough
2892 
2893     case Decl::ImplicitParam:
2894     case Decl::ParmVar: {
2895       // These are always l-values.
2896       valueKind = VK_LValue;
2897       type = type.getNonReferenceType();
2898 
2899       // FIXME: Does the addition of const really only apply in
2900       // potentially-evaluated contexts? Since the variable isn't actually
2901       // captured in an unevaluated context, it seems that the answer is no.
2902       if (!isUnevaluatedContext()) {
2903         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2904         if (!CapturedType.isNull())
2905           type = CapturedType;
2906       }
2907 
2908       break;
2909     }
2910 
2911     case Decl::Function: {
2912       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2913         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2914           type = Context.BuiltinFnTy;
2915           valueKind = VK_RValue;
2916           break;
2917         }
2918       }
2919 
2920       const FunctionType *fty = type->castAs<FunctionType>();
2921 
2922       // If we're referring to a function with an __unknown_anytype
2923       // result type, make the entire expression __unknown_anytype.
2924       if (fty->getReturnType() == Context.UnknownAnyTy) {
2925         type = Context.UnknownAnyTy;
2926         valueKind = VK_RValue;
2927         break;
2928       }
2929 
2930       // Functions are l-values in C++.
2931       if (getLangOpts().CPlusPlus) {
2932         valueKind = VK_LValue;
2933         break;
2934       }
2935 
2936       // C99 DR 316 says that, if a function type comes from a
2937       // function definition (without a prototype), that type is only
2938       // used for checking compatibility. Therefore, when referencing
2939       // the function, we pretend that we don't have the full function
2940       // type.
2941       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2942           isa<FunctionProtoType>(fty))
2943         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2944                                               fty->getExtInfo());
2945 
2946       // Functions are r-values in C.
2947       valueKind = VK_RValue;
2948       break;
2949     }
2950 
2951     case Decl::MSProperty:
2952       valueKind = VK_LValue;
2953       break;
2954 
2955     case Decl::CXXMethod:
2956       // If we're referring to a method with an __unknown_anytype
2957       // result type, make the entire expression __unknown_anytype.
2958       // This should only be possible with a type written directly.
2959       if (const FunctionProtoType *proto
2960             = dyn_cast<FunctionProtoType>(VD->getType()))
2961         if (proto->getReturnType() == Context.UnknownAnyTy) {
2962           type = Context.UnknownAnyTy;
2963           valueKind = VK_RValue;
2964           break;
2965         }
2966 
2967       // C++ methods are l-values if static, r-values if non-static.
2968       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2969         valueKind = VK_LValue;
2970         break;
2971       }
2972       // fallthrough
2973 
2974     case Decl::CXXConversion:
2975     case Decl::CXXDestructor:
2976     case Decl::CXXConstructor:
2977       valueKind = VK_RValue;
2978       break;
2979     }
2980 
2981     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2982                             TemplateArgs);
2983   }
2984 }
2985 
2986 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2987                                     SmallString<32> &Target) {
2988   Target.resize(CharByteWidth * (Source.size() + 1));
2989   char *ResultPtr = &Target[0];
2990   const UTF8 *ErrorPtr;
2991   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2992   (void)success;
2993   assert(success);
2994   Target.resize(ResultPtr - &Target[0]);
2995 }
2996 
2997 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2998                                      PredefinedExpr::IdentType IT) {
2999   // Pick the current block, lambda, captured statement or function.
3000   Decl *currentDecl = nullptr;
3001   if (const BlockScopeInfo *BSI = getCurBlock())
3002     currentDecl = BSI->TheDecl;
3003   else if (const LambdaScopeInfo *LSI = getCurLambda())
3004     currentDecl = LSI->CallOperator;
3005   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
3006     currentDecl = CSI->TheCapturedDecl;
3007   else
3008     currentDecl = getCurFunctionOrMethodDecl();
3009 
3010   if (!currentDecl) {
3011     Diag(Loc, diag::ext_predef_outside_function);
3012     currentDecl = Context.getTranslationUnitDecl();
3013   }
3014 
3015   QualType ResTy;
3016   StringLiteral *SL = nullptr;
3017   if (cast<DeclContext>(currentDecl)->isDependentContext())
3018     ResTy = Context.DependentTy;
3019   else {
3020     // Pre-defined identifiers are of type char[x], where x is the length of
3021     // the string.
3022     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3023     unsigned Length = Str.length();
3024 
3025     llvm::APInt LengthI(32, Length + 1);
3026     if (IT == PredefinedExpr::LFunction) {
3027       ResTy = Context.WideCharTy.withConst();
3028       SmallString<32> RawChars;
3029       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3030                               Str, RawChars);
3031       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3032                                            /*IndexTypeQuals*/ 0);
3033       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3034                                  /*Pascal*/ false, ResTy, Loc);
3035     } else {
3036       ResTy = Context.CharTy.withConst();
3037       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3038                                            /*IndexTypeQuals*/ 0);
3039       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3040                                  /*Pascal*/ false, ResTy, Loc);
3041     }
3042   }
3043 
3044   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3045 }
3046 
3047 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3048   PredefinedExpr::IdentType IT;
3049 
3050   switch (Kind) {
3051   default: llvm_unreachable("Unknown simple primary expr!");
3052   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3053   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3054   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3055   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3056   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3057   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3058   }
3059 
3060   return BuildPredefinedExpr(Loc, IT);
3061 }
3062 
3063 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3064   SmallString<16> CharBuffer;
3065   bool Invalid = false;
3066   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3067   if (Invalid)
3068     return ExprError();
3069 
3070   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3071                             PP, Tok.getKind());
3072   if (Literal.hadError())
3073     return ExprError();
3074 
3075   QualType Ty;
3076   if (Literal.isWide())
3077     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3078   else if (Literal.isUTF16())
3079     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3080   else if (Literal.isUTF32())
3081     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3082   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3083     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3084   else
3085     Ty = Context.CharTy;  // 'x' -> char in C++
3086 
3087   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3088   if (Literal.isWide())
3089     Kind = CharacterLiteral::Wide;
3090   else if (Literal.isUTF16())
3091     Kind = CharacterLiteral::UTF16;
3092   else if (Literal.isUTF32())
3093     Kind = CharacterLiteral::UTF32;
3094 
3095   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3096                                              Tok.getLocation());
3097 
3098   if (Literal.getUDSuffix().empty())
3099     return Lit;
3100 
3101   // We're building a user-defined literal.
3102   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3103   SourceLocation UDSuffixLoc =
3104     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3105 
3106   // Make sure we're allowed user-defined literals here.
3107   if (!UDLScope)
3108     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3109 
3110   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3111   //   operator "" X (ch)
3112   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3113                                         Lit, Tok.getLocation());
3114 }
3115 
3116 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3117   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3118   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3119                                 Context.IntTy, Loc);
3120 }
3121 
3122 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3123                                   QualType Ty, SourceLocation Loc) {
3124   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3125 
3126   using llvm::APFloat;
3127   APFloat Val(Format);
3128 
3129   APFloat::opStatus result = Literal.GetFloatValue(Val);
3130 
3131   // Overflow is always an error, but underflow is only an error if
3132   // we underflowed to zero (APFloat reports denormals as underflow).
3133   if ((result & APFloat::opOverflow) ||
3134       ((result & APFloat::opUnderflow) && Val.isZero())) {
3135     unsigned diagnostic;
3136     SmallString<20> buffer;
3137     if (result & APFloat::opOverflow) {
3138       diagnostic = diag::warn_float_overflow;
3139       APFloat::getLargest(Format).toString(buffer);
3140     } else {
3141       diagnostic = diag::warn_float_underflow;
3142       APFloat::getSmallest(Format).toString(buffer);
3143     }
3144 
3145     S.Diag(Loc, diagnostic)
3146       << Ty
3147       << StringRef(buffer.data(), buffer.size());
3148   }
3149 
3150   bool isExact = (result == APFloat::opOK);
3151   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3152 }
3153 
3154 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3155   assert(E && "Invalid expression");
3156 
3157   if (E->isValueDependent())
3158     return false;
3159 
3160   QualType QT = E->getType();
3161   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3162     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3163     return true;
3164   }
3165 
3166   llvm::APSInt ValueAPS;
3167   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3168 
3169   if (R.isInvalid())
3170     return true;
3171 
3172   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3173   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3174     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3175         << ValueAPS.toString(10) << ValueIsPositive;
3176     return true;
3177   }
3178 
3179   return false;
3180 }
3181 
3182 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3183   // Fast path for a single digit (which is quite common).  A single digit
3184   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3185   if (Tok.getLength() == 1) {
3186     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3187     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3188   }
3189 
3190   SmallString<128> SpellingBuffer;
3191   // NumericLiteralParser wants to overread by one character.  Add padding to
3192   // the buffer in case the token is copied to the buffer.  If getSpelling()
3193   // returns a StringRef to the memory buffer, it should have a null char at
3194   // the EOF, so it is also safe.
3195   SpellingBuffer.resize(Tok.getLength() + 1);
3196 
3197   // Get the spelling of the token, which eliminates trigraphs, etc.
3198   bool Invalid = false;
3199   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3200   if (Invalid)
3201     return ExprError();
3202 
3203   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3204   if (Literal.hadError)
3205     return ExprError();
3206 
3207   if (Literal.hasUDSuffix()) {
3208     // We're building a user-defined literal.
3209     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3210     SourceLocation UDSuffixLoc =
3211       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3212 
3213     // Make sure we're allowed user-defined literals here.
3214     if (!UDLScope)
3215       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3216 
3217     QualType CookedTy;
3218     if (Literal.isFloatingLiteral()) {
3219       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3220       // long double, the literal is treated as a call of the form
3221       //   operator "" X (f L)
3222       CookedTy = Context.LongDoubleTy;
3223     } else {
3224       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3225       // unsigned long long, the literal is treated as a call of the form
3226       //   operator "" X (n ULL)
3227       CookedTy = Context.UnsignedLongLongTy;
3228     }
3229 
3230     DeclarationName OpName =
3231       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3232     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3233     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3234 
3235     SourceLocation TokLoc = Tok.getLocation();
3236 
3237     // Perform literal operator lookup to determine if we're building a raw
3238     // literal or a cooked one.
3239     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3240     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3241                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3242                                   /*AllowStringTemplate*/false)) {
3243     case LOLR_Error:
3244       return ExprError();
3245 
3246     case LOLR_Cooked: {
3247       Expr *Lit;
3248       if (Literal.isFloatingLiteral()) {
3249         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3250       } else {
3251         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3252         if (Literal.GetIntegerValue(ResultVal))
3253           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3254               << /* Unsigned */ 1;
3255         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3256                                      Tok.getLocation());
3257       }
3258       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3259     }
3260 
3261     case LOLR_Raw: {
3262       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3263       // literal is treated as a call of the form
3264       //   operator "" X ("n")
3265       unsigned Length = Literal.getUDSuffixOffset();
3266       QualType StrTy = Context.getConstantArrayType(
3267           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3268           ArrayType::Normal, 0);
3269       Expr *Lit = StringLiteral::Create(
3270           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3271           /*Pascal*/false, StrTy, &TokLoc, 1);
3272       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3273     }
3274 
3275     case LOLR_Template: {
3276       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3277       // template), L is treated as a call fo the form
3278       //   operator "" X <'c1', 'c2', ... 'ck'>()
3279       // where n is the source character sequence c1 c2 ... ck.
3280       TemplateArgumentListInfo ExplicitArgs;
3281       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3282       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3283       llvm::APSInt Value(CharBits, CharIsUnsigned);
3284       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3285         Value = TokSpelling[I];
3286         TemplateArgument Arg(Context, Value, Context.CharTy);
3287         TemplateArgumentLocInfo ArgInfo;
3288         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3289       }
3290       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3291                                       &ExplicitArgs);
3292     }
3293     case LOLR_StringTemplate:
3294       llvm_unreachable("unexpected literal operator lookup result");
3295     }
3296   }
3297 
3298   Expr *Res;
3299 
3300   if (Literal.isFloatingLiteral()) {
3301     QualType Ty;
3302     if (Literal.isFloat)
3303       Ty = Context.FloatTy;
3304     else if (!Literal.isLong)
3305       Ty = Context.DoubleTy;
3306     else
3307       Ty = Context.LongDoubleTy;
3308 
3309     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3310 
3311     if (Ty == Context.DoubleTy) {
3312       if (getLangOpts().SinglePrecisionConstants) {
3313         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3314       } else if (getLangOpts().OpenCL &&
3315                  !((getLangOpts().OpenCLVersion >= 120) ||
3316                    getOpenCLOptions().cl_khr_fp64)) {
3317         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3318         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3319       }
3320     }
3321   } else if (!Literal.isIntegerLiteral()) {
3322     return ExprError();
3323   } else {
3324     QualType Ty;
3325 
3326     // 'long long' is a C99 or C++11 feature.
3327     if (!getLangOpts().C99 && Literal.isLongLong) {
3328       if (getLangOpts().CPlusPlus)
3329         Diag(Tok.getLocation(),
3330              getLangOpts().CPlusPlus11 ?
3331              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3332       else
3333         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3334     }
3335 
3336     // Get the value in the widest-possible width.
3337     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3338     llvm::APInt ResultVal(MaxWidth, 0);
3339 
3340     if (Literal.GetIntegerValue(ResultVal)) {
3341       // If this value didn't fit into uintmax_t, error and force to ull.
3342       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3343           << /* Unsigned */ 1;
3344       Ty = Context.UnsignedLongLongTy;
3345       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3346              "long long is not intmax_t?");
3347     } else {
3348       // If this value fits into a ULL, try to figure out what else it fits into
3349       // according to the rules of C99 6.4.4.1p5.
3350 
3351       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3352       // be an unsigned int.
3353       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3354 
3355       // Check from smallest to largest, picking the smallest type we can.
3356       unsigned Width = 0;
3357 
3358       // Microsoft specific integer suffixes are explicitly sized.
3359       if (Literal.MicrosoftInteger) {
3360         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3361           Width = 8;
3362           Ty = Context.CharTy;
3363         } else {
3364           Width = Literal.MicrosoftInteger;
3365           Ty = Context.getIntTypeForBitwidth(Width,
3366                                              /*Signed=*/!Literal.isUnsigned);
3367         }
3368       }
3369 
3370       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3371         // Are int/unsigned possibilities?
3372         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3373 
3374         // Does it fit in a unsigned int?
3375         if (ResultVal.isIntN(IntSize)) {
3376           // Does it fit in a signed int?
3377           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3378             Ty = Context.IntTy;
3379           else if (AllowUnsigned)
3380             Ty = Context.UnsignedIntTy;
3381           Width = IntSize;
3382         }
3383       }
3384 
3385       // Are long/unsigned long possibilities?
3386       if (Ty.isNull() && !Literal.isLongLong) {
3387         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3388 
3389         // Does it fit in a unsigned long?
3390         if (ResultVal.isIntN(LongSize)) {
3391           // Does it fit in a signed long?
3392           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3393             Ty = Context.LongTy;
3394           else if (AllowUnsigned)
3395             Ty = Context.UnsignedLongTy;
3396           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3397           // is compatible.
3398           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3399             const unsigned LongLongSize =
3400                 Context.getTargetInfo().getLongLongWidth();
3401             Diag(Tok.getLocation(),
3402                  getLangOpts().CPlusPlus
3403                      ? Literal.isLong
3404                            ? diag::warn_old_implicitly_unsigned_long_cxx
3405                            : /*C++98 UB*/ diag::
3406                                  ext_old_implicitly_unsigned_long_cxx
3407                      : diag::warn_old_implicitly_unsigned_long)
3408                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3409                                             : /*will be ill-formed*/ 1);
3410             Ty = Context.UnsignedLongTy;
3411           }
3412           Width = LongSize;
3413         }
3414       }
3415 
3416       // Check long long if needed.
3417       if (Ty.isNull()) {
3418         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3419 
3420         // Does it fit in a unsigned long long?
3421         if (ResultVal.isIntN(LongLongSize)) {
3422           // Does it fit in a signed long long?
3423           // To be compatible with MSVC, hex integer literals ending with the
3424           // LL or i64 suffix are always signed in Microsoft mode.
3425           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3426               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3427             Ty = Context.LongLongTy;
3428           else if (AllowUnsigned)
3429             Ty = Context.UnsignedLongLongTy;
3430           Width = LongLongSize;
3431         }
3432       }
3433 
3434       // If we still couldn't decide a type, we probably have something that
3435       // does not fit in a signed long long, but has no U suffix.
3436       if (Ty.isNull()) {
3437         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3438         Ty = Context.UnsignedLongLongTy;
3439         Width = Context.getTargetInfo().getLongLongWidth();
3440       }
3441 
3442       if (ResultVal.getBitWidth() != Width)
3443         ResultVal = ResultVal.trunc(Width);
3444     }
3445     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3446   }
3447 
3448   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3449   if (Literal.isImaginary)
3450     Res = new (Context) ImaginaryLiteral(Res,
3451                                         Context.getComplexType(Res->getType()));
3452 
3453   return Res;
3454 }
3455 
3456 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3457   assert(E && "ActOnParenExpr() missing expr");
3458   return new (Context) ParenExpr(L, R, E);
3459 }
3460 
3461 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3462                                          SourceLocation Loc,
3463                                          SourceRange ArgRange) {
3464   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3465   // scalar or vector data type argument..."
3466   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3467   // type (C99 6.2.5p18) or void.
3468   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3469     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3470       << T << ArgRange;
3471     return true;
3472   }
3473 
3474   assert((T->isVoidType() || !T->isIncompleteType()) &&
3475          "Scalar types should always be complete");
3476   return false;
3477 }
3478 
3479 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3480                                            SourceLocation Loc,
3481                                            SourceRange ArgRange,
3482                                            UnaryExprOrTypeTrait TraitKind) {
3483   // Invalid types must be hard errors for SFINAE in C++.
3484   if (S.LangOpts.CPlusPlus)
3485     return true;
3486 
3487   // C99 6.5.3.4p1:
3488   if (T->isFunctionType() &&
3489       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3490     // sizeof(function)/alignof(function) is allowed as an extension.
3491     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3492       << TraitKind << ArgRange;
3493     return false;
3494   }
3495 
3496   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3497   // this is an error (OpenCL v1.1 s6.3.k)
3498   if (T->isVoidType()) {
3499     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3500                                         : diag::ext_sizeof_alignof_void_type;
3501     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3502     return false;
3503   }
3504 
3505   return true;
3506 }
3507 
3508 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3509                                              SourceLocation Loc,
3510                                              SourceRange ArgRange,
3511                                              UnaryExprOrTypeTrait TraitKind) {
3512   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3513   // runtime doesn't allow it.
3514   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3515     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3516       << T << (TraitKind == UETT_SizeOf)
3517       << ArgRange;
3518     return true;
3519   }
3520 
3521   return false;
3522 }
3523 
3524 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3525 /// pointer type is equal to T) and emit a warning if it is.
3526 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3527                                      Expr *E) {
3528   // Don't warn if the operation changed the type.
3529   if (T != E->getType())
3530     return;
3531 
3532   // Now look for array decays.
3533   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3534   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3535     return;
3536 
3537   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3538                                              << ICE->getType()
3539                                              << ICE->getSubExpr()->getType();
3540 }
3541 
3542 /// \brief Check the constraints on expression operands to unary type expression
3543 /// and type traits.
3544 ///
3545 /// Completes any types necessary and validates the constraints on the operand
3546 /// expression. The logic mostly mirrors the type-based overload, but may modify
3547 /// the expression as it completes the type for that expression through template
3548 /// instantiation, etc.
3549 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3550                                             UnaryExprOrTypeTrait ExprKind) {
3551   QualType ExprTy = E->getType();
3552   assert(!ExprTy->isReferenceType());
3553 
3554   if (ExprKind == UETT_VecStep)
3555     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3556                                         E->getSourceRange());
3557 
3558   // Whitelist some types as extensions
3559   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3560                                       E->getSourceRange(), ExprKind))
3561     return false;
3562 
3563   // 'alignof' applied to an expression only requires the base element type of
3564   // the expression to be complete. 'sizeof' requires the expression's type to
3565   // be complete (and will attempt to complete it if it's an array of unknown
3566   // bound).
3567   if (ExprKind == UETT_AlignOf) {
3568     if (RequireCompleteType(E->getExprLoc(),
3569                             Context.getBaseElementType(E->getType()),
3570                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3571                             E->getSourceRange()))
3572       return true;
3573   } else {
3574     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3575                                 ExprKind, E->getSourceRange()))
3576       return true;
3577   }
3578 
3579   // Completing the expression's type may have changed it.
3580   ExprTy = E->getType();
3581   assert(!ExprTy->isReferenceType());
3582 
3583   if (ExprTy->isFunctionType()) {
3584     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3585       << ExprKind << E->getSourceRange();
3586     return true;
3587   }
3588 
3589   // The operand for sizeof and alignof is in an unevaluated expression context,
3590   // so side effects could result in unintended consequences.
3591   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3592       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3593     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3594 
3595   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3596                                        E->getSourceRange(), ExprKind))
3597     return true;
3598 
3599   if (ExprKind == UETT_SizeOf) {
3600     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3601       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3602         QualType OType = PVD->getOriginalType();
3603         QualType Type = PVD->getType();
3604         if (Type->isPointerType() && OType->isArrayType()) {
3605           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3606             << Type << OType;
3607           Diag(PVD->getLocation(), diag::note_declared_at);
3608         }
3609       }
3610     }
3611 
3612     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3613     // decays into a pointer and returns an unintended result. This is most
3614     // likely a typo for "sizeof(array) op x".
3615     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3616       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3617                                BO->getLHS());
3618       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3619                                BO->getRHS());
3620     }
3621   }
3622 
3623   return false;
3624 }
3625 
3626 /// \brief Check the constraints on operands to unary expression and type
3627 /// traits.
3628 ///
3629 /// This will complete any types necessary, and validate the various constraints
3630 /// on those operands.
3631 ///
3632 /// The UsualUnaryConversions() function is *not* called by this routine.
3633 /// C99 6.3.2.1p[2-4] all state:
3634 ///   Except when it is the operand of the sizeof operator ...
3635 ///
3636 /// C++ [expr.sizeof]p4
3637 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3638 ///   standard conversions are not applied to the operand of sizeof.
3639 ///
3640 /// This policy is followed for all of the unary trait expressions.
3641 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3642                                             SourceLocation OpLoc,
3643                                             SourceRange ExprRange,
3644                                             UnaryExprOrTypeTrait ExprKind) {
3645   if (ExprType->isDependentType())
3646     return false;
3647 
3648   // C++ [expr.sizeof]p2:
3649   //     When applied to a reference or a reference type, the result
3650   //     is the size of the referenced type.
3651   // C++11 [expr.alignof]p3:
3652   //     When alignof is applied to a reference type, the result
3653   //     shall be the alignment of the referenced type.
3654   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3655     ExprType = Ref->getPointeeType();
3656 
3657   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3658   //   When alignof or _Alignof is applied to an array type, the result
3659   //   is the alignment of the element type.
3660   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3661     ExprType = Context.getBaseElementType(ExprType);
3662 
3663   if (ExprKind == UETT_VecStep)
3664     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3665 
3666   // Whitelist some types as extensions
3667   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3668                                       ExprKind))
3669     return false;
3670 
3671   if (RequireCompleteType(OpLoc, ExprType,
3672                           diag::err_sizeof_alignof_incomplete_type,
3673                           ExprKind, ExprRange))
3674     return true;
3675 
3676   if (ExprType->isFunctionType()) {
3677     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3678       << ExprKind << ExprRange;
3679     return true;
3680   }
3681 
3682   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3683                                        ExprKind))
3684     return true;
3685 
3686   return false;
3687 }
3688 
3689 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3690   E = E->IgnoreParens();
3691 
3692   // Cannot know anything else if the expression is dependent.
3693   if (E->isTypeDependent())
3694     return false;
3695 
3696   if (E->getObjectKind() == OK_BitField) {
3697     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3698        << 1 << E->getSourceRange();
3699     return true;
3700   }
3701 
3702   ValueDecl *D = nullptr;
3703   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3704     D = DRE->getDecl();
3705   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3706     D = ME->getMemberDecl();
3707   }
3708 
3709   // If it's a field, require the containing struct to have a
3710   // complete definition so that we can compute the layout.
3711   //
3712   // This can happen in C++11 onwards, either by naming the member
3713   // in a way that is not transformed into a member access expression
3714   // (in an unevaluated operand, for instance), or by naming the member
3715   // in a trailing-return-type.
3716   //
3717   // For the record, since __alignof__ on expressions is a GCC
3718   // extension, GCC seems to permit this but always gives the
3719   // nonsensical answer 0.
3720   //
3721   // We don't really need the layout here --- we could instead just
3722   // directly check for all the appropriate alignment-lowing
3723   // attributes --- but that would require duplicating a lot of
3724   // logic that just isn't worth duplicating for such a marginal
3725   // use-case.
3726   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3727     // Fast path this check, since we at least know the record has a
3728     // definition if we can find a member of it.
3729     if (!FD->getParent()->isCompleteDefinition()) {
3730       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3731         << E->getSourceRange();
3732       return true;
3733     }
3734 
3735     // Otherwise, if it's a field, and the field doesn't have
3736     // reference type, then it must have a complete type (or be a
3737     // flexible array member, which we explicitly want to
3738     // white-list anyway), which makes the following checks trivial.
3739     if (!FD->getType()->isReferenceType())
3740       return false;
3741   }
3742 
3743   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3744 }
3745 
3746 bool Sema::CheckVecStepExpr(Expr *E) {
3747   E = E->IgnoreParens();
3748 
3749   // Cannot know anything else if the expression is dependent.
3750   if (E->isTypeDependent())
3751     return false;
3752 
3753   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3754 }
3755 
3756 /// \brief Build a sizeof or alignof expression given a type operand.
3757 ExprResult
3758 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3759                                      SourceLocation OpLoc,
3760                                      UnaryExprOrTypeTrait ExprKind,
3761                                      SourceRange R) {
3762   if (!TInfo)
3763     return ExprError();
3764 
3765   QualType T = TInfo->getType();
3766 
3767   if (!T->isDependentType() &&
3768       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3769     return ExprError();
3770 
3771   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3772   return new (Context) UnaryExprOrTypeTraitExpr(
3773       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3774 }
3775 
3776 /// \brief Build a sizeof or alignof expression given an expression
3777 /// operand.
3778 ExprResult
3779 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3780                                      UnaryExprOrTypeTrait ExprKind) {
3781   ExprResult PE = CheckPlaceholderExpr(E);
3782   if (PE.isInvalid())
3783     return ExprError();
3784 
3785   E = PE.get();
3786 
3787   // Verify that the operand is valid.
3788   bool isInvalid = false;
3789   if (E->isTypeDependent()) {
3790     // Delay type-checking for type-dependent expressions.
3791   } else if (ExprKind == UETT_AlignOf) {
3792     isInvalid = CheckAlignOfExpr(*this, E);
3793   } else if (ExprKind == UETT_VecStep) {
3794     isInvalid = CheckVecStepExpr(E);
3795   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3796       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3797       isInvalid = true;
3798   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3799     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3800     isInvalid = true;
3801   } else {
3802     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3803   }
3804 
3805   if (isInvalid)
3806     return ExprError();
3807 
3808   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3809     PE = TransformToPotentiallyEvaluated(E);
3810     if (PE.isInvalid()) return ExprError();
3811     E = PE.get();
3812   }
3813 
3814   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3815   return new (Context) UnaryExprOrTypeTraitExpr(
3816       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3817 }
3818 
3819 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3820 /// expr and the same for @c alignof and @c __alignof
3821 /// Note that the ArgRange is invalid if isType is false.
3822 ExprResult
3823 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3824                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3825                                     void *TyOrEx, SourceRange ArgRange) {
3826   // If error parsing type, ignore.
3827   if (!TyOrEx) return ExprError();
3828 
3829   if (IsType) {
3830     TypeSourceInfo *TInfo;
3831     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3832     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3833   }
3834 
3835   Expr *ArgEx = (Expr *)TyOrEx;
3836   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3837   return Result;
3838 }
3839 
3840 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3841                                      bool IsReal) {
3842   if (V.get()->isTypeDependent())
3843     return S.Context.DependentTy;
3844 
3845   // _Real and _Imag are only l-values for normal l-values.
3846   if (V.get()->getObjectKind() != OK_Ordinary) {
3847     V = S.DefaultLvalueConversion(V.get());
3848     if (V.isInvalid())
3849       return QualType();
3850   }
3851 
3852   // These operators return the element type of a complex type.
3853   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3854     return CT->getElementType();
3855 
3856   // Otherwise they pass through real integer and floating point types here.
3857   if (V.get()->getType()->isArithmeticType())
3858     return V.get()->getType();
3859 
3860   // Test for placeholders.
3861   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3862   if (PR.isInvalid()) return QualType();
3863   if (PR.get() != V.get()) {
3864     V = PR;
3865     return CheckRealImagOperand(S, V, Loc, IsReal);
3866   }
3867 
3868   // Reject anything else.
3869   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3870     << (IsReal ? "__real" : "__imag");
3871   return QualType();
3872 }
3873 
3874 
3875 
3876 ExprResult
3877 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3878                           tok::TokenKind Kind, Expr *Input) {
3879   UnaryOperatorKind Opc;
3880   switch (Kind) {
3881   default: llvm_unreachable("Unknown unary op!");
3882   case tok::plusplus:   Opc = UO_PostInc; break;
3883   case tok::minusminus: Opc = UO_PostDec; break;
3884   }
3885 
3886   // Since this might is a postfix expression, get rid of ParenListExprs.
3887   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3888   if (Result.isInvalid()) return ExprError();
3889   Input = Result.get();
3890 
3891   return BuildUnaryOp(S, OpLoc, Opc, Input);
3892 }
3893 
3894 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3895 ///
3896 /// \return true on error
3897 static bool checkArithmeticOnObjCPointer(Sema &S,
3898                                          SourceLocation opLoc,
3899                                          Expr *op) {
3900   assert(op->getType()->isObjCObjectPointerType());
3901   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3902       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3903     return false;
3904 
3905   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3906     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3907     << op->getSourceRange();
3908   return true;
3909 }
3910 
3911 static bool isMSPropertySubscriptExpr(Sema &S, Expr *Base) {
3912   auto *BaseNoParens = Base->IgnoreParens();
3913   if (auto *MSProp = dyn_cast<MSPropertyRefExpr>(BaseNoParens))
3914     return MSProp->getPropertyDecl()->getType()->isArrayType();
3915   return isa<MSPropertySubscriptExpr>(BaseNoParens);
3916 }
3917 
3918 ExprResult
3919 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3920                               Expr *idx, SourceLocation rbLoc) {
3921   if (base && !base->getType().isNull() &&
3922       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
3923     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
3924                                     /*Length=*/nullptr, rbLoc);
3925 
3926   // Since this might be a postfix expression, get rid of ParenListExprs.
3927   if (isa<ParenListExpr>(base)) {
3928     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3929     if (result.isInvalid()) return ExprError();
3930     base = result.get();
3931   }
3932 
3933   // Handle any non-overload placeholder types in the base and index
3934   // expressions.  We can't handle overloads here because the other
3935   // operand might be an overloadable type, in which case the overload
3936   // resolution for the operator overload should get the first crack
3937   // at the overload.
3938   bool IsMSPropertySubscript = false;
3939   if (base->getType()->isNonOverloadPlaceholderType()) {
3940     IsMSPropertySubscript = isMSPropertySubscriptExpr(*this, base);
3941     if (!IsMSPropertySubscript) {
3942       ExprResult result = CheckPlaceholderExpr(base);
3943       if (result.isInvalid())
3944         return ExprError();
3945       base = result.get();
3946     }
3947   }
3948   if (idx->getType()->isNonOverloadPlaceholderType()) {
3949     ExprResult result = CheckPlaceholderExpr(idx);
3950     if (result.isInvalid()) return ExprError();
3951     idx = result.get();
3952   }
3953 
3954   // Build an unanalyzed expression if either operand is type-dependent.
3955   if (getLangOpts().CPlusPlus &&
3956       (base->isTypeDependent() || idx->isTypeDependent())) {
3957     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3958                                             VK_LValue, OK_Ordinary, rbLoc);
3959   }
3960 
3961   // MSDN, property (C++)
3962   // https://msdn.microsoft.com/en-us/library/yhfk0thd(v=vs.120).aspx
3963   // This attribute can also be used in the declaration of an empty array in a
3964   // class or structure definition. For example:
3965   // __declspec(property(get=GetX, put=PutX)) int x[];
3966   // The above statement indicates that x[] can be used with one or more array
3967   // indices. In this case, i=p->x[a][b] will be turned into i=p->GetX(a, b),
3968   // and p->x[a][b] = i will be turned into p->PutX(a, b, i);
3969   if (IsMSPropertySubscript) {
3970     // Build MS property subscript expression if base is MS property reference
3971     // or MS property subscript.
3972     return new (Context) MSPropertySubscriptExpr(
3973         base, idx, Context.PseudoObjectTy, VK_LValue, OK_Ordinary, rbLoc);
3974   }
3975 
3976   // Use C++ overloaded-operator rules if either operand has record
3977   // type.  The spec says to do this if either type is *overloadable*,
3978   // but enum types can't declare subscript operators or conversion
3979   // operators, so there's nothing interesting for overload resolution
3980   // to do if there aren't any record types involved.
3981   //
3982   // ObjC pointers have their own subscripting logic that is not tied
3983   // to overload resolution and so should not take this path.
3984   if (getLangOpts().CPlusPlus &&
3985       (base->getType()->isRecordType() ||
3986        (!base->getType()->isObjCObjectPointerType() &&
3987         idx->getType()->isRecordType()))) {
3988     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3989   }
3990 
3991   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3992 }
3993 
3994 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
3995                                           Expr *LowerBound,
3996                                           SourceLocation ColonLoc, Expr *Length,
3997                                           SourceLocation RBLoc) {
3998   if (Base->getType()->isPlaceholderType() &&
3999       !Base->getType()->isSpecificPlaceholderType(
4000           BuiltinType::OMPArraySection)) {
4001     ExprResult Result = CheckPlaceholderExpr(Base);
4002     if (Result.isInvalid())
4003       return ExprError();
4004     Base = Result.get();
4005   }
4006   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
4007     ExprResult Result = CheckPlaceholderExpr(LowerBound);
4008     if (Result.isInvalid())
4009       return ExprError();
4010     LowerBound = Result.get();
4011   }
4012   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
4013     ExprResult Result = CheckPlaceholderExpr(Length);
4014     if (Result.isInvalid())
4015       return ExprError();
4016     Length = Result.get();
4017   }
4018 
4019   // Build an unanalyzed expression if either operand is type-dependent.
4020   if (Base->isTypeDependent() ||
4021       (LowerBound &&
4022        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
4023       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
4024     return new (Context)
4025         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
4026                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4027   }
4028 
4029   // Perform default conversions.
4030   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
4031   QualType ResultTy;
4032   if (OriginalTy->isAnyPointerType()) {
4033     ResultTy = OriginalTy->getPointeeType();
4034   } else if (OriginalTy->isArrayType()) {
4035     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4036   } else {
4037     return ExprError(
4038         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4039         << Base->getSourceRange());
4040   }
4041   // C99 6.5.2.1p1
4042   if (LowerBound) {
4043     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4044                                                       LowerBound);
4045     if (Res.isInvalid())
4046       return ExprError(Diag(LowerBound->getExprLoc(),
4047                             diag::err_omp_typecheck_section_not_integer)
4048                        << 0 << LowerBound->getSourceRange());
4049     LowerBound = Res.get();
4050 
4051     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4052         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4053       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4054           << 0 << LowerBound->getSourceRange();
4055   }
4056   if (Length) {
4057     auto Res =
4058         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4059     if (Res.isInvalid())
4060       return ExprError(Diag(Length->getExprLoc(),
4061                             diag::err_omp_typecheck_section_not_integer)
4062                        << 1 << Length->getSourceRange());
4063     Length = Res.get();
4064 
4065     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4066         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4067       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4068           << 1 << Length->getSourceRange();
4069   }
4070 
4071   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4072   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4073   // type. Note that functions are not objects, and that (in C99 parlance)
4074   // incomplete types are not object types.
4075   if (ResultTy->isFunctionType()) {
4076     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4077         << ResultTy << Base->getSourceRange();
4078     return ExprError();
4079   }
4080 
4081   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4082                           diag::err_omp_section_incomplete_type, Base))
4083     return ExprError();
4084 
4085   if (LowerBound) {
4086     llvm::APSInt LowerBoundValue;
4087     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4088       // OpenMP 4.0, [2.4 Array Sections]
4089       // The lower-bound and length must evaluate to non-negative integers.
4090       if (LowerBoundValue.isNegative()) {
4091         Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4092             << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4093             << LowerBound->getSourceRange();
4094         return ExprError();
4095       }
4096     }
4097   }
4098 
4099   if (Length) {
4100     llvm::APSInt LengthValue;
4101     if (Length->EvaluateAsInt(LengthValue, Context)) {
4102       // OpenMP 4.0, [2.4 Array Sections]
4103       // The lower-bound and length must evaluate to non-negative integers.
4104       if (LengthValue.isNegative()) {
4105         Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4106             << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4107             << Length->getSourceRange();
4108         return ExprError();
4109       }
4110     }
4111   } else if (ColonLoc.isValid() &&
4112              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4113                                       !OriginalTy->isVariableArrayType()))) {
4114     // OpenMP 4.0, [2.4 Array Sections]
4115     // When the size of the array dimension is not known, the length must be
4116     // specified explicitly.
4117     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4118         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4119     return ExprError();
4120   }
4121 
4122   return new (Context)
4123       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4124                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4125 }
4126 
4127 ExprResult
4128 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4129                                       Expr *Idx, SourceLocation RLoc) {
4130   Expr *LHSExp = Base;
4131   Expr *RHSExp = Idx;
4132 
4133   // Perform default conversions.
4134   if (!LHSExp->getType()->getAs<VectorType>()) {
4135     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4136     if (Result.isInvalid())
4137       return ExprError();
4138     LHSExp = Result.get();
4139   }
4140   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4141   if (Result.isInvalid())
4142     return ExprError();
4143   RHSExp = Result.get();
4144 
4145   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4146   ExprValueKind VK = VK_LValue;
4147   ExprObjectKind OK = OK_Ordinary;
4148 
4149   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4150   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4151   // in the subscript position. As a result, we need to derive the array base
4152   // and index from the expression types.
4153   Expr *BaseExpr, *IndexExpr;
4154   QualType ResultType;
4155   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4156     BaseExpr = LHSExp;
4157     IndexExpr = RHSExp;
4158     ResultType = Context.DependentTy;
4159   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4160     BaseExpr = LHSExp;
4161     IndexExpr = RHSExp;
4162     ResultType = PTy->getPointeeType();
4163   } else if (const ObjCObjectPointerType *PTy =
4164                LHSTy->getAs<ObjCObjectPointerType>()) {
4165     BaseExpr = LHSExp;
4166     IndexExpr = RHSExp;
4167 
4168     // Use custom logic if this should be the pseudo-object subscript
4169     // expression.
4170     if (!LangOpts.isSubscriptPointerArithmetic())
4171       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4172                                           nullptr);
4173 
4174     ResultType = PTy->getPointeeType();
4175   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4176      // Handle the uncommon case of "123[Ptr]".
4177     BaseExpr = RHSExp;
4178     IndexExpr = LHSExp;
4179     ResultType = PTy->getPointeeType();
4180   } else if (const ObjCObjectPointerType *PTy =
4181                RHSTy->getAs<ObjCObjectPointerType>()) {
4182      // Handle the uncommon case of "123[Ptr]".
4183     BaseExpr = RHSExp;
4184     IndexExpr = LHSExp;
4185     ResultType = PTy->getPointeeType();
4186     if (!LangOpts.isSubscriptPointerArithmetic()) {
4187       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4188         << ResultType << BaseExpr->getSourceRange();
4189       return ExprError();
4190     }
4191   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4192     BaseExpr = LHSExp;    // vectors: V[123]
4193     IndexExpr = RHSExp;
4194     VK = LHSExp->getValueKind();
4195     if (VK != VK_RValue)
4196       OK = OK_VectorComponent;
4197 
4198     // FIXME: need to deal with const...
4199     ResultType = VTy->getElementType();
4200   } else if (LHSTy->isArrayType()) {
4201     // If we see an array that wasn't promoted by
4202     // DefaultFunctionArrayLvalueConversion, it must be an array that
4203     // wasn't promoted because of the C90 rule that doesn't
4204     // allow promoting non-lvalue arrays.  Warn, then
4205     // force the promotion here.
4206     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4207         LHSExp->getSourceRange();
4208     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4209                                CK_ArrayToPointerDecay).get();
4210     LHSTy = LHSExp->getType();
4211 
4212     BaseExpr = LHSExp;
4213     IndexExpr = RHSExp;
4214     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4215   } else if (RHSTy->isArrayType()) {
4216     // Same as previous, except for 123[f().a] case
4217     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4218         RHSExp->getSourceRange();
4219     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4220                                CK_ArrayToPointerDecay).get();
4221     RHSTy = RHSExp->getType();
4222 
4223     BaseExpr = RHSExp;
4224     IndexExpr = LHSExp;
4225     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4226   } else {
4227     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4228        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4229   }
4230   // C99 6.5.2.1p1
4231   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4232     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4233                      << IndexExpr->getSourceRange());
4234 
4235   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4236        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4237          && !IndexExpr->isTypeDependent())
4238     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4239 
4240   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4241   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4242   // type. Note that Functions are not objects, and that (in C99 parlance)
4243   // incomplete types are not object types.
4244   if (ResultType->isFunctionType()) {
4245     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4246       << ResultType << BaseExpr->getSourceRange();
4247     return ExprError();
4248   }
4249 
4250   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4251     // GNU extension: subscripting on pointer to void
4252     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4253       << BaseExpr->getSourceRange();
4254 
4255     // C forbids expressions of unqualified void type from being l-values.
4256     // See IsCForbiddenLValueType.
4257     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4258   } else if (!ResultType->isDependentType() &&
4259       RequireCompleteType(LLoc, ResultType,
4260                           diag::err_subscript_incomplete_type, BaseExpr))
4261     return ExprError();
4262 
4263   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4264          !ResultType.isCForbiddenLValueType());
4265 
4266   return new (Context)
4267       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4268 }
4269 
4270 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4271                                         FunctionDecl *FD,
4272                                         ParmVarDecl *Param) {
4273   if (Param->hasUnparsedDefaultArg()) {
4274     Diag(CallLoc,
4275          diag::err_use_of_default_argument_to_function_declared_later) <<
4276       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4277     Diag(UnparsedDefaultArgLocs[Param],
4278          diag::note_default_argument_declared_here);
4279     return ExprError();
4280   }
4281 
4282   if (Param->hasUninstantiatedDefaultArg()) {
4283     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4284 
4285     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4286                                                  Param);
4287 
4288     // Instantiate the expression.
4289     MultiLevelTemplateArgumentList MutiLevelArgList
4290       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4291 
4292     InstantiatingTemplate Inst(*this, CallLoc, Param,
4293                                MutiLevelArgList.getInnermost());
4294     if (Inst.isInvalid())
4295       return ExprError();
4296 
4297     ExprResult Result;
4298     {
4299       // C++ [dcl.fct.default]p5:
4300       //   The names in the [default argument] expression are bound, and
4301       //   the semantic constraints are checked, at the point where the
4302       //   default argument expression appears.
4303       ContextRAII SavedContext(*this, FD);
4304       LocalInstantiationScope Local(*this);
4305       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4306     }
4307     if (Result.isInvalid())
4308       return ExprError();
4309 
4310     // Check the expression as an initializer for the parameter.
4311     InitializedEntity Entity
4312       = InitializedEntity::InitializeParameter(Context, Param);
4313     InitializationKind Kind
4314       = InitializationKind::CreateCopy(Param->getLocation(),
4315              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4316     Expr *ResultE = Result.getAs<Expr>();
4317 
4318     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4319     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4320     if (Result.isInvalid())
4321       return ExprError();
4322 
4323     Expr *Arg = Result.getAs<Expr>();
4324     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4325     // Build the default argument expression.
4326     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4327   }
4328 
4329   // If the default expression creates temporaries, we need to
4330   // push them to the current stack of expression temporaries so they'll
4331   // be properly destroyed.
4332   // FIXME: We should really be rebuilding the default argument with new
4333   // bound temporaries; see the comment in PR5810.
4334   // We don't need to do that with block decls, though, because
4335   // blocks in default argument expression can never capture anything.
4336   if (isa<ExprWithCleanups>(Param->getInit())) {
4337     // Set the "needs cleanups" bit regardless of whether there are
4338     // any explicit objects.
4339     ExprNeedsCleanups = true;
4340 
4341     // Append all the objects to the cleanup list.  Right now, this
4342     // should always be a no-op, because blocks in default argument
4343     // expressions should never be able to capture anything.
4344     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4345            "default argument expression has capturing blocks?");
4346   }
4347 
4348   // We already type-checked the argument, so we know it works.
4349   // Just mark all of the declarations in this potentially-evaluated expression
4350   // as being "referenced".
4351   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4352                                    /*SkipLocalVariables=*/true);
4353   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4354 }
4355 
4356 
4357 Sema::VariadicCallType
4358 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4359                           Expr *Fn) {
4360   if (Proto && Proto->isVariadic()) {
4361     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4362       return VariadicConstructor;
4363     else if (Fn && Fn->getType()->isBlockPointerType())
4364       return VariadicBlock;
4365     else if (FDecl) {
4366       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4367         if (Method->isInstance())
4368           return VariadicMethod;
4369     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4370       return VariadicMethod;
4371     return VariadicFunction;
4372   }
4373   return VariadicDoesNotApply;
4374 }
4375 
4376 namespace {
4377 class FunctionCallCCC : public FunctionCallFilterCCC {
4378 public:
4379   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4380                   unsigned NumArgs, MemberExpr *ME)
4381       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4382         FunctionName(FuncName) {}
4383 
4384   bool ValidateCandidate(const TypoCorrection &candidate) override {
4385     if (!candidate.getCorrectionSpecifier() ||
4386         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4387       return false;
4388     }
4389 
4390     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4391   }
4392 
4393 private:
4394   const IdentifierInfo *const FunctionName;
4395 };
4396 }
4397 
4398 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4399                                                FunctionDecl *FDecl,
4400                                                ArrayRef<Expr *> Args) {
4401   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4402   DeclarationName FuncName = FDecl->getDeclName();
4403   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4404 
4405   if (TypoCorrection Corrected = S.CorrectTypo(
4406           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4407           S.getScopeForContext(S.CurContext), nullptr,
4408           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4409                                              Args.size(), ME),
4410           Sema::CTK_ErrorRecovery)) {
4411     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4412       if (Corrected.isOverloaded()) {
4413         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4414         OverloadCandidateSet::iterator Best;
4415         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4416                                            CDEnd = Corrected.end();
4417              CD != CDEnd; ++CD) {
4418           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4419             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4420                                    OCS);
4421         }
4422         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4423         case OR_Success:
4424           ND = Best->Function;
4425           Corrected.setCorrectionDecl(ND);
4426           break;
4427         default:
4428           break;
4429         }
4430       }
4431       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4432         return Corrected;
4433       }
4434     }
4435   }
4436   return TypoCorrection();
4437 }
4438 
4439 /// ConvertArgumentsForCall - Converts the arguments specified in
4440 /// Args/NumArgs to the parameter types of the function FDecl with
4441 /// function prototype Proto. Call is the call expression itself, and
4442 /// Fn is the function expression. For a C++ member function, this
4443 /// routine does not attempt to convert the object argument. Returns
4444 /// true if the call is ill-formed.
4445 bool
4446 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4447                               FunctionDecl *FDecl,
4448                               const FunctionProtoType *Proto,
4449                               ArrayRef<Expr *> Args,
4450                               SourceLocation RParenLoc,
4451                               bool IsExecConfig) {
4452   // Bail out early if calling a builtin with custom typechecking.
4453   if (FDecl)
4454     if (unsigned ID = FDecl->getBuiltinID())
4455       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4456         return false;
4457 
4458   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4459   // assignment, to the types of the corresponding parameter, ...
4460   unsigned NumParams = Proto->getNumParams();
4461   bool Invalid = false;
4462   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4463   unsigned FnKind = Fn->getType()->isBlockPointerType()
4464                        ? 1 /* block */
4465                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4466                                        : 0 /* function */);
4467 
4468   // If too few arguments are available (and we don't have default
4469   // arguments for the remaining parameters), don't make the call.
4470   if (Args.size() < NumParams) {
4471     if (Args.size() < MinArgs) {
4472       TypoCorrection TC;
4473       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4474         unsigned diag_id =
4475             MinArgs == NumParams && !Proto->isVariadic()
4476                 ? diag::err_typecheck_call_too_few_args_suggest
4477                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4478         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4479                                         << static_cast<unsigned>(Args.size())
4480                                         << TC.getCorrectionRange());
4481       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4482         Diag(RParenLoc,
4483              MinArgs == NumParams && !Proto->isVariadic()
4484                  ? diag::err_typecheck_call_too_few_args_one
4485                  : diag::err_typecheck_call_too_few_args_at_least_one)
4486             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4487       else
4488         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4489                             ? diag::err_typecheck_call_too_few_args
4490                             : diag::err_typecheck_call_too_few_args_at_least)
4491             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4492             << Fn->getSourceRange();
4493 
4494       // Emit the location of the prototype.
4495       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4496         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4497           << FDecl;
4498 
4499       return true;
4500     }
4501     Call->setNumArgs(Context, NumParams);
4502   }
4503 
4504   // If too many are passed and not variadic, error on the extras and drop
4505   // them.
4506   if (Args.size() > NumParams) {
4507     if (!Proto->isVariadic()) {
4508       TypoCorrection TC;
4509       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4510         unsigned diag_id =
4511             MinArgs == NumParams && !Proto->isVariadic()
4512                 ? diag::err_typecheck_call_too_many_args_suggest
4513                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4514         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4515                                         << static_cast<unsigned>(Args.size())
4516                                         << TC.getCorrectionRange());
4517       } else if (NumParams == 1 && FDecl &&
4518                  FDecl->getParamDecl(0)->getDeclName())
4519         Diag(Args[NumParams]->getLocStart(),
4520              MinArgs == NumParams
4521                  ? diag::err_typecheck_call_too_many_args_one
4522                  : diag::err_typecheck_call_too_many_args_at_most_one)
4523             << FnKind << FDecl->getParamDecl(0)
4524             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4525             << SourceRange(Args[NumParams]->getLocStart(),
4526                            Args.back()->getLocEnd());
4527       else
4528         Diag(Args[NumParams]->getLocStart(),
4529              MinArgs == NumParams
4530                  ? diag::err_typecheck_call_too_many_args
4531                  : diag::err_typecheck_call_too_many_args_at_most)
4532             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4533             << Fn->getSourceRange()
4534             << SourceRange(Args[NumParams]->getLocStart(),
4535                            Args.back()->getLocEnd());
4536 
4537       // Emit the location of the prototype.
4538       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4539         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4540           << FDecl;
4541 
4542       // This deletes the extra arguments.
4543       Call->setNumArgs(Context, NumParams);
4544       return true;
4545     }
4546   }
4547   SmallVector<Expr *, 8> AllArgs;
4548   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4549 
4550   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4551                                    Proto, 0, Args, AllArgs, CallType);
4552   if (Invalid)
4553     return true;
4554   unsigned TotalNumArgs = AllArgs.size();
4555   for (unsigned i = 0; i < TotalNumArgs; ++i)
4556     Call->setArg(i, AllArgs[i]);
4557 
4558   return false;
4559 }
4560 
4561 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4562                                   const FunctionProtoType *Proto,
4563                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4564                                   SmallVectorImpl<Expr *> &AllArgs,
4565                                   VariadicCallType CallType, bool AllowExplicit,
4566                                   bool IsListInitialization) {
4567   unsigned NumParams = Proto->getNumParams();
4568   bool Invalid = false;
4569   unsigned ArgIx = 0;
4570   // Continue to check argument types (even if we have too few/many args).
4571   for (unsigned i = FirstParam; i < NumParams; i++) {
4572     QualType ProtoArgType = Proto->getParamType(i);
4573 
4574     Expr *Arg;
4575     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4576     if (ArgIx < Args.size()) {
4577       Arg = Args[ArgIx++];
4578 
4579       if (RequireCompleteType(Arg->getLocStart(),
4580                               ProtoArgType,
4581                               diag::err_call_incomplete_argument, Arg))
4582         return true;
4583 
4584       // Strip the unbridged-cast placeholder expression off, if applicable.
4585       bool CFAudited = false;
4586       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4587           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4588           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4589         Arg = stripARCUnbridgedCast(Arg);
4590       else if (getLangOpts().ObjCAutoRefCount &&
4591                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4592                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4593         CFAudited = true;
4594 
4595       InitializedEntity Entity =
4596           Param ? InitializedEntity::InitializeParameter(Context, Param,
4597                                                          ProtoArgType)
4598                 : InitializedEntity::InitializeParameter(
4599                       Context, ProtoArgType, Proto->isParamConsumed(i));
4600 
4601       // Remember that parameter belongs to a CF audited API.
4602       if (CFAudited)
4603         Entity.setParameterCFAudited();
4604 
4605       ExprResult ArgE = PerformCopyInitialization(
4606           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4607       if (ArgE.isInvalid())
4608         return true;
4609 
4610       Arg = ArgE.getAs<Expr>();
4611     } else {
4612       assert(Param && "can't use default arguments without a known callee");
4613 
4614       ExprResult ArgExpr =
4615         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4616       if (ArgExpr.isInvalid())
4617         return true;
4618 
4619       Arg = ArgExpr.getAs<Expr>();
4620     }
4621 
4622     // Check for array bounds violations for each argument to the call. This
4623     // check only triggers warnings when the argument isn't a more complex Expr
4624     // with its own checking, such as a BinaryOperator.
4625     CheckArrayAccess(Arg);
4626 
4627     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4628     CheckStaticArrayArgument(CallLoc, Param, Arg);
4629 
4630     AllArgs.push_back(Arg);
4631   }
4632 
4633   // If this is a variadic call, handle args passed through "...".
4634   if (CallType != VariadicDoesNotApply) {
4635     // Assume that extern "C" functions with variadic arguments that
4636     // return __unknown_anytype aren't *really* variadic.
4637     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4638         FDecl->isExternC()) {
4639       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4640         QualType paramType; // ignored
4641         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4642         Invalid |= arg.isInvalid();
4643         AllArgs.push_back(arg.get());
4644       }
4645 
4646     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4647     } else {
4648       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4649         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4650                                                           FDecl);
4651         Invalid |= Arg.isInvalid();
4652         AllArgs.push_back(Arg.get());
4653       }
4654     }
4655 
4656     // Check for array bounds violations.
4657     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4658       CheckArrayAccess(Args[i]);
4659   }
4660   return Invalid;
4661 }
4662 
4663 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4664   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4665   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4666     TL = DTL.getOriginalLoc();
4667   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4668     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4669       << ATL.getLocalSourceRange();
4670 }
4671 
4672 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4673 /// array parameter, check that it is non-null, and that if it is formed by
4674 /// array-to-pointer decay, the underlying array is sufficiently large.
4675 ///
4676 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4677 /// array type derivation, then for each call to the function, the value of the
4678 /// corresponding actual argument shall provide access to the first element of
4679 /// an array with at least as many elements as specified by the size expression.
4680 void
4681 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4682                                ParmVarDecl *Param,
4683                                const Expr *ArgExpr) {
4684   // Static array parameters are not supported in C++.
4685   if (!Param || getLangOpts().CPlusPlus)
4686     return;
4687 
4688   QualType OrigTy = Param->getOriginalType();
4689 
4690   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4691   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4692     return;
4693 
4694   if (ArgExpr->isNullPointerConstant(Context,
4695                                      Expr::NPC_NeverValueDependent)) {
4696     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4697     DiagnoseCalleeStaticArrayParam(*this, Param);
4698     return;
4699   }
4700 
4701   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4702   if (!CAT)
4703     return;
4704 
4705   const ConstantArrayType *ArgCAT =
4706     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4707   if (!ArgCAT)
4708     return;
4709 
4710   if (ArgCAT->getSize().ult(CAT->getSize())) {
4711     Diag(CallLoc, diag::warn_static_array_too_small)
4712       << ArgExpr->getSourceRange()
4713       << (unsigned) ArgCAT->getSize().getZExtValue()
4714       << (unsigned) CAT->getSize().getZExtValue();
4715     DiagnoseCalleeStaticArrayParam(*this, Param);
4716   }
4717 }
4718 
4719 /// Given a function expression of unknown-any type, try to rebuild it
4720 /// to have a function type.
4721 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4722 
4723 /// Is the given type a placeholder that we need to lower out
4724 /// immediately during argument processing?
4725 static bool isPlaceholderToRemoveAsArg(QualType type) {
4726   // Placeholders are never sugared.
4727   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4728   if (!placeholder) return false;
4729 
4730   switch (placeholder->getKind()) {
4731   // Ignore all the non-placeholder types.
4732 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4733 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4734 #include "clang/AST/BuiltinTypes.def"
4735     return false;
4736 
4737   // We cannot lower out overload sets; they might validly be resolved
4738   // by the call machinery.
4739   case BuiltinType::Overload:
4740     return false;
4741 
4742   // Unbridged casts in ARC can be handled in some call positions and
4743   // should be left in place.
4744   case BuiltinType::ARCUnbridgedCast:
4745     return false;
4746 
4747   // Pseudo-objects should be converted as soon as possible.
4748   case BuiltinType::PseudoObject:
4749     return true;
4750 
4751   // The debugger mode could theoretically but currently does not try
4752   // to resolve unknown-typed arguments based on known parameter types.
4753   case BuiltinType::UnknownAny:
4754     return true;
4755 
4756   // These are always invalid as call arguments and should be reported.
4757   case BuiltinType::BoundMember:
4758   case BuiltinType::BuiltinFn:
4759   case BuiltinType::OMPArraySection:
4760     return true;
4761 
4762   }
4763   llvm_unreachable("bad builtin type kind");
4764 }
4765 
4766 /// Check an argument list for placeholders that we won't try to
4767 /// handle later.
4768 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4769   // Apply this processing to all the arguments at once instead of
4770   // dying at the first failure.
4771   bool hasInvalid = false;
4772   for (size_t i = 0, e = args.size(); i != e; i++) {
4773     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4774       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4775       if (result.isInvalid()) hasInvalid = true;
4776       else args[i] = result.get();
4777     } else if (hasInvalid) {
4778       (void)S.CorrectDelayedTyposInExpr(args[i]);
4779     }
4780   }
4781   return hasInvalid;
4782 }
4783 
4784 /// If a builtin function has a pointer argument with no explicit address
4785 /// space, than it should be able to accept a pointer to any address
4786 /// space as input.  In order to do this, we need to replace the
4787 /// standard builtin declaration with one that uses the same address space
4788 /// as the call.
4789 ///
4790 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4791 ///                  it does not contain any pointer arguments without
4792 ///                  an address space qualifer.  Otherwise the rewritten
4793 ///                  FunctionDecl is returned.
4794 /// TODO: Handle pointer return types.
4795 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4796                                                 const FunctionDecl *FDecl,
4797                                                 MultiExprArg ArgExprs) {
4798 
4799   QualType DeclType = FDecl->getType();
4800   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4801 
4802   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4803       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4804     return nullptr;
4805 
4806   bool NeedsNewDecl = false;
4807   unsigned i = 0;
4808   SmallVector<QualType, 8> OverloadParams;
4809 
4810   for (QualType ParamType : FT->param_types()) {
4811 
4812     // Convert array arguments to pointer to simplify type lookup.
4813     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
4814     QualType ArgType = Arg->getType();
4815     if (!ParamType->isPointerType() ||
4816         ParamType.getQualifiers().hasAddressSpace() ||
4817         !ArgType->isPointerType() ||
4818         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
4819       OverloadParams.push_back(ParamType);
4820       continue;
4821     }
4822 
4823     NeedsNewDecl = true;
4824     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
4825 
4826     QualType PointeeType = ParamType->getPointeeType();
4827     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
4828     OverloadParams.push_back(Context.getPointerType(PointeeType));
4829   }
4830 
4831   if (!NeedsNewDecl)
4832     return nullptr;
4833 
4834   FunctionProtoType::ExtProtoInfo EPI;
4835   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
4836                                                 OverloadParams, EPI);
4837   DeclContext *Parent = Context.getTranslationUnitDecl();
4838   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
4839                                                     FDecl->getLocation(),
4840                                                     FDecl->getLocation(),
4841                                                     FDecl->getIdentifier(),
4842                                                     OverloadTy,
4843                                                     /*TInfo=*/nullptr,
4844                                                     SC_Extern, false,
4845                                                     /*hasPrototype=*/true);
4846   SmallVector<ParmVarDecl*, 16> Params;
4847   FT = cast<FunctionProtoType>(OverloadTy);
4848   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
4849     QualType ParamType = FT->getParamType(i);
4850     ParmVarDecl *Parm =
4851         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
4852                                 SourceLocation(), nullptr, ParamType,
4853                                 /*TInfo=*/nullptr, SC_None, nullptr);
4854     Parm->setScopeInfo(0, i);
4855     Params.push_back(Parm);
4856   }
4857   OverloadDecl->setParams(Params);
4858   return OverloadDecl;
4859 }
4860 
4861 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4862 /// This provides the location of the left/right parens and a list of comma
4863 /// locations.
4864 ExprResult
4865 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4866                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4867                     Expr *ExecConfig, bool IsExecConfig) {
4868   // Since this might be a postfix expression, get rid of ParenListExprs.
4869   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4870   if (Result.isInvalid()) return ExprError();
4871   Fn = Result.get();
4872 
4873   if (checkArgsForPlaceholders(*this, ArgExprs))
4874     return ExprError();
4875 
4876   if (getLangOpts().CPlusPlus) {
4877     // If this is a pseudo-destructor expression, build the call immediately.
4878     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4879       if (!ArgExprs.empty()) {
4880         // Pseudo-destructor calls should not have any arguments.
4881         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4882           << FixItHint::CreateRemoval(
4883                                     SourceRange(ArgExprs.front()->getLocStart(),
4884                                                 ArgExprs.back()->getLocEnd()));
4885       }
4886 
4887       return new (Context)
4888           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4889     }
4890     if (Fn->getType() == Context.PseudoObjectTy) {
4891       ExprResult result = CheckPlaceholderExpr(Fn);
4892       if (result.isInvalid()) return ExprError();
4893       Fn = result.get();
4894     }
4895 
4896     // Determine whether this is a dependent call inside a C++ template,
4897     // in which case we won't do any semantic analysis now.
4898     // FIXME: Will need to cache the results of name lookup (including ADL) in
4899     // Fn.
4900     bool Dependent = false;
4901     if (Fn->isTypeDependent())
4902       Dependent = true;
4903     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4904       Dependent = true;
4905 
4906     if (Dependent) {
4907       if (ExecConfig) {
4908         return new (Context) CUDAKernelCallExpr(
4909             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4910             Context.DependentTy, VK_RValue, RParenLoc);
4911       } else {
4912         return new (Context) CallExpr(
4913             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4914       }
4915     }
4916 
4917     // Determine whether this is a call to an object (C++ [over.call.object]).
4918     if (Fn->getType()->isRecordType())
4919       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4920                                           RParenLoc);
4921 
4922     if (Fn->getType() == Context.UnknownAnyTy) {
4923       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4924       if (result.isInvalid()) return ExprError();
4925       Fn = result.get();
4926     }
4927 
4928     if (Fn->getType() == Context.BoundMemberTy) {
4929       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4930     }
4931   }
4932 
4933   // Check for overloaded calls.  This can happen even in C due to extensions.
4934   if (Fn->getType() == Context.OverloadTy) {
4935     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4936 
4937     // We aren't supposed to apply this logic for if there's an '&' involved.
4938     if (!find.HasFormOfMemberPointer) {
4939       OverloadExpr *ovl = find.Expression;
4940       if (isa<UnresolvedLookupExpr>(ovl)) {
4941         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4942         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4943                                        RParenLoc, ExecConfig);
4944       } else {
4945         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4946                                          RParenLoc);
4947       }
4948     }
4949   }
4950 
4951   // If we're directly calling a function, get the appropriate declaration.
4952   if (Fn->getType() == Context.UnknownAnyTy) {
4953     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4954     if (result.isInvalid()) return ExprError();
4955     Fn = result.get();
4956   }
4957 
4958   Expr *NakedFn = Fn->IgnoreParens();
4959 
4960   NamedDecl *NDecl = nullptr;
4961   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4962     if (UnOp->getOpcode() == UO_AddrOf)
4963       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4964 
4965   if (isa<DeclRefExpr>(NakedFn)) {
4966     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4967 
4968     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
4969     if (FDecl && FDecl->getBuiltinID()) {
4970       // Rewrite the function decl for this builtin by replacing paramaters
4971       // with no explicit address space with the address space of the arguments
4972       // in ArgExprs.
4973       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
4974         NDecl = FDecl;
4975         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
4976                            SourceLocation(), FDecl, false,
4977                            SourceLocation(), FDecl->getType(),
4978                            Fn->getValueKind(), FDecl);
4979       }
4980     }
4981   } else if (isa<MemberExpr>(NakedFn))
4982     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4983 
4984   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4985     if (FD->hasAttr<EnableIfAttr>()) {
4986       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4987         Diag(Fn->getLocStart(),
4988              isa<CXXMethodDecl>(FD) ?
4989                  diag::err_ovl_no_viable_member_function_in_call :
4990                  diag::err_ovl_no_viable_function_in_call)
4991           << FD << FD->getSourceRange();
4992         Diag(FD->getLocation(),
4993              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4994             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4995       }
4996     }
4997   }
4998 
4999   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
5000                                ExecConfig, IsExecConfig);
5001 }
5002 
5003 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
5004 ///
5005 /// __builtin_astype( value, dst type )
5006 ///
5007 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
5008                                  SourceLocation BuiltinLoc,
5009                                  SourceLocation RParenLoc) {
5010   ExprValueKind VK = VK_RValue;
5011   ExprObjectKind OK = OK_Ordinary;
5012   QualType DstTy = GetTypeFromParser(ParsedDestTy);
5013   QualType SrcTy = E->getType();
5014   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
5015     return ExprError(Diag(BuiltinLoc,
5016                           diag::err_invalid_astype_of_different_size)
5017                      << DstTy
5018                      << SrcTy
5019                      << E->getSourceRange());
5020   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
5021 }
5022 
5023 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
5024 /// provided arguments.
5025 ///
5026 /// __builtin_convertvector( value, dst type )
5027 ///
5028 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
5029                                         SourceLocation BuiltinLoc,
5030                                         SourceLocation RParenLoc) {
5031   TypeSourceInfo *TInfo;
5032   GetTypeFromParser(ParsedDestTy, &TInfo);
5033   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5034 }
5035 
5036 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5037 /// i.e. an expression not of \p OverloadTy.  The expression should
5038 /// unary-convert to an expression of function-pointer or
5039 /// block-pointer type.
5040 ///
5041 /// \param NDecl the declaration being called, if available
5042 ExprResult
5043 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5044                             SourceLocation LParenLoc,
5045                             ArrayRef<Expr *> Args,
5046                             SourceLocation RParenLoc,
5047                             Expr *Config, bool IsExecConfig) {
5048   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5049   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5050 
5051   // Promote the function operand.
5052   // We special-case function promotion here because we only allow promoting
5053   // builtin functions to function pointers in the callee of a call.
5054   ExprResult Result;
5055   if (BuiltinID &&
5056       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5057     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5058                                CK_BuiltinFnToFnPtr).get();
5059   } else {
5060     Result = CallExprUnaryConversions(Fn);
5061   }
5062   if (Result.isInvalid())
5063     return ExprError();
5064   Fn = Result.get();
5065 
5066   // Make the call expr early, before semantic checks.  This guarantees cleanup
5067   // of arguments and function on error.
5068   CallExpr *TheCall;
5069   if (Config)
5070     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5071                                                cast<CallExpr>(Config), Args,
5072                                                Context.BoolTy, VK_RValue,
5073                                                RParenLoc);
5074   else
5075     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5076                                      VK_RValue, RParenLoc);
5077 
5078   if (!getLangOpts().CPlusPlus) {
5079     // C cannot always handle TypoExpr nodes in builtin calls and direct
5080     // function calls as their argument checking don't necessarily handle
5081     // dependent types properly, so make sure any TypoExprs have been
5082     // dealt with.
5083     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5084     if (!Result.isUsable()) return ExprError();
5085     TheCall = dyn_cast<CallExpr>(Result.get());
5086     if (!TheCall) return Result;
5087     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5088   }
5089 
5090   // Bail out early if calling a builtin with custom typechecking.
5091   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5092     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5093 
5094  retry:
5095   const FunctionType *FuncT;
5096   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5097     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5098     // have type pointer to function".
5099     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5100     if (!FuncT)
5101       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5102                          << Fn->getType() << Fn->getSourceRange());
5103   } else if (const BlockPointerType *BPT =
5104                Fn->getType()->getAs<BlockPointerType>()) {
5105     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5106   } else {
5107     // Handle calls to expressions of unknown-any type.
5108     if (Fn->getType() == Context.UnknownAnyTy) {
5109       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5110       if (rewrite.isInvalid()) return ExprError();
5111       Fn = rewrite.get();
5112       TheCall->setCallee(Fn);
5113       goto retry;
5114     }
5115 
5116     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5117       << Fn->getType() << Fn->getSourceRange());
5118   }
5119 
5120   if (getLangOpts().CUDA) {
5121     if (Config) {
5122       // CUDA: Kernel calls must be to global functions
5123       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5124         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5125             << FDecl->getName() << Fn->getSourceRange());
5126 
5127       // CUDA: Kernel function must have 'void' return type
5128       if (!FuncT->getReturnType()->isVoidType())
5129         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5130             << Fn->getType() << Fn->getSourceRange());
5131     } else {
5132       // CUDA: Calls to global functions must be configured
5133       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5134         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5135             << FDecl->getName() << Fn->getSourceRange());
5136     }
5137   }
5138 
5139   // Check for a valid return type
5140   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5141                           FDecl))
5142     return ExprError();
5143 
5144   // We know the result type of the call, set it.
5145   TheCall->setType(FuncT->getCallResultType(Context));
5146   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5147 
5148   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5149   if (Proto) {
5150     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5151                                 IsExecConfig))
5152       return ExprError();
5153   } else {
5154     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5155 
5156     if (FDecl) {
5157       // Check if we have too few/too many template arguments, based
5158       // on our knowledge of the function definition.
5159       const FunctionDecl *Def = nullptr;
5160       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5161         Proto = Def->getType()->getAs<FunctionProtoType>();
5162        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5163           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5164           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5165       }
5166 
5167       // If the function we're calling isn't a function prototype, but we have
5168       // a function prototype from a prior declaratiom, use that prototype.
5169       if (!FDecl->hasPrototype())
5170         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5171     }
5172 
5173     // Promote the arguments (C99 6.5.2.2p6).
5174     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5175       Expr *Arg = Args[i];
5176 
5177       if (Proto && i < Proto->getNumParams()) {
5178         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5179             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5180         ExprResult ArgE =
5181             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5182         if (ArgE.isInvalid())
5183           return true;
5184 
5185         Arg = ArgE.getAs<Expr>();
5186 
5187       } else {
5188         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5189 
5190         if (ArgE.isInvalid())
5191           return true;
5192 
5193         Arg = ArgE.getAs<Expr>();
5194       }
5195 
5196       if (RequireCompleteType(Arg->getLocStart(),
5197                               Arg->getType(),
5198                               diag::err_call_incomplete_argument, Arg))
5199         return ExprError();
5200 
5201       TheCall->setArg(i, Arg);
5202     }
5203   }
5204 
5205   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5206     if (!Method->isStatic())
5207       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5208         << Fn->getSourceRange());
5209 
5210   // Check for sentinels
5211   if (NDecl)
5212     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5213 
5214   // Do special checking on direct calls to functions.
5215   if (FDecl) {
5216     if (CheckFunctionCall(FDecl, TheCall, Proto))
5217       return ExprError();
5218 
5219     if (BuiltinID)
5220       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5221   } else if (NDecl) {
5222     if (CheckPointerCall(NDecl, TheCall, Proto))
5223       return ExprError();
5224   } else {
5225     if (CheckOtherCall(TheCall, Proto))
5226       return ExprError();
5227   }
5228 
5229   return MaybeBindToTemporary(TheCall);
5230 }
5231 
5232 ExprResult
5233 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5234                            SourceLocation RParenLoc, Expr *InitExpr) {
5235   assert(Ty && "ActOnCompoundLiteral(): missing type");
5236   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5237 
5238   TypeSourceInfo *TInfo;
5239   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5240   if (!TInfo)
5241     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5242 
5243   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5244 }
5245 
5246 ExprResult
5247 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5248                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5249   QualType literalType = TInfo->getType();
5250 
5251   if (literalType->isArrayType()) {
5252     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5253           diag::err_illegal_decl_array_incomplete_type,
5254           SourceRange(LParenLoc,
5255                       LiteralExpr->getSourceRange().getEnd())))
5256       return ExprError();
5257     if (literalType->isVariableArrayType())
5258       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5259         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5260   } else if (!literalType->isDependentType() &&
5261              RequireCompleteType(LParenLoc, literalType,
5262                diag::err_typecheck_decl_incomplete_type,
5263                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5264     return ExprError();
5265 
5266   InitializedEntity Entity
5267     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5268   InitializationKind Kind
5269     = InitializationKind::CreateCStyleCast(LParenLoc,
5270                                            SourceRange(LParenLoc, RParenLoc),
5271                                            /*InitList=*/true);
5272   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5273   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5274                                       &literalType);
5275   if (Result.isInvalid())
5276     return ExprError();
5277   LiteralExpr = Result.get();
5278 
5279   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5280   if (isFileScope &&
5281       !LiteralExpr->isTypeDependent() &&
5282       !LiteralExpr->isValueDependent() &&
5283       !literalType->isDependentType()) { // 6.5.2.5p3
5284     if (CheckForConstantInitializer(LiteralExpr, literalType))
5285       return ExprError();
5286   }
5287 
5288   // In C, compound literals are l-values for some reason.
5289   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5290 
5291   return MaybeBindToTemporary(
5292            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5293                                              VK, LiteralExpr, isFileScope));
5294 }
5295 
5296 ExprResult
5297 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5298                     SourceLocation RBraceLoc) {
5299   // Immediately handle non-overload placeholders.  Overloads can be
5300   // resolved contextually, but everything else here can't.
5301   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5302     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5303       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5304 
5305       // Ignore failures; dropping the entire initializer list because
5306       // of one failure would be terrible for indexing/etc.
5307       if (result.isInvalid()) continue;
5308 
5309       InitArgList[I] = result.get();
5310     }
5311   }
5312 
5313   // Semantic analysis for initializers is done by ActOnDeclarator() and
5314   // CheckInitializer() - it requires knowledge of the object being intialized.
5315 
5316   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5317                                                RBraceLoc);
5318   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5319   return E;
5320 }
5321 
5322 /// Do an explicit extend of the given block pointer if we're in ARC.
5323 void Sema::maybeExtendBlockObject(ExprResult &E) {
5324   assert(E.get()->getType()->isBlockPointerType());
5325   assert(E.get()->isRValue());
5326 
5327   // Only do this in an r-value context.
5328   if (!getLangOpts().ObjCAutoRefCount) return;
5329 
5330   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5331                                CK_ARCExtendBlockObject, E.get(),
5332                                /*base path*/ nullptr, VK_RValue);
5333   ExprNeedsCleanups = true;
5334 }
5335 
5336 /// Prepare a conversion of the given expression to an ObjC object
5337 /// pointer type.
5338 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5339   QualType type = E.get()->getType();
5340   if (type->isObjCObjectPointerType()) {
5341     return CK_BitCast;
5342   } else if (type->isBlockPointerType()) {
5343     maybeExtendBlockObject(E);
5344     return CK_BlockPointerToObjCPointerCast;
5345   } else {
5346     assert(type->isPointerType());
5347     return CK_CPointerToObjCPointerCast;
5348   }
5349 }
5350 
5351 /// Prepares for a scalar cast, performing all the necessary stages
5352 /// except the final cast and returning the kind required.
5353 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5354   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5355   // Also, callers should have filtered out the invalid cases with
5356   // pointers.  Everything else should be possible.
5357 
5358   QualType SrcTy = Src.get()->getType();
5359   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5360     return CK_NoOp;
5361 
5362   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5363   case Type::STK_MemberPointer:
5364     llvm_unreachable("member pointer type in C");
5365 
5366   case Type::STK_CPointer:
5367   case Type::STK_BlockPointer:
5368   case Type::STK_ObjCObjectPointer:
5369     switch (DestTy->getScalarTypeKind()) {
5370     case Type::STK_CPointer: {
5371       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5372       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5373       if (SrcAS != DestAS)
5374         return CK_AddressSpaceConversion;
5375       return CK_BitCast;
5376     }
5377     case Type::STK_BlockPointer:
5378       return (SrcKind == Type::STK_BlockPointer
5379                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5380     case Type::STK_ObjCObjectPointer:
5381       if (SrcKind == Type::STK_ObjCObjectPointer)
5382         return CK_BitCast;
5383       if (SrcKind == Type::STK_CPointer)
5384         return CK_CPointerToObjCPointerCast;
5385       maybeExtendBlockObject(Src);
5386       return CK_BlockPointerToObjCPointerCast;
5387     case Type::STK_Bool:
5388       return CK_PointerToBoolean;
5389     case Type::STK_Integral:
5390       return CK_PointerToIntegral;
5391     case Type::STK_Floating:
5392     case Type::STK_FloatingComplex:
5393     case Type::STK_IntegralComplex:
5394     case Type::STK_MemberPointer:
5395       llvm_unreachable("illegal cast from pointer");
5396     }
5397     llvm_unreachable("Should have returned before this");
5398 
5399   case Type::STK_Bool: // casting from bool is like casting from an integer
5400   case Type::STK_Integral:
5401     switch (DestTy->getScalarTypeKind()) {
5402     case Type::STK_CPointer:
5403     case Type::STK_ObjCObjectPointer:
5404     case Type::STK_BlockPointer:
5405       if (Src.get()->isNullPointerConstant(Context,
5406                                            Expr::NPC_ValueDependentIsNull))
5407         return CK_NullToPointer;
5408       return CK_IntegralToPointer;
5409     case Type::STK_Bool:
5410       return CK_IntegralToBoolean;
5411     case Type::STK_Integral:
5412       return CK_IntegralCast;
5413     case Type::STK_Floating:
5414       return CK_IntegralToFloating;
5415     case Type::STK_IntegralComplex:
5416       Src = ImpCastExprToType(Src.get(),
5417                       DestTy->castAs<ComplexType>()->getElementType(),
5418                       CK_IntegralCast);
5419       return CK_IntegralRealToComplex;
5420     case Type::STK_FloatingComplex:
5421       Src = ImpCastExprToType(Src.get(),
5422                       DestTy->castAs<ComplexType>()->getElementType(),
5423                       CK_IntegralToFloating);
5424       return CK_FloatingRealToComplex;
5425     case Type::STK_MemberPointer:
5426       llvm_unreachable("member pointer type in C");
5427     }
5428     llvm_unreachable("Should have returned before this");
5429 
5430   case Type::STK_Floating:
5431     switch (DestTy->getScalarTypeKind()) {
5432     case Type::STK_Floating:
5433       return CK_FloatingCast;
5434     case Type::STK_Bool:
5435       return CK_FloatingToBoolean;
5436     case Type::STK_Integral:
5437       return CK_FloatingToIntegral;
5438     case Type::STK_FloatingComplex:
5439       Src = ImpCastExprToType(Src.get(),
5440                               DestTy->castAs<ComplexType>()->getElementType(),
5441                               CK_FloatingCast);
5442       return CK_FloatingRealToComplex;
5443     case Type::STK_IntegralComplex:
5444       Src = ImpCastExprToType(Src.get(),
5445                               DestTy->castAs<ComplexType>()->getElementType(),
5446                               CK_FloatingToIntegral);
5447       return CK_IntegralRealToComplex;
5448     case Type::STK_CPointer:
5449     case Type::STK_ObjCObjectPointer:
5450     case Type::STK_BlockPointer:
5451       llvm_unreachable("valid float->pointer cast?");
5452     case Type::STK_MemberPointer:
5453       llvm_unreachable("member pointer type in C");
5454     }
5455     llvm_unreachable("Should have returned before this");
5456 
5457   case Type::STK_FloatingComplex:
5458     switch (DestTy->getScalarTypeKind()) {
5459     case Type::STK_FloatingComplex:
5460       return CK_FloatingComplexCast;
5461     case Type::STK_IntegralComplex:
5462       return CK_FloatingComplexToIntegralComplex;
5463     case Type::STK_Floating: {
5464       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5465       if (Context.hasSameType(ET, DestTy))
5466         return CK_FloatingComplexToReal;
5467       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5468       return CK_FloatingCast;
5469     }
5470     case Type::STK_Bool:
5471       return CK_FloatingComplexToBoolean;
5472     case Type::STK_Integral:
5473       Src = ImpCastExprToType(Src.get(),
5474                               SrcTy->castAs<ComplexType>()->getElementType(),
5475                               CK_FloatingComplexToReal);
5476       return CK_FloatingToIntegral;
5477     case Type::STK_CPointer:
5478     case Type::STK_ObjCObjectPointer:
5479     case Type::STK_BlockPointer:
5480       llvm_unreachable("valid complex float->pointer cast?");
5481     case Type::STK_MemberPointer:
5482       llvm_unreachable("member pointer type in C");
5483     }
5484     llvm_unreachable("Should have returned before this");
5485 
5486   case Type::STK_IntegralComplex:
5487     switch (DestTy->getScalarTypeKind()) {
5488     case Type::STK_FloatingComplex:
5489       return CK_IntegralComplexToFloatingComplex;
5490     case Type::STK_IntegralComplex:
5491       return CK_IntegralComplexCast;
5492     case Type::STK_Integral: {
5493       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5494       if (Context.hasSameType(ET, DestTy))
5495         return CK_IntegralComplexToReal;
5496       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5497       return CK_IntegralCast;
5498     }
5499     case Type::STK_Bool:
5500       return CK_IntegralComplexToBoolean;
5501     case Type::STK_Floating:
5502       Src = ImpCastExprToType(Src.get(),
5503                               SrcTy->castAs<ComplexType>()->getElementType(),
5504                               CK_IntegralComplexToReal);
5505       return CK_IntegralToFloating;
5506     case Type::STK_CPointer:
5507     case Type::STK_ObjCObjectPointer:
5508     case Type::STK_BlockPointer:
5509       llvm_unreachable("valid complex int->pointer cast?");
5510     case Type::STK_MemberPointer:
5511       llvm_unreachable("member pointer type in C");
5512     }
5513     llvm_unreachable("Should have returned before this");
5514   }
5515 
5516   llvm_unreachable("Unhandled scalar cast");
5517 }
5518 
5519 static bool breakDownVectorType(QualType type, uint64_t &len,
5520                                 QualType &eltType) {
5521   // Vectors are simple.
5522   if (const VectorType *vecType = type->getAs<VectorType>()) {
5523     len = vecType->getNumElements();
5524     eltType = vecType->getElementType();
5525     assert(eltType->isScalarType());
5526     return true;
5527   }
5528 
5529   // We allow lax conversion to and from non-vector types, but only if
5530   // they're real types (i.e. non-complex, non-pointer scalar types).
5531   if (!type->isRealType()) return false;
5532 
5533   len = 1;
5534   eltType = type;
5535   return true;
5536 }
5537 
5538 /// Are the two types lax-compatible vector types?  That is, given
5539 /// that one of them is a vector, do they have equal storage sizes,
5540 /// where the storage size is the number of elements times the element
5541 /// size?
5542 ///
5543 /// This will also return false if either of the types is neither a
5544 /// vector nor a real type.
5545 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5546   assert(destTy->isVectorType() || srcTy->isVectorType());
5547 
5548   // Disallow lax conversions between scalars and ExtVectors (these
5549   // conversions are allowed for other vector types because common headers
5550   // depend on them).  Most scalar OP ExtVector cases are handled by the
5551   // splat path anyway, which does what we want (convert, not bitcast).
5552   // What this rules out for ExtVectors is crazy things like char4*float.
5553   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5554   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5555 
5556   uint64_t srcLen, destLen;
5557   QualType srcEltTy, destEltTy;
5558   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5559   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5560 
5561   // ASTContext::getTypeSize will return the size rounded up to a
5562   // power of 2, so instead of using that, we need to use the raw
5563   // element size multiplied by the element count.
5564   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5565   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5566 
5567   return (srcLen * srcEltSize == destLen * destEltSize);
5568 }
5569 
5570 /// Is this a legal conversion between two types, one of which is
5571 /// known to be a vector type?
5572 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5573   assert(destTy->isVectorType() || srcTy->isVectorType());
5574 
5575   if (!Context.getLangOpts().LaxVectorConversions)
5576     return false;
5577   return areLaxCompatibleVectorTypes(srcTy, destTy);
5578 }
5579 
5580 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5581                            CastKind &Kind) {
5582   assert(VectorTy->isVectorType() && "Not a vector type!");
5583 
5584   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5585     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5586       return Diag(R.getBegin(),
5587                   Ty->isVectorType() ?
5588                   diag::err_invalid_conversion_between_vectors :
5589                   diag::err_invalid_conversion_between_vector_and_integer)
5590         << VectorTy << Ty << R;
5591   } else
5592     return Diag(R.getBegin(),
5593                 diag::err_invalid_conversion_between_vector_and_scalar)
5594       << VectorTy << Ty << R;
5595 
5596   Kind = CK_BitCast;
5597   return false;
5598 }
5599 
5600 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5601                                     Expr *CastExpr, CastKind &Kind) {
5602   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5603 
5604   QualType SrcTy = CastExpr->getType();
5605 
5606   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5607   // an ExtVectorType.
5608   // In OpenCL, casts between vectors of different types are not allowed.
5609   // (See OpenCL 6.2).
5610   if (SrcTy->isVectorType()) {
5611     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5612         || (getLangOpts().OpenCL &&
5613             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5614       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5615         << DestTy << SrcTy << R;
5616       return ExprError();
5617     }
5618     Kind = CK_BitCast;
5619     return CastExpr;
5620   }
5621 
5622   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5623   // conversion will take place first from scalar to elt type, and then
5624   // splat from elt type to vector.
5625   if (SrcTy->isPointerType())
5626     return Diag(R.getBegin(),
5627                 diag::err_invalid_conversion_between_vector_and_scalar)
5628       << DestTy << SrcTy << R;
5629 
5630   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5631   ExprResult CastExprRes = CastExpr;
5632   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5633   if (CastExprRes.isInvalid())
5634     return ExprError();
5635   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5636 
5637   Kind = CK_VectorSplat;
5638   return CastExpr;
5639 }
5640 
5641 ExprResult
5642 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5643                     Declarator &D, ParsedType &Ty,
5644                     SourceLocation RParenLoc, Expr *CastExpr) {
5645   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5646          "ActOnCastExpr(): missing type or expr");
5647 
5648   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5649   if (D.isInvalidType())
5650     return ExprError();
5651 
5652   if (getLangOpts().CPlusPlus) {
5653     // Check that there are no default arguments (C++ only).
5654     CheckExtraCXXDefaultArguments(D);
5655   } else {
5656     // Make sure any TypoExprs have been dealt with.
5657     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5658     if (!Res.isUsable())
5659       return ExprError();
5660     CastExpr = Res.get();
5661   }
5662 
5663   checkUnusedDeclAttributes(D);
5664 
5665   QualType castType = castTInfo->getType();
5666   Ty = CreateParsedType(castType, castTInfo);
5667 
5668   bool isVectorLiteral = false;
5669 
5670   // Check for an altivec or OpenCL literal,
5671   // i.e. all the elements are integer constants.
5672   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5673   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5674   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5675        && castType->isVectorType() && (PE || PLE)) {
5676     if (PLE && PLE->getNumExprs() == 0) {
5677       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5678       return ExprError();
5679     }
5680     if (PE || PLE->getNumExprs() == 1) {
5681       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5682       if (!E->getType()->isVectorType())
5683         isVectorLiteral = true;
5684     }
5685     else
5686       isVectorLiteral = true;
5687   }
5688 
5689   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5690   // then handle it as such.
5691   if (isVectorLiteral)
5692     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5693 
5694   // If the Expr being casted is a ParenListExpr, handle it specially.
5695   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5696   // sequence of BinOp comma operators.
5697   if (isa<ParenListExpr>(CastExpr)) {
5698     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5699     if (Result.isInvalid()) return ExprError();
5700     CastExpr = Result.get();
5701   }
5702 
5703   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5704       !getSourceManager().isInSystemMacro(LParenLoc))
5705     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5706 
5707   CheckTollFreeBridgeCast(castType, CastExpr);
5708 
5709   CheckObjCBridgeRelatedCast(castType, CastExpr);
5710 
5711   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5712 }
5713 
5714 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5715                                     SourceLocation RParenLoc, Expr *E,
5716                                     TypeSourceInfo *TInfo) {
5717   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5718          "Expected paren or paren list expression");
5719 
5720   Expr **exprs;
5721   unsigned numExprs;
5722   Expr *subExpr;
5723   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5724   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5725     LiteralLParenLoc = PE->getLParenLoc();
5726     LiteralRParenLoc = PE->getRParenLoc();
5727     exprs = PE->getExprs();
5728     numExprs = PE->getNumExprs();
5729   } else { // isa<ParenExpr> by assertion at function entrance
5730     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5731     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5732     subExpr = cast<ParenExpr>(E)->getSubExpr();
5733     exprs = &subExpr;
5734     numExprs = 1;
5735   }
5736 
5737   QualType Ty = TInfo->getType();
5738   assert(Ty->isVectorType() && "Expected vector type");
5739 
5740   SmallVector<Expr *, 8> initExprs;
5741   const VectorType *VTy = Ty->getAs<VectorType>();
5742   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5743 
5744   // '(...)' form of vector initialization in AltiVec: the number of
5745   // initializers must be one or must match the size of the vector.
5746   // If a single value is specified in the initializer then it will be
5747   // replicated to all the components of the vector
5748   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5749     // The number of initializers must be one or must match the size of the
5750     // vector. If a single value is specified in the initializer then it will
5751     // be replicated to all the components of the vector
5752     if (numExprs == 1) {
5753       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5754       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5755       if (Literal.isInvalid())
5756         return ExprError();
5757       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5758                                   PrepareScalarCast(Literal, ElemTy));
5759       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5760     }
5761     else if (numExprs < numElems) {
5762       Diag(E->getExprLoc(),
5763            diag::err_incorrect_number_of_vector_initializers);
5764       return ExprError();
5765     }
5766     else
5767       initExprs.append(exprs, exprs + numExprs);
5768   }
5769   else {
5770     // For OpenCL, when the number of initializers is a single value,
5771     // it will be replicated to all components of the vector.
5772     if (getLangOpts().OpenCL &&
5773         VTy->getVectorKind() == VectorType::GenericVector &&
5774         numExprs == 1) {
5775         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5776         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5777         if (Literal.isInvalid())
5778           return ExprError();
5779         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5780                                     PrepareScalarCast(Literal, ElemTy));
5781         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5782     }
5783 
5784     initExprs.append(exprs, exprs + numExprs);
5785   }
5786   // FIXME: This means that pretty-printing the final AST will produce curly
5787   // braces instead of the original commas.
5788   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5789                                                    initExprs, LiteralRParenLoc);
5790   initE->setType(Ty);
5791   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5792 }
5793 
5794 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5795 /// the ParenListExpr into a sequence of comma binary operators.
5796 ExprResult
5797 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5798   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5799   if (!E)
5800     return OrigExpr;
5801 
5802   ExprResult Result(E->getExpr(0));
5803 
5804   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5805     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5806                         E->getExpr(i));
5807 
5808   if (Result.isInvalid()) return ExprError();
5809 
5810   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5811 }
5812 
5813 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5814                                     SourceLocation R,
5815                                     MultiExprArg Val) {
5816   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5817   return expr;
5818 }
5819 
5820 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5821 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5822 /// emitted.
5823 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5824                                       SourceLocation QuestionLoc) {
5825   Expr *NullExpr = LHSExpr;
5826   Expr *NonPointerExpr = RHSExpr;
5827   Expr::NullPointerConstantKind NullKind =
5828       NullExpr->isNullPointerConstant(Context,
5829                                       Expr::NPC_ValueDependentIsNotNull);
5830 
5831   if (NullKind == Expr::NPCK_NotNull) {
5832     NullExpr = RHSExpr;
5833     NonPointerExpr = LHSExpr;
5834     NullKind =
5835         NullExpr->isNullPointerConstant(Context,
5836                                         Expr::NPC_ValueDependentIsNotNull);
5837   }
5838 
5839   if (NullKind == Expr::NPCK_NotNull)
5840     return false;
5841 
5842   if (NullKind == Expr::NPCK_ZeroExpression)
5843     return false;
5844 
5845   if (NullKind == Expr::NPCK_ZeroLiteral) {
5846     // In this case, check to make sure that we got here from a "NULL"
5847     // string in the source code.
5848     NullExpr = NullExpr->IgnoreParenImpCasts();
5849     SourceLocation loc = NullExpr->getExprLoc();
5850     if (!findMacroSpelling(loc, "NULL"))
5851       return false;
5852   }
5853 
5854   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5855   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5856       << NonPointerExpr->getType() << DiagType
5857       << NonPointerExpr->getSourceRange();
5858   return true;
5859 }
5860 
5861 /// \brief Return false if the condition expression is valid, true otherwise.
5862 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
5863   QualType CondTy = Cond->getType();
5864 
5865   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
5866   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
5867     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
5868       << CondTy << Cond->getSourceRange();
5869     return true;
5870   }
5871 
5872   // C99 6.5.15p2
5873   if (CondTy->isScalarType()) return false;
5874 
5875   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
5876     << CondTy << Cond->getSourceRange();
5877   return true;
5878 }
5879 
5880 /// \brief Handle when one or both operands are void type.
5881 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5882                                          ExprResult &RHS) {
5883     Expr *LHSExpr = LHS.get();
5884     Expr *RHSExpr = RHS.get();
5885 
5886     if (!LHSExpr->getType()->isVoidType())
5887       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5888         << RHSExpr->getSourceRange();
5889     if (!RHSExpr->getType()->isVoidType())
5890       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5891         << LHSExpr->getSourceRange();
5892     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5893     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5894     return S.Context.VoidTy;
5895 }
5896 
5897 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5898 /// true otherwise.
5899 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5900                                         QualType PointerTy) {
5901   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5902       !NullExpr.get()->isNullPointerConstant(S.Context,
5903                                             Expr::NPC_ValueDependentIsNull))
5904     return true;
5905 
5906   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5907   return false;
5908 }
5909 
5910 /// \brief Checks compatibility between two pointers and return the resulting
5911 /// type.
5912 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5913                                                      ExprResult &RHS,
5914                                                      SourceLocation Loc) {
5915   QualType LHSTy = LHS.get()->getType();
5916   QualType RHSTy = RHS.get()->getType();
5917 
5918   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5919     // Two identical pointers types are always compatible.
5920     return LHSTy;
5921   }
5922 
5923   QualType lhptee, rhptee;
5924 
5925   // Get the pointee types.
5926   bool IsBlockPointer = false;
5927   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5928     lhptee = LHSBTy->getPointeeType();
5929     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5930     IsBlockPointer = true;
5931   } else {
5932     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5933     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5934   }
5935 
5936   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5937   // differently qualified versions of compatible types, the result type is
5938   // a pointer to an appropriately qualified version of the composite
5939   // type.
5940 
5941   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5942   // clause doesn't make sense for our extensions. E.g. address space 2 should
5943   // be incompatible with address space 3: they may live on different devices or
5944   // anything.
5945   Qualifiers lhQual = lhptee.getQualifiers();
5946   Qualifiers rhQual = rhptee.getQualifiers();
5947 
5948   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5949   lhQual.removeCVRQualifiers();
5950   rhQual.removeCVRQualifiers();
5951 
5952   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5953   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5954 
5955   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5956 
5957   if (CompositeTy.isNull()) {
5958     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5959       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5960       << RHS.get()->getSourceRange();
5961     // In this situation, we assume void* type. No especially good
5962     // reason, but this is what gcc does, and we do have to pick
5963     // to get a consistent AST.
5964     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5965     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5966     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5967     return incompatTy;
5968   }
5969 
5970   // The pointer types are compatible.
5971   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5972   if (IsBlockPointer)
5973     ResultTy = S.Context.getBlockPointerType(ResultTy);
5974   else
5975     ResultTy = S.Context.getPointerType(ResultTy);
5976 
5977   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5978   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5979   return ResultTy;
5980 }
5981 
5982 /// \brief Return the resulting type when the operands are both block pointers.
5983 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5984                                                           ExprResult &LHS,
5985                                                           ExprResult &RHS,
5986                                                           SourceLocation Loc) {
5987   QualType LHSTy = LHS.get()->getType();
5988   QualType RHSTy = RHS.get()->getType();
5989 
5990   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5991     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5992       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5993       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5994       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5995       return destType;
5996     }
5997     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5998       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5999       << RHS.get()->getSourceRange();
6000     return QualType();
6001   }
6002 
6003   // We have 2 block pointer types.
6004   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6005 }
6006 
6007 /// \brief Return the resulting type when the operands are both pointers.
6008 static QualType
6009 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
6010                                             ExprResult &RHS,
6011                                             SourceLocation Loc) {
6012   // get the pointer types
6013   QualType LHSTy = LHS.get()->getType();
6014   QualType RHSTy = RHS.get()->getType();
6015 
6016   // get the "pointed to" types
6017   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6018   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6019 
6020   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
6021   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
6022     // Figure out necessary qualifiers (C99 6.5.15p6)
6023     QualType destPointee
6024       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6025     QualType destType = S.Context.getPointerType(destPointee);
6026     // Add qualifiers if necessary.
6027     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6028     // Promote to void*.
6029     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6030     return destType;
6031   }
6032   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
6033     QualType destPointee
6034       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6035     QualType destType = S.Context.getPointerType(destPointee);
6036     // Add qualifiers if necessary.
6037     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6038     // Promote to void*.
6039     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6040     return destType;
6041   }
6042 
6043   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6044 }
6045 
6046 /// \brief Return false if the first expression is not an integer and the second
6047 /// expression is not a pointer, true otherwise.
6048 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6049                                         Expr* PointerExpr, SourceLocation Loc,
6050                                         bool IsIntFirstExpr) {
6051   if (!PointerExpr->getType()->isPointerType() ||
6052       !Int.get()->getType()->isIntegerType())
6053     return false;
6054 
6055   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6056   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6057 
6058   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6059     << Expr1->getType() << Expr2->getType()
6060     << Expr1->getSourceRange() << Expr2->getSourceRange();
6061   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6062                             CK_IntegralToPointer);
6063   return true;
6064 }
6065 
6066 /// \brief Simple conversion between integer and floating point types.
6067 ///
6068 /// Used when handling the OpenCL conditional operator where the
6069 /// condition is a vector while the other operands are scalar.
6070 ///
6071 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6072 /// types are either integer or floating type. Between the two
6073 /// operands, the type with the higher rank is defined as the "result
6074 /// type". The other operand needs to be promoted to the same type. No
6075 /// other type promotion is allowed. We cannot use
6076 /// UsualArithmeticConversions() for this purpose, since it always
6077 /// promotes promotable types.
6078 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6079                                             ExprResult &RHS,
6080                                             SourceLocation QuestionLoc) {
6081   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6082   if (LHS.isInvalid())
6083     return QualType();
6084   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6085   if (RHS.isInvalid())
6086     return QualType();
6087 
6088   // For conversion purposes, we ignore any qualifiers.
6089   // For example, "const float" and "float" are equivalent.
6090   QualType LHSType =
6091     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6092   QualType RHSType =
6093     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6094 
6095   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6096     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6097       << LHSType << LHS.get()->getSourceRange();
6098     return QualType();
6099   }
6100 
6101   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6102     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6103       << RHSType << RHS.get()->getSourceRange();
6104     return QualType();
6105   }
6106 
6107   // If both types are identical, no conversion is needed.
6108   if (LHSType == RHSType)
6109     return LHSType;
6110 
6111   // Now handle "real" floating types (i.e. float, double, long double).
6112   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6113     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6114                                  /*IsCompAssign = */ false);
6115 
6116   // Finally, we have two differing integer types.
6117   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6118   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6119 }
6120 
6121 /// \brief Convert scalar operands to a vector that matches the
6122 ///        condition in length.
6123 ///
6124 /// Used when handling the OpenCL conditional operator where the
6125 /// condition is a vector while the other operands are scalar.
6126 ///
6127 /// We first compute the "result type" for the scalar operands
6128 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6129 /// into a vector of that type where the length matches the condition
6130 /// vector type. s6.11.6 requires that the element types of the result
6131 /// and the condition must have the same number of bits.
6132 static QualType
6133 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6134                               QualType CondTy, SourceLocation QuestionLoc) {
6135   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6136   if (ResTy.isNull()) return QualType();
6137 
6138   const VectorType *CV = CondTy->getAs<VectorType>();
6139   assert(CV);
6140 
6141   // Determine the vector result type
6142   unsigned NumElements = CV->getNumElements();
6143   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6144 
6145   // Ensure that all types have the same number of bits
6146   if (S.Context.getTypeSize(CV->getElementType())
6147       != S.Context.getTypeSize(ResTy)) {
6148     // Since VectorTy is created internally, it does not pretty print
6149     // with an OpenCL name. Instead, we just print a description.
6150     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6151     SmallString<64> Str;
6152     llvm::raw_svector_ostream OS(Str);
6153     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6154     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6155       << CondTy << OS.str();
6156     return QualType();
6157   }
6158 
6159   // Convert operands to the vector result type
6160   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6161   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6162 
6163   return VectorTy;
6164 }
6165 
6166 /// \brief Return false if this is a valid OpenCL condition vector
6167 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6168                                        SourceLocation QuestionLoc) {
6169   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6170   // integral type.
6171   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6172   assert(CondTy);
6173   QualType EleTy = CondTy->getElementType();
6174   if (EleTy->isIntegerType()) return false;
6175 
6176   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6177     << Cond->getType() << Cond->getSourceRange();
6178   return true;
6179 }
6180 
6181 /// \brief Return false if the vector condition type and the vector
6182 ///        result type are compatible.
6183 ///
6184 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6185 /// number of elements, and their element types have the same number
6186 /// of bits.
6187 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6188                               SourceLocation QuestionLoc) {
6189   const VectorType *CV = CondTy->getAs<VectorType>();
6190   const VectorType *RV = VecResTy->getAs<VectorType>();
6191   assert(CV && RV);
6192 
6193   if (CV->getNumElements() != RV->getNumElements()) {
6194     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6195       << CondTy << VecResTy;
6196     return true;
6197   }
6198 
6199   QualType CVE = CV->getElementType();
6200   QualType RVE = RV->getElementType();
6201 
6202   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6203     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6204       << CondTy << VecResTy;
6205     return true;
6206   }
6207 
6208   return false;
6209 }
6210 
6211 /// \brief Return the resulting type for the conditional operator in
6212 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6213 ///        s6.3.i) when the condition is a vector type.
6214 static QualType
6215 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6216                              ExprResult &LHS, ExprResult &RHS,
6217                              SourceLocation QuestionLoc) {
6218   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6219   if (Cond.isInvalid())
6220     return QualType();
6221   QualType CondTy = Cond.get()->getType();
6222 
6223   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6224     return QualType();
6225 
6226   // If either operand is a vector then find the vector type of the
6227   // result as specified in OpenCL v1.1 s6.3.i.
6228   if (LHS.get()->getType()->isVectorType() ||
6229       RHS.get()->getType()->isVectorType()) {
6230     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6231                                               /*isCompAssign*/false,
6232                                               /*AllowBothBool*/true,
6233                                               /*AllowBoolConversions*/false);
6234     if (VecResTy.isNull()) return QualType();
6235     // The result type must match the condition type as specified in
6236     // OpenCL v1.1 s6.11.6.
6237     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6238       return QualType();
6239     return VecResTy;
6240   }
6241 
6242   // Both operands are scalar.
6243   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6244 }
6245 
6246 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6247 /// In that case, LHS = cond.
6248 /// C99 6.5.15
6249 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6250                                         ExprResult &RHS, ExprValueKind &VK,
6251                                         ExprObjectKind &OK,
6252                                         SourceLocation QuestionLoc) {
6253 
6254   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6255   if (!LHSResult.isUsable()) return QualType();
6256   LHS = LHSResult;
6257 
6258   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6259   if (!RHSResult.isUsable()) return QualType();
6260   RHS = RHSResult;
6261 
6262   // C++ is sufficiently different to merit its own checker.
6263   if (getLangOpts().CPlusPlus)
6264     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6265 
6266   VK = VK_RValue;
6267   OK = OK_Ordinary;
6268 
6269   // The OpenCL operator with a vector condition is sufficiently
6270   // different to merit its own checker.
6271   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6272     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6273 
6274   // First, check the condition.
6275   Cond = UsualUnaryConversions(Cond.get());
6276   if (Cond.isInvalid())
6277     return QualType();
6278   if (checkCondition(*this, Cond.get(), QuestionLoc))
6279     return QualType();
6280 
6281   // Now check the two expressions.
6282   if (LHS.get()->getType()->isVectorType() ||
6283       RHS.get()->getType()->isVectorType())
6284     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6285                                /*AllowBothBool*/true,
6286                                /*AllowBoolConversions*/false);
6287 
6288   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6289   if (LHS.isInvalid() || RHS.isInvalid())
6290     return QualType();
6291 
6292   QualType LHSTy = LHS.get()->getType();
6293   QualType RHSTy = RHS.get()->getType();
6294 
6295   // If both operands have arithmetic type, do the usual arithmetic conversions
6296   // to find a common type: C99 6.5.15p3,5.
6297   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6298     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6299     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6300 
6301     return ResTy;
6302   }
6303 
6304   // If both operands are the same structure or union type, the result is that
6305   // type.
6306   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6307     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6308       if (LHSRT->getDecl() == RHSRT->getDecl())
6309         // "If both the operands have structure or union type, the result has
6310         // that type."  This implies that CV qualifiers are dropped.
6311         return LHSTy.getUnqualifiedType();
6312     // FIXME: Type of conditional expression must be complete in C mode.
6313   }
6314 
6315   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6316   // The following || allows only one side to be void (a GCC-ism).
6317   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6318     return checkConditionalVoidType(*this, LHS, RHS);
6319   }
6320 
6321   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6322   // the type of the other operand."
6323   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6324   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6325 
6326   // All objective-c pointer type analysis is done here.
6327   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6328                                                         QuestionLoc);
6329   if (LHS.isInvalid() || RHS.isInvalid())
6330     return QualType();
6331   if (!compositeType.isNull())
6332     return compositeType;
6333 
6334 
6335   // Handle block pointer types.
6336   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6337     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6338                                                      QuestionLoc);
6339 
6340   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6341   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6342     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6343                                                        QuestionLoc);
6344 
6345   // GCC compatibility: soften pointer/integer mismatch.  Note that
6346   // null pointers have been filtered out by this point.
6347   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6348       /*isIntFirstExpr=*/true))
6349     return RHSTy;
6350   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6351       /*isIntFirstExpr=*/false))
6352     return LHSTy;
6353 
6354   // Emit a better diagnostic if one of the expressions is a null pointer
6355   // constant and the other is not a pointer type. In this case, the user most
6356   // likely forgot to take the address of the other expression.
6357   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6358     return QualType();
6359 
6360   // Otherwise, the operands are not compatible.
6361   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6362     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6363     << RHS.get()->getSourceRange();
6364   return QualType();
6365 }
6366 
6367 /// FindCompositeObjCPointerType - Helper method to find composite type of
6368 /// two objective-c pointer types of the two input expressions.
6369 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6370                                             SourceLocation QuestionLoc) {
6371   QualType LHSTy = LHS.get()->getType();
6372   QualType RHSTy = RHS.get()->getType();
6373 
6374   // Handle things like Class and struct objc_class*.  Here we case the result
6375   // to the pseudo-builtin, because that will be implicitly cast back to the
6376   // redefinition type if an attempt is made to access its fields.
6377   if (LHSTy->isObjCClassType() &&
6378       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6379     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6380     return LHSTy;
6381   }
6382   if (RHSTy->isObjCClassType() &&
6383       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6384     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6385     return RHSTy;
6386   }
6387   // And the same for struct objc_object* / id
6388   if (LHSTy->isObjCIdType() &&
6389       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6390     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6391     return LHSTy;
6392   }
6393   if (RHSTy->isObjCIdType() &&
6394       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6395     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6396     return RHSTy;
6397   }
6398   // And the same for struct objc_selector* / SEL
6399   if (Context.isObjCSelType(LHSTy) &&
6400       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6401     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6402     return LHSTy;
6403   }
6404   if (Context.isObjCSelType(RHSTy) &&
6405       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6406     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6407     return RHSTy;
6408   }
6409   // Check constraints for Objective-C object pointers types.
6410   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6411 
6412     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6413       // Two identical object pointer types are always compatible.
6414       return LHSTy;
6415     }
6416     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6417     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6418     QualType compositeType = LHSTy;
6419 
6420     // If both operands are interfaces and either operand can be
6421     // assigned to the other, use that type as the composite
6422     // type. This allows
6423     //   xxx ? (A*) a : (B*) b
6424     // where B is a subclass of A.
6425     //
6426     // Additionally, as for assignment, if either type is 'id'
6427     // allow silent coercion. Finally, if the types are
6428     // incompatible then make sure to use 'id' as the composite
6429     // type so the result is acceptable for sending messages to.
6430 
6431     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6432     // It could return the composite type.
6433     if (!(compositeType =
6434           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6435       // Nothing more to do.
6436     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6437       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6438     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6439       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6440     } else if ((LHSTy->isObjCQualifiedIdType() ||
6441                 RHSTy->isObjCQualifiedIdType()) &&
6442                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6443       // Need to handle "id<xx>" explicitly.
6444       // GCC allows qualified id and any Objective-C type to devolve to
6445       // id. Currently localizing to here until clear this should be
6446       // part of ObjCQualifiedIdTypesAreCompatible.
6447       compositeType = Context.getObjCIdType();
6448     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6449       compositeType = Context.getObjCIdType();
6450     } else {
6451       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6452       << LHSTy << RHSTy
6453       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6454       QualType incompatTy = Context.getObjCIdType();
6455       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6456       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6457       return incompatTy;
6458     }
6459     // The object pointer types are compatible.
6460     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6461     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6462     return compositeType;
6463   }
6464   // Check Objective-C object pointer types and 'void *'
6465   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6466     if (getLangOpts().ObjCAutoRefCount) {
6467       // ARC forbids the implicit conversion of object pointers to 'void *',
6468       // so these types are not compatible.
6469       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6470           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6471       LHS = RHS = true;
6472       return QualType();
6473     }
6474     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6475     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6476     QualType destPointee
6477     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6478     QualType destType = Context.getPointerType(destPointee);
6479     // Add qualifiers if necessary.
6480     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6481     // Promote to void*.
6482     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6483     return destType;
6484   }
6485   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6486     if (getLangOpts().ObjCAutoRefCount) {
6487       // ARC forbids the implicit conversion of object pointers to 'void *',
6488       // so these types are not compatible.
6489       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6490           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6491       LHS = RHS = true;
6492       return QualType();
6493     }
6494     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6495     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6496     QualType destPointee
6497     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6498     QualType destType = Context.getPointerType(destPointee);
6499     // Add qualifiers if necessary.
6500     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6501     // Promote to void*.
6502     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6503     return destType;
6504   }
6505   return QualType();
6506 }
6507 
6508 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6509 /// ParenRange in parentheses.
6510 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6511                                const PartialDiagnostic &Note,
6512                                SourceRange ParenRange) {
6513   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6514   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6515       EndLoc.isValid()) {
6516     Self.Diag(Loc, Note)
6517       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6518       << FixItHint::CreateInsertion(EndLoc, ")");
6519   } else {
6520     // We can't display the parentheses, so just show the bare note.
6521     Self.Diag(Loc, Note) << ParenRange;
6522   }
6523 }
6524 
6525 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6526   return Opc >= BO_Mul && Opc <= BO_Shr;
6527 }
6528 
6529 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6530 /// expression, either using a built-in or overloaded operator,
6531 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6532 /// expression.
6533 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6534                                    Expr **RHSExprs) {
6535   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6536   E = E->IgnoreImpCasts();
6537   E = E->IgnoreConversionOperator();
6538   E = E->IgnoreImpCasts();
6539 
6540   // Built-in binary operator.
6541   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6542     if (IsArithmeticOp(OP->getOpcode())) {
6543       *Opcode = OP->getOpcode();
6544       *RHSExprs = OP->getRHS();
6545       return true;
6546     }
6547   }
6548 
6549   // Overloaded operator.
6550   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6551     if (Call->getNumArgs() != 2)
6552       return false;
6553 
6554     // Make sure this is really a binary operator that is safe to pass into
6555     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6556     OverloadedOperatorKind OO = Call->getOperator();
6557     if (OO < OO_Plus || OO > OO_Arrow ||
6558         OO == OO_PlusPlus || OO == OO_MinusMinus)
6559       return false;
6560 
6561     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6562     if (IsArithmeticOp(OpKind)) {
6563       *Opcode = OpKind;
6564       *RHSExprs = Call->getArg(1);
6565       return true;
6566     }
6567   }
6568 
6569   return false;
6570 }
6571 
6572 static bool IsLogicOp(BinaryOperatorKind Opc) {
6573   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6574 }
6575 
6576 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6577 /// or is a logical expression such as (x==y) which has int type, but is
6578 /// commonly interpreted as boolean.
6579 static bool ExprLooksBoolean(Expr *E) {
6580   E = E->IgnoreParenImpCasts();
6581 
6582   if (E->getType()->isBooleanType())
6583     return true;
6584   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6585     return IsLogicOp(OP->getOpcode());
6586   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6587     return OP->getOpcode() == UO_LNot;
6588   if (E->getType()->isPointerType())
6589     return true;
6590 
6591   return false;
6592 }
6593 
6594 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6595 /// and binary operator are mixed in a way that suggests the programmer assumed
6596 /// the conditional operator has higher precedence, for example:
6597 /// "int x = a + someBinaryCondition ? 1 : 2".
6598 static void DiagnoseConditionalPrecedence(Sema &Self,
6599                                           SourceLocation OpLoc,
6600                                           Expr *Condition,
6601                                           Expr *LHSExpr,
6602                                           Expr *RHSExpr) {
6603   BinaryOperatorKind CondOpcode;
6604   Expr *CondRHS;
6605 
6606   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6607     return;
6608   if (!ExprLooksBoolean(CondRHS))
6609     return;
6610 
6611   // The condition is an arithmetic binary expression, with a right-
6612   // hand side that looks boolean, so warn.
6613 
6614   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6615       << Condition->getSourceRange()
6616       << BinaryOperator::getOpcodeStr(CondOpcode);
6617 
6618   SuggestParentheses(Self, OpLoc,
6619     Self.PDiag(diag::note_precedence_silence)
6620       << BinaryOperator::getOpcodeStr(CondOpcode),
6621     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6622 
6623   SuggestParentheses(Self, OpLoc,
6624     Self.PDiag(diag::note_precedence_conditional_first),
6625     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6626 }
6627 
6628 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6629 /// in the case of a the GNU conditional expr extension.
6630 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6631                                     SourceLocation ColonLoc,
6632                                     Expr *CondExpr, Expr *LHSExpr,
6633                                     Expr *RHSExpr) {
6634   if (!getLangOpts().CPlusPlus) {
6635     // C cannot handle TypoExpr nodes in the condition because it
6636     // doesn't handle dependent types properly, so make sure any TypoExprs have
6637     // been dealt with before checking the operands.
6638     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6639     if (!CondResult.isUsable()) return ExprError();
6640     CondExpr = CondResult.get();
6641   }
6642 
6643   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6644   // was the condition.
6645   OpaqueValueExpr *opaqueValue = nullptr;
6646   Expr *commonExpr = nullptr;
6647   if (!LHSExpr) {
6648     commonExpr = CondExpr;
6649     // Lower out placeholder types first.  This is important so that we don't
6650     // try to capture a placeholder. This happens in few cases in C++; such
6651     // as Objective-C++'s dictionary subscripting syntax.
6652     if (commonExpr->hasPlaceholderType()) {
6653       ExprResult result = CheckPlaceholderExpr(commonExpr);
6654       if (!result.isUsable()) return ExprError();
6655       commonExpr = result.get();
6656     }
6657     // We usually want to apply unary conversions *before* saving, except
6658     // in the special case of a C++ l-value conditional.
6659     if (!(getLangOpts().CPlusPlus
6660           && !commonExpr->isTypeDependent()
6661           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6662           && commonExpr->isGLValue()
6663           && commonExpr->isOrdinaryOrBitFieldObject()
6664           && RHSExpr->isOrdinaryOrBitFieldObject()
6665           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6666       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6667       if (commonRes.isInvalid())
6668         return ExprError();
6669       commonExpr = commonRes.get();
6670     }
6671 
6672     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6673                                                 commonExpr->getType(),
6674                                                 commonExpr->getValueKind(),
6675                                                 commonExpr->getObjectKind(),
6676                                                 commonExpr);
6677     LHSExpr = CondExpr = opaqueValue;
6678   }
6679 
6680   ExprValueKind VK = VK_RValue;
6681   ExprObjectKind OK = OK_Ordinary;
6682   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6683   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6684                                              VK, OK, QuestionLoc);
6685   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6686       RHS.isInvalid())
6687     return ExprError();
6688 
6689   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6690                                 RHS.get());
6691 
6692   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
6693 
6694   if (!commonExpr)
6695     return new (Context)
6696         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6697                             RHS.get(), result, VK, OK);
6698 
6699   return new (Context) BinaryConditionalOperator(
6700       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6701       ColonLoc, result, VK, OK);
6702 }
6703 
6704 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6705 // being closely modeled after the C99 spec:-). The odd characteristic of this
6706 // routine is it effectively iqnores the qualifiers on the top level pointee.
6707 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6708 // FIXME: add a couple examples in this comment.
6709 static Sema::AssignConvertType
6710 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6711   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6712   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6713 
6714   // get the "pointed to" type (ignoring qualifiers at the top level)
6715   const Type *lhptee, *rhptee;
6716   Qualifiers lhq, rhq;
6717   std::tie(lhptee, lhq) =
6718       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6719   std::tie(rhptee, rhq) =
6720       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6721 
6722   Sema::AssignConvertType ConvTy = Sema::Compatible;
6723 
6724   // C99 6.5.16.1p1: This following citation is common to constraints
6725   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6726   // qualifiers of the type *pointed to* by the right;
6727 
6728   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6729   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6730       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6731     // Ignore lifetime for further calculation.
6732     lhq.removeObjCLifetime();
6733     rhq.removeObjCLifetime();
6734   }
6735 
6736   if (!lhq.compatiblyIncludes(rhq)) {
6737     // Treat address-space mismatches as fatal.  TODO: address subspaces
6738     if (!lhq.isAddressSpaceSupersetOf(rhq))
6739       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6740 
6741     // It's okay to add or remove GC or lifetime qualifiers when converting to
6742     // and from void*.
6743     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6744                         .compatiblyIncludes(
6745                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6746              && (lhptee->isVoidType() || rhptee->isVoidType()))
6747       ; // keep old
6748 
6749     // Treat lifetime mismatches as fatal.
6750     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6751       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6752 
6753     // For GCC compatibility, other qualifier mismatches are treated
6754     // as still compatible in C.
6755     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6756   }
6757 
6758   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6759   // incomplete type and the other is a pointer to a qualified or unqualified
6760   // version of void...
6761   if (lhptee->isVoidType()) {
6762     if (rhptee->isIncompleteOrObjectType())
6763       return ConvTy;
6764 
6765     // As an extension, we allow cast to/from void* to function pointer.
6766     assert(rhptee->isFunctionType());
6767     return Sema::FunctionVoidPointer;
6768   }
6769 
6770   if (rhptee->isVoidType()) {
6771     if (lhptee->isIncompleteOrObjectType())
6772       return ConvTy;
6773 
6774     // As an extension, we allow cast to/from void* to function pointer.
6775     assert(lhptee->isFunctionType());
6776     return Sema::FunctionVoidPointer;
6777   }
6778 
6779   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6780   // unqualified versions of compatible types, ...
6781   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6782   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6783     // Check if the pointee types are compatible ignoring the sign.
6784     // We explicitly check for char so that we catch "char" vs
6785     // "unsigned char" on systems where "char" is unsigned.
6786     if (lhptee->isCharType())
6787       ltrans = S.Context.UnsignedCharTy;
6788     else if (lhptee->hasSignedIntegerRepresentation())
6789       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6790 
6791     if (rhptee->isCharType())
6792       rtrans = S.Context.UnsignedCharTy;
6793     else if (rhptee->hasSignedIntegerRepresentation())
6794       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6795 
6796     if (ltrans == rtrans) {
6797       // Types are compatible ignoring the sign. Qualifier incompatibility
6798       // takes priority over sign incompatibility because the sign
6799       // warning can be disabled.
6800       if (ConvTy != Sema::Compatible)
6801         return ConvTy;
6802 
6803       return Sema::IncompatiblePointerSign;
6804     }
6805 
6806     // If we are a multi-level pointer, it's possible that our issue is simply
6807     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6808     // the eventual target type is the same and the pointers have the same
6809     // level of indirection, this must be the issue.
6810     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6811       do {
6812         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6813         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6814       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6815 
6816       if (lhptee == rhptee)
6817         return Sema::IncompatibleNestedPointerQualifiers;
6818     }
6819 
6820     // General pointer incompatibility takes priority over qualifiers.
6821     return Sema::IncompatiblePointer;
6822   }
6823   if (!S.getLangOpts().CPlusPlus &&
6824       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6825     return Sema::IncompatiblePointer;
6826   return ConvTy;
6827 }
6828 
6829 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6830 /// block pointer types are compatible or whether a block and normal pointer
6831 /// are compatible. It is more restrict than comparing two function pointer
6832 // types.
6833 static Sema::AssignConvertType
6834 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6835                                     QualType RHSType) {
6836   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6837   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6838 
6839   QualType lhptee, rhptee;
6840 
6841   // get the "pointed to" type (ignoring qualifiers at the top level)
6842   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6843   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6844 
6845   // In C++, the types have to match exactly.
6846   if (S.getLangOpts().CPlusPlus)
6847     return Sema::IncompatibleBlockPointer;
6848 
6849   Sema::AssignConvertType ConvTy = Sema::Compatible;
6850 
6851   // For blocks we enforce that qualifiers are identical.
6852   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6853     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6854 
6855   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6856     return Sema::IncompatibleBlockPointer;
6857 
6858   return ConvTy;
6859 }
6860 
6861 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6862 /// for assignment compatibility.
6863 static Sema::AssignConvertType
6864 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6865                                    QualType RHSType) {
6866   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6867   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6868 
6869   if (LHSType->isObjCBuiltinType()) {
6870     // Class is not compatible with ObjC object pointers.
6871     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6872         !RHSType->isObjCQualifiedClassType())
6873       return Sema::IncompatiblePointer;
6874     return Sema::Compatible;
6875   }
6876   if (RHSType->isObjCBuiltinType()) {
6877     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6878         !LHSType->isObjCQualifiedClassType())
6879       return Sema::IncompatiblePointer;
6880     return Sema::Compatible;
6881   }
6882   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6883   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6884 
6885   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6886       // make an exception for id<P>
6887       !LHSType->isObjCQualifiedIdType())
6888     return Sema::CompatiblePointerDiscardsQualifiers;
6889 
6890   if (S.Context.typesAreCompatible(LHSType, RHSType))
6891     return Sema::Compatible;
6892   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6893     return Sema::IncompatibleObjCQualifiedId;
6894   return Sema::IncompatiblePointer;
6895 }
6896 
6897 Sema::AssignConvertType
6898 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6899                                  QualType LHSType, QualType RHSType) {
6900   // Fake up an opaque expression.  We don't actually care about what
6901   // cast operations are required, so if CheckAssignmentConstraints
6902   // adds casts to this they'll be wasted, but fortunately that doesn't
6903   // usually happen on valid code.
6904   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6905   ExprResult RHSPtr = &RHSExpr;
6906   CastKind K = CK_Invalid;
6907 
6908   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
6909 }
6910 
6911 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6912 /// has code to accommodate several GCC extensions when type checking
6913 /// pointers. Here are some objectionable examples that GCC considers warnings:
6914 ///
6915 ///  int a, *pint;
6916 ///  short *pshort;
6917 ///  struct foo *pfoo;
6918 ///
6919 ///  pint = pshort; // warning: assignment from incompatible pointer type
6920 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6921 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6922 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6923 ///
6924 /// As a result, the code for dealing with pointers is more complex than the
6925 /// C99 spec dictates.
6926 ///
6927 /// Sets 'Kind' for any result kind except Incompatible.
6928 Sema::AssignConvertType
6929 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6930                                  CastKind &Kind, bool ConvertRHS) {
6931   QualType RHSType = RHS.get()->getType();
6932   QualType OrigLHSType = LHSType;
6933 
6934   // Get canonical types.  We're not formatting these types, just comparing
6935   // them.
6936   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6937   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6938 
6939   // Common case: no conversion required.
6940   if (LHSType == RHSType) {
6941     Kind = CK_NoOp;
6942     return Compatible;
6943   }
6944 
6945   // If we have an atomic type, try a non-atomic assignment, then just add an
6946   // atomic qualification step.
6947   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6948     Sema::AssignConvertType result =
6949       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6950     if (result != Compatible)
6951       return result;
6952     if (Kind != CK_NoOp && ConvertRHS)
6953       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6954     Kind = CK_NonAtomicToAtomic;
6955     return Compatible;
6956   }
6957 
6958   // If the left-hand side is a reference type, then we are in a
6959   // (rare!) case where we've allowed the use of references in C,
6960   // e.g., as a parameter type in a built-in function. In this case,
6961   // just make sure that the type referenced is compatible with the
6962   // right-hand side type. The caller is responsible for adjusting
6963   // LHSType so that the resulting expression does not have reference
6964   // type.
6965   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6966     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6967       Kind = CK_LValueBitCast;
6968       return Compatible;
6969     }
6970     return Incompatible;
6971   }
6972 
6973   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6974   // to the same ExtVector type.
6975   if (LHSType->isExtVectorType()) {
6976     if (RHSType->isExtVectorType())
6977       return Incompatible;
6978     if (RHSType->isArithmeticType()) {
6979       // CK_VectorSplat does T -> vector T, so first cast to the
6980       // element type.
6981       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6982       if (elType != RHSType && ConvertRHS) {
6983         Kind = PrepareScalarCast(RHS, elType);
6984         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6985       }
6986       Kind = CK_VectorSplat;
6987       return Compatible;
6988     }
6989   }
6990 
6991   // Conversions to or from vector type.
6992   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6993     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6994       // Allow assignments of an AltiVec vector type to an equivalent GCC
6995       // vector type and vice versa
6996       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6997         Kind = CK_BitCast;
6998         return Compatible;
6999       }
7000 
7001       // If we are allowing lax vector conversions, and LHS and RHS are both
7002       // vectors, the total size only needs to be the same. This is a bitcast;
7003       // no bits are changed but the result type is different.
7004       if (isLaxVectorConversion(RHSType, LHSType)) {
7005         Kind = CK_BitCast;
7006         return IncompatibleVectors;
7007       }
7008     }
7009     return Incompatible;
7010   }
7011 
7012   // Arithmetic conversions.
7013   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
7014       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
7015     if (ConvertRHS)
7016       Kind = PrepareScalarCast(RHS, LHSType);
7017     return Compatible;
7018   }
7019 
7020   // Conversions to normal pointers.
7021   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
7022     // U* -> T*
7023     if (isa<PointerType>(RHSType)) {
7024       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
7025       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
7026       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
7027       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
7028     }
7029 
7030     // int -> T*
7031     if (RHSType->isIntegerType()) {
7032       Kind = CK_IntegralToPointer; // FIXME: null?
7033       return IntToPointer;
7034     }
7035 
7036     // C pointers are not compatible with ObjC object pointers,
7037     // with two exceptions:
7038     if (isa<ObjCObjectPointerType>(RHSType)) {
7039       //  - conversions to void*
7040       if (LHSPointer->getPointeeType()->isVoidType()) {
7041         Kind = CK_BitCast;
7042         return Compatible;
7043       }
7044 
7045       //  - conversions from 'Class' to the redefinition type
7046       if (RHSType->isObjCClassType() &&
7047           Context.hasSameType(LHSType,
7048                               Context.getObjCClassRedefinitionType())) {
7049         Kind = CK_BitCast;
7050         return Compatible;
7051       }
7052 
7053       Kind = CK_BitCast;
7054       return IncompatiblePointer;
7055     }
7056 
7057     // U^ -> void*
7058     if (RHSType->getAs<BlockPointerType>()) {
7059       if (LHSPointer->getPointeeType()->isVoidType()) {
7060         Kind = CK_BitCast;
7061         return Compatible;
7062       }
7063     }
7064 
7065     return Incompatible;
7066   }
7067 
7068   // Conversions to block pointers.
7069   if (isa<BlockPointerType>(LHSType)) {
7070     // U^ -> T^
7071     if (RHSType->isBlockPointerType()) {
7072       Kind = CK_BitCast;
7073       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7074     }
7075 
7076     // int or null -> T^
7077     if (RHSType->isIntegerType()) {
7078       Kind = CK_IntegralToPointer; // FIXME: null
7079       return IntToBlockPointer;
7080     }
7081 
7082     // id -> T^
7083     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7084       Kind = CK_AnyPointerToBlockPointerCast;
7085       return Compatible;
7086     }
7087 
7088     // void* -> T^
7089     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7090       if (RHSPT->getPointeeType()->isVoidType()) {
7091         Kind = CK_AnyPointerToBlockPointerCast;
7092         return Compatible;
7093       }
7094 
7095     return Incompatible;
7096   }
7097 
7098   // Conversions to Objective-C pointers.
7099   if (isa<ObjCObjectPointerType>(LHSType)) {
7100     // A* -> B*
7101     if (RHSType->isObjCObjectPointerType()) {
7102       Kind = CK_BitCast;
7103       Sema::AssignConvertType result =
7104         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7105       if (getLangOpts().ObjCAutoRefCount &&
7106           result == Compatible &&
7107           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7108         result = IncompatibleObjCWeakRef;
7109       return result;
7110     }
7111 
7112     // int or null -> A*
7113     if (RHSType->isIntegerType()) {
7114       Kind = CK_IntegralToPointer; // FIXME: null
7115       return IntToPointer;
7116     }
7117 
7118     // In general, C pointers are not compatible with ObjC object pointers,
7119     // with two exceptions:
7120     if (isa<PointerType>(RHSType)) {
7121       Kind = CK_CPointerToObjCPointerCast;
7122 
7123       //  - conversions from 'void*'
7124       if (RHSType->isVoidPointerType()) {
7125         return Compatible;
7126       }
7127 
7128       //  - conversions to 'Class' from its redefinition type
7129       if (LHSType->isObjCClassType() &&
7130           Context.hasSameType(RHSType,
7131                               Context.getObjCClassRedefinitionType())) {
7132         return Compatible;
7133       }
7134 
7135       return IncompatiblePointer;
7136     }
7137 
7138     // Only under strict condition T^ is compatible with an Objective-C pointer.
7139     if (RHSType->isBlockPointerType() &&
7140         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7141       if (ConvertRHS)
7142         maybeExtendBlockObject(RHS);
7143       Kind = CK_BlockPointerToObjCPointerCast;
7144       return Compatible;
7145     }
7146 
7147     return Incompatible;
7148   }
7149 
7150   // Conversions from pointers that are not covered by the above.
7151   if (isa<PointerType>(RHSType)) {
7152     // T* -> _Bool
7153     if (LHSType == Context.BoolTy) {
7154       Kind = CK_PointerToBoolean;
7155       return Compatible;
7156     }
7157 
7158     // T* -> int
7159     if (LHSType->isIntegerType()) {
7160       Kind = CK_PointerToIntegral;
7161       return PointerToInt;
7162     }
7163 
7164     return Incompatible;
7165   }
7166 
7167   // Conversions from Objective-C pointers that are not covered by the above.
7168   if (isa<ObjCObjectPointerType>(RHSType)) {
7169     // T* -> _Bool
7170     if (LHSType == Context.BoolTy) {
7171       Kind = CK_PointerToBoolean;
7172       return Compatible;
7173     }
7174 
7175     // T* -> int
7176     if (LHSType->isIntegerType()) {
7177       Kind = CK_PointerToIntegral;
7178       return PointerToInt;
7179     }
7180 
7181     return Incompatible;
7182   }
7183 
7184   // struct A -> struct B
7185   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7186     if (Context.typesAreCompatible(LHSType, RHSType)) {
7187       Kind = CK_NoOp;
7188       return Compatible;
7189     }
7190   }
7191 
7192   return Incompatible;
7193 }
7194 
7195 /// \brief Constructs a transparent union from an expression that is
7196 /// used to initialize the transparent union.
7197 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7198                                       ExprResult &EResult, QualType UnionType,
7199                                       FieldDecl *Field) {
7200   // Build an initializer list that designates the appropriate member
7201   // of the transparent union.
7202   Expr *E = EResult.get();
7203   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7204                                                    E, SourceLocation());
7205   Initializer->setType(UnionType);
7206   Initializer->setInitializedFieldInUnion(Field);
7207 
7208   // Build a compound literal constructing a value of the transparent
7209   // union type from this initializer list.
7210   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7211   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7212                                         VK_RValue, Initializer, false);
7213 }
7214 
7215 Sema::AssignConvertType
7216 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7217                                                ExprResult &RHS) {
7218   QualType RHSType = RHS.get()->getType();
7219 
7220   // If the ArgType is a Union type, we want to handle a potential
7221   // transparent_union GCC extension.
7222   const RecordType *UT = ArgType->getAsUnionType();
7223   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7224     return Incompatible;
7225 
7226   // The field to initialize within the transparent union.
7227   RecordDecl *UD = UT->getDecl();
7228   FieldDecl *InitField = nullptr;
7229   // It's compatible if the expression matches any of the fields.
7230   for (auto *it : UD->fields()) {
7231     if (it->getType()->isPointerType()) {
7232       // If the transparent union contains a pointer type, we allow:
7233       // 1) void pointer
7234       // 2) null pointer constant
7235       if (RHSType->isPointerType())
7236         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7237           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7238           InitField = it;
7239           break;
7240         }
7241 
7242       if (RHS.get()->isNullPointerConstant(Context,
7243                                            Expr::NPC_ValueDependentIsNull)) {
7244         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7245                                 CK_NullToPointer);
7246         InitField = it;
7247         break;
7248       }
7249     }
7250 
7251     CastKind Kind = CK_Invalid;
7252     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7253           == Compatible) {
7254       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7255       InitField = it;
7256       break;
7257     }
7258   }
7259 
7260   if (!InitField)
7261     return Incompatible;
7262 
7263   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7264   return Compatible;
7265 }
7266 
7267 Sema::AssignConvertType
7268 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7269                                        bool Diagnose,
7270                                        bool DiagnoseCFAudited,
7271                                        bool ConvertRHS) {
7272   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7273   // we can't avoid *all* modifications at the moment, so we need some somewhere
7274   // to put the updated value.
7275   ExprResult LocalRHS = CallerRHS;
7276   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7277 
7278   if (getLangOpts().CPlusPlus) {
7279     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7280       // C++ 5.17p3: If the left operand is not of class type, the
7281       // expression is implicitly converted (C++ 4) to the
7282       // cv-unqualified type of the left operand.
7283       ExprResult Res;
7284       if (Diagnose) {
7285         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7286                                         AA_Assigning);
7287       } else {
7288         ImplicitConversionSequence ICS =
7289             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7290                                   /*SuppressUserConversions=*/false,
7291                                   /*AllowExplicit=*/false,
7292                                   /*InOverloadResolution=*/false,
7293                                   /*CStyle=*/false,
7294                                   /*AllowObjCWritebackConversion=*/false);
7295         if (ICS.isFailure())
7296           return Incompatible;
7297         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7298                                         ICS, AA_Assigning);
7299       }
7300       if (Res.isInvalid())
7301         return Incompatible;
7302       Sema::AssignConvertType result = Compatible;
7303       if (getLangOpts().ObjCAutoRefCount &&
7304           !CheckObjCARCUnavailableWeakConversion(LHSType,
7305                                                  RHS.get()->getType()))
7306         result = IncompatibleObjCWeakRef;
7307       RHS = Res;
7308       return result;
7309     }
7310 
7311     // FIXME: Currently, we fall through and treat C++ classes like C
7312     // structures.
7313     // FIXME: We also fall through for atomics; not sure what should
7314     // happen there, though.
7315   } else if (RHS.get()->getType() == Context.OverloadTy) {
7316     // As a set of extensions to C, we support overloading on functions. These
7317     // functions need to be resolved here.
7318     DeclAccessPair DAP;
7319     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7320             RHS.get(), LHSType, /*Complain=*/false, DAP))
7321       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7322     else
7323       return Incompatible;
7324   }
7325 
7326   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7327   // a null pointer constant.
7328   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7329        LHSType->isBlockPointerType()) &&
7330       RHS.get()->isNullPointerConstant(Context,
7331                                        Expr::NPC_ValueDependentIsNull)) {
7332     CastKind Kind;
7333     CXXCastPath Path;
7334     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
7335     if (ConvertRHS)
7336       RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7337     return Compatible;
7338   }
7339 
7340   // This check seems unnatural, however it is necessary to ensure the proper
7341   // conversion of functions/arrays. If the conversion were done for all
7342   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7343   // expressions that suppress this implicit conversion (&, sizeof).
7344   //
7345   // Suppress this for references: C++ 8.5.3p5.
7346   if (!LHSType->isReferenceType()) {
7347     // FIXME: We potentially allocate here even if ConvertRHS is false.
7348     RHS = DefaultFunctionArrayLvalueConversion(RHS.get(), Diagnose);
7349     if (RHS.isInvalid())
7350       return Incompatible;
7351   }
7352 
7353   Expr *PRE = RHS.get()->IgnoreParenCasts();
7354   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
7355     ObjCProtocolDecl *PDecl = OPE->getProtocol();
7356     if (PDecl && !PDecl->hasDefinition()) {
7357       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7358       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7359     }
7360   }
7361 
7362   CastKind Kind = CK_Invalid;
7363   Sema::AssignConvertType result =
7364     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7365 
7366   // C99 6.5.16.1p2: The value of the right operand is converted to the
7367   // type of the assignment expression.
7368   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7369   // so that we can use references in built-in functions even in C.
7370   // The getNonReferenceType() call makes sure that the resulting expression
7371   // does not have reference type.
7372   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7373     QualType Ty = LHSType.getNonLValueExprType(Context);
7374     Expr *E = RHS.get();
7375     if (getLangOpts().ObjCAutoRefCount)
7376       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7377                              DiagnoseCFAudited);
7378     if (getLangOpts().ObjC1 &&
7379         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
7380                                           LHSType, E->getType(), E) ||
7381          ConversionToObjCStringLiteralCheck(LHSType, E))) {
7382       RHS = E;
7383       return Compatible;
7384     }
7385 
7386     if (ConvertRHS)
7387       RHS = ImpCastExprToType(E, Ty, Kind);
7388   }
7389   return result;
7390 }
7391 
7392 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7393                                ExprResult &RHS) {
7394   Diag(Loc, diag::err_typecheck_invalid_operands)
7395     << LHS.get()->getType() << RHS.get()->getType()
7396     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7397   return QualType();
7398 }
7399 
7400 /// Try to convert a value of non-vector type to a vector type by converting
7401 /// the type to the element type of the vector and then performing a splat.
7402 /// If the language is OpenCL, we only use conversions that promote scalar
7403 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7404 /// for float->int.
7405 ///
7406 /// \param scalar - if non-null, actually perform the conversions
7407 /// \return true if the operation fails (but without diagnosing the failure)
7408 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7409                                      QualType scalarTy,
7410                                      QualType vectorEltTy,
7411                                      QualType vectorTy) {
7412   // The conversion to apply to the scalar before splatting it,
7413   // if necessary.
7414   CastKind scalarCast = CK_Invalid;
7415 
7416   if (vectorEltTy->isIntegralType(S.Context)) {
7417     if (!scalarTy->isIntegralType(S.Context))
7418       return true;
7419     if (S.getLangOpts().OpenCL &&
7420         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7421       return true;
7422     scalarCast = CK_IntegralCast;
7423   } else if (vectorEltTy->isRealFloatingType()) {
7424     if (scalarTy->isRealFloatingType()) {
7425       if (S.getLangOpts().OpenCL &&
7426           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7427         return true;
7428       scalarCast = CK_FloatingCast;
7429     }
7430     else if (scalarTy->isIntegralType(S.Context))
7431       scalarCast = CK_IntegralToFloating;
7432     else
7433       return true;
7434   } else {
7435     return true;
7436   }
7437 
7438   // Adjust scalar if desired.
7439   if (scalar) {
7440     if (scalarCast != CK_Invalid)
7441       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7442     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7443   }
7444   return false;
7445 }
7446 
7447 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7448                                    SourceLocation Loc, bool IsCompAssign,
7449                                    bool AllowBothBool,
7450                                    bool AllowBoolConversions) {
7451   if (!IsCompAssign) {
7452     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7453     if (LHS.isInvalid())
7454       return QualType();
7455   }
7456   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7457   if (RHS.isInvalid())
7458     return QualType();
7459 
7460   // For conversion purposes, we ignore any qualifiers.
7461   // For example, "const float" and "float" are equivalent.
7462   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7463   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7464 
7465   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7466   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7467   assert(LHSVecType || RHSVecType);
7468 
7469   // AltiVec-style "vector bool op vector bool" combinations are allowed
7470   // for some operators but not others.
7471   if (!AllowBothBool &&
7472       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7473       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7474     return InvalidOperands(Loc, LHS, RHS);
7475 
7476   // If the vector types are identical, return.
7477   if (Context.hasSameType(LHSType, RHSType))
7478     return LHSType;
7479 
7480   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7481   if (LHSVecType && RHSVecType &&
7482       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7483     if (isa<ExtVectorType>(LHSVecType)) {
7484       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7485       return LHSType;
7486     }
7487 
7488     if (!IsCompAssign)
7489       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7490     return RHSType;
7491   }
7492 
7493   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7494   // can be mixed, with the result being the non-bool type.  The non-bool
7495   // operand must have integer element type.
7496   if (AllowBoolConversions && LHSVecType && RHSVecType &&
7497       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7498       (Context.getTypeSize(LHSVecType->getElementType()) ==
7499        Context.getTypeSize(RHSVecType->getElementType()))) {
7500     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7501         LHSVecType->getElementType()->isIntegerType() &&
7502         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7503       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7504       return LHSType;
7505     }
7506     if (!IsCompAssign &&
7507         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7508         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7509         RHSVecType->getElementType()->isIntegerType()) {
7510       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7511       return RHSType;
7512     }
7513   }
7514 
7515   // If there's an ext-vector type and a scalar, try to convert the scalar to
7516   // the vector element type and splat.
7517   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7518     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7519                                   LHSVecType->getElementType(), LHSType))
7520       return LHSType;
7521   }
7522   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7523     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7524                                   LHSType, RHSVecType->getElementType(),
7525                                   RHSType))
7526       return RHSType;
7527   }
7528 
7529   // If we're allowing lax vector conversions, only the total (data) size
7530   // needs to be the same.
7531   // FIXME: Should we really be allowing this?
7532   // FIXME: We really just pick the LHS type arbitrarily?
7533   if (isLaxVectorConversion(RHSType, LHSType)) {
7534     QualType resultType = LHSType;
7535     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
7536     return resultType;
7537   }
7538 
7539   // Okay, the expression is invalid.
7540 
7541   // If there's a non-vector, non-real operand, diagnose that.
7542   if ((!RHSVecType && !RHSType->isRealType()) ||
7543       (!LHSVecType && !LHSType->isRealType())) {
7544     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7545       << LHSType << RHSType
7546       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7547     return QualType();
7548   }
7549 
7550   // OpenCL V1.1 6.2.6.p1:
7551   // If the operands are of more than one vector type, then an error shall
7552   // occur. Implicit conversions between vector types are not permitted, per
7553   // section 6.2.1.
7554   if (getLangOpts().OpenCL &&
7555       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7556       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7557     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7558                                                            << RHSType;
7559     return QualType();
7560   }
7561 
7562   // Otherwise, use the generic diagnostic.
7563   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7564     << LHSType << RHSType
7565     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7566   return QualType();
7567 }
7568 
7569 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7570 // expression.  These are mainly cases where the null pointer is used as an
7571 // integer instead of a pointer.
7572 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7573                                 SourceLocation Loc, bool IsCompare) {
7574   // The canonical way to check for a GNU null is with isNullPointerConstant,
7575   // but we use a bit of a hack here for speed; this is a relatively
7576   // hot path, and isNullPointerConstant is slow.
7577   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7578   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7579 
7580   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7581 
7582   // Avoid analyzing cases where the result will either be invalid (and
7583   // diagnosed as such) or entirely valid and not something to warn about.
7584   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7585       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7586     return;
7587 
7588   // Comparison operations would not make sense with a null pointer no matter
7589   // what the other expression is.
7590   if (!IsCompare) {
7591     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7592         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7593         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7594     return;
7595   }
7596 
7597   // The rest of the operations only make sense with a null pointer
7598   // if the other expression is a pointer.
7599   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7600       NonNullType->canDecayToPointerType())
7601     return;
7602 
7603   S.Diag(Loc, diag::warn_null_in_comparison_operation)
7604       << LHSNull /* LHS is NULL */ << NonNullType
7605       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7606 }
7607 
7608 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
7609                                                ExprResult &RHS,
7610                                                SourceLocation Loc, bool IsDiv) {
7611   // Check for division/remainder by zero.
7612   llvm::APSInt RHSValue;
7613   if (!RHS.get()->isValueDependent() &&
7614       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
7615     S.DiagRuntimeBehavior(Loc, RHS.get(),
7616                           S.PDiag(diag::warn_remainder_division_by_zero)
7617                             << IsDiv << RHS.get()->getSourceRange());
7618 }
7619 
7620 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7621                                            SourceLocation Loc,
7622                                            bool IsCompAssign, bool IsDiv) {
7623   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7624 
7625   if (LHS.get()->getType()->isVectorType() ||
7626       RHS.get()->getType()->isVectorType())
7627     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7628                                /*AllowBothBool*/getLangOpts().AltiVec,
7629                                /*AllowBoolConversions*/false);
7630 
7631   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7632   if (LHS.isInvalid() || RHS.isInvalid())
7633     return QualType();
7634 
7635 
7636   if (compType.isNull() || !compType->isArithmeticType())
7637     return InvalidOperands(Loc, LHS, RHS);
7638   if (IsDiv)
7639     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
7640   return compType;
7641 }
7642 
7643 QualType Sema::CheckRemainderOperands(
7644   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7645   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7646 
7647   if (LHS.get()->getType()->isVectorType() ||
7648       RHS.get()->getType()->isVectorType()) {
7649     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7650         RHS.get()->getType()->hasIntegerRepresentation())
7651       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7652                                  /*AllowBothBool*/getLangOpts().AltiVec,
7653                                  /*AllowBoolConversions*/false);
7654     return InvalidOperands(Loc, LHS, RHS);
7655   }
7656 
7657   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7658   if (LHS.isInvalid() || RHS.isInvalid())
7659     return QualType();
7660 
7661   if (compType.isNull() || !compType->isIntegerType())
7662     return InvalidOperands(Loc, LHS, RHS);
7663   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
7664   return compType;
7665 }
7666 
7667 /// \brief Diagnose invalid arithmetic on two void pointers.
7668 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7669                                                 Expr *LHSExpr, Expr *RHSExpr) {
7670   S.Diag(Loc, S.getLangOpts().CPlusPlus
7671                 ? diag::err_typecheck_pointer_arith_void_type
7672                 : diag::ext_gnu_void_ptr)
7673     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7674                             << RHSExpr->getSourceRange();
7675 }
7676 
7677 /// \brief Diagnose invalid arithmetic on a void pointer.
7678 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7679                                             Expr *Pointer) {
7680   S.Diag(Loc, S.getLangOpts().CPlusPlus
7681                 ? diag::err_typecheck_pointer_arith_void_type
7682                 : diag::ext_gnu_void_ptr)
7683     << 0 /* one pointer */ << Pointer->getSourceRange();
7684 }
7685 
7686 /// \brief Diagnose invalid arithmetic on two function pointers.
7687 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7688                                                     Expr *LHS, Expr *RHS) {
7689   assert(LHS->getType()->isAnyPointerType());
7690   assert(RHS->getType()->isAnyPointerType());
7691   S.Diag(Loc, S.getLangOpts().CPlusPlus
7692                 ? diag::err_typecheck_pointer_arith_function_type
7693                 : diag::ext_gnu_ptr_func_arith)
7694     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7695     // We only show the second type if it differs from the first.
7696     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7697                                                    RHS->getType())
7698     << RHS->getType()->getPointeeType()
7699     << LHS->getSourceRange() << RHS->getSourceRange();
7700 }
7701 
7702 /// \brief Diagnose invalid arithmetic on a function pointer.
7703 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7704                                                 Expr *Pointer) {
7705   assert(Pointer->getType()->isAnyPointerType());
7706   S.Diag(Loc, S.getLangOpts().CPlusPlus
7707                 ? diag::err_typecheck_pointer_arith_function_type
7708                 : diag::ext_gnu_ptr_func_arith)
7709     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7710     << 0 /* one pointer, so only one type */
7711     << Pointer->getSourceRange();
7712 }
7713 
7714 /// \brief Emit error if Operand is incomplete pointer type
7715 ///
7716 /// \returns True if pointer has incomplete type
7717 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7718                                                  Expr *Operand) {
7719   QualType ResType = Operand->getType();
7720   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7721     ResType = ResAtomicType->getValueType();
7722 
7723   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
7724   QualType PointeeTy = ResType->getPointeeType();
7725   return S.RequireCompleteType(Loc, PointeeTy,
7726                                diag::err_typecheck_arithmetic_incomplete_type,
7727                                PointeeTy, Operand->getSourceRange());
7728 }
7729 
7730 /// \brief Check the validity of an arithmetic pointer operand.
7731 ///
7732 /// If the operand has pointer type, this code will check for pointer types
7733 /// which are invalid in arithmetic operations. These will be diagnosed
7734 /// appropriately, including whether or not the use is supported as an
7735 /// extension.
7736 ///
7737 /// \returns True when the operand is valid to use (even if as an extension).
7738 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7739                                             Expr *Operand) {
7740   QualType ResType = Operand->getType();
7741   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7742     ResType = ResAtomicType->getValueType();
7743 
7744   if (!ResType->isAnyPointerType()) return true;
7745 
7746   QualType PointeeTy = ResType->getPointeeType();
7747   if (PointeeTy->isVoidType()) {
7748     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7749     return !S.getLangOpts().CPlusPlus;
7750   }
7751   if (PointeeTy->isFunctionType()) {
7752     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7753     return !S.getLangOpts().CPlusPlus;
7754   }
7755 
7756   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7757 
7758   return true;
7759 }
7760 
7761 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7762 /// operands.
7763 ///
7764 /// This routine will diagnose any invalid arithmetic on pointer operands much
7765 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7766 /// for emitting a single diagnostic even for operations where both LHS and RHS
7767 /// are (potentially problematic) pointers.
7768 ///
7769 /// \returns True when the operand is valid to use (even if as an extension).
7770 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7771                                                 Expr *LHSExpr, Expr *RHSExpr) {
7772   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7773   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7774   if (!isLHSPointer && !isRHSPointer) return true;
7775 
7776   QualType LHSPointeeTy, RHSPointeeTy;
7777   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7778   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7779 
7780   // if both are pointers check if operation is valid wrt address spaces
7781   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
7782     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7783     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7784     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7785       S.Diag(Loc,
7786              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7787           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7788           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7789       return false;
7790     }
7791   }
7792 
7793   // Check for arithmetic on pointers to incomplete types.
7794   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7795   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7796   if (isLHSVoidPtr || isRHSVoidPtr) {
7797     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7798     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7799     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7800 
7801     return !S.getLangOpts().CPlusPlus;
7802   }
7803 
7804   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7805   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7806   if (isLHSFuncPtr || isRHSFuncPtr) {
7807     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7808     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7809                                                                 RHSExpr);
7810     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7811 
7812     return !S.getLangOpts().CPlusPlus;
7813   }
7814 
7815   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7816     return false;
7817   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7818     return false;
7819 
7820   return true;
7821 }
7822 
7823 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7824 /// literal.
7825 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7826                                   Expr *LHSExpr, Expr *RHSExpr) {
7827   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7828   Expr* IndexExpr = RHSExpr;
7829   if (!StrExpr) {
7830     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7831     IndexExpr = LHSExpr;
7832   }
7833 
7834   bool IsStringPlusInt = StrExpr &&
7835       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7836   if (!IsStringPlusInt || IndexExpr->isValueDependent())
7837     return;
7838 
7839   llvm::APSInt index;
7840   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7841     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7842     if (index.isNonNegative() &&
7843         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7844                               index.isUnsigned()))
7845       return;
7846   }
7847 
7848   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7849   Self.Diag(OpLoc, diag::warn_string_plus_int)
7850       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7851 
7852   // Only print a fixit for "str" + int, not for int + "str".
7853   if (IndexExpr == RHSExpr) {
7854     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
7855     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7856         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7857         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7858         << FixItHint::CreateInsertion(EndLoc, "]");
7859   } else
7860     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7861 }
7862 
7863 /// \brief Emit a warning when adding a char literal to a string.
7864 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7865                                    Expr *LHSExpr, Expr *RHSExpr) {
7866   const Expr *StringRefExpr = LHSExpr;
7867   const CharacterLiteral *CharExpr =
7868       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7869 
7870   if (!CharExpr) {
7871     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7872     StringRefExpr = RHSExpr;
7873   }
7874 
7875   if (!CharExpr || !StringRefExpr)
7876     return;
7877 
7878   const QualType StringType = StringRefExpr->getType();
7879 
7880   // Return if not a PointerType.
7881   if (!StringType->isAnyPointerType())
7882     return;
7883 
7884   // Return if not a CharacterType.
7885   if (!StringType->getPointeeType()->isAnyCharacterType())
7886     return;
7887 
7888   ASTContext &Ctx = Self.getASTContext();
7889   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7890 
7891   const QualType CharType = CharExpr->getType();
7892   if (!CharType->isAnyCharacterType() &&
7893       CharType->isIntegerType() &&
7894       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7895     Self.Diag(OpLoc, diag::warn_string_plus_char)
7896         << DiagRange << Ctx.CharTy;
7897   } else {
7898     Self.Diag(OpLoc, diag::warn_string_plus_char)
7899         << DiagRange << CharExpr->getType();
7900   }
7901 
7902   // Only print a fixit for str + char, not for char + str.
7903   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7904     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
7905     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7906         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7907         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7908         << FixItHint::CreateInsertion(EndLoc, "]");
7909   } else {
7910     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7911   }
7912 }
7913 
7914 /// \brief Emit error when two pointers are incompatible.
7915 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7916                                            Expr *LHSExpr, Expr *RHSExpr) {
7917   assert(LHSExpr->getType()->isAnyPointerType());
7918   assert(RHSExpr->getType()->isAnyPointerType());
7919   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7920     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7921     << RHSExpr->getSourceRange();
7922 }
7923 
7924 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7925     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7926     QualType* CompLHSTy) {
7927   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7928 
7929   if (LHS.get()->getType()->isVectorType() ||
7930       RHS.get()->getType()->isVectorType()) {
7931     QualType compType = CheckVectorOperands(
7932         LHS, RHS, Loc, CompLHSTy,
7933         /*AllowBothBool*/getLangOpts().AltiVec,
7934         /*AllowBoolConversions*/getLangOpts().ZVector);
7935     if (CompLHSTy) *CompLHSTy = compType;
7936     return compType;
7937   }
7938 
7939   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7940   if (LHS.isInvalid() || RHS.isInvalid())
7941     return QualType();
7942 
7943   // Diagnose "string literal" '+' int and string '+' "char literal".
7944   if (Opc == BO_Add) {
7945     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7946     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7947   }
7948 
7949   // handle the common case first (both operands are arithmetic).
7950   if (!compType.isNull() && compType->isArithmeticType()) {
7951     if (CompLHSTy) *CompLHSTy = compType;
7952     return compType;
7953   }
7954 
7955   // Type-checking.  Ultimately the pointer's going to be in PExp;
7956   // note that we bias towards the LHS being the pointer.
7957   Expr *PExp = LHS.get(), *IExp = RHS.get();
7958 
7959   bool isObjCPointer;
7960   if (PExp->getType()->isPointerType()) {
7961     isObjCPointer = false;
7962   } else if (PExp->getType()->isObjCObjectPointerType()) {
7963     isObjCPointer = true;
7964   } else {
7965     std::swap(PExp, IExp);
7966     if (PExp->getType()->isPointerType()) {
7967       isObjCPointer = false;
7968     } else if (PExp->getType()->isObjCObjectPointerType()) {
7969       isObjCPointer = true;
7970     } else {
7971       return InvalidOperands(Loc, LHS, RHS);
7972     }
7973   }
7974   assert(PExp->getType()->isAnyPointerType());
7975 
7976   if (!IExp->getType()->isIntegerType())
7977     return InvalidOperands(Loc, LHS, RHS);
7978 
7979   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7980     return QualType();
7981 
7982   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7983     return QualType();
7984 
7985   // Check array bounds for pointer arithemtic
7986   CheckArrayAccess(PExp, IExp);
7987 
7988   if (CompLHSTy) {
7989     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7990     if (LHSTy.isNull()) {
7991       LHSTy = LHS.get()->getType();
7992       if (LHSTy->isPromotableIntegerType())
7993         LHSTy = Context.getPromotedIntegerType(LHSTy);
7994     }
7995     *CompLHSTy = LHSTy;
7996   }
7997 
7998   return PExp->getType();
7999 }
8000 
8001 // C99 6.5.6
8002 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
8003                                         SourceLocation Loc,
8004                                         QualType* CompLHSTy) {
8005   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8006 
8007   if (LHS.get()->getType()->isVectorType() ||
8008       RHS.get()->getType()->isVectorType()) {
8009     QualType compType = CheckVectorOperands(
8010         LHS, RHS, Loc, CompLHSTy,
8011         /*AllowBothBool*/getLangOpts().AltiVec,
8012         /*AllowBoolConversions*/getLangOpts().ZVector);
8013     if (CompLHSTy) *CompLHSTy = compType;
8014     return compType;
8015   }
8016 
8017   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
8018   if (LHS.isInvalid() || RHS.isInvalid())
8019     return QualType();
8020 
8021   // Enforce type constraints: C99 6.5.6p3.
8022 
8023   // Handle the common case first (both operands are arithmetic).
8024   if (!compType.isNull() && compType->isArithmeticType()) {
8025     if (CompLHSTy) *CompLHSTy = compType;
8026     return compType;
8027   }
8028 
8029   // Either ptr - int   or   ptr - ptr.
8030   if (LHS.get()->getType()->isAnyPointerType()) {
8031     QualType lpointee = LHS.get()->getType()->getPointeeType();
8032 
8033     // Diagnose bad cases where we step over interface counts.
8034     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8035         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8036       return QualType();
8037 
8038     // The result type of a pointer-int computation is the pointer type.
8039     if (RHS.get()->getType()->isIntegerType()) {
8040       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8041         return QualType();
8042 
8043       // Check array bounds for pointer arithemtic
8044       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8045                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8046 
8047       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8048       return LHS.get()->getType();
8049     }
8050 
8051     // Handle pointer-pointer subtractions.
8052     if (const PointerType *RHSPTy
8053           = RHS.get()->getType()->getAs<PointerType>()) {
8054       QualType rpointee = RHSPTy->getPointeeType();
8055 
8056       if (getLangOpts().CPlusPlus) {
8057         // Pointee types must be the same: C++ [expr.add]
8058         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8059           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8060         }
8061       } else {
8062         // Pointee types must be compatible C99 6.5.6p3
8063         if (!Context.typesAreCompatible(
8064                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8065                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8066           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8067           return QualType();
8068         }
8069       }
8070 
8071       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8072                                                LHS.get(), RHS.get()))
8073         return QualType();
8074 
8075       // The pointee type may have zero size.  As an extension, a structure or
8076       // union may have zero size or an array may have zero length.  In this
8077       // case subtraction does not make sense.
8078       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8079         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8080         if (ElementSize.isZero()) {
8081           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8082             << rpointee.getUnqualifiedType()
8083             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8084         }
8085       }
8086 
8087       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8088       return Context.getPointerDiffType();
8089     }
8090   }
8091 
8092   return InvalidOperands(Loc, LHS, RHS);
8093 }
8094 
8095 static bool isScopedEnumerationType(QualType T) {
8096   if (const EnumType *ET = T->getAs<EnumType>())
8097     return ET->getDecl()->isScoped();
8098   return false;
8099 }
8100 
8101 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8102                                    SourceLocation Loc, unsigned Opc,
8103                                    QualType LHSType) {
8104   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8105   // so skip remaining warnings as we don't want to modify values within Sema.
8106   if (S.getLangOpts().OpenCL)
8107     return;
8108 
8109   llvm::APSInt Right;
8110   // Check right/shifter operand
8111   if (RHS.get()->isValueDependent() ||
8112       !RHS.get()->EvaluateAsInt(Right, S.Context))
8113     return;
8114 
8115   if (Right.isNegative()) {
8116     S.DiagRuntimeBehavior(Loc, RHS.get(),
8117                           S.PDiag(diag::warn_shift_negative)
8118                             << RHS.get()->getSourceRange());
8119     return;
8120   }
8121   llvm::APInt LeftBits(Right.getBitWidth(),
8122                        S.Context.getTypeSize(LHS.get()->getType()));
8123   if (Right.uge(LeftBits)) {
8124     S.DiagRuntimeBehavior(Loc, RHS.get(),
8125                           S.PDiag(diag::warn_shift_gt_typewidth)
8126                             << RHS.get()->getSourceRange());
8127     return;
8128   }
8129   if (Opc != BO_Shl)
8130     return;
8131 
8132   // When left shifting an ICE which is signed, we can check for overflow which
8133   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8134   // integers have defined behavior modulo one more than the maximum value
8135   // representable in the result type, so never warn for those.
8136   llvm::APSInt Left;
8137   if (LHS.get()->isValueDependent() ||
8138       LHSType->hasUnsignedIntegerRepresentation() ||
8139       !LHS.get()->EvaluateAsInt(Left, S.Context))
8140     return;
8141 
8142   // If LHS does not have a signed type and non-negative value
8143   // then, the behavior is undefined. Warn about it.
8144   if (Left.isNegative()) {
8145     S.DiagRuntimeBehavior(Loc, LHS.get(),
8146                           S.PDiag(diag::warn_shift_lhs_negative)
8147                             << LHS.get()->getSourceRange());
8148     return;
8149   }
8150 
8151   llvm::APInt ResultBits =
8152       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8153   if (LeftBits.uge(ResultBits))
8154     return;
8155   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8156   Result = Result.shl(Right);
8157 
8158   // Print the bit representation of the signed integer as an unsigned
8159   // hexadecimal number.
8160   SmallString<40> HexResult;
8161   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8162 
8163   // If we are only missing a sign bit, this is less likely to result in actual
8164   // bugs -- if the result is cast back to an unsigned type, it will have the
8165   // expected value. Thus we place this behind a different warning that can be
8166   // turned off separately if needed.
8167   if (LeftBits == ResultBits - 1) {
8168     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8169         << HexResult << LHSType
8170         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8171     return;
8172   }
8173 
8174   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8175     << HexResult.str() << Result.getMinSignedBits() << LHSType
8176     << Left.getBitWidth() << LHS.get()->getSourceRange()
8177     << RHS.get()->getSourceRange();
8178 }
8179 
8180 /// \brief Return the resulting type when an OpenCL vector is shifted
8181 ///        by a scalar or vector shift amount.
8182 static QualType checkOpenCLVectorShift(Sema &S,
8183                                        ExprResult &LHS, ExprResult &RHS,
8184                                        SourceLocation Loc, bool IsCompAssign) {
8185   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8186   if (!LHS.get()->getType()->isVectorType()) {
8187     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8188       << RHS.get()->getType() << LHS.get()->getType()
8189       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8190     return QualType();
8191   }
8192 
8193   if (!IsCompAssign) {
8194     LHS = S.UsualUnaryConversions(LHS.get());
8195     if (LHS.isInvalid()) return QualType();
8196   }
8197 
8198   RHS = S.UsualUnaryConversions(RHS.get());
8199   if (RHS.isInvalid()) return QualType();
8200 
8201   QualType LHSType = LHS.get()->getType();
8202   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8203   QualType LHSEleType = LHSVecTy->getElementType();
8204 
8205   // Note that RHS might not be a vector.
8206   QualType RHSType = RHS.get()->getType();
8207   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8208   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8209 
8210   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8211   if (!LHSEleType->isIntegerType()) {
8212     S.Diag(Loc, diag::err_typecheck_expect_int)
8213       << LHS.get()->getType() << LHS.get()->getSourceRange();
8214     return QualType();
8215   }
8216 
8217   if (!RHSEleType->isIntegerType()) {
8218     S.Diag(Loc, diag::err_typecheck_expect_int)
8219       << RHS.get()->getType() << RHS.get()->getSourceRange();
8220     return QualType();
8221   }
8222 
8223   if (RHSVecTy) {
8224     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8225     // are applied component-wise. So if RHS is a vector, then ensure
8226     // that the number of elements is the same as LHS...
8227     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8228       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8229         << LHS.get()->getType() << RHS.get()->getType()
8230         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8231       return QualType();
8232     }
8233   } else {
8234     // ...else expand RHS to match the number of elements in LHS.
8235     QualType VecTy =
8236       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8237     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8238   }
8239 
8240   return LHSType;
8241 }
8242 
8243 // C99 6.5.7
8244 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8245                                   SourceLocation Loc, unsigned Opc,
8246                                   bool IsCompAssign) {
8247   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8248 
8249   // Vector shifts promote their scalar inputs to vector type.
8250   if (LHS.get()->getType()->isVectorType() ||
8251       RHS.get()->getType()->isVectorType()) {
8252     if (LangOpts.OpenCL)
8253       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8254     if (LangOpts.ZVector) {
8255       // The shift operators for the z vector extensions work basically
8256       // like OpenCL shifts, except that neither the LHS nor the RHS is
8257       // allowed to be a "vector bool".
8258       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8259         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8260           return InvalidOperands(Loc, LHS, RHS);
8261       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8262         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8263           return InvalidOperands(Loc, LHS, RHS);
8264       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8265     }
8266     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8267                                /*AllowBothBool*/true,
8268                                /*AllowBoolConversions*/false);
8269   }
8270 
8271   // Shifts don't perform usual arithmetic conversions, they just do integer
8272   // promotions on each operand. C99 6.5.7p3
8273 
8274   // For the LHS, do usual unary conversions, but then reset them away
8275   // if this is a compound assignment.
8276   ExprResult OldLHS = LHS;
8277   LHS = UsualUnaryConversions(LHS.get());
8278   if (LHS.isInvalid())
8279     return QualType();
8280   QualType LHSType = LHS.get()->getType();
8281   if (IsCompAssign) LHS = OldLHS;
8282 
8283   // The RHS is simpler.
8284   RHS = UsualUnaryConversions(RHS.get());
8285   if (RHS.isInvalid())
8286     return QualType();
8287   QualType RHSType = RHS.get()->getType();
8288 
8289   // C99 6.5.7p2: Each of the operands shall have integer type.
8290   if (!LHSType->hasIntegerRepresentation() ||
8291       !RHSType->hasIntegerRepresentation())
8292     return InvalidOperands(Loc, LHS, RHS);
8293 
8294   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8295   // hasIntegerRepresentation() above instead of this.
8296   if (isScopedEnumerationType(LHSType) ||
8297       isScopedEnumerationType(RHSType)) {
8298     return InvalidOperands(Loc, LHS, RHS);
8299   }
8300   // Sanity-check shift operands
8301   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8302 
8303   // "The type of the result is that of the promoted left operand."
8304   return LHSType;
8305 }
8306 
8307 static bool IsWithinTemplateSpecialization(Decl *D) {
8308   if (DeclContext *DC = D->getDeclContext()) {
8309     if (isa<ClassTemplateSpecializationDecl>(DC))
8310       return true;
8311     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8312       return FD->isFunctionTemplateSpecialization();
8313   }
8314   return false;
8315 }
8316 
8317 /// If two different enums are compared, raise a warning.
8318 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8319                                 Expr *RHS) {
8320   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8321   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8322 
8323   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8324   if (!LHSEnumType)
8325     return;
8326   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8327   if (!RHSEnumType)
8328     return;
8329 
8330   // Ignore anonymous enums.
8331   if (!LHSEnumType->getDecl()->getIdentifier())
8332     return;
8333   if (!RHSEnumType->getDecl()->getIdentifier())
8334     return;
8335 
8336   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8337     return;
8338 
8339   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8340       << LHSStrippedType << RHSStrippedType
8341       << LHS->getSourceRange() << RHS->getSourceRange();
8342 }
8343 
8344 /// \brief Diagnose bad pointer comparisons.
8345 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8346                                               ExprResult &LHS, ExprResult &RHS,
8347                                               bool IsError) {
8348   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8349                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8350     << LHS.get()->getType() << RHS.get()->getType()
8351     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8352 }
8353 
8354 /// \brief Returns false if the pointers are converted to a composite type,
8355 /// true otherwise.
8356 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8357                                            ExprResult &LHS, ExprResult &RHS) {
8358   // C++ [expr.rel]p2:
8359   //   [...] Pointer conversions (4.10) and qualification
8360   //   conversions (4.4) are performed on pointer operands (or on
8361   //   a pointer operand and a null pointer constant) to bring
8362   //   them to their composite pointer type. [...]
8363   //
8364   // C++ [expr.eq]p1 uses the same notion for (in)equality
8365   // comparisons of pointers.
8366 
8367   // C++ [expr.eq]p2:
8368   //   In addition, pointers to members can be compared, or a pointer to
8369   //   member and a null pointer constant. Pointer to member conversions
8370   //   (4.11) and qualification conversions (4.4) are performed to bring
8371   //   them to a common type. If one operand is a null pointer constant,
8372   //   the common type is the type of the other operand. Otherwise, the
8373   //   common type is a pointer to member type similar (4.4) to the type
8374   //   of one of the operands, with a cv-qualification signature (4.4)
8375   //   that is the union of the cv-qualification signatures of the operand
8376   //   types.
8377 
8378   QualType LHSType = LHS.get()->getType();
8379   QualType RHSType = RHS.get()->getType();
8380   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8381          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8382 
8383   bool NonStandardCompositeType = false;
8384   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8385   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8386   if (T.isNull()) {
8387     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8388     return true;
8389   }
8390 
8391   if (NonStandardCompositeType)
8392     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8393       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8394       << RHS.get()->getSourceRange();
8395 
8396   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8397   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8398   return false;
8399 }
8400 
8401 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8402                                                     ExprResult &LHS,
8403                                                     ExprResult &RHS,
8404                                                     bool IsError) {
8405   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8406                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8407     << LHS.get()->getType() << RHS.get()->getType()
8408     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8409 }
8410 
8411 static bool isObjCObjectLiteral(ExprResult &E) {
8412   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8413   case Stmt::ObjCArrayLiteralClass:
8414   case Stmt::ObjCDictionaryLiteralClass:
8415   case Stmt::ObjCStringLiteralClass:
8416   case Stmt::ObjCBoxedExprClass:
8417     return true;
8418   default:
8419     // Note that ObjCBoolLiteral is NOT an object literal!
8420     return false;
8421   }
8422 }
8423 
8424 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8425   const ObjCObjectPointerType *Type =
8426     LHS->getType()->getAs<ObjCObjectPointerType>();
8427 
8428   // If this is not actually an Objective-C object, bail out.
8429   if (!Type)
8430     return false;
8431 
8432   // Get the LHS object's interface type.
8433   QualType InterfaceType = Type->getPointeeType();
8434 
8435   // If the RHS isn't an Objective-C object, bail out.
8436   if (!RHS->getType()->isObjCObjectPointerType())
8437     return false;
8438 
8439   // Try to find the -isEqual: method.
8440   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8441   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8442                                                       InterfaceType,
8443                                                       /*instance=*/true);
8444   if (!Method) {
8445     if (Type->isObjCIdType()) {
8446       // For 'id', just check the global pool.
8447       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8448                                                   /*receiverId=*/true);
8449     } else {
8450       // Check protocols.
8451       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8452                                              /*instance=*/true);
8453     }
8454   }
8455 
8456   if (!Method)
8457     return false;
8458 
8459   QualType T = Method->parameters()[0]->getType();
8460   if (!T->isObjCObjectPointerType())
8461     return false;
8462 
8463   QualType R = Method->getReturnType();
8464   if (!R->isScalarType())
8465     return false;
8466 
8467   return true;
8468 }
8469 
8470 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8471   FromE = FromE->IgnoreParenImpCasts();
8472   switch (FromE->getStmtClass()) {
8473     default:
8474       break;
8475     case Stmt::ObjCStringLiteralClass:
8476       // "string literal"
8477       return LK_String;
8478     case Stmt::ObjCArrayLiteralClass:
8479       // "array literal"
8480       return LK_Array;
8481     case Stmt::ObjCDictionaryLiteralClass:
8482       // "dictionary literal"
8483       return LK_Dictionary;
8484     case Stmt::BlockExprClass:
8485       return LK_Block;
8486     case Stmt::ObjCBoxedExprClass: {
8487       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8488       switch (Inner->getStmtClass()) {
8489         case Stmt::IntegerLiteralClass:
8490         case Stmt::FloatingLiteralClass:
8491         case Stmt::CharacterLiteralClass:
8492         case Stmt::ObjCBoolLiteralExprClass:
8493         case Stmt::CXXBoolLiteralExprClass:
8494           // "numeric literal"
8495           return LK_Numeric;
8496         case Stmt::ImplicitCastExprClass: {
8497           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8498           // Boolean literals can be represented by implicit casts.
8499           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8500             return LK_Numeric;
8501           break;
8502         }
8503         default:
8504           break;
8505       }
8506       return LK_Boxed;
8507     }
8508   }
8509   return LK_None;
8510 }
8511 
8512 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8513                                           ExprResult &LHS, ExprResult &RHS,
8514                                           BinaryOperator::Opcode Opc){
8515   Expr *Literal;
8516   Expr *Other;
8517   if (isObjCObjectLiteral(LHS)) {
8518     Literal = LHS.get();
8519     Other = RHS.get();
8520   } else {
8521     Literal = RHS.get();
8522     Other = LHS.get();
8523   }
8524 
8525   // Don't warn on comparisons against nil.
8526   Other = Other->IgnoreParenCasts();
8527   if (Other->isNullPointerConstant(S.getASTContext(),
8528                                    Expr::NPC_ValueDependentIsNotNull))
8529     return;
8530 
8531   // This should be kept in sync with warn_objc_literal_comparison.
8532   // LK_String should always be after the other literals, since it has its own
8533   // warning flag.
8534   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8535   assert(LiteralKind != Sema::LK_Block);
8536   if (LiteralKind == Sema::LK_None) {
8537     llvm_unreachable("Unknown Objective-C object literal kind");
8538   }
8539 
8540   if (LiteralKind == Sema::LK_String)
8541     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8542       << Literal->getSourceRange();
8543   else
8544     S.Diag(Loc, diag::warn_objc_literal_comparison)
8545       << LiteralKind << Literal->getSourceRange();
8546 
8547   if (BinaryOperator::isEqualityOp(Opc) &&
8548       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8549     SourceLocation Start = LHS.get()->getLocStart();
8550     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8551     CharSourceRange OpRange =
8552       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8553 
8554     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8555       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8556       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8557       << FixItHint::CreateInsertion(End, "]");
8558   }
8559 }
8560 
8561 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8562                                                 ExprResult &RHS,
8563                                                 SourceLocation Loc,
8564                                                 unsigned OpaqueOpc) {
8565   // Check that left hand side is !something.
8566   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8567   if (!UO || UO->getOpcode() != UO_LNot) return;
8568 
8569   // Only check if the right hand side is non-bool arithmetic type.
8570   if (RHS.get()->isKnownToHaveBooleanValue()) return;
8571 
8572   // Make sure that the something in !something is not bool.
8573   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8574   if (SubExpr->isKnownToHaveBooleanValue()) return;
8575 
8576   // Emit warning.
8577   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8578       << Loc;
8579 
8580   // First note suggest !(x < y)
8581   SourceLocation FirstOpen = SubExpr->getLocStart();
8582   SourceLocation FirstClose = RHS.get()->getLocEnd();
8583   FirstClose = S.getLocForEndOfToken(FirstClose);
8584   if (FirstClose.isInvalid())
8585     FirstOpen = SourceLocation();
8586   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8587       << FixItHint::CreateInsertion(FirstOpen, "(")
8588       << FixItHint::CreateInsertion(FirstClose, ")");
8589 
8590   // Second note suggests (!x) < y
8591   SourceLocation SecondOpen = LHS.get()->getLocStart();
8592   SourceLocation SecondClose = LHS.get()->getLocEnd();
8593   SecondClose = S.getLocForEndOfToken(SecondClose);
8594   if (SecondClose.isInvalid())
8595     SecondOpen = SourceLocation();
8596   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8597       << FixItHint::CreateInsertion(SecondOpen, "(")
8598       << FixItHint::CreateInsertion(SecondClose, ")");
8599 }
8600 
8601 // Get the decl for a simple expression: a reference to a variable,
8602 // an implicit C++ field reference, or an implicit ObjC ivar reference.
8603 static ValueDecl *getCompareDecl(Expr *E) {
8604   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8605     return DR->getDecl();
8606   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8607     if (Ivar->isFreeIvar())
8608       return Ivar->getDecl();
8609   }
8610   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8611     if (Mem->isImplicitAccess())
8612       return Mem->getMemberDecl();
8613   }
8614   return nullptr;
8615 }
8616 
8617 // C99 6.5.8, C++ [expr.rel]
8618 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
8619                                     SourceLocation Loc, unsigned OpaqueOpc,
8620                                     bool IsRelational) {
8621   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8622 
8623   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
8624 
8625   // Handle vector comparisons separately.
8626   if (LHS.get()->getType()->isVectorType() ||
8627       RHS.get()->getType()->isVectorType())
8628     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
8629 
8630   QualType LHSType = LHS.get()->getType();
8631   QualType RHSType = RHS.get()->getType();
8632 
8633   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8634   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
8635 
8636   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
8637   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
8638 
8639   if (!LHSType->hasFloatingRepresentation() &&
8640       !(LHSType->isBlockPointerType() && IsRelational) &&
8641       !LHS.get()->getLocStart().isMacroID() &&
8642       !RHS.get()->getLocStart().isMacroID() &&
8643       ActiveTemplateInstantiations.empty()) {
8644     // For non-floating point types, check for self-comparisons of the form
8645     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8646     // often indicate logic errors in the program.
8647     //
8648     // NOTE: Don't warn about comparison expressions resulting from macro
8649     // expansion. Also don't warn about comparisons which are only self
8650     // comparisons within a template specialization. The warnings should catch
8651     // obvious cases in the definition of the template anyways. The idea is to
8652     // warn when the typed comparison operator will always evaluate to the same
8653     // result.
8654     ValueDecl *DL = getCompareDecl(LHSStripped);
8655     ValueDecl *DR = getCompareDecl(RHSStripped);
8656     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
8657       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8658                           << 0 // self-
8659                           << (Opc == BO_EQ
8660                               || Opc == BO_LE
8661                               || Opc == BO_GE));
8662     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8663                !DL->getType()->isReferenceType() &&
8664                !DR->getType()->isReferenceType()) {
8665         // what is it always going to eval to?
8666         char always_evals_to;
8667         switch(Opc) {
8668         case BO_EQ: // e.g. array1 == array2
8669           always_evals_to = 0; // false
8670           break;
8671         case BO_NE: // e.g. array1 != array2
8672           always_evals_to = 1; // true
8673           break;
8674         default:
8675           // best we can say is 'a constant'
8676           always_evals_to = 2; // e.g. array1 <= array2
8677           break;
8678         }
8679         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8680                             << 1 // array
8681                             << always_evals_to);
8682     }
8683 
8684     if (isa<CastExpr>(LHSStripped))
8685       LHSStripped = LHSStripped->IgnoreParenCasts();
8686     if (isa<CastExpr>(RHSStripped))
8687       RHSStripped = RHSStripped->IgnoreParenCasts();
8688 
8689     // Warn about comparisons against a string constant (unless the other
8690     // operand is null), the user probably wants strcmp.
8691     Expr *literalString = nullptr;
8692     Expr *literalStringStripped = nullptr;
8693     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8694         !RHSStripped->isNullPointerConstant(Context,
8695                                             Expr::NPC_ValueDependentIsNull)) {
8696       literalString = LHS.get();
8697       literalStringStripped = LHSStripped;
8698     } else if ((isa<StringLiteral>(RHSStripped) ||
8699                 isa<ObjCEncodeExpr>(RHSStripped)) &&
8700                !LHSStripped->isNullPointerConstant(Context,
8701                                             Expr::NPC_ValueDependentIsNull)) {
8702       literalString = RHS.get();
8703       literalStringStripped = RHSStripped;
8704     }
8705 
8706     if (literalString) {
8707       DiagRuntimeBehavior(Loc, nullptr,
8708         PDiag(diag::warn_stringcompare)
8709           << isa<ObjCEncodeExpr>(literalStringStripped)
8710           << literalString->getSourceRange());
8711     }
8712   }
8713 
8714   // C99 6.5.8p3 / C99 6.5.9p4
8715   UsualArithmeticConversions(LHS, RHS);
8716   if (LHS.isInvalid() || RHS.isInvalid())
8717     return QualType();
8718 
8719   LHSType = LHS.get()->getType();
8720   RHSType = RHS.get()->getType();
8721 
8722   // The result of comparisons is 'bool' in C++, 'int' in C.
8723   QualType ResultTy = Context.getLogicalOperationType();
8724 
8725   if (IsRelational) {
8726     if (LHSType->isRealType() && RHSType->isRealType())
8727       return ResultTy;
8728   } else {
8729     // Check for comparisons of floating point operands using != and ==.
8730     if (LHSType->hasFloatingRepresentation())
8731       CheckFloatComparison(Loc, LHS.get(), RHS.get());
8732 
8733     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
8734       return ResultTy;
8735   }
8736 
8737   const Expr::NullPointerConstantKind LHSNullKind =
8738       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8739   const Expr::NullPointerConstantKind RHSNullKind =
8740       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8741   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8742   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8743 
8744   if (!IsRelational && LHSIsNull != RHSIsNull) {
8745     bool IsEquality = Opc == BO_EQ;
8746     if (RHSIsNull)
8747       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8748                                    RHS.get()->getSourceRange());
8749     else
8750       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8751                                    LHS.get()->getSourceRange());
8752   }
8753 
8754   // All of the following pointer-related warnings are GCC extensions, except
8755   // when handling null pointer constants.
8756   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
8757     QualType LCanPointeeTy =
8758       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8759     QualType RCanPointeeTy =
8760       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8761 
8762     if (getLangOpts().CPlusPlus) {
8763       if (LCanPointeeTy == RCanPointeeTy)
8764         return ResultTy;
8765       if (!IsRelational &&
8766           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8767         // Valid unless comparison between non-null pointer and function pointer
8768         // This is a gcc extension compatibility comparison.
8769         // In a SFINAE context, we treat this as a hard error to maintain
8770         // conformance with the C++ standard.
8771         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8772             && !LHSIsNull && !RHSIsNull) {
8773           diagnoseFunctionPointerToVoidComparison(
8774               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8775 
8776           if (isSFINAEContext())
8777             return QualType();
8778 
8779           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8780           return ResultTy;
8781         }
8782       }
8783 
8784       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8785         return QualType();
8786       else
8787         return ResultTy;
8788     }
8789     // C99 6.5.9p2 and C99 6.5.8p2
8790     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8791                                    RCanPointeeTy.getUnqualifiedType())) {
8792       // Valid unless a relational comparison of function pointers
8793       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8794         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8795           << LHSType << RHSType << LHS.get()->getSourceRange()
8796           << RHS.get()->getSourceRange();
8797       }
8798     } else if (!IsRelational &&
8799                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8800       // Valid unless comparison between non-null pointer and function pointer
8801       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8802           && !LHSIsNull && !RHSIsNull)
8803         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8804                                                 /*isError*/false);
8805     } else {
8806       // Invalid
8807       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8808     }
8809     if (LCanPointeeTy != RCanPointeeTy) {
8810       if (getLangOpts().OpenCL) {
8811         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
8812         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8813           Diag(Loc,
8814                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8815               << LHSType << RHSType << 0 /* comparison */
8816               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8817         }
8818       }
8819       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8820       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8821       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8822                                                : CK_BitCast;
8823       if (LHSIsNull && !RHSIsNull)
8824         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8825       else
8826         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8827     }
8828     return ResultTy;
8829   }
8830 
8831   if (getLangOpts().CPlusPlus) {
8832     // Comparison of nullptr_t with itself.
8833     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8834       return ResultTy;
8835 
8836     // Comparison of pointers with null pointer constants and equality
8837     // comparisons of member pointers to null pointer constants.
8838     if (RHSIsNull &&
8839         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8840          (!IsRelational &&
8841           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8842       RHS = ImpCastExprToType(RHS.get(), LHSType,
8843                         LHSType->isMemberPointerType()
8844                           ? CK_NullToMemberPointer
8845                           : CK_NullToPointer);
8846       return ResultTy;
8847     }
8848     if (LHSIsNull &&
8849         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8850          (!IsRelational &&
8851           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8852       LHS = ImpCastExprToType(LHS.get(), RHSType,
8853                         RHSType->isMemberPointerType()
8854                           ? CK_NullToMemberPointer
8855                           : CK_NullToPointer);
8856       return ResultTy;
8857     }
8858 
8859     // Comparison of member pointers.
8860     if (!IsRelational &&
8861         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8862       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8863         return QualType();
8864       else
8865         return ResultTy;
8866     }
8867 
8868     // Handle scoped enumeration types specifically, since they don't promote
8869     // to integers.
8870     if (LHS.get()->getType()->isEnumeralType() &&
8871         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8872                                        RHS.get()->getType()))
8873       return ResultTy;
8874   }
8875 
8876   // Handle block pointer types.
8877   if (!IsRelational && LHSType->isBlockPointerType() &&
8878       RHSType->isBlockPointerType()) {
8879     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8880     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8881 
8882     if (!LHSIsNull && !RHSIsNull &&
8883         !Context.typesAreCompatible(lpointee, rpointee)) {
8884       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8885         << LHSType << RHSType << LHS.get()->getSourceRange()
8886         << RHS.get()->getSourceRange();
8887     }
8888     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8889     return ResultTy;
8890   }
8891 
8892   // Allow block pointers to be compared with null pointer constants.
8893   if (!IsRelational
8894       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8895           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8896     if (!LHSIsNull && !RHSIsNull) {
8897       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8898              ->getPointeeType()->isVoidType())
8899             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8900                 ->getPointeeType()->isVoidType())))
8901         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8902           << LHSType << RHSType << LHS.get()->getSourceRange()
8903           << RHS.get()->getSourceRange();
8904     }
8905     if (LHSIsNull && !RHSIsNull)
8906       LHS = ImpCastExprToType(LHS.get(), RHSType,
8907                               RHSType->isPointerType() ? CK_BitCast
8908                                 : CK_AnyPointerToBlockPointerCast);
8909     else
8910       RHS = ImpCastExprToType(RHS.get(), LHSType,
8911                               LHSType->isPointerType() ? CK_BitCast
8912                                 : CK_AnyPointerToBlockPointerCast);
8913     return ResultTy;
8914   }
8915 
8916   if (LHSType->isObjCObjectPointerType() ||
8917       RHSType->isObjCObjectPointerType()) {
8918     const PointerType *LPT = LHSType->getAs<PointerType>();
8919     const PointerType *RPT = RHSType->getAs<PointerType>();
8920     if (LPT || RPT) {
8921       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8922       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8923 
8924       if (!LPtrToVoid && !RPtrToVoid &&
8925           !Context.typesAreCompatible(LHSType, RHSType)) {
8926         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8927                                           /*isError*/false);
8928       }
8929       if (LHSIsNull && !RHSIsNull) {
8930         Expr *E = LHS.get();
8931         if (getLangOpts().ObjCAutoRefCount)
8932           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8933         LHS = ImpCastExprToType(E, RHSType,
8934                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8935       }
8936       else {
8937         Expr *E = RHS.get();
8938         if (getLangOpts().ObjCAutoRefCount)
8939           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8940                                  Opc);
8941         RHS = ImpCastExprToType(E, LHSType,
8942                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8943       }
8944       return ResultTy;
8945     }
8946     if (LHSType->isObjCObjectPointerType() &&
8947         RHSType->isObjCObjectPointerType()) {
8948       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8949         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8950                                           /*isError*/false);
8951       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8952         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8953 
8954       if (LHSIsNull && !RHSIsNull)
8955         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8956       else
8957         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8958       return ResultTy;
8959     }
8960   }
8961   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8962       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8963     unsigned DiagID = 0;
8964     bool isError = false;
8965     if (LangOpts.DebuggerSupport) {
8966       // Under a debugger, allow the comparison of pointers to integers,
8967       // since users tend to want to compare addresses.
8968     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8969         (RHSIsNull && RHSType->isIntegerType())) {
8970       if (IsRelational && !getLangOpts().CPlusPlus)
8971         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8972     } else if (IsRelational && !getLangOpts().CPlusPlus)
8973       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8974     else if (getLangOpts().CPlusPlus) {
8975       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8976       isError = true;
8977     } else
8978       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8979 
8980     if (DiagID) {
8981       Diag(Loc, DiagID)
8982         << LHSType << RHSType << LHS.get()->getSourceRange()
8983         << RHS.get()->getSourceRange();
8984       if (isError)
8985         return QualType();
8986     }
8987 
8988     if (LHSType->isIntegerType())
8989       LHS = ImpCastExprToType(LHS.get(), RHSType,
8990                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8991     else
8992       RHS = ImpCastExprToType(RHS.get(), LHSType,
8993                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8994     return ResultTy;
8995   }
8996 
8997   // Handle block pointers.
8998   if (!IsRelational && RHSIsNull
8999       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
9000     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
9001     return ResultTy;
9002   }
9003   if (!IsRelational && LHSIsNull
9004       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
9005     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
9006     return ResultTy;
9007   }
9008 
9009   return InvalidOperands(Loc, LHS, RHS);
9010 }
9011 
9012 
9013 // Return a signed type that is of identical size and number of elements.
9014 // For floating point vectors, return an integer type of identical size
9015 // and number of elements.
9016 QualType Sema::GetSignedVectorType(QualType V) {
9017   const VectorType *VTy = V->getAs<VectorType>();
9018   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
9019   if (TypeSize == Context.getTypeSize(Context.CharTy))
9020     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
9021   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
9022     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
9023   else if (TypeSize == Context.getTypeSize(Context.IntTy))
9024     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
9025   else if (TypeSize == Context.getTypeSize(Context.LongTy))
9026     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
9027   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
9028          "Unhandled vector element size in vector compare");
9029   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
9030 }
9031 
9032 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
9033 /// operates on extended vector types.  Instead of producing an IntTy result,
9034 /// like a scalar comparison, a vector comparison produces a vector of integer
9035 /// types.
9036 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9037                                           SourceLocation Loc,
9038                                           bool IsRelational) {
9039   // Check to make sure we're operating on vectors of the same type and width,
9040   // Allowing one side to be a scalar of element type.
9041   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9042                               /*AllowBothBool*/true,
9043                               /*AllowBoolConversions*/getLangOpts().ZVector);
9044   if (vType.isNull())
9045     return vType;
9046 
9047   QualType LHSType = LHS.get()->getType();
9048 
9049   // If AltiVec, the comparison results in a numeric type, i.e.
9050   // bool for C++, int for C
9051   if (getLangOpts().AltiVec &&
9052       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9053     return Context.getLogicalOperationType();
9054 
9055   // For non-floating point types, check for self-comparisons of the form
9056   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9057   // often indicate logic errors in the program.
9058   if (!LHSType->hasFloatingRepresentation() &&
9059       ActiveTemplateInstantiations.empty()) {
9060     if (DeclRefExpr* DRL
9061           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9062       if (DeclRefExpr* DRR
9063             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9064         if (DRL->getDecl() == DRR->getDecl())
9065           DiagRuntimeBehavior(Loc, nullptr,
9066                               PDiag(diag::warn_comparison_always)
9067                                 << 0 // self-
9068                                 << 2 // "a constant"
9069                               );
9070   }
9071 
9072   // Check for comparisons of floating point operands using != and ==.
9073   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9074     assert (RHS.get()->getType()->hasFloatingRepresentation());
9075     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9076   }
9077 
9078   // Return a signed type for the vector.
9079   return GetSignedVectorType(LHSType);
9080 }
9081 
9082 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9083                                           SourceLocation Loc) {
9084   // Ensure that either both operands are of the same vector type, or
9085   // one operand is of a vector type and the other is of its element type.
9086   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9087                                        /*AllowBothBool*/true,
9088                                        /*AllowBoolConversions*/false);
9089   if (vType.isNull())
9090     return InvalidOperands(Loc, LHS, RHS);
9091   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9092       vType->hasFloatingRepresentation())
9093     return InvalidOperands(Loc, LHS, RHS);
9094 
9095   return GetSignedVectorType(LHS.get()->getType());
9096 }
9097 
9098 inline QualType Sema::CheckBitwiseOperands(
9099   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9100   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9101 
9102   if (LHS.get()->getType()->isVectorType() ||
9103       RHS.get()->getType()->isVectorType()) {
9104     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9105         RHS.get()->getType()->hasIntegerRepresentation())
9106       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9107                         /*AllowBothBool*/true,
9108                         /*AllowBoolConversions*/getLangOpts().ZVector);
9109     return InvalidOperands(Loc, LHS, RHS);
9110   }
9111 
9112   ExprResult LHSResult = LHS, RHSResult = RHS;
9113   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9114                                                  IsCompAssign);
9115   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9116     return QualType();
9117   LHS = LHSResult.get();
9118   RHS = RHSResult.get();
9119 
9120   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9121     return compType;
9122   return InvalidOperands(Loc, LHS, RHS);
9123 }
9124 
9125 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
9126   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
9127 
9128   // Check vector operands differently.
9129   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9130     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9131 
9132   // Diagnose cases where the user write a logical and/or but probably meant a
9133   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9134   // is a constant.
9135   if (LHS.get()->getType()->isIntegerType() &&
9136       !LHS.get()->getType()->isBooleanType() &&
9137       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9138       // Don't warn in macros or template instantiations.
9139       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9140     // If the RHS can be constant folded, and if it constant folds to something
9141     // that isn't 0 or 1 (which indicate a potential logical operation that
9142     // happened to fold to true/false) then warn.
9143     // Parens on the RHS are ignored.
9144     llvm::APSInt Result;
9145     if (RHS.get()->EvaluateAsInt(Result, Context))
9146       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9147            !RHS.get()->getExprLoc().isMacroID()) ||
9148           (Result != 0 && Result != 1)) {
9149         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9150           << RHS.get()->getSourceRange()
9151           << (Opc == BO_LAnd ? "&&" : "||");
9152         // Suggest replacing the logical operator with the bitwise version
9153         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9154             << (Opc == BO_LAnd ? "&" : "|")
9155             << FixItHint::CreateReplacement(SourceRange(
9156                                                  Loc, getLocForEndOfToken(Loc)),
9157                                             Opc == BO_LAnd ? "&" : "|");
9158         if (Opc == BO_LAnd)
9159           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9160           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9161               << FixItHint::CreateRemoval(
9162                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9163                               RHS.get()->getLocEnd()));
9164       }
9165   }
9166 
9167   if (!Context.getLangOpts().CPlusPlus) {
9168     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9169     // not operate on the built-in scalar and vector float types.
9170     if (Context.getLangOpts().OpenCL &&
9171         Context.getLangOpts().OpenCLVersion < 120) {
9172       if (LHS.get()->getType()->isFloatingType() ||
9173           RHS.get()->getType()->isFloatingType())
9174         return InvalidOperands(Loc, LHS, RHS);
9175     }
9176 
9177     LHS = UsualUnaryConversions(LHS.get());
9178     if (LHS.isInvalid())
9179       return QualType();
9180 
9181     RHS = UsualUnaryConversions(RHS.get());
9182     if (RHS.isInvalid())
9183       return QualType();
9184 
9185     if (!LHS.get()->getType()->isScalarType() ||
9186         !RHS.get()->getType()->isScalarType())
9187       return InvalidOperands(Loc, LHS, RHS);
9188 
9189     return Context.IntTy;
9190   }
9191 
9192   // The following is safe because we only use this method for
9193   // non-overloadable operands.
9194 
9195   // C++ [expr.log.and]p1
9196   // C++ [expr.log.or]p1
9197   // The operands are both contextually converted to type bool.
9198   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9199   if (LHSRes.isInvalid())
9200     return InvalidOperands(Loc, LHS, RHS);
9201   LHS = LHSRes;
9202 
9203   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9204   if (RHSRes.isInvalid())
9205     return InvalidOperands(Loc, LHS, RHS);
9206   RHS = RHSRes;
9207 
9208   // C++ [expr.log.and]p2
9209   // C++ [expr.log.or]p2
9210   // The result is a bool.
9211   return Context.BoolTy;
9212 }
9213 
9214 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9215   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9216   if (!ME) return false;
9217   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9218   ObjCMessageExpr *Base =
9219     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9220   if (!Base) return false;
9221   return Base->getMethodDecl() != nullptr;
9222 }
9223 
9224 /// Is the given expression (which must be 'const') a reference to a
9225 /// variable which was originally non-const, but which has become
9226 /// 'const' due to being captured within a block?
9227 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9228 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9229   assert(E->isLValue() && E->getType().isConstQualified());
9230   E = E->IgnoreParens();
9231 
9232   // Must be a reference to a declaration from an enclosing scope.
9233   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9234   if (!DRE) return NCCK_None;
9235   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9236 
9237   // The declaration must be a variable which is not declared 'const'.
9238   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9239   if (!var) return NCCK_None;
9240   if (var->getType().isConstQualified()) return NCCK_None;
9241   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9242 
9243   // Decide whether the first capture was for a block or a lambda.
9244   DeclContext *DC = S.CurContext, *Prev = nullptr;
9245   while (DC != var->getDeclContext()) {
9246     Prev = DC;
9247     DC = DC->getParent();
9248   }
9249   // Unless we have an init-capture, we've gone one step too far.
9250   if (!var->isInitCapture())
9251     DC = Prev;
9252   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9253 }
9254 
9255 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9256   Ty = Ty.getNonReferenceType();
9257   if (IsDereference && Ty->isPointerType())
9258     Ty = Ty->getPointeeType();
9259   return !Ty.isConstQualified();
9260 }
9261 
9262 /// Emit the "read-only variable not assignable" error and print notes to give
9263 /// more information about why the variable is not assignable, such as pointing
9264 /// to the declaration of a const variable, showing that a method is const, or
9265 /// that the function is returning a const reference.
9266 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9267                                     SourceLocation Loc) {
9268   // Update err_typecheck_assign_const and note_typecheck_assign_const
9269   // when this enum is changed.
9270   enum {
9271     ConstFunction,
9272     ConstVariable,
9273     ConstMember,
9274     ConstMethod,
9275     ConstUnknown,  // Keep as last element
9276   };
9277 
9278   SourceRange ExprRange = E->getSourceRange();
9279 
9280   // Only emit one error on the first const found.  All other consts will emit
9281   // a note to the error.
9282   bool DiagnosticEmitted = false;
9283 
9284   // Track if the current expression is the result of a derefence, and if the
9285   // next checked expression is the result of a derefence.
9286   bool IsDereference = false;
9287   bool NextIsDereference = false;
9288 
9289   // Loop to process MemberExpr chains.
9290   while (true) {
9291     IsDereference = NextIsDereference;
9292     NextIsDereference = false;
9293 
9294     E = E->IgnoreParenImpCasts();
9295     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9296       NextIsDereference = ME->isArrow();
9297       const ValueDecl *VD = ME->getMemberDecl();
9298       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9299         // Mutable fields can be modified even if the class is const.
9300         if (Field->isMutable()) {
9301           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9302           break;
9303         }
9304 
9305         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9306           if (!DiagnosticEmitted) {
9307             S.Diag(Loc, diag::err_typecheck_assign_const)
9308                 << ExprRange << ConstMember << false /*static*/ << Field
9309                 << Field->getType();
9310             DiagnosticEmitted = true;
9311           }
9312           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9313               << ConstMember << false /*static*/ << Field << Field->getType()
9314               << Field->getSourceRange();
9315         }
9316         E = ME->getBase();
9317         continue;
9318       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9319         if (VDecl->getType().isConstQualified()) {
9320           if (!DiagnosticEmitted) {
9321             S.Diag(Loc, diag::err_typecheck_assign_const)
9322                 << ExprRange << ConstMember << true /*static*/ << VDecl
9323                 << VDecl->getType();
9324             DiagnosticEmitted = true;
9325           }
9326           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9327               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9328               << VDecl->getSourceRange();
9329         }
9330         // Static fields do not inherit constness from parents.
9331         break;
9332       }
9333       break;
9334     } // End MemberExpr
9335     break;
9336   }
9337 
9338   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9339     // Function calls
9340     const FunctionDecl *FD = CE->getDirectCallee();
9341     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9342       if (!DiagnosticEmitted) {
9343         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9344                                                       << ConstFunction << FD;
9345         DiagnosticEmitted = true;
9346       }
9347       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9348              diag::note_typecheck_assign_const)
9349           << ConstFunction << FD << FD->getReturnType()
9350           << FD->getReturnTypeSourceRange();
9351     }
9352   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9353     // Point to variable declaration.
9354     if (const ValueDecl *VD = DRE->getDecl()) {
9355       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9356         if (!DiagnosticEmitted) {
9357           S.Diag(Loc, diag::err_typecheck_assign_const)
9358               << ExprRange << ConstVariable << VD << VD->getType();
9359           DiagnosticEmitted = true;
9360         }
9361         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9362             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9363       }
9364     }
9365   } else if (isa<CXXThisExpr>(E)) {
9366     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9367       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9368         if (MD->isConst()) {
9369           if (!DiagnosticEmitted) {
9370             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9371                                                           << ConstMethod << MD;
9372             DiagnosticEmitted = true;
9373           }
9374           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9375               << ConstMethod << MD << MD->getSourceRange();
9376         }
9377       }
9378     }
9379   }
9380 
9381   if (DiagnosticEmitted)
9382     return;
9383 
9384   // Can't determine a more specific message, so display the generic error.
9385   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9386 }
9387 
9388 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9389 /// emit an error and return true.  If so, return false.
9390 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9391   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9392   SourceLocation OrigLoc = Loc;
9393   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9394                                                               &Loc);
9395   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9396     IsLV = Expr::MLV_InvalidMessageExpression;
9397   if (IsLV == Expr::MLV_Valid)
9398     return false;
9399 
9400   unsigned DiagID = 0;
9401   bool NeedType = false;
9402   switch (IsLV) { // C99 6.5.16p2
9403   case Expr::MLV_ConstQualified:
9404     // Use a specialized diagnostic when we're assigning to an object
9405     // from an enclosing function or block.
9406     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9407       if (NCCK == NCCK_Block)
9408         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9409       else
9410         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9411       break;
9412     }
9413 
9414     // In ARC, use some specialized diagnostics for occasions where we
9415     // infer 'const'.  These are always pseudo-strong variables.
9416     if (S.getLangOpts().ObjCAutoRefCount) {
9417       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9418       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9419         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9420 
9421         // Use the normal diagnostic if it's pseudo-__strong but the
9422         // user actually wrote 'const'.
9423         if (var->isARCPseudoStrong() &&
9424             (!var->getTypeSourceInfo() ||
9425              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9426           // There are two pseudo-strong cases:
9427           //  - self
9428           ObjCMethodDecl *method = S.getCurMethodDecl();
9429           if (method && var == method->getSelfDecl())
9430             DiagID = method->isClassMethod()
9431               ? diag::err_typecheck_arc_assign_self_class_method
9432               : diag::err_typecheck_arc_assign_self;
9433 
9434           //  - fast enumeration variables
9435           else
9436             DiagID = diag::err_typecheck_arr_assign_enumeration;
9437 
9438           SourceRange Assign;
9439           if (Loc != OrigLoc)
9440             Assign = SourceRange(OrigLoc, OrigLoc);
9441           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9442           // We need to preserve the AST regardless, so migration tool
9443           // can do its job.
9444           return false;
9445         }
9446       }
9447     }
9448 
9449     // If none of the special cases above are triggered, then this is a
9450     // simple const assignment.
9451     if (DiagID == 0) {
9452       DiagnoseConstAssignment(S, E, Loc);
9453       return true;
9454     }
9455 
9456     break;
9457   case Expr::MLV_ConstAddrSpace:
9458     DiagnoseConstAssignment(S, E, Loc);
9459     return true;
9460   case Expr::MLV_ArrayType:
9461   case Expr::MLV_ArrayTemporary:
9462     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9463     NeedType = true;
9464     break;
9465   case Expr::MLV_NotObjectType:
9466     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9467     NeedType = true;
9468     break;
9469   case Expr::MLV_LValueCast:
9470     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9471     break;
9472   case Expr::MLV_Valid:
9473     llvm_unreachable("did not take early return for MLV_Valid");
9474   case Expr::MLV_InvalidExpression:
9475   case Expr::MLV_MemberFunction:
9476   case Expr::MLV_ClassTemporary:
9477     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9478     break;
9479   case Expr::MLV_IncompleteType:
9480   case Expr::MLV_IncompleteVoidType:
9481     return S.RequireCompleteType(Loc, E->getType(),
9482              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9483   case Expr::MLV_DuplicateVectorComponents:
9484     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9485     break;
9486   case Expr::MLV_NoSetterProperty:
9487     llvm_unreachable("readonly properties should be processed differently");
9488   case Expr::MLV_InvalidMessageExpression:
9489     DiagID = diag::error_readonly_message_assignment;
9490     break;
9491   case Expr::MLV_SubObjCPropertySetting:
9492     DiagID = diag::error_no_subobject_property_setting;
9493     break;
9494   }
9495 
9496   SourceRange Assign;
9497   if (Loc != OrigLoc)
9498     Assign = SourceRange(OrigLoc, OrigLoc);
9499   if (NeedType)
9500     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9501   else
9502     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9503   return true;
9504 }
9505 
9506 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9507                                          SourceLocation Loc,
9508                                          Sema &Sema) {
9509   // C / C++ fields
9510   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9511   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9512   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9513     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9514       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9515   }
9516 
9517   // Objective-C instance variables
9518   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9519   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9520   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9521     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9522     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9523     if (RL && RR && RL->getDecl() == RR->getDecl())
9524       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9525   }
9526 }
9527 
9528 // C99 6.5.16.1
9529 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9530                                        SourceLocation Loc,
9531                                        QualType CompoundType) {
9532   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9533 
9534   // Verify that LHS is a modifiable lvalue, and emit error if not.
9535   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9536     return QualType();
9537 
9538   QualType LHSType = LHSExpr->getType();
9539   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9540                                              CompoundType;
9541   AssignConvertType ConvTy;
9542   if (CompoundType.isNull()) {
9543     Expr *RHSCheck = RHS.get();
9544 
9545     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9546 
9547     QualType LHSTy(LHSType);
9548     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9549     if (RHS.isInvalid())
9550       return QualType();
9551     // Special case of NSObject attributes on c-style pointer types.
9552     if (ConvTy == IncompatiblePointer &&
9553         ((Context.isObjCNSObjectType(LHSType) &&
9554           RHSType->isObjCObjectPointerType()) ||
9555          (Context.isObjCNSObjectType(RHSType) &&
9556           LHSType->isObjCObjectPointerType())))
9557       ConvTy = Compatible;
9558 
9559     if (ConvTy == Compatible &&
9560         LHSType->isObjCObjectType())
9561         Diag(Loc, diag::err_objc_object_assignment)
9562           << LHSType;
9563 
9564     // If the RHS is a unary plus or minus, check to see if they = and + are
9565     // right next to each other.  If so, the user may have typo'd "x =+ 4"
9566     // instead of "x += 4".
9567     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9568       RHSCheck = ICE->getSubExpr();
9569     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
9570       if ((UO->getOpcode() == UO_Plus ||
9571            UO->getOpcode() == UO_Minus) &&
9572           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
9573           // Only if the two operators are exactly adjacent.
9574           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
9575           // And there is a space or other character before the subexpr of the
9576           // unary +/-.  We don't want to warn on "x=-1".
9577           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
9578           UO->getSubExpr()->getLocStart().isFileID()) {
9579         Diag(Loc, diag::warn_not_compound_assign)
9580           << (UO->getOpcode() == UO_Plus ? "+" : "-")
9581           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
9582       }
9583     }
9584 
9585     if (ConvTy == Compatible) {
9586       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9587         // Warn about retain cycles where a block captures the LHS, but
9588         // not if the LHS is a simple variable into which the block is
9589         // being stored...unless that variable can be captured by reference!
9590         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9591         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9592         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9593           checkRetainCycles(LHSExpr, RHS.get());
9594 
9595         // It is safe to assign a weak reference into a strong variable.
9596         // Although this code can still have problems:
9597         //   id x = self.weakProp;
9598         //   id y = self.weakProp;
9599         // we do not warn to warn spuriously when 'x' and 'y' are on separate
9600         // paths through the function. This should be revisited if
9601         // -Wrepeated-use-of-weak is made flow-sensitive.
9602         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9603                              RHS.get()->getLocStart()))
9604           getCurFunction()->markSafeWeakUse(RHS.get());
9605 
9606       } else if (getLangOpts().ObjCAutoRefCount) {
9607         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
9608       }
9609     }
9610   } else {
9611     // Compound assignment "x += y"
9612     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
9613   }
9614 
9615   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
9616                                RHS.get(), AA_Assigning))
9617     return QualType();
9618 
9619   CheckForNullPointerDereference(*this, LHSExpr);
9620 
9621   // C99 6.5.16p3: The type of an assignment expression is the type of the
9622   // left operand unless the left operand has qualified type, in which case
9623   // it is the unqualified version of the type of the left operand.
9624   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9625   // is converted to the type of the assignment expression (above).
9626   // C++ 5.17p1: the type of the assignment expression is that of its left
9627   // operand.
9628   return (getLangOpts().CPlusPlus
9629           ? LHSType : LHSType.getUnqualifiedType());
9630 }
9631 
9632 // C99 6.5.17
9633 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
9634                                    SourceLocation Loc) {
9635   LHS = S.CheckPlaceholderExpr(LHS.get());
9636   RHS = S.CheckPlaceholderExpr(RHS.get());
9637   if (LHS.isInvalid() || RHS.isInvalid())
9638     return QualType();
9639 
9640   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9641   // operands, but not unary promotions.
9642   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
9643 
9644   // So we treat the LHS as a ignored value, and in C++ we allow the
9645   // containing site to determine what should be done with the RHS.
9646   LHS = S.IgnoredValueConversions(LHS.get());
9647   if (LHS.isInvalid())
9648     return QualType();
9649 
9650   S.DiagnoseUnusedExprResult(LHS.get());
9651 
9652   if (!S.getLangOpts().CPlusPlus) {
9653     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
9654     if (RHS.isInvalid())
9655       return QualType();
9656     if (!RHS.get()->getType()->isVoidType())
9657       S.RequireCompleteType(Loc, RHS.get()->getType(),
9658                             diag::err_incomplete_type);
9659   }
9660 
9661   return RHS.get()->getType();
9662 }
9663 
9664 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
9665 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
9666 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
9667                                                ExprValueKind &VK,
9668                                                ExprObjectKind &OK,
9669                                                SourceLocation OpLoc,
9670                                                bool IsInc, bool IsPrefix) {
9671   if (Op->isTypeDependent())
9672     return S.Context.DependentTy;
9673 
9674   QualType ResType = Op->getType();
9675   // Atomic types can be used for increment / decrement where the non-atomic
9676   // versions can, so ignore the _Atomic() specifier for the purpose of
9677   // checking.
9678   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9679     ResType = ResAtomicType->getValueType();
9680 
9681   assert(!ResType.isNull() && "no type for increment/decrement expression");
9682 
9683   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
9684     // Decrement of bool is not allowed.
9685     if (!IsInc) {
9686       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
9687       return QualType();
9688     }
9689     // Increment of bool sets it to true, but is deprecated.
9690     S.Diag(OpLoc, S.getLangOpts().CPlusPlus1z ? diag::ext_increment_bool
9691                                               : diag::warn_increment_bool)
9692       << Op->getSourceRange();
9693   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
9694     // Error on enum increments and decrements in C++ mode
9695     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
9696     return QualType();
9697   } else if (ResType->isRealType()) {
9698     // OK!
9699   } else if (ResType->isPointerType()) {
9700     // C99 6.5.2.4p2, 6.5.6p2
9701     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
9702       return QualType();
9703   } else if (ResType->isObjCObjectPointerType()) {
9704     // On modern runtimes, ObjC pointer arithmetic is forbidden.
9705     // Otherwise, we just need a complete type.
9706     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
9707         checkArithmeticOnObjCPointer(S, OpLoc, Op))
9708       return QualType();
9709   } else if (ResType->isAnyComplexType()) {
9710     // C99 does not support ++/-- on complex types, we allow as an extension.
9711     S.Diag(OpLoc, diag::ext_integer_increment_complex)
9712       << ResType << Op->getSourceRange();
9713   } else if (ResType->isPlaceholderType()) {
9714     ExprResult PR = S.CheckPlaceholderExpr(Op);
9715     if (PR.isInvalid()) return QualType();
9716     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
9717                                           IsInc, IsPrefix);
9718   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
9719     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
9720   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
9721              (ResType->getAs<VectorType>()->getVectorKind() !=
9722               VectorType::AltiVecBool)) {
9723     // The z vector extensions allow ++ and -- for non-bool vectors.
9724   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
9725             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
9726     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
9727   } else {
9728     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
9729       << ResType << int(IsInc) << Op->getSourceRange();
9730     return QualType();
9731   }
9732   // At this point, we know we have a real, complex or pointer type.
9733   // Now make sure the operand is a modifiable lvalue.
9734   if (CheckForModifiableLvalue(Op, OpLoc, S))
9735     return QualType();
9736   // In C++, a prefix increment is the same type as the operand. Otherwise
9737   // (in C or with postfix), the increment is the unqualified type of the
9738   // operand.
9739   if (IsPrefix && S.getLangOpts().CPlusPlus) {
9740     VK = VK_LValue;
9741     OK = Op->getObjectKind();
9742     return ResType;
9743   } else {
9744     VK = VK_RValue;
9745     return ResType.getUnqualifiedType();
9746   }
9747 }
9748 
9749 
9750 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
9751 /// This routine allows us to typecheck complex/recursive expressions
9752 /// where the declaration is needed for type checking. We only need to
9753 /// handle cases when the expression references a function designator
9754 /// or is an lvalue. Here are some examples:
9755 ///  - &(x) => x
9756 ///  - &*****f => f for f a function designator.
9757 ///  - &s.xx => s
9758 ///  - &s.zz[1].yy -> s, if zz is an array
9759 ///  - *(x + 1) -> x, if x is an array
9760 ///  - &"123"[2] -> 0
9761 ///  - & __real__ x -> x
9762 static ValueDecl *getPrimaryDecl(Expr *E) {
9763   switch (E->getStmtClass()) {
9764   case Stmt::DeclRefExprClass:
9765     return cast<DeclRefExpr>(E)->getDecl();
9766   case Stmt::MemberExprClass:
9767     // If this is an arrow operator, the address is an offset from
9768     // the base's value, so the object the base refers to is
9769     // irrelevant.
9770     if (cast<MemberExpr>(E)->isArrow())
9771       return nullptr;
9772     // Otherwise, the expression refers to a part of the base
9773     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
9774   case Stmt::ArraySubscriptExprClass: {
9775     // FIXME: This code shouldn't be necessary!  We should catch the implicit
9776     // promotion of register arrays earlier.
9777     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
9778     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
9779       if (ICE->getSubExpr()->getType()->isArrayType())
9780         return getPrimaryDecl(ICE->getSubExpr());
9781     }
9782     return nullptr;
9783   }
9784   case Stmt::UnaryOperatorClass: {
9785     UnaryOperator *UO = cast<UnaryOperator>(E);
9786 
9787     switch(UO->getOpcode()) {
9788     case UO_Real:
9789     case UO_Imag:
9790     case UO_Extension:
9791       return getPrimaryDecl(UO->getSubExpr());
9792     default:
9793       return nullptr;
9794     }
9795   }
9796   case Stmt::ParenExprClass:
9797     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
9798   case Stmt::ImplicitCastExprClass:
9799     // If the result of an implicit cast is an l-value, we care about
9800     // the sub-expression; otherwise, the result here doesn't matter.
9801     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
9802   default:
9803     return nullptr;
9804   }
9805 }
9806 
9807 namespace {
9808   enum {
9809     AO_Bit_Field = 0,
9810     AO_Vector_Element = 1,
9811     AO_Property_Expansion = 2,
9812     AO_Register_Variable = 3,
9813     AO_No_Error = 4
9814   };
9815 }
9816 /// \brief Diagnose invalid operand for address of operations.
9817 ///
9818 /// \param Type The type of operand which cannot have its address taken.
9819 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9820                                          Expr *E, unsigned Type) {
9821   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9822 }
9823 
9824 /// CheckAddressOfOperand - The operand of & must be either a function
9825 /// designator or an lvalue designating an object. If it is an lvalue, the
9826 /// object cannot be declared with storage class register or be a bit field.
9827 /// Note: The usual conversions are *not* applied to the operand of the &
9828 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
9829 /// In C++, the operand might be an overloaded function name, in which case
9830 /// we allow the '&' but retain the overloaded-function type.
9831 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
9832   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9833     if (PTy->getKind() == BuiltinType::Overload) {
9834       Expr *E = OrigOp.get()->IgnoreParens();
9835       if (!isa<OverloadExpr>(E)) {
9836         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
9837         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
9838           << OrigOp.get()->getSourceRange();
9839         return QualType();
9840       }
9841 
9842       OverloadExpr *Ovl = cast<OverloadExpr>(E);
9843       if (isa<UnresolvedMemberExpr>(Ovl))
9844         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9845           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9846             << OrigOp.get()->getSourceRange();
9847           return QualType();
9848         }
9849 
9850       return Context.OverloadTy;
9851     }
9852 
9853     if (PTy->getKind() == BuiltinType::UnknownAny)
9854       return Context.UnknownAnyTy;
9855 
9856     if (PTy->getKind() == BuiltinType::BoundMember) {
9857       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9858         << OrigOp.get()->getSourceRange();
9859       return QualType();
9860     }
9861 
9862     OrigOp = CheckPlaceholderExpr(OrigOp.get());
9863     if (OrigOp.isInvalid()) return QualType();
9864   }
9865 
9866   if (OrigOp.get()->isTypeDependent())
9867     return Context.DependentTy;
9868 
9869   assert(!OrigOp.get()->getType()->isPlaceholderType());
9870 
9871   // Make sure to ignore parentheses in subsequent checks
9872   Expr *op = OrigOp.get()->IgnoreParens();
9873 
9874   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9875   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9876     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9877     return QualType();
9878   }
9879 
9880   if (getLangOpts().C99) {
9881     // Implement C99-only parts of addressof rules.
9882     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
9883       if (uOp->getOpcode() == UO_Deref)
9884         // Per C99 6.5.3.2, the address of a deref always returns a valid result
9885         // (assuming the deref expression is valid).
9886         return uOp->getSubExpr()->getType();
9887     }
9888     // Technically, there should be a check for array subscript
9889     // expressions here, but the result of one is always an lvalue anyway.
9890   }
9891   ValueDecl *dcl = getPrimaryDecl(op);
9892 
9893   if (auto *FD = dyn_cast_or_null<FunctionDecl>(dcl))
9894     if (!checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
9895                                            op->getLocStart()))
9896       return QualType();
9897 
9898   Expr::LValueClassification lval = op->ClassifyLValue(Context);
9899   unsigned AddressOfError = AO_No_Error;
9900 
9901   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
9902     bool sfinae = (bool)isSFINAEContext();
9903     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9904                                   : diag::ext_typecheck_addrof_temporary)
9905       << op->getType() << op->getSourceRange();
9906     if (sfinae)
9907       return QualType();
9908     // Materialize the temporary as an lvalue so that we can take its address.
9909     OrigOp = op = new (Context)
9910         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
9911   } else if (isa<ObjCSelectorExpr>(op)) {
9912     return Context.getPointerType(op->getType());
9913   } else if (lval == Expr::LV_MemberFunction) {
9914     // If it's an instance method, make a member pointer.
9915     // The expression must have exactly the form &A::foo.
9916 
9917     // If the underlying expression isn't a decl ref, give up.
9918     if (!isa<DeclRefExpr>(op)) {
9919       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9920         << OrigOp.get()->getSourceRange();
9921       return QualType();
9922     }
9923     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9924     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9925 
9926     // The id-expression was parenthesized.
9927     if (OrigOp.get() != DRE) {
9928       Diag(OpLoc, diag::err_parens_pointer_member_function)
9929         << OrigOp.get()->getSourceRange();
9930 
9931     // The method was named without a qualifier.
9932     } else if (!DRE->getQualifier()) {
9933       if (MD->getParent()->getName().empty())
9934         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9935           << op->getSourceRange();
9936       else {
9937         SmallString<32> Str;
9938         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9939         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9940           << op->getSourceRange()
9941           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9942       }
9943     }
9944 
9945     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9946     if (isa<CXXDestructorDecl>(MD))
9947       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9948 
9949     QualType MPTy = Context.getMemberPointerType(
9950         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9951     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9952       RequireCompleteType(OpLoc, MPTy, 0);
9953     return MPTy;
9954   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9955     // C99 6.5.3.2p1
9956     // The operand must be either an l-value or a function designator
9957     if (!op->getType()->isFunctionType()) {
9958       // Use a special diagnostic for loads from property references.
9959       if (isa<PseudoObjectExpr>(op)) {
9960         AddressOfError = AO_Property_Expansion;
9961       } else {
9962         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9963           << op->getType() << op->getSourceRange();
9964         return QualType();
9965       }
9966     }
9967   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9968     // The operand cannot be a bit-field
9969     AddressOfError = AO_Bit_Field;
9970   } else if (op->getObjectKind() == OK_VectorComponent) {
9971     // The operand cannot be an element of a vector
9972     AddressOfError = AO_Vector_Element;
9973   } else if (dcl) { // C99 6.5.3.2p1
9974     // We have an lvalue with a decl. Make sure the decl is not declared
9975     // with the register storage-class specifier.
9976     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9977       // in C++ it is not error to take address of a register
9978       // variable (c++03 7.1.1P3)
9979       if (vd->getStorageClass() == SC_Register &&
9980           !getLangOpts().CPlusPlus) {
9981         AddressOfError = AO_Register_Variable;
9982       }
9983     } else if (isa<MSPropertyDecl>(dcl)) {
9984       AddressOfError = AO_Property_Expansion;
9985     } else if (isa<FunctionTemplateDecl>(dcl)) {
9986       return Context.OverloadTy;
9987     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9988       // Okay: we can take the address of a field.
9989       // Could be a pointer to member, though, if there is an explicit
9990       // scope qualifier for the class.
9991       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9992         DeclContext *Ctx = dcl->getDeclContext();
9993         if (Ctx && Ctx->isRecord()) {
9994           if (dcl->getType()->isReferenceType()) {
9995             Diag(OpLoc,
9996                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9997               << dcl->getDeclName() << dcl->getType();
9998             return QualType();
9999           }
10000 
10001           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
10002             Ctx = Ctx->getParent();
10003 
10004           QualType MPTy = Context.getMemberPointerType(
10005               op->getType(),
10006               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
10007           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
10008             RequireCompleteType(OpLoc, MPTy, 0);
10009           return MPTy;
10010         }
10011       }
10012     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
10013       llvm_unreachable("Unknown/unexpected decl type");
10014   }
10015 
10016   if (AddressOfError != AO_No_Error) {
10017     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
10018     return QualType();
10019   }
10020 
10021   if (lval == Expr::LV_IncompleteVoidType) {
10022     // Taking the address of a void variable is technically illegal, but we
10023     // allow it in cases which are otherwise valid.
10024     // Example: "extern void x; void* y = &x;".
10025     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
10026   }
10027 
10028   // If the operand has type "type", the result has type "pointer to type".
10029   if (op->getType()->isObjCObjectType())
10030     return Context.getObjCObjectPointerType(op->getType());
10031   return Context.getPointerType(op->getType());
10032 }
10033 
10034 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
10035   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
10036   if (!DRE)
10037     return;
10038   const Decl *D = DRE->getDecl();
10039   if (!D)
10040     return;
10041   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10042   if (!Param)
10043     return;
10044   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10045     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10046       return;
10047   if (FunctionScopeInfo *FD = S.getCurFunction())
10048     if (!FD->ModifiedNonNullParams.count(Param))
10049       FD->ModifiedNonNullParams.insert(Param);
10050 }
10051 
10052 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10053 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10054                                         SourceLocation OpLoc) {
10055   if (Op->isTypeDependent())
10056     return S.Context.DependentTy;
10057 
10058   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10059   if (ConvResult.isInvalid())
10060     return QualType();
10061   Op = ConvResult.get();
10062   QualType OpTy = Op->getType();
10063   QualType Result;
10064 
10065   if (isa<CXXReinterpretCastExpr>(Op)) {
10066     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10067     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10068                                      Op->getSourceRange());
10069   }
10070 
10071   if (const PointerType *PT = OpTy->getAs<PointerType>())
10072     Result = PT->getPointeeType();
10073   else if (const ObjCObjectPointerType *OPT =
10074              OpTy->getAs<ObjCObjectPointerType>())
10075     Result = OPT->getPointeeType();
10076   else {
10077     ExprResult PR = S.CheckPlaceholderExpr(Op);
10078     if (PR.isInvalid()) return QualType();
10079     if (PR.get() != Op)
10080       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10081   }
10082 
10083   if (Result.isNull()) {
10084     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10085       << OpTy << Op->getSourceRange();
10086     return QualType();
10087   }
10088 
10089   // Note that per both C89 and C99, indirection is always legal, even if Result
10090   // is an incomplete type or void.  It would be possible to warn about
10091   // dereferencing a void pointer, but it's completely well-defined, and such a
10092   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10093   // for pointers to 'void' but is fine for any other pointer type:
10094   //
10095   // C++ [expr.unary.op]p1:
10096   //   [...] the expression to which [the unary * operator] is applied shall
10097   //   be a pointer to an object type, or a pointer to a function type
10098   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10099     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10100       << OpTy << Op->getSourceRange();
10101 
10102   // Dereferences are usually l-values...
10103   VK = VK_LValue;
10104 
10105   // ...except that certain expressions are never l-values in C.
10106   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10107     VK = VK_RValue;
10108 
10109   return Result;
10110 }
10111 
10112 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10113   BinaryOperatorKind Opc;
10114   switch (Kind) {
10115   default: llvm_unreachable("Unknown binop!");
10116   case tok::periodstar:           Opc = BO_PtrMemD; break;
10117   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10118   case tok::star:                 Opc = BO_Mul; break;
10119   case tok::slash:                Opc = BO_Div; break;
10120   case tok::percent:              Opc = BO_Rem; break;
10121   case tok::plus:                 Opc = BO_Add; break;
10122   case tok::minus:                Opc = BO_Sub; break;
10123   case tok::lessless:             Opc = BO_Shl; break;
10124   case tok::greatergreater:       Opc = BO_Shr; break;
10125   case tok::lessequal:            Opc = BO_LE; break;
10126   case tok::less:                 Opc = BO_LT; break;
10127   case tok::greaterequal:         Opc = BO_GE; break;
10128   case tok::greater:              Opc = BO_GT; break;
10129   case tok::exclaimequal:         Opc = BO_NE; break;
10130   case tok::equalequal:           Opc = BO_EQ; break;
10131   case tok::amp:                  Opc = BO_And; break;
10132   case tok::caret:                Opc = BO_Xor; break;
10133   case tok::pipe:                 Opc = BO_Or; break;
10134   case tok::ampamp:               Opc = BO_LAnd; break;
10135   case tok::pipepipe:             Opc = BO_LOr; break;
10136   case tok::equal:                Opc = BO_Assign; break;
10137   case tok::starequal:            Opc = BO_MulAssign; break;
10138   case tok::slashequal:           Opc = BO_DivAssign; break;
10139   case tok::percentequal:         Opc = BO_RemAssign; break;
10140   case tok::plusequal:            Opc = BO_AddAssign; break;
10141   case tok::minusequal:           Opc = BO_SubAssign; break;
10142   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10143   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10144   case tok::ampequal:             Opc = BO_AndAssign; break;
10145   case tok::caretequal:           Opc = BO_XorAssign; break;
10146   case tok::pipeequal:            Opc = BO_OrAssign; break;
10147   case tok::comma:                Opc = BO_Comma; break;
10148   }
10149   return Opc;
10150 }
10151 
10152 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10153   tok::TokenKind Kind) {
10154   UnaryOperatorKind Opc;
10155   switch (Kind) {
10156   default: llvm_unreachable("Unknown unary op!");
10157   case tok::plusplus:     Opc = UO_PreInc; break;
10158   case tok::minusminus:   Opc = UO_PreDec; break;
10159   case tok::amp:          Opc = UO_AddrOf; break;
10160   case tok::star:         Opc = UO_Deref; break;
10161   case tok::plus:         Opc = UO_Plus; break;
10162   case tok::minus:        Opc = UO_Minus; break;
10163   case tok::tilde:        Opc = UO_Not; break;
10164   case tok::exclaim:      Opc = UO_LNot; break;
10165   case tok::kw___real:    Opc = UO_Real; break;
10166   case tok::kw___imag:    Opc = UO_Imag; break;
10167   case tok::kw___extension__: Opc = UO_Extension; break;
10168   }
10169   return Opc;
10170 }
10171 
10172 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10173 /// This warning is only emitted for builtin assignment operations. It is also
10174 /// suppressed in the event of macro expansions.
10175 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10176                                    SourceLocation OpLoc) {
10177   if (!S.ActiveTemplateInstantiations.empty())
10178     return;
10179   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10180     return;
10181   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10182   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10183   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10184   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10185   if (!LHSDeclRef || !RHSDeclRef ||
10186       LHSDeclRef->getLocation().isMacroID() ||
10187       RHSDeclRef->getLocation().isMacroID())
10188     return;
10189   const ValueDecl *LHSDecl =
10190     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10191   const ValueDecl *RHSDecl =
10192     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10193   if (LHSDecl != RHSDecl)
10194     return;
10195   if (LHSDecl->getType().isVolatileQualified())
10196     return;
10197   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10198     if (RefTy->getPointeeType().isVolatileQualified())
10199       return;
10200 
10201   S.Diag(OpLoc, diag::warn_self_assignment)
10202       << LHSDeclRef->getType()
10203       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10204 }
10205 
10206 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10207 /// is usually indicative of introspection within the Objective-C pointer.
10208 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10209                                           SourceLocation OpLoc) {
10210   if (!S.getLangOpts().ObjC1)
10211     return;
10212 
10213   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10214   const Expr *LHS = L.get();
10215   const Expr *RHS = R.get();
10216 
10217   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10218     ObjCPointerExpr = LHS;
10219     OtherExpr = RHS;
10220   }
10221   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10222     ObjCPointerExpr = RHS;
10223     OtherExpr = LHS;
10224   }
10225 
10226   // This warning is deliberately made very specific to reduce false
10227   // positives with logic that uses '&' for hashing.  This logic mainly
10228   // looks for code trying to introspect into tagged pointers, which
10229   // code should generally never do.
10230   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10231     unsigned Diag = diag::warn_objc_pointer_masking;
10232     // Determine if we are introspecting the result of performSelectorXXX.
10233     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10234     // Special case messages to -performSelector and friends, which
10235     // can return non-pointer values boxed in a pointer value.
10236     // Some clients may wish to silence warnings in this subcase.
10237     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10238       Selector S = ME->getSelector();
10239       StringRef SelArg0 = S.getNameForSlot(0);
10240       if (SelArg0.startswith("performSelector"))
10241         Diag = diag::warn_objc_pointer_masking_performSelector;
10242     }
10243 
10244     S.Diag(OpLoc, Diag)
10245       << ObjCPointerExpr->getSourceRange();
10246   }
10247 }
10248 
10249 static NamedDecl *getDeclFromExpr(Expr *E) {
10250   if (!E)
10251     return nullptr;
10252   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10253     return DRE->getDecl();
10254   if (auto *ME = dyn_cast<MemberExpr>(E))
10255     return ME->getMemberDecl();
10256   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10257     return IRE->getDecl();
10258   return nullptr;
10259 }
10260 
10261 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10262 /// operator @p Opc at location @c TokLoc. This routine only supports
10263 /// built-in operations; ActOnBinOp handles overloaded operators.
10264 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10265                                     BinaryOperatorKind Opc,
10266                                     Expr *LHSExpr, Expr *RHSExpr) {
10267   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10268     // The syntax only allows initializer lists on the RHS of assignment,
10269     // so we don't need to worry about accepting invalid code for
10270     // non-assignment operators.
10271     // C++11 5.17p9:
10272     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10273     //   of x = {} is x = T().
10274     InitializationKind Kind =
10275         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10276     InitializedEntity Entity =
10277         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10278     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10279     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10280     if (Init.isInvalid())
10281       return Init;
10282     RHSExpr = Init.get();
10283   }
10284 
10285   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10286   QualType ResultTy;     // Result type of the binary operator.
10287   // The following two variables are used for compound assignment operators
10288   QualType CompLHSTy;    // Type of LHS after promotions for computation
10289   QualType CompResultTy; // Type of computation result
10290   ExprValueKind VK = VK_RValue;
10291   ExprObjectKind OK = OK_Ordinary;
10292 
10293   if (!getLangOpts().CPlusPlus) {
10294     // C cannot handle TypoExpr nodes on either side of a binop because it
10295     // doesn't handle dependent types properly, so make sure any TypoExprs have
10296     // been dealt with before checking the operands.
10297     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10298     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10299       if (Opc != BO_Assign)
10300         return ExprResult(E);
10301       // Avoid correcting the RHS to the same Expr as the LHS.
10302       Decl *D = getDeclFromExpr(E);
10303       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10304     });
10305     if (!LHS.isUsable() || !RHS.isUsable())
10306       return ExprError();
10307   }
10308 
10309   if (getLangOpts().OpenCL) {
10310     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10311     // the ATOMIC_VAR_INIT macro.
10312     if (LHSExpr->getType()->isAtomicType() ||
10313         RHSExpr->getType()->isAtomicType()) {
10314       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10315       if (BO_Assign == Opc)
10316         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10317       else
10318         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10319       return ExprError();
10320     }
10321   }
10322 
10323   switch (Opc) {
10324   case BO_Assign:
10325     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10326     if (getLangOpts().CPlusPlus &&
10327         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10328       VK = LHS.get()->getValueKind();
10329       OK = LHS.get()->getObjectKind();
10330     }
10331     if (!ResultTy.isNull()) {
10332       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10333       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10334     }
10335     RecordModifiableNonNullParam(*this, LHS.get());
10336     break;
10337   case BO_PtrMemD:
10338   case BO_PtrMemI:
10339     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10340                                             Opc == BO_PtrMemI);
10341     break;
10342   case BO_Mul:
10343   case BO_Div:
10344     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10345                                            Opc == BO_Div);
10346     break;
10347   case BO_Rem:
10348     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10349     break;
10350   case BO_Add:
10351     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10352     break;
10353   case BO_Sub:
10354     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10355     break;
10356   case BO_Shl:
10357   case BO_Shr:
10358     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10359     break;
10360   case BO_LE:
10361   case BO_LT:
10362   case BO_GE:
10363   case BO_GT:
10364     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10365     break;
10366   case BO_EQ:
10367   case BO_NE:
10368     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10369     break;
10370   case BO_And:
10371     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10372   case BO_Xor:
10373   case BO_Or:
10374     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10375     break;
10376   case BO_LAnd:
10377   case BO_LOr:
10378     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10379     break;
10380   case BO_MulAssign:
10381   case BO_DivAssign:
10382     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10383                                                Opc == BO_DivAssign);
10384     CompLHSTy = CompResultTy;
10385     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10386       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10387     break;
10388   case BO_RemAssign:
10389     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10390     CompLHSTy = CompResultTy;
10391     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10392       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10393     break;
10394   case BO_AddAssign:
10395     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10396     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10397       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10398     break;
10399   case BO_SubAssign:
10400     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10401     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10402       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10403     break;
10404   case BO_ShlAssign:
10405   case BO_ShrAssign:
10406     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10407     CompLHSTy = CompResultTy;
10408     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10409       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10410     break;
10411   case BO_AndAssign:
10412   case BO_OrAssign: // fallthrough
10413 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10414   case BO_XorAssign:
10415     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10416     CompLHSTy = CompResultTy;
10417     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10418       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10419     break;
10420   case BO_Comma:
10421     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10422     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10423       VK = RHS.get()->getValueKind();
10424       OK = RHS.get()->getObjectKind();
10425     }
10426     break;
10427   }
10428   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10429     return ExprError();
10430 
10431   // Check for array bounds violations for both sides of the BinaryOperator
10432   CheckArrayAccess(LHS.get());
10433   CheckArrayAccess(RHS.get());
10434 
10435   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10436     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10437                                                  &Context.Idents.get("object_setClass"),
10438                                                  SourceLocation(), LookupOrdinaryName);
10439     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10440       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10441       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10442       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10443       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10444       FixItHint::CreateInsertion(RHSLocEnd, ")");
10445     }
10446     else
10447       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10448   }
10449   else if (const ObjCIvarRefExpr *OIRE =
10450            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10451     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10452 
10453   if (CompResultTy.isNull())
10454     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10455                                         OK, OpLoc, FPFeatures.fp_contract);
10456   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10457       OK_ObjCProperty) {
10458     VK = VK_LValue;
10459     OK = LHS.get()->getObjectKind();
10460   }
10461   return new (Context) CompoundAssignOperator(
10462       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10463       OpLoc, FPFeatures.fp_contract);
10464 }
10465 
10466 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10467 /// operators are mixed in a way that suggests that the programmer forgot that
10468 /// comparison operators have higher precedence. The most typical example of
10469 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
10470 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10471                                       SourceLocation OpLoc, Expr *LHSExpr,
10472                                       Expr *RHSExpr) {
10473   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10474   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10475 
10476   // Check that one of the sides is a comparison operator.
10477   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10478   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10479   if (!isLeftComp && !isRightComp)
10480     return;
10481 
10482   // Bitwise operations are sometimes used as eager logical ops.
10483   // Don't diagnose this.
10484   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10485   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10486   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
10487     return;
10488 
10489   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10490                                                    OpLoc)
10491                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
10492   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
10493   SourceRange ParensRange = isLeftComp ?
10494       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
10495     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
10496 
10497   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
10498     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
10499   SuggestParentheses(Self, OpLoc,
10500     Self.PDiag(diag::note_precedence_silence) << OpStr,
10501     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
10502   SuggestParentheses(Self, OpLoc,
10503     Self.PDiag(diag::note_precedence_bitwise_first)
10504       << BinaryOperator::getOpcodeStr(Opc),
10505     ParensRange);
10506 }
10507 
10508 /// \brief It accepts a '&' expr that is inside a '|' one.
10509 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
10510 /// in parentheses.
10511 static void
10512 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
10513                                        BinaryOperator *Bop) {
10514   assert(Bop->getOpcode() == BO_And);
10515   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
10516       << Bop->getSourceRange() << OpLoc;
10517   SuggestParentheses(Self, Bop->getOperatorLoc(),
10518     Self.PDiag(diag::note_precedence_silence)
10519       << Bop->getOpcodeStr(),
10520     Bop->getSourceRange());
10521 }
10522 
10523 /// \brief It accepts a '&&' expr that is inside a '||' one.
10524 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10525 /// in parentheses.
10526 static void
10527 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
10528                                        BinaryOperator *Bop) {
10529   assert(Bop->getOpcode() == BO_LAnd);
10530   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10531       << Bop->getSourceRange() << OpLoc;
10532   SuggestParentheses(Self, Bop->getOperatorLoc(),
10533     Self.PDiag(diag::note_precedence_silence)
10534       << Bop->getOpcodeStr(),
10535     Bop->getSourceRange());
10536 }
10537 
10538 /// \brief Returns true if the given expression can be evaluated as a constant
10539 /// 'true'.
10540 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10541   bool Res;
10542   return !E->isValueDependent() &&
10543          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
10544 }
10545 
10546 /// \brief Returns true if the given expression can be evaluated as a constant
10547 /// 'false'.
10548 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10549   bool Res;
10550   return !E->isValueDependent() &&
10551          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
10552 }
10553 
10554 /// \brief Look for '&&' in the left hand of a '||' expr.
10555 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
10556                                              Expr *LHSExpr, Expr *RHSExpr) {
10557   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
10558     if (Bop->getOpcode() == BO_LAnd) {
10559       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
10560       if (EvaluatesAsFalse(S, RHSExpr))
10561         return;
10562       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10563       if (!EvaluatesAsTrue(S, Bop->getLHS()))
10564         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10565     } else if (Bop->getOpcode() == BO_LOr) {
10566       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10567         // If it's "a || b && 1 || c" we didn't warn earlier for
10568         // "a || b && 1", but warn now.
10569         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10570           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10571       }
10572     }
10573   }
10574 }
10575 
10576 /// \brief Look for '&&' in the right hand of a '||' expr.
10577 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
10578                                              Expr *LHSExpr, Expr *RHSExpr) {
10579   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
10580     if (Bop->getOpcode() == BO_LAnd) {
10581       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
10582       if (EvaluatesAsFalse(S, LHSExpr))
10583         return;
10584       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10585       if (!EvaluatesAsTrue(S, Bop->getRHS()))
10586         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10587     }
10588   }
10589 }
10590 
10591 /// \brief Look for '&' in the left or right hand of a '|' expr.
10592 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
10593                                              Expr *OrArg) {
10594   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
10595     if (Bop->getOpcode() == BO_And)
10596       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
10597   }
10598 }
10599 
10600 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
10601                                     Expr *SubExpr, StringRef Shift) {
10602   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10603     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
10604       StringRef Op = Bop->getOpcodeStr();
10605       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
10606           << Bop->getSourceRange() << OpLoc << Shift << Op;
10607       SuggestParentheses(S, Bop->getOperatorLoc(),
10608           S.PDiag(diag::note_precedence_silence) << Op,
10609           Bop->getSourceRange());
10610     }
10611   }
10612 }
10613 
10614 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10615                                  Expr *LHSExpr, Expr *RHSExpr) {
10616   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10617   if (!OCE)
10618     return;
10619 
10620   FunctionDecl *FD = OCE->getDirectCallee();
10621   if (!FD || !FD->isOverloadedOperator())
10622     return;
10623 
10624   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10625   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10626     return;
10627 
10628   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10629       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10630       << (Kind == OO_LessLess);
10631   SuggestParentheses(S, OCE->getOperatorLoc(),
10632                      S.PDiag(diag::note_precedence_silence)
10633                          << (Kind == OO_LessLess ? "<<" : ">>"),
10634                      OCE->getSourceRange());
10635   SuggestParentheses(S, OpLoc,
10636                      S.PDiag(diag::note_evaluate_comparison_first),
10637                      SourceRange(OCE->getArg(1)->getLocStart(),
10638                                  RHSExpr->getLocEnd()));
10639 }
10640 
10641 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
10642 /// precedence.
10643 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
10644                                     SourceLocation OpLoc, Expr *LHSExpr,
10645                                     Expr *RHSExpr){
10646   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
10647   if (BinaryOperator::isBitwiseOp(Opc))
10648     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
10649 
10650   // Diagnose "arg1 & arg2 | arg3"
10651   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10652     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
10653     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
10654   }
10655 
10656   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
10657   // We don't warn for 'assert(a || b && "bad")' since this is safe.
10658   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10659     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
10660     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
10661   }
10662 
10663   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
10664       || Opc == BO_Shr) {
10665     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
10666     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
10667     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
10668   }
10669 
10670   // Warn on overloaded shift operators and comparisons, such as:
10671   // cout << 5 == 4;
10672   if (BinaryOperator::isComparisonOp(Opc))
10673     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
10674 }
10675 
10676 // Binary Operators.  'Tok' is the token for the operator.
10677 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
10678                             tok::TokenKind Kind,
10679                             Expr *LHSExpr, Expr *RHSExpr) {
10680   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
10681   assert(LHSExpr && "ActOnBinOp(): missing left expression");
10682   assert(RHSExpr && "ActOnBinOp(): missing right expression");
10683 
10684   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
10685   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
10686 
10687   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
10688 }
10689 
10690 /// Build an overloaded binary operator expression in the given scope.
10691 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
10692                                        BinaryOperatorKind Opc,
10693                                        Expr *LHS, Expr *RHS) {
10694   // Find all of the overloaded operators visible from this
10695   // point. We perform both an operator-name lookup from the local
10696   // scope and an argument-dependent lookup based on the types of
10697   // the arguments.
10698   UnresolvedSet<16> Functions;
10699   OverloadedOperatorKind OverOp
10700     = BinaryOperator::getOverloadedOperator(Opc);
10701   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
10702     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
10703                                    RHS->getType(), Functions);
10704 
10705   // Build the (potentially-overloaded, potentially-dependent)
10706   // binary operation.
10707   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
10708 }
10709 
10710 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
10711                             BinaryOperatorKind Opc,
10712                             Expr *LHSExpr, Expr *RHSExpr) {
10713   // We want to end up calling one of checkPseudoObjectAssignment
10714   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
10715   // both expressions are overloadable or either is type-dependent),
10716   // or CreateBuiltinBinOp (in any other case).  We also want to get
10717   // any placeholder types out of the way.
10718 
10719   // Handle pseudo-objects in the LHS.
10720   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
10721     // Assignments with a pseudo-object l-value need special analysis.
10722     if (pty->getKind() == BuiltinType::PseudoObject &&
10723         BinaryOperator::isAssignmentOp(Opc))
10724       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
10725 
10726     // Don't resolve overloads if the other type is overloadable.
10727     if (pty->getKind() == BuiltinType::Overload) {
10728       // We can't actually test that if we still have a placeholder,
10729       // though.  Fortunately, none of the exceptions we see in that
10730       // code below are valid when the LHS is an overload set.  Note
10731       // that an overload set can be dependently-typed, but it never
10732       // instantiates to having an overloadable type.
10733       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10734       if (resolvedRHS.isInvalid()) return ExprError();
10735       RHSExpr = resolvedRHS.get();
10736 
10737       if (RHSExpr->isTypeDependent() ||
10738           RHSExpr->getType()->isOverloadableType())
10739         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10740     }
10741 
10742     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
10743     if (LHS.isInvalid()) return ExprError();
10744     LHSExpr = LHS.get();
10745   }
10746 
10747   // Handle pseudo-objects in the RHS.
10748   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
10749     // An overload in the RHS can potentially be resolved by the type
10750     // being assigned to.
10751     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
10752       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10753         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10754 
10755       if (LHSExpr->getType()->isOverloadableType())
10756         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10757 
10758       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10759     }
10760 
10761     // Don't resolve overloads if the other type is overloadable.
10762     if (pty->getKind() == BuiltinType::Overload &&
10763         LHSExpr->getType()->isOverloadableType())
10764       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10765 
10766     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10767     if (!resolvedRHS.isUsable()) return ExprError();
10768     RHSExpr = resolvedRHS.get();
10769   }
10770 
10771   if (getLangOpts().CPlusPlus) {
10772     // If either expression is type-dependent, always build an
10773     // overloaded op.
10774     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10775       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10776 
10777     // Otherwise, build an overloaded op if either expression has an
10778     // overloadable type.
10779     if (LHSExpr->getType()->isOverloadableType() ||
10780         RHSExpr->getType()->isOverloadableType())
10781       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10782   }
10783 
10784   // Build a built-in binary operation.
10785   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10786 }
10787 
10788 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
10789                                       UnaryOperatorKind Opc,
10790                                       Expr *InputExpr) {
10791   ExprResult Input = InputExpr;
10792   ExprValueKind VK = VK_RValue;
10793   ExprObjectKind OK = OK_Ordinary;
10794   QualType resultType;
10795   if (getLangOpts().OpenCL) {
10796     // The only legal unary operation for atomics is '&'.
10797     if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
10798       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10799                        << InputExpr->getType()
10800                        << Input.get()->getSourceRange());
10801     }
10802   }
10803   switch (Opc) {
10804   case UO_PreInc:
10805   case UO_PreDec:
10806   case UO_PostInc:
10807   case UO_PostDec:
10808     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
10809                                                 OpLoc,
10810                                                 Opc == UO_PreInc ||
10811                                                 Opc == UO_PostInc,
10812                                                 Opc == UO_PreInc ||
10813                                                 Opc == UO_PreDec);
10814     break;
10815   case UO_AddrOf:
10816     resultType = CheckAddressOfOperand(Input, OpLoc);
10817     RecordModifiableNonNullParam(*this, InputExpr);
10818     break;
10819   case UO_Deref: {
10820     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10821     if (Input.isInvalid()) return ExprError();
10822     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
10823     break;
10824   }
10825   case UO_Plus:
10826   case UO_Minus:
10827     Input = UsualUnaryConversions(Input.get());
10828     if (Input.isInvalid()) return ExprError();
10829     resultType = Input.get()->getType();
10830     if (resultType->isDependentType())
10831       break;
10832     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
10833       break;
10834     else if (resultType->isVectorType() &&
10835              // The z vector extensions don't allow + or - with bool vectors.
10836              (!Context.getLangOpts().ZVector ||
10837               resultType->getAs<VectorType>()->getVectorKind() !=
10838               VectorType::AltiVecBool))
10839       break;
10840     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
10841              Opc == UO_Plus &&
10842              resultType->isPointerType())
10843       break;
10844 
10845     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10846       << resultType << Input.get()->getSourceRange());
10847 
10848   case UO_Not: // bitwise complement
10849     Input = UsualUnaryConversions(Input.get());
10850     if (Input.isInvalid())
10851       return ExprError();
10852     resultType = Input.get()->getType();
10853     if (resultType->isDependentType())
10854       break;
10855     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
10856     if (resultType->isComplexType() || resultType->isComplexIntegerType())
10857       // C99 does not support '~' for complex conjugation.
10858       Diag(OpLoc, diag::ext_integer_complement_complex)
10859           << resultType << Input.get()->getSourceRange();
10860     else if (resultType->hasIntegerRepresentation())
10861       break;
10862     else if (resultType->isExtVectorType()) {
10863       if (Context.getLangOpts().OpenCL) {
10864         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
10865         // on vector float types.
10866         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10867         if (!T->isIntegerType())
10868           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10869                            << resultType << Input.get()->getSourceRange());
10870       }
10871       break;
10872     } else {
10873       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10874                        << resultType << Input.get()->getSourceRange());
10875     }
10876     break;
10877 
10878   case UO_LNot: // logical negation
10879     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
10880     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10881     if (Input.isInvalid()) return ExprError();
10882     resultType = Input.get()->getType();
10883 
10884     // Though we still have to promote half FP to float...
10885     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
10886       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
10887       resultType = Context.FloatTy;
10888     }
10889 
10890     if (resultType->isDependentType())
10891       break;
10892     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
10893       // C99 6.5.3.3p1: ok, fallthrough;
10894       if (Context.getLangOpts().CPlusPlus) {
10895         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10896         // operand contextually converted to bool.
10897         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
10898                                   ScalarTypeToBooleanCastKind(resultType));
10899       } else if (Context.getLangOpts().OpenCL &&
10900                  Context.getLangOpts().OpenCLVersion < 120) {
10901         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10902         // operate on scalar float types.
10903         if (!resultType->isIntegerType())
10904           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10905                            << resultType << Input.get()->getSourceRange());
10906       }
10907     } else if (resultType->isExtVectorType()) {
10908       if (Context.getLangOpts().OpenCL &&
10909           Context.getLangOpts().OpenCLVersion < 120) {
10910         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10911         // operate on vector float types.
10912         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10913         if (!T->isIntegerType())
10914           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10915                            << resultType << Input.get()->getSourceRange());
10916       }
10917       // Vector logical not returns the signed variant of the operand type.
10918       resultType = GetSignedVectorType(resultType);
10919       break;
10920     } else {
10921       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10922         << resultType << Input.get()->getSourceRange());
10923     }
10924 
10925     // LNot always has type int. C99 6.5.3.3p5.
10926     // In C++, it's bool. C++ 5.3.1p8
10927     resultType = Context.getLogicalOperationType();
10928     break;
10929   case UO_Real:
10930   case UO_Imag:
10931     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
10932     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10933     // complex l-values to ordinary l-values and all other values to r-values.
10934     if (Input.isInvalid()) return ExprError();
10935     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10936       if (Input.get()->getValueKind() != VK_RValue &&
10937           Input.get()->getObjectKind() == OK_Ordinary)
10938         VK = Input.get()->getValueKind();
10939     } else if (!getLangOpts().CPlusPlus) {
10940       // In C, a volatile scalar is read by __imag. In C++, it is not.
10941       Input = DefaultLvalueConversion(Input.get());
10942     }
10943     break;
10944   case UO_Extension:
10945   case UO_Coawait:
10946     resultType = Input.get()->getType();
10947     VK = Input.get()->getValueKind();
10948     OK = Input.get()->getObjectKind();
10949     break;
10950   }
10951   if (resultType.isNull() || Input.isInvalid())
10952     return ExprError();
10953 
10954   // Check for array bounds violations in the operand of the UnaryOperator,
10955   // except for the '*' and '&' operators that have to be handled specially
10956   // by CheckArrayAccess (as there are special cases like &array[arraysize]
10957   // that are explicitly defined as valid by the standard).
10958   if (Opc != UO_AddrOf && Opc != UO_Deref)
10959     CheckArrayAccess(Input.get());
10960 
10961   return new (Context)
10962       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
10963 }
10964 
10965 /// \brief Determine whether the given expression is a qualified member
10966 /// access expression, of a form that could be turned into a pointer to member
10967 /// with the address-of operator.
10968 static bool isQualifiedMemberAccess(Expr *E) {
10969   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10970     if (!DRE->getQualifier())
10971       return false;
10972 
10973     ValueDecl *VD = DRE->getDecl();
10974     if (!VD->isCXXClassMember())
10975       return false;
10976 
10977     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10978       return true;
10979     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10980       return Method->isInstance();
10981 
10982     return false;
10983   }
10984 
10985   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10986     if (!ULE->getQualifier())
10987       return false;
10988 
10989     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10990                                            DEnd = ULE->decls_end();
10991          D != DEnd; ++D) {
10992       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10993         if (Method->isInstance())
10994           return true;
10995       } else {
10996         // Overload set does not contain methods.
10997         break;
10998       }
10999     }
11000 
11001     return false;
11002   }
11003 
11004   return false;
11005 }
11006 
11007 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
11008                               UnaryOperatorKind Opc, Expr *Input) {
11009   // First things first: handle placeholders so that the
11010   // overloaded-operator check considers the right type.
11011   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
11012     // Increment and decrement of pseudo-object references.
11013     if (pty->getKind() == BuiltinType::PseudoObject &&
11014         UnaryOperator::isIncrementDecrementOp(Opc))
11015       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
11016 
11017     // extension is always a builtin operator.
11018     if (Opc == UO_Extension)
11019       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11020 
11021     // & gets special logic for several kinds of placeholder.
11022     // The builtin code knows what to do.
11023     if (Opc == UO_AddrOf &&
11024         (pty->getKind() == BuiltinType::Overload ||
11025          pty->getKind() == BuiltinType::UnknownAny ||
11026          pty->getKind() == BuiltinType::BoundMember))
11027       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11028 
11029     // Anything else needs to be handled now.
11030     ExprResult Result = CheckPlaceholderExpr(Input);
11031     if (Result.isInvalid()) return ExprError();
11032     Input = Result.get();
11033   }
11034 
11035   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
11036       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
11037       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
11038     // Find all of the overloaded operators visible from this
11039     // point. We perform both an operator-name lookup from the local
11040     // scope and an argument-dependent lookup based on the types of
11041     // the arguments.
11042     UnresolvedSet<16> Functions;
11043     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11044     if (S && OverOp != OO_None)
11045       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11046                                    Functions);
11047 
11048     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11049   }
11050 
11051   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11052 }
11053 
11054 // Unary Operators.  'Tok' is the token for the operator.
11055 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11056                               tok::TokenKind Op, Expr *Input) {
11057   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11058 }
11059 
11060 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11061 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11062                                 LabelDecl *TheDecl) {
11063   TheDecl->markUsed(Context);
11064   // Create the AST node.  The address of a label always has type 'void*'.
11065   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11066                                      Context.getPointerType(Context.VoidTy));
11067 }
11068 
11069 /// Given the last statement in a statement-expression, check whether
11070 /// the result is a producing expression (like a call to an
11071 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11072 /// release out of the full-expression.  Otherwise, return null.
11073 /// Cannot fail.
11074 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11075   // Should always be wrapped with one of these.
11076   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11077   if (!cleanups) return nullptr;
11078 
11079   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11080   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11081     return nullptr;
11082 
11083   // Splice out the cast.  This shouldn't modify any interesting
11084   // features of the statement.
11085   Expr *producer = cast->getSubExpr();
11086   assert(producer->getType() == cast->getType());
11087   assert(producer->getValueKind() == cast->getValueKind());
11088   cleanups->setSubExpr(producer);
11089   return cleanups;
11090 }
11091 
11092 void Sema::ActOnStartStmtExpr() {
11093   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11094 }
11095 
11096 void Sema::ActOnStmtExprError() {
11097   // Note that function is also called by TreeTransform when leaving a
11098   // StmtExpr scope without rebuilding anything.
11099 
11100   DiscardCleanupsInEvaluationContext();
11101   PopExpressionEvaluationContext();
11102 }
11103 
11104 ExprResult
11105 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11106                     SourceLocation RPLoc) { // "({..})"
11107   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11108   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11109 
11110   if (hasAnyUnrecoverableErrorsInThisFunction())
11111     DiscardCleanupsInEvaluationContext();
11112   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
11113   PopExpressionEvaluationContext();
11114 
11115   // FIXME: there are a variety of strange constraints to enforce here, for
11116   // example, it is not possible to goto into a stmt expression apparently.
11117   // More semantic analysis is needed.
11118 
11119   // If there are sub-stmts in the compound stmt, take the type of the last one
11120   // as the type of the stmtexpr.
11121   QualType Ty = Context.VoidTy;
11122   bool StmtExprMayBindToTemp = false;
11123   if (!Compound->body_empty()) {
11124     Stmt *LastStmt = Compound->body_back();
11125     LabelStmt *LastLabelStmt = nullptr;
11126     // If LastStmt is a label, skip down through into the body.
11127     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11128       LastLabelStmt = Label;
11129       LastStmt = Label->getSubStmt();
11130     }
11131 
11132     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11133       // Do function/array conversion on the last expression, but not
11134       // lvalue-to-rvalue.  However, initialize an unqualified type.
11135       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11136       if (LastExpr.isInvalid())
11137         return ExprError();
11138       Ty = LastExpr.get()->getType().getUnqualifiedType();
11139 
11140       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11141         // In ARC, if the final expression ends in a consume, splice
11142         // the consume out and bind it later.  In the alternate case
11143         // (when dealing with a retainable type), the result
11144         // initialization will create a produce.  In both cases the
11145         // result will be +1, and we'll need to balance that out with
11146         // a bind.
11147         if (Expr *rebuiltLastStmt
11148               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11149           LastExpr = rebuiltLastStmt;
11150         } else {
11151           LastExpr = PerformCopyInitialization(
11152                             InitializedEntity::InitializeResult(LPLoc,
11153                                                                 Ty,
11154                                                                 false),
11155                                                    SourceLocation(),
11156                                                LastExpr);
11157         }
11158 
11159         if (LastExpr.isInvalid())
11160           return ExprError();
11161         if (LastExpr.get() != nullptr) {
11162           if (!LastLabelStmt)
11163             Compound->setLastStmt(LastExpr.get());
11164           else
11165             LastLabelStmt->setSubStmt(LastExpr.get());
11166           StmtExprMayBindToTemp = true;
11167         }
11168       }
11169     }
11170   }
11171 
11172   // FIXME: Check that expression type is complete/non-abstract; statement
11173   // expressions are not lvalues.
11174   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11175   if (StmtExprMayBindToTemp)
11176     return MaybeBindToTemporary(ResStmtExpr);
11177   return ResStmtExpr;
11178 }
11179 
11180 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11181                                       TypeSourceInfo *TInfo,
11182                                       ArrayRef<OffsetOfComponent> Components,
11183                                       SourceLocation RParenLoc) {
11184   QualType ArgTy = TInfo->getType();
11185   bool Dependent = ArgTy->isDependentType();
11186   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11187 
11188   // We must have at least one component that refers to the type, and the first
11189   // one is known to be a field designator.  Verify that the ArgTy represents
11190   // a struct/union/class.
11191   if (!Dependent && !ArgTy->isRecordType())
11192     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11193                        << ArgTy << TypeRange);
11194 
11195   // Type must be complete per C99 7.17p3 because a declaring a variable
11196   // with an incomplete type would be ill-formed.
11197   if (!Dependent
11198       && RequireCompleteType(BuiltinLoc, ArgTy,
11199                              diag::err_offsetof_incomplete_type, TypeRange))
11200     return ExprError();
11201 
11202   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11203   // GCC extension, diagnose them.
11204   // FIXME: This diagnostic isn't actually visible because the location is in
11205   // a system header!
11206   if (Components.size() != 1)
11207     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11208       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11209 
11210   bool DidWarnAboutNonPOD = false;
11211   QualType CurrentType = ArgTy;
11212   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
11213   SmallVector<OffsetOfNode, 4> Comps;
11214   SmallVector<Expr*, 4> Exprs;
11215   for (const OffsetOfComponent &OC : Components) {
11216     if (OC.isBrackets) {
11217       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11218       if (!CurrentType->isDependentType()) {
11219         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11220         if(!AT)
11221           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11222                            << CurrentType);
11223         CurrentType = AT->getElementType();
11224       } else
11225         CurrentType = Context.DependentTy;
11226 
11227       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11228       if (IdxRval.isInvalid())
11229         return ExprError();
11230       Expr *Idx = IdxRval.get();
11231 
11232       // The expression must be an integral expression.
11233       // FIXME: An integral constant expression?
11234       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11235           !Idx->getType()->isIntegerType())
11236         return ExprError(Diag(Idx->getLocStart(),
11237                               diag::err_typecheck_subscript_not_integer)
11238                          << Idx->getSourceRange());
11239 
11240       // Record this array index.
11241       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11242       Exprs.push_back(Idx);
11243       continue;
11244     }
11245 
11246     // Offset of a field.
11247     if (CurrentType->isDependentType()) {
11248       // We have the offset of a field, but we can't look into the dependent
11249       // type. Just record the identifier of the field.
11250       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11251       CurrentType = Context.DependentTy;
11252       continue;
11253     }
11254 
11255     // We need to have a complete type to look into.
11256     if (RequireCompleteType(OC.LocStart, CurrentType,
11257                             diag::err_offsetof_incomplete_type))
11258       return ExprError();
11259 
11260     // Look for the designated field.
11261     const RecordType *RC = CurrentType->getAs<RecordType>();
11262     if (!RC)
11263       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11264                        << CurrentType);
11265     RecordDecl *RD = RC->getDecl();
11266 
11267     // C++ [lib.support.types]p5:
11268     //   The macro offsetof accepts a restricted set of type arguments in this
11269     //   International Standard. type shall be a POD structure or a POD union
11270     //   (clause 9).
11271     // C++11 [support.types]p4:
11272     //   If type is not a standard-layout class (Clause 9), the results are
11273     //   undefined.
11274     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11275       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11276       unsigned DiagID =
11277         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11278                             : diag::ext_offsetof_non_pod_type;
11279 
11280       if (!IsSafe && !DidWarnAboutNonPOD &&
11281           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11282                               PDiag(DiagID)
11283                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11284                               << CurrentType))
11285         DidWarnAboutNonPOD = true;
11286     }
11287 
11288     // Look for the field.
11289     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11290     LookupQualifiedName(R, RD);
11291     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11292     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11293     if (!MemberDecl) {
11294       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11295         MemberDecl = IndirectMemberDecl->getAnonField();
11296     }
11297 
11298     if (!MemberDecl)
11299       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11300                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11301                                                               OC.LocEnd));
11302 
11303     // C99 7.17p3:
11304     //   (If the specified member is a bit-field, the behavior is undefined.)
11305     //
11306     // We diagnose this as an error.
11307     if (MemberDecl->isBitField()) {
11308       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11309         << MemberDecl->getDeclName()
11310         << SourceRange(BuiltinLoc, RParenLoc);
11311       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11312       return ExprError();
11313     }
11314 
11315     RecordDecl *Parent = MemberDecl->getParent();
11316     if (IndirectMemberDecl)
11317       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11318 
11319     // If the member was found in a base class, introduce OffsetOfNodes for
11320     // the base class indirections.
11321     CXXBasePaths Paths;
11322     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
11323       if (Paths.getDetectedVirtual()) {
11324         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11325           << MemberDecl->getDeclName()
11326           << SourceRange(BuiltinLoc, RParenLoc);
11327         return ExprError();
11328       }
11329 
11330       CXXBasePath &Path = Paths.front();
11331       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
11332            B != BEnd; ++B)
11333         Comps.push_back(OffsetOfNode(B->Base));
11334     }
11335 
11336     if (IndirectMemberDecl) {
11337       for (auto *FI : IndirectMemberDecl->chain()) {
11338         assert(isa<FieldDecl>(FI));
11339         Comps.push_back(OffsetOfNode(OC.LocStart,
11340                                      cast<FieldDecl>(FI), OC.LocEnd));
11341       }
11342     } else
11343       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11344 
11345     CurrentType = MemberDecl->getType().getNonReferenceType();
11346   }
11347 
11348   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11349                               Comps, Exprs, RParenLoc);
11350 }
11351 
11352 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11353                                       SourceLocation BuiltinLoc,
11354                                       SourceLocation TypeLoc,
11355                                       ParsedType ParsedArgTy,
11356                                       ArrayRef<OffsetOfComponent> Components,
11357                                       SourceLocation RParenLoc) {
11358 
11359   TypeSourceInfo *ArgTInfo;
11360   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11361   if (ArgTy.isNull())
11362     return ExprError();
11363 
11364   if (!ArgTInfo)
11365     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11366 
11367   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11368 }
11369 
11370 
11371 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11372                                  Expr *CondExpr,
11373                                  Expr *LHSExpr, Expr *RHSExpr,
11374                                  SourceLocation RPLoc) {
11375   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11376 
11377   ExprValueKind VK = VK_RValue;
11378   ExprObjectKind OK = OK_Ordinary;
11379   QualType resType;
11380   bool ValueDependent = false;
11381   bool CondIsTrue = false;
11382   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11383     resType = Context.DependentTy;
11384     ValueDependent = true;
11385   } else {
11386     // The conditional expression is required to be a constant expression.
11387     llvm::APSInt condEval(32);
11388     ExprResult CondICE
11389       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11390           diag::err_typecheck_choose_expr_requires_constant, false);
11391     if (CondICE.isInvalid())
11392       return ExprError();
11393     CondExpr = CondICE.get();
11394     CondIsTrue = condEval.getZExtValue();
11395 
11396     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11397     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11398 
11399     resType = ActiveExpr->getType();
11400     ValueDependent = ActiveExpr->isValueDependent();
11401     VK = ActiveExpr->getValueKind();
11402     OK = ActiveExpr->getObjectKind();
11403   }
11404 
11405   return new (Context)
11406       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11407                  CondIsTrue, resType->isDependentType(), ValueDependent);
11408 }
11409 
11410 //===----------------------------------------------------------------------===//
11411 // Clang Extensions.
11412 //===----------------------------------------------------------------------===//
11413 
11414 /// ActOnBlockStart - This callback is invoked when a block literal is started.
11415 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11416   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11417 
11418   if (LangOpts.CPlusPlus) {
11419     Decl *ManglingContextDecl;
11420     if (MangleNumberingContext *MCtx =
11421             getCurrentMangleNumberContext(Block->getDeclContext(),
11422                                           ManglingContextDecl)) {
11423       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11424       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11425     }
11426   }
11427 
11428   PushBlockScope(CurScope, Block);
11429   CurContext->addDecl(Block);
11430   if (CurScope)
11431     PushDeclContext(CurScope, Block);
11432   else
11433     CurContext = Block;
11434 
11435   getCurBlock()->HasImplicitReturnType = true;
11436 
11437   // Enter a new evaluation context to insulate the block from any
11438   // cleanups from the enclosing full-expression.
11439   PushExpressionEvaluationContext(PotentiallyEvaluated);
11440 }
11441 
11442 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11443                                Scope *CurScope) {
11444   assert(ParamInfo.getIdentifier() == nullptr &&
11445          "block-id should have no identifier!");
11446   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11447   BlockScopeInfo *CurBlock = getCurBlock();
11448 
11449   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11450   QualType T = Sig->getType();
11451 
11452   // FIXME: We should allow unexpanded parameter packs here, but that would,
11453   // in turn, make the block expression contain unexpanded parameter packs.
11454   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11455     // Drop the parameters.
11456     FunctionProtoType::ExtProtoInfo EPI;
11457     EPI.HasTrailingReturn = false;
11458     EPI.TypeQuals |= DeclSpec::TQ_const;
11459     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11460     Sig = Context.getTrivialTypeSourceInfo(T);
11461   }
11462 
11463   // GetTypeForDeclarator always produces a function type for a block
11464   // literal signature.  Furthermore, it is always a FunctionProtoType
11465   // unless the function was written with a typedef.
11466   assert(T->isFunctionType() &&
11467          "GetTypeForDeclarator made a non-function block signature");
11468 
11469   // Look for an explicit signature in that function type.
11470   FunctionProtoTypeLoc ExplicitSignature;
11471 
11472   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11473   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11474 
11475     // Check whether that explicit signature was synthesized by
11476     // GetTypeForDeclarator.  If so, don't save that as part of the
11477     // written signature.
11478     if (ExplicitSignature.getLocalRangeBegin() ==
11479         ExplicitSignature.getLocalRangeEnd()) {
11480       // This would be much cheaper if we stored TypeLocs instead of
11481       // TypeSourceInfos.
11482       TypeLoc Result = ExplicitSignature.getReturnLoc();
11483       unsigned Size = Result.getFullDataSize();
11484       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11485       Sig->getTypeLoc().initializeFullCopy(Result, Size);
11486 
11487       ExplicitSignature = FunctionProtoTypeLoc();
11488     }
11489   }
11490 
11491   CurBlock->TheDecl->setSignatureAsWritten(Sig);
11492   CurBlock->FunctionType = T;
11493 
11494   const FunctionType *Fn = T->getAs<FunctionType>();
11495   QualType RetTy = Fn->getReturnType();
11496   bool isVariadic =
11497     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11498 
11499   CurBlock->TheDecl->setIsVariadic(isVariadic);
11500 
11501   // Context.DependentTy is used as a placeholder for a missing block
11502   // return type.  TODO:  what should we do with declarators like:
11503   //   ^ * { ... }
11504   // If the answer is "apply template argument deduction"....
11505   if (RetTy != Context.DependentTy) {
11506     CurBlock->ReturnType = RetTy;
11507     CurBlock->TheDecl->setBlockMissingReturnType(false);
11508     CurBlock->HasImplicitReturnType = false;
11509   }
11510 
11511   // Push block parameters from the declarator if we had them.
11512   SmallVector<ParmVarDecl*, 8> Params;
11513   if (ExplicitSignature) {
11514     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11515       ParmVarDecl *Param = ExplicitSignature.getParam(I);
11516       if (Param->getIdentifier() == nullptr &&
11517           !Param->isImplicit() &&
11518           !Param->isInvalidDecl() &&
11519           !getLangOpts().CPlusPlus)
11520         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11521       Params.push_back(Param);
11522     }
11523 
11524   // Fake up parameter variables if we have a typedef, like
11525   //   ^ fntype { ... }
11526   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
11527     for (const auto &I : Fn->param_types()) {
11528       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11529           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
11530       Params.push_back(Param);
11531     }
11532   }
11533 
11534   // Set the parameters on the block decl.
11535   if (!Params.empty()) {
11536     CurBlock->TheDecl->setParams(Params);
11537     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11538                              CurBlock->TheDecl->param_end(),
11539                              /*CheckParameterNames=*/false);
11540   }
11541 
11542   // Finally we can process decl attributes.
11543   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
11544 
11545   // Put the parameter variables in scope.
11546   for (auto AI : CurBlock->TheDecl->params()) {
11547     AI->setOwningFunction(CurBlock->TheDecl);
11548 
11549     // If this has an identifier, add it to the scope stack.
11550     if (AI->getIdentifier()) {
11551       CheckShadow(CurBlock->TheScope, AI);
11552 
11553       PushOnScopeChains(AI, CurBlock->TheScope);
11554     }
11555   }
11556 }
11557 
11558 /// ActOnBlockError - If there is an error parsing a block, this callback
11559 /// is invoked to pop the information about the block from the action impl.
11560 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
11561   // Leave the expression-evaluation context.
11562   DiscardCleanupsInEvaluationContext();
11563   PopExpressionEvaluationContext();
11564 
11565   // Pop off CurBlock, handle nested blocks.
11566   PopDeclContext();
11567   PopFunctionScopeInfo();
11568 }
11569 
11570 /// ActOnBlockStmtExpr - This is called when the body of a block statement
11571 /// literal was successfully completed.  ^(int x){...}
11572 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
11573                                     Stmt *Body, Scope *CurScope) {
11574   // If blocks are disabled, emit an error.
11575   if (!LangOpts.Blocks)
11576     Diag(CaretLoc, diag::err_blocks_disable);
11577 
11578   // Leave the expression-evaluation context.
11579   if (hasAnyUnrecoverableErrorsInThisFunction())
11580     DiscardCleanupsInEvaluationContext();
11581   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11582   PopExpressionEvaluationContext();
11583 
11584   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
11585 
11586   if (BSI->HasImplicitReturnType)
11587     deduceClosureReturnType(*BSI);
11588 
11589   PopDeclContext();
11590 
11591   QualType RetTy = Context.VoidTy;
11592   if (!BSI->ReturnType.isNull())
11593     RetTy = BSI->ReturnType;
11594 
11595   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
11596   QualType BlockTy;
11597 
11598   // Set the captured variables on the block.
11599   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11600   SmallVector<BlockDecl::Capture, 4> Captures;
11601   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
11602     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
11603     if (Cap.isThisCapture())
11604       continue;
11605     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
11606                               Cap.isNested(), Cap.getInitExpr());
11607     Captures.push_back(NewCap);
11608   }
11609   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
11610 
11611   // If the user wrote a function type in some form, try to use that.
11612   if (!BSI->FunctionType.isNull()) {
11613     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11614 
11615     FunctionType::ExtInfo Ext = FTy->getExtInfo();
11616     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11617 
11618     // Turn protoless block types into nullary block types.
11619     if (isa<FunctionNoProtoType>(FTy)) {
11620       FunctionProtoType::ExtProtoInfo EPI;
11621       EPI.ExtInfo = Ext;
11622       BlockTy = Context.getFunctionType(RetTy, None, EPI);
11623 
11624     // Otherwise, if we don't need to change anything about the function type,
11625     // preserve its sugar structure.
11626     } else if (FTy->getReturnType() == RetTy &&
11627                (!NoReturn || FTy->getNoReturnAttr())) {
11628       BlockTy = BSI->FunctionType;
11629 
11630     // Otherwise, make the minimal modifications to the function type.
11631     } else {
11632       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
11633       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11634       EPI.TypeQuals = 0; // FIXME: silently?
11635       EPI.ExtInfo = Ext;
11636       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
11637     }
11638 
11639   // If we don't have a function type, just build one from nothing.
11640   } else {
11641     FunctionProtoType::ExtProtoInfo EPI;
11642     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
11643     BlockTy = Context.getFunctionType(RetTy, None, EPI);
11644   }
11645 
11646   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
11647                            BSI->TheDecl->param_end());
11648   BlockTy = Context.getBlockPointerType(BlockTy);
11649 
11650   // If needed, diagnose invalid gotos and switches in the block.
11651   if (getCurFunction()->NeedsScopeChecking() &&
11652       !PP.isCodeCompletionEnabled())
11653     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
11654 
11655   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
11656 
11657   // Try to apply the named return value optimization. We have to check again
11658   // if we can do this, though, because blocks keep return statements around
11659   // to deduce an implicit return type.
11660   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
11661       !BSI->TheDecl->isDependentContext())
11662     computeNRVO(Body, BSI);
11663 
11664   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
11665   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11666   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
11667 
11668   // If the block isn't obviously global, i.e. it captures anything at
11669   // all, then we need to do a few things in the surrounding context:
11670   if (Result->getBlockDecl()->hasCaptures()) {
11671     // First, this expression has a new cleanup object.
11672     ExprCleanupObjects.push_back(Result->getBlockDecl());
11673     ExprNeedsCleanups = true;
11674 
11675     // It also gets a branch-protected scope if any of the captured
11676     // variables needs destruction.
11677     for (const auto &CI : Result->getBlockDecl()->captures()) {
11678       const VarDecl *var = CI.getVariable();
11679       if (var->getType().isDestructedType() != QualType::DK_none) {
11680         getCurFunction()->setHasBranchProtectedScope();
11681         break;
11682       }
11683     }
11684   }
11685 
11686   return Result;
11687 }
11688 
11689 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
11690                                         Expr *E, ParsedType Ty,
11691                                         SourceLocation RPLoc) {
11692   TypeSourceInfo *TInfo;
11693   GetTypeFromParser(Ty, &TInfo);
11694   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
11695 }
11696 
11697 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
11698                                 Expr *E, TypeSourceInfo *TInfo,
11699                                 SourceLocation RPLoc) {
11700   Expr *OrigExpr = E;
11701   bool IsMS = false;
11702 
11703   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
11704   // as Microsoft ABI on an actual Microsoft platform, where
11705   // __builtin_ms_va_list and __builtin_va_list are the same.)
11706   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
11707       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
11708     QualType MSVaListType = Context.getBuiltinMSVaListType();
11709     if (Context.hasSameType(MSVaListType, E->getType())) {
11710       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
11711         return ExprError();
11712       IsMS = true;
11713     }
11714   }
11715 
11716   // Get the va_list type
11717   QualType VaListType = Context.getBuiltinVaListType();
11718   if (!IsMS) {
11719     if (VaListType->isArrayType()) {
11720       // Deal with implicit array decay; for example, on x86-64,
11721       // va_list is an array, but it's supposed to decay to
11722       // a pointer for va_arg.
11723       VaListType = Context.getArrayDecayedType(VaListType);
11724       // Make sure the input expression also decays appropriately.
11725       ExprResult Result = UsualUnaryConversions(E);
11726       if (Result.isInvalid())
11727         return ExprError();
11728       E = Result.get();
11729     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
11730       // If va_list is a record type and we are compiling in C++ mode,
11731       // check the argument using reference binding.
11732       InitializedEntity Entity = InitializedEntity::InitializeParameter(
11733           Context, Context.getLValueReferenceType(VaListType), false);
11734       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
11735       if (Init.isInvalid())
11736         return ExprError();
11737       E = Init.getAs<Expr>();
11738     } else {
11739       // Otherwise, the va_list argument must be an l-value because
11740       // it is modified by va_arg.
11741       if (!E->isTypeDependent() &&
11742           CheckForModifiableLvalue(E, BuiltinLoc, *this))
11743         return ExprError();
11744     }
11745   }
11746 
11747   if (!IsMS && !E->isTypeDependent() &&
11748       !Context.hasSameType(VaListType, E->getType()))
11749     return ExprError(Diag(E->getLocStart(),
11750                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
11751       << OrigExpr->getType() << E->getSourceRange());
11752 
11753   if (!TInfo->getType()->isDependentType()) {
11754     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
11755                             diag::err_second_parameter_to_va_arg_incomplete,
11756                             TInfo->getTypeLoc()))
11757       return ExprError();
11758 
11759     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
11760                                TInfo->getType(),
11761                                diag::err_second_parameter_to_va_arg_abstract,
11762                                TInfo->getTypeLoc()))
11763       return ExprError();
11764 
11765     if (!TInfo->getType().isPODType(Context)) {
11766       Diag(TInfo->getTypeLoc().getBeginLoc(),
11767            TInfo->getType()->isObjCLifetimeType()
11768              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
11769              : diag::warn_second_parameter_to_va_arg_not_pod)
11770         << TInfo->getType()
11771         << TInfo->getTypeLoc().getSourceRange();
11772     }
11773 
11774     // Check for va_arg where arguments of the given type will be promoted
11775     // (i.e. this va_arg is guaranteed to have undefined behavior).
11776     QualType PromoteType;
11777     if (TInfo->getType()->isPromotableIntegerType()) {
11778       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
11779       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
11780         PromoteType = QualType();
11781     }
11782     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
11783       PromoteType = Context.DoubleTy;
11784     if (!PromoteType.isNull())
11785       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
11786                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
11787                           << TInfo->getType()
11788                           << PromoteType
11789                           << TInfo->getTypeLoc().getSourceRange());
11790   }
11791 
11792   QualType T = TInfo->getType().getNonLValueExprType(Context);
11793   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
11794 }
11795 
11796 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
11797   // The type of __null will be int or long, depending on the size of
11798   // pointers on the target.
11799   QualType Ty;
11800   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
11801   if (pw == Context.getTargetInfo().getIntWidth())
11802     Ty = Context.IntTy;
11803   else if (pw == Context.getTargetInfo().getLongWidth())
11804     Ty = Context.LongTy;
11805   else if (pw == Context.getTargetInfo().getLongLongWidth())
11806     Ty = Context.LongLongTy;
11807   else {
11808     llvm_unreachable("I don't know size of pointer!");
11809   }
11810 
11811   return new (Context) GNUNullExpr(Ty, TokenLoc);
11812 }
11813 
11814 bool
11815 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
11816   if (!getLangOpts().ObjC1)
11817     return false;
11818 
11819   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
11820   if (!PT)
11821     return false;
11822 
11823   if (!PT->isObjCIdType()) {
11824     // Check if the destination is the 'NSString' interface.
11825     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
11826     if (!ID || !ID->getIdentifier()->isStr("NSString"))
11827       return false;
11828   }
11829 
11830   // Ignore any parens, implicit casts (should only be
11831   // array-to-pointer decays), and not-so-opaque values.  The last is
11832   // important for making this trigger for property assignments.
11833   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
11834   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
11835     if (OV->getSourceExpr())
11836       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
11837 
11838   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
11839   if (!SL || !SL->isAscii())
11840     return false;
11841   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
11842     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
11843   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
11844   return true;
11845 }
11846 
11847 static bool maybeDiagnoseAssignmentToFunction(Sema &S, QualType DstType,
11848                                               const Expr *SrcExpr) {
11849   if (!DstType->isFunctionPointerType() ||
11850       !SrcExpr->getType()->isFunctionType())
11851     return false;
11852 
11853   auto *DRE = dyn_cast<DeclRefExpr>(SrcExpr->IgnoreParenImpCasts());
11854   if (!DRE)
11855     return false;
11856 
11857   auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
11858   if (!FD)
11859     return false;
11860 
11861   return !S.checkAddressOfFunctionIsAvailable(FD,
11862                                               /*Complain=*/true,
11863                                               SrcExpr->getLocStart());
11864 }
11865 
11866 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
11867                                     SourceLocation Loc,
11868                                     QualType DstType, QualType SrcType,
11869                                     Expr *SrcExpr, AssignmentAction Action,
11870                                     bool *Complained) {
11871   if (Complained)
11872     *Complained = false;
11873 
11874   // Decode the result (notice that AST's are still created for extensions).
11875   bool CheckInferredResultType = false;
11876   bool isInvalid = false;
11877   unsigned DiagKind = 0;
11878   FixItHint Hint;
11879   ConversionFixItGenerator ConvHints;
11880   bool MayHaveConvFixit = false;
11881   bool MayHaveFunctionDiff = false;
11882   const ObjCInterfaceDecl *IFace = nullptr;
11883   const ObjCProtocolDecl *PDecl = nullptr;
11884 
11885   switch (ConvTy) {
11886   case Compatible:
11887       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
11888       return false;
11889 
11890   case PointerToInt:
11891     DiagKind = diag::ext_typecheck_convert_pointer_int;
11892     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11893     MayHaveConvFixit = true;
11894     break;
11895   case IntToPointer:
11896     DiagKind = diag::ext_typecheck_convert_int_pointer;
11897     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11898     MayHaveConvFixit = true;
11899     break;
11900   case IncompatiblePointer:
11901       DiagKind =
11902         (Action == AA_Passing_CFAudited ?
11903           diag::err_arc_typecheck_convert_incompatible_pointer :
11904           diag::ext_typecheck_convert_incompatible_pointer);
11905     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
11906       SrcType->isObjCObjectPointerType();
11907     if (Hint.isNull() && !CheckInferredResultType) {
11908       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11909     }
11910     else if (CheckInferredResultType) {
11911       SrcType = SrcType.getUnqualifiedType();
11912       DstType = DstType.getUnqualifiedType();
11913     }
11914     MayHaveConvFixit = true;
11915     break;
11916   case IncompatiblePointerSign:
11917     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11918     break;
11919   case FunctionVoidPointer:
11920     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11921     break;
11922   case IncompatiblePointerDiscardsQualifiers: {
11923     // Perform array-to-pointer decay if necessary.
11924     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11925 
11926     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11927     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11928     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11929       DiagKind = diag::err_typecheck_incompatible_address_space;
11930       break;
11931 
11932 
11933     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
11934       DiagKind = diag::err_typecheck_incompatible_ownership;
11935       break;
11936     }
11937 
11938     llvm_unreachable("unknown error case for discarding qualifiers!");
11939     // fallthrough
11940   }
11941   case CompatiblePointerDiscardsQualifiers:
11942     // If the qualifiers lost were because we were applying the
11943     // (deprecated) C++ conversion from a string literal to a char*
11944     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
11945     // Ideally, this check would be performed in
11946     // checkPointerTypesForAssignment. However, that would require a
11947     // bit of refactoring (so that the second argument is an
11948     // expression, rather than a type), which should be done as part
11949     // of a larger effort to fix checkPointerTypesForAssignment for
11950     // C++ semantics.
11951     if (getLangOpts().CPlusPlus &&
11952         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11953       return false;
11954     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11955     break;
11956   case IncompatibleNestedPointerQualifiers:
11957     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
11958     break;
11959   case IntToBlockPointer:
11960     DiagKind = diag::err_int_to_block_pointer;
11961     break;
11962   case IncompatibleBlockPointer:
11963     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
11964     break;
11965   case IncompatibleObjCQualifiedId: {
11966     if (SrcType->isObjCQualifiedIdType()) {
11967       const ObjCObjectPointerType *srcOPT =
11968                 SrcType->getAs<ObjCObjectPointerType>();
11969       for (auto *srcProto : srcOPT->quals()) {
11970         PDecl = srcProto;
11971         break;
11972       }
11973       if (const ObjCInterfaceType *IFaceT =
11974             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11975         IFace = IFaceT->getDecl();
11976     }
11977     else if (DstType->isObjCQualifiedIdType()) {
11978       const ObjCObjectPointerType *dstOPT =
11979         DstType->getAs<ObjCObjectPointerType>();
11980       for (auto *dstProto : dstOPT->quals()) {
11981         PDecl = dstProto;
11982         break;
11983       }
11984       if (const ObjCInterfaceType *IFaceT =
11985             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11986         IFace = IFaceT->getDecl();
11987     }
11988     DiagKind = diag::warn_incompatible_qualified_id;
11989     break;
11990   }
11991   case IncompatibleVectors:
11992     DiagKind = diag::warn_incompatible_vectors;
11993     break;
11994   case IncompatibleObjCWeakRef:
11995     DiagKind = diag::err_arc_weak_unavailable_assign;
11996     break;
11997   case Incompatible:
11998     if (maybeDiagnoseAssignmentToFunction(*this, DstType, SrcExpr)) {
11999       if (Complained)
12000         *Complained = true;
12001       return true;
12002     }
12003 
12004     DiagKind = diag::err_typecheck_convert_incompatible;
12005     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
12006     MayHaveConvFixit = true;
12007     isInvalid = true;
12008     MayHaveFunctionDiff = true;
12009     break;
12010   }
12011 
12012   QualType FirstType, SecondType;
12013   switch (Action) {
12014   case AA_Assigning:
12015   case AA_Initializing:
12016     // The destination type comes first.
12017     FirstType = DstType;
12018     SecondType = SrcType;
12019     break;
12020 
12021   case AA_Returning:
12022   case AA_Passing:
12023   case AA_Passing_CFAudited:
12024   case AA_Converting:
12025   case AA_Sending:
12026   case AA_Casting:
12027     // The source type comes first.
12028     FirstType = SrcType;
12029     SecondType = DstType;
12030     break;
12031   }
12032 
12033   PartialDiagnostic FDiag = PDiag(DiagKind);
12034   if (Action == AA_Passing_CFAudited)
12035     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
12036   else
12037     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
12038 
12039   // If we can fix the conversion, suggest the FixIts.
12040   assert(ConvHints.isNull() || Hint.isNull());
12041   if (!ConvHints.isNull()) {
12042     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
12043          HE = ConvHints.Hints.end(); HI != HE; ++HI)
12044       FDiag << *HI;
12045   } else {
12046     FDiag << Hint;
12047   }
12048   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
12049 
12050   if (MayHaveFunctionDiff)
12051     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
12052 
12053   Diag(Loc, FDiag);
12054   if (DiagKind == diag::warn_incompatible_qualified_id &&
12055       PDecl && IFace && !IFace->hasDefinition())
12056       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
12057         << IFace->getName() << PDecl->getName();
12058 
12059   if (SecondType == Context.OverloadTy)
12060     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
12061                               FirstType, /*TakingAddress=*/true);
12062 
12063   if (CheckInferredResultType)
12064     EmitRelatedResultTypeNote(SrcExpr);
12065 
12066   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12067     EmitRelatedResultTypeNoteForReturn(DstType);
12068 
12069   if (Complained)
12070     *Complained = true;
12071   return isInvalid;
12072 }
12073 
12074 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12075                                                  llvm::APSInt *Result) {
12076   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12077   public:
12078     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12079       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12080     }
12081   } Diagnoser;
12082 
12083   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12084 }
12085 
12086 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12087                                                  llvm::APSInt *Result,
12088                                                  unsigned DiagID,
12089                                                  bool AllowFold) {
12090   class IDDiagnoser : public VerifyICEDiagnoser {
12091     unsigned DiagID;
12092 
12093   public:
12094     IDDiagnoser(unsigned DiagID)
12095       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12096 
12097     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12098       S.Diag(Loc, DiagID) << SR;
12099     }
12100   } Diagnoser(DiagID);
12101 
12102   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12103 }
12104 
12105 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12106                                             SourceRange SR) {
12107   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12108 }
12109 
12110 ExprResult
12111 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12112                                       VerifyICEDiagnoser &Diagnoser,
12113                                       bool AllowFold) {
12114   SourceLocation DiagLoc = E->getLocStart();
12115 
12116   if (getLangOpts().CPlusPlus11) {
12117     // C++11 [expr.const]p5:
12118     //   If an expression of literal class type is used in a context where an
12119     //   integral constant expression is required, then that class type shall
12120     //   have a single non-explicit conversion function to an integral or
12121     //   unscoped enumeration type
12122     ExprResult Converted;
12123     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12124     public:
12125       CXX11ConvertDiagnoser(bool Silent)
12126           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12127                                 Silent, true) {}
12128 
12129       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12130                                            QualType T) override {
12131         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12132       }
12133 
12134       SemaDiagnosticBuilder diagnoseIncomplete(
12135           Sema &S, SourceLocation Loc, QualType T) override {
12136         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12137       }
12138 
12139       SemaDiagnosticBuilder diagnoseExplicitConv(
12140           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12141         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12142       }
12143 
12144       SemaDiagnosticBuilder noteExplicitConv(
12145           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12146         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12147                  << ConvTy->isEnumeralType() << ConvTy;
12148       }
12149 
12150       SemaDiagnosticBuilder diagnoseAmbiguous(
12151           Sema &S, SourceLocation Loc, QualType T) override {
12152         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12153       }
12154 
12155       SemaDiagnosticBuilder noteAmbiguous(
12156           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12157         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12158                  << ConvTy->isEnumeralType() << ConvTy;
12159       }
12160 
12161       SemaDiagnosticBuilder diagnoseConversion(
12162           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12163         llvm_unreachable("conversion functions are permitted");
12164       }
12165     } ConvertDiagnoser(Diagnoser.Suppress);
12166 
12167     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12168                                                     ConvertDiagnoser);
12169     if (Converted.isInvalid())
12170       return Converted;
12171     E = Converted.get();
12172     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12173       return ExprError();
12174   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12175     // An ICE must be of integral or unscoped enumeration type.
12176     if (!Diagnoser.Suppress)
12177       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12178     return ExprError();
12179   }
12180 
12181   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12182   // in the non-ICE case.
12183   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12184     if (Result)
12185       *Result = E->EvaluateKnownConstInt(Context);
12186     return E;
12187   }
12188 
12189   Expr::EvalResult EvalResult;
12190   SmallVector<PartialDiagnosticAt, 8> Notes;
12191   EvalResult.Diag = &Notes;
12192 
12193   // Try to evaluate the expression, and produce diagnostics explaining why it's
12194   // not a constant expression as a side-effect.
12195   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12196                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12197 
12198   // In C++11, we can rely on diagnostics being produced for any expression
12199   // which is not a constant expression. If no diagnostics were produced, then
12200   // this is a constant expression.
12201   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12202     if (Result)
12203       *Result = EvalResult.Val.getInt();
12204     return E;
12205   }
12206 
12207   // If our only note is the usual "invalid subexpression" note, just point
12208   // the caret at its location rather than producing an essentially
12209   // redundant note.
12210   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12211         diag::note_invalid_subexpr_in_const_expr) {
12212     DiagLoc = Notes[0].first;
12213     Notes.clear();
12214   }
12215 
12216   if (!Folded || !AllowFold) {
12217     if (!Diagnoser.Suppress) {
12218       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12219       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12220         Diag(Notes[I].first, Notes[I].second);
12221     }
12222 
12223     return ExprError();
12224   }
12225 
12226   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12227   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12228     Diag(Notes[I].first, Notes[I].second);
12229 
12230   if (Result)
12231     *Result = EvalResult.Val.getInt();
12232   return E;
12233 }
12234 
12235 namespace {
12236   // Handle the case where we conclude a expression which we speculatively
12237   // considered to be unevaluated is actually evaluated.
12238   class TransformToPE : public TreeTransform<TransformToPE> {
12239     typedef TreeTransform<TransformToPE> BaseTransform;
12240 
12241   public:
12242     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12243 
12244     // Make sure we redo semantic analysis
12245     bool AlwaysRebuild() { return true; }
12246 
12247     // Make sure we handle LabelStmts correctly.
12248     // FIXME: This does the right thing, but maybe we need a more general
12249     // fix to TreeTransform?
12250     StmtResult TransformLabelStmt(LabelStmt *S) {
12251       S->getDecl()->setStmt(nullptr);
12252       return BaseTransform::TransformLabelStmt(S);
12253     }
12254 
12255     // We need to special-case DeclRefExprs referring to FieldDecls which
12256     // are not part of a member pointer formation; normal TreeTransforming
12257     // doesn't catch this case because of the way we represent them in the AST.
12258     // FIXME: This is a bit ugly; is it really the best way to handle this
12259     // case?
12260     //
12261     // Error on DeclRefExprs referring to FieldDecls.
12262     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12263       if (isa<FieldDecl>(E->getDecl()) &&
12264           !SemaRef.isUnevaluatedContext())
12265         return SemaRef.Diag(E->getLocation(),
12266                             diag::err_invalid_non_static_member_use)
12267             << E->getDecl() << E->getSourceRange();
12268 
12269       return BaseTransform::TransformDeclRefExpr(E);
12270     }
12271 
12272     // Exception: filter out member pointer formation
12273     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12274       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12275         return E;
12276 
12277       return BaseTransform::TransformUnaryOperator(E);
12278     }
12279 
12280     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12281       // Lambdas never need to be transformed.
12282       return E;
12283     }
12284   };
12285 }
12286 
12287 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12288   assert(isUnevaluatedContext() &&
12289          "Should only transform unevaluated expressions");
12290   ExprEvalContexts.back().Context =
12291       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12292   if (isUnevaluatedContext())
12293     return E;
12294   return TransformToPE(*this).TransformExpr(E);
12295 }
12296 
12297 void
12298 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12299                                       Decl *LambdaContextDecl,
12300                                       bool IsDecltype) {
12301   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
12302                                 ExprNeedsCleanups, LambdaContextDecl,
12303                                 IsDecltype);
12304   ExprNeedsCleanups = false;
12305   if (!MaybeODRUseExprs.empty())
12306     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12307 }
12308 
12309 void
12310 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12311                                       ReuseLambdaContextDecl_t,
12312                                       bool IsDecltype) {
12313   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12314   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12315 }
12316 
12317 void Sema::PopExpressionEvaluationContext() {
12318   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12319   unsigned NumTypos = Rec.NumTypos;
12320 
12321   if (!Rec.Lambdas.empty()) {
12322     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12323       unsigned D;
12324       if (Rec.isUnevaluated()) {
12325         // C++11 [expr.prim.lambda]p2:
12326         //   A lambda-expression shall not appear in an unevaluated operand
12327         //   (Clause 5).
12328         D = diag::err_lambda_unevaluated_operand;
12329       } else {
12330         // C++1y [expr.const]p2:
12331         //   A conditional-expression e is a core constant expression unless the
12332         //   evaluation of e, following the rules of the abstract machine, would
12333         //   evaluate [...] a lambda-expression.
12334         D = diag::err_lambda_in_constant_expression;
12335       }
12336       for (const auto *L : Rec.Lambdas)
12337         Diag(L->getLocStart(), D);
12338     } else {
12339       // Mark the capture expressions odr-used. This was deferred
12340       // during lambda expression creation.
12341       for (auto *Lambda : Rec.Lambdas) {
12342         for (auto *C : Lambda->capture_inits())
12343           MarkDeclarationsReferencedInExpr(C);
12344       }
12345     }
12346   }
12347 
12348   // When are coming out of an unevaluated context, clear out any
12349   // temporaries that we may have created as part of the evaluation of
12350   // the expression in that context: they aren't relevant because they
12351   // will never be constructed.
12352   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12353     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12354                              ExprCleanupObjects.end());
12355     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
12356     CleanupVarDeclMarking();
12357     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12358   // Otherwise, merge the contexts together.
12359   } else {
12360     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
12361     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12362                             Rec.SavedMaybeODRUseExprs.end());
12363   }
12364 
12365   // Pop the current expression evaluation context off the stack.
12366   ExprEvalContexts.pop_back();
12367 
12368   if (!ExprEvalContexts.empty())
12369     ExprEvalContexts.back().NumTypos += NumTypos;
12370   else
12371     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12372                             "last ExpressionEvaluationContextRecord");
12373 }
12374 
12375 void Sema::DiscardCleanupsInEvaluationContext() {
12376   ExprCleanupObjects.erase(
12377          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12378          ExprCleanupObjects.end());
12379   ExprNeedsCleanups = false;
12380   MaybeODRUseExprs.clear();
12381 }
12382 
12383 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12384   if (!E->getType()->isVariablyModifiedType())
12385     return E;
12386   return TransformToPotentiallyEvaluated(E);
12387 }
12388 
12389 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12390   // Do not mark anything as "used" within a dependent context; wait for
12391   // an instantiation.
12392   if (SemaRef.CurContext->isDependentContext())
12393     return false;
12394 
12395   switch (SemaRef.ExprEvalContexts.back().Context) {
12396     case Sema::Unevaluated:
12397     case Sema::UnevaluatedAbstract:
12398       // We are in an expression that is not potentially evaluated; do nothing.
12399       // (Depending on how you read the standard, we actually do need to do
12400       // something here for null pointer constants, but the standard's
12401       // definition of a null pointer constant is completely crazy.)
12402       return false;
12403 
12404     case Sema::ConstantEvaluated:
12405     case Sema::PotentiallyEvaluated:
12406       // We are in a potentially evaluated expression (or a constant-expression
12407       // in C++03); we need to do implicit template instantiation, implicitly
12408       // define class members, and mark most declarations as used.
12409       return true;
12410 
12411     case Sema::PotentiallyEvaluatedIfUsed:
12412       // Referenced declarations will only be used if the construct in the
12413       // containing expression is used.
12414       return false;
12415   }
12416   llvm_unreachable("Invalid context");
12417 }
12418 
12419 /// \brief Mark a function referenced, and check whether it is odr-used
12420 /// (C++ [basic.def.odr]p2, C99 6.9p3)
12421 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12422                                   bool OdrUse) {
12423   assert(Func && "No function?");
12424 
12425   Func->setReferenced();
12426 
12427   // C++11 [basic.def.odr]p3:
12428   //   A function whose name appears as a potentially-evaluated expression is
12429   //   odr-used if it is the unique lookup result or the selected member of a
12430   //   set of overloaded functions [...].
12431   //
12432   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12433   // can just check that here. Skip the rest of this function if we've already
12434   // marked the function as used.
12435   if (Func->isUsed(/*CheckUsedAttr=*/false) ||
12436       !IsPotentiallyEvaluatedContext(*this)) {
12437     // C++11 [temp.inst]p3:
12438     //   Unless a function template specialization has been explicitly
12439     //   instantiated or explicitly specialized, the function template
12440     //   specialization is implicitly instantiated when the specialization is
12441     //   referenced in a context that requires a function definition to exist.
12442     //
12443     // We consider constexpr function templates to be referenced in a context
12444     // that requires a definition to exist whenever they are referenced.
12445     //
12446     // FIXME: This instantiates constexpr functions too frequently. If this is
12447     // really an unevaluated context (and we're not just in the definition of a
12448     // function template or overload resolution or other cases which we
12449     // incorrectly consider to be unevaluated contexts), and we're not in a
12450     // subexpression which we actually need to evaluate (for instance, a
12451     // template argument, array bound or an expression in a braced-init-list),
12452     // we are not permitted to instantiate this constexpr function definition.
12453     //
12454     // FIXME: This also implicitly defines special members too frequently. They
12455     // are only supposed to be implicitly defined if they are odr-used, but they
12456     // are not odr-used from constant expressions in unevaluated contexts.
12457     // However, they cannot be referenced if they are deleted, and they are
12458     // deleted whenever the implicit definition of the special member would
12459     // fail.
12460     if (!Func->isConstexpr() || Func->getBody())
12461       return;
12462     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12463     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12464       return;
12465   }
12466 
12467   // Note that this declaration has been used.
12468   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
12469     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
12470     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
12471       if (Constructor->isDefaultConstructor()) {
12472         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
12473           return;
12474         DefineImplicitDefaultConstructor(Loc, Constructor);
12475       } else if (Constructor->isCopyConstructor()) {
12476         DefineImplicitCopyConstructor(Loc, Constructor);
12477       } else if (Constructor->isMoveConstructor()) {
12478         DefineImplicitMoveConstructor(Loc, Constructor);
12479       }
12480     } else if (Constructor->getInheritedConstructor()) {
12481       DefineInheritingConstructor(Loc, Constructor);
12482     }
12483   } else if (CXXDestructorDecl *Destructor =
12484                  dyn_cast<CXXDestructorDecl>(Func)) {
12485     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
12486     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12487       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12488         return;
12489       DefineImplicitDestructor(Loc, Destructor);
12490     }
12491     if (Destructor->isVirtual() && getLangOpts().AppleKext)
12492       MarkVTableUsed(Loc, Destructor->getParent());
12493   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
12494     if (MethodDecl->isOverloadedOperator() &&
12495         MethodDecl->getOverloadedOperator() == OO_Equal) {
12496       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12497       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
12498         if (MethodDecl->isCopyAssignmentOperator())
12499           DefineImplicitCopyAssignment(Loc, MethodDecl);
12500         else
12501           DefineImplicitMoveAssignment(Loc, MethodDecl);
12502       }
12503     } else if (isa<CXXConversionDecl>(MethodDecl) &&
12504                MethodDecl->getParent()->isLambda()) {
12505       CXXConversionDecl *Conversion =
12506           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
12507       if (Conversion->isLambdaToBlockPointerConversion())
12508         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12509       else
12510         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
12511     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
12512       MarkVTableUsed(Loc, MethodDecl->getParent());
12513   }
12514 
12515   // Recursive functions should be marked when used from another function.
12516   // FIXME: Is this really right?
12517   if (CurContext == Func) return;
12518 
12519   // Resolve the exception specification for any function which is
12520   // used: CodeGen will need it.
12521   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
12522   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12523     ResolveExceptionSpec(Loc, FPT);
12524 
12525   if (!OdrUse) return;
12526 
12527   // Implicit instantiation of function templates and member functions of
12528   // class templates.
12529   if (Func->isImplicitlyInstantiable()) {
12530     bool AlreadyInstantiated = false;
12531     SourceLocation PointOfInstantiation = Loc;
12532     if (FunctionTemplateSpecializationInfo *SpecInfo
12533                               = Func->getTemplateSpecializationInfo()) {
12534       if (SpecInfo->getPointOfInstantiation().isInvalid())
12535         SpecInfo->setPointOfInstantiation(Loc);
12536       else if (SpecInfo->getTemplateSpecializationKind()
12537                  == TSK_ImplicitInstantiation) {
12538         AlreadyInstantiated = true;
12539         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12540       }
12541     } else if (MemberSpecializationInfo *MSInfo
12542                                 = Func->getMemberSpecializationInfo()) {
12543       if (MSInfo->getPointOfInstantiation().isInvalid())
12544         MSInfo->setPointOfInstantiation(Loc);
12545       else if (MSInfo->getTemplateSpecializationKind()
12546                  == TSK_ImplicitInstantiation) {
12547         AlreadyInstantiated = true;
12548         PointOfInstantiation = MSInfo->getPointOfInstantiation();
12549       }
12550     }
12551 
12552     if (!AlreadyInstantiated || Func->isConstexpr()) {
12553       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
12554           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12555           ActiveTemplateInstantiations.size())
12556         PendingLocalImplicitInstantiations.push_back(
12557             std::make_pair(Func, PointOfInstantiation));
12558       else if (Func->isConstexpr())
12559         // Do not defer instantiations of constexpr functions, to avoid the
12560         // expression evaluator needing to call back into Sema if it sees a
12561         // call to such a function.
12562         InstantiateFunctionDefinition(PointOfInstantiation, Func);
12563       else {
12564         PendingInstantiations.push_back(std::make_pair(Func,
12565                                                        PointOfInstantiation));
12566         // Notify the consumer that a function was implicitly instantiated.
12567         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12568       }
12569     }
12570   } else {
12571     // Walk redefinitions, as some of them may be instantiable.
12572     for (auto i : Func->redecls()) {
12573       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
12574         MarkFunctionReferenced(Loc, i);
12575     }
12576   }
12577 
12578   // Keep track of used but undefined functions.
12579   if (!Func->isDefined()) {
12580     if (mightHaveNonExternalLinkage(Func))
12581       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12582     else if (Func->getMostRecentDecl()->isInlined() &&
12583              !LangOpts.GNUInline &&
12584              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12585       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12586   }
12587 
12588   // Normally the most current decl is marked used while processing the use and
12589   // any subsequent decls are marked used by decl merging. This fails with
12590   // template instantiation since marking can happen at the end of the file
12591   // and, because of the two phase lookup, this function is called with at
12592   // decl in the middle of a decl chain. We loop to maintain the invariant
12593   // that once a decl is used, all decls after it are also used.
12594   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
12595     F->markUsed(Context);
12596     if (F == Func)
12597       break;
12598   }
12599 }
12600 
12601 static void
12602 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12603                                    VarDecl *var, DeclContext *DC) {
12604   DeclContext *VarDC = var->getDeclContext();
12605 
12606   //  If the parameter still belongs to the translation unit, then
12607   //  we're actually just using one parameter in the declaration of
12608   //  the next.
12609   if (isa<ParmVarDecl>(var) &&
12610       isa<TranslationUnitDecl>(VarDC))
12611     return;
12612 
12613   // For C code, don't diagnose about capture if we're not actually in code
12614   // right now; it's impossible to write a non-constant expression outside of
12615   // function context, so we'll get other (more useful) diagnostics later.
12616   //
12617   // For C++, things get a bit more nasty... it would be nice to suppress this
12618   // diagnostic for certain cases like using a local variable in an array bound
12619   // for a member of a local class, but the correct predicate is not obvious.
12620   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
12621     return;
12622 
12623   if (isa<CXXMethodDecl>(VarDC) &&
12624       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12625     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12626       << var->getIdentifier();
12627   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12628     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12629       << var->getIdentifier() << fn->getDeclName();
12630   } else if (isa<BlockDecl>(VarDC)) {
12631     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12632       << var->getIdentifier();
12633   } else {
12634     // FIXME: Is there any other context where a local variable can be
12635     // declared?
12636     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
12637       << var->getIdentifier();
12638   }
12639 
12640   S.Diag(var->getLocation(), diag::note_entity_declared_at)
12641       << var->getIdentifier();
12642 
12643   // FIXME: Add additional diagnostic info about class etc. which prevents
12644   // capture.
12645 }
12646 
12647 
12648 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
12649                                       bool &SubCapturesAreNested,
12650                                       QualType &CaptureType,
12651                                       QualType &DeclRefType) {
12652    // Check whether we've already captured it.
12653   if (CSI->CaptureMap.count(Var)) {
12654     // If we found a capture, any subcaptures are nested.
12655     SubCapturesAreNested = true;
12656 
12657     // Retrieve the capture type for this variable.
12658     CaptureType = CSI->getCapture(Var).getCaptureType();
12659 
12660     // Compute the type of an expression that refers to this variable.
12661     DeclRefType = CaptureType.getNonReferenceType();
12662 
12663     // Similarly to mutable captures in lambda, all the OpenMP captures by copy
12664     // are mutable in the sense that user can change their value - they are
12665     // private instances of the captured declarations.
12666     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
12667     if (Cap.isCopyCapture() &&
12668         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable) &&
12669         !(isa<CapturedRegionScopeInfo>(CSI) &&
12670           cast<CapturedRegionScopeInfo>(CSI)->CapRegionKind == CR_OpenMP))
12671       DeclRefType.addConst();
12672     return true;
12673   }
12674   return false;
12675 }
12676 
12677 // Only block literals, captured statements, and lambda expressions can
12678 // capture; other scopes don't work.
12679 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
12680                                  SourceLocation Loc,
12681                                  const bool Diagnose, Sema &S) {
12682   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
12683     return getLambdaAwareParentOfDeclContext(DC);
12684   else if (Var->hasLocalStorage()) {
12685     if (Diagnose)
12686        diagnoseUncapturableValueReference(S, Loc, Var, DC);
12687   }
12688   return nullptr;
12689 }
12690 
12691 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12692 // certain types of variables (unnamed, variably modified types etc.)
12693 // so check for eligibility.
12694 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
12695                                  SourceLocation Loc,
12696                                  const bool Diagnose, Sema &S) {
12697 
12698   bool IsBlock = isa<BlockScopeInfo>(CSI);
12699   bool IsLambda = isa<LambdaScopeInfo>(CSI);
12700 
12701   // Lambdas are not allowed to capture unnamed variables
12702   // (e.g. anonymous unions).
12703   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
12704   // assuming that's the intent.
12705   if (IsLambda && !Var->getDeclName()) {
12706     if (Diagnose) {
12707       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
12708       S.Diag(Var->getLocation(), diag::note_declared_at);
12709     }
12710     return false;
12711   }
12712 
12713   // Prohibit variably-modified types in blocks; they're difficult to deal with.
12714   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
12715     if (Diagnose) {
12716       S.Diag(Loc, diag::err_ref_vm_type);
12717       S.Diag(Var->getLocation(), diag::note_previous_decl)
12718         << Var->getDeclName();
12719     }
12720     return false;
12721   }
12722   // Prohibit structs with flexible array members too.
12723   // We cannot capture what is in the tail end of the struct.
12724   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
12725     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
12726       if (Diagnose) {
12727         if (IsBlock)
12728           S.Diag(Loc, diag::err_ref_flexarray_type);
12729         else
12730           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
12731             << Var->getDeclName();
12732         S.Diag(Var->getLocation(), diag::note_previous_decl)
12733           << Var->getDeclName();
12734       }
12735       return false;
12736     }
12737   }
12738   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12739   // Lambdas and captured statements are not allowed to capture __block
12740   // variables; they don't support the expected semantics.
12741   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
12742     if (Diagnose) {
12743       S.Diag(Loc, diag::err_capture_block_variable)
12744         << Var->getDeclName() << !IsLambda;
12745       S.Diag(Var->getLocation(), diag::note_previous_decl)
12746         << Var->getDeclName();
12747     }
12748     return false;
12749   }
12750 
12751   return true;
12752 }
12753 
12754 // Returns true if the capture by block was successful.
12755 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
12756                                  SourceLocation Loc,
12757                                  const bool BuildAndDiagnose,
12758                                  QualType &CaptureType,
12759                                  QualType &DeclRefType,
12760                                  const bool Nested,
12761                                  Sema &S) {
12762   Expr *CopyExpr = nullptr;
12763   bool ByRef = false;
12764 
12765   // Blocks are not allowed to capture arrays.
12766   if (CaptureType->isArrayType()) {
12767     if (BuildAndDiagnose) {
12768       S.Diag(Loc, diag::err_ref_array_type);
12769       S.Diag(Var->getLocation(), diag::note_previous_decl)
12770       << Var->getDeclName();
12771     }
12772     return false;
12773   }
12774 
12775   // Forbid the block-capture of autoreleasing variables.
12776   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12777     if (BuildAndDiagnose) {
12778       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
12779         << /*block*/ 0;
12780       S.Diag(Var->getLocation(), diag::note_previous_decl)
12781         << Var->getDeclName();
12782     }
12783     return false;
12784   }
12785   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12786   if (HasBlocksAttr || CaptureType->isReferenceType()) {
12787     // Block capture by reference does not change the capture or
12788     // declaration reference types.
12789     ByRef = true;
12790   } else {
12791     // Block capture by copy introduces 'const'.
12792     CaptureType = CaptureType.getNonReferenceType().withConst();
12793     DeclRefType = CaptureType;
12794 
12795     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
12796       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
12797         // The capture logic needs the destructor, so make sure we mark it.
12798         // Usually this is unnecessary because most local variables have
12799         // their destructors marked at declaration time, but parameters are
12800         // an exception because it's technically only the call site that
12801         // actually requires the destructor.
12802         if (isa<ParmVarDecl>(Var))
12803           S.FinalizeVarWithDestructor(Var, Record);
12804 
12805         // Enter a new evaluation context to insulate the copy
12806         // full-expression.
12807         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
12808 
12809         // According to the blocks spec, the capture of a variable from
12810         // the stack requires a const copy constructor.  This is not true
12811         // of the copy/move done to move a __block variable to the heap.
12812         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
12813                                                   DeclRefType.withConst(),
12814                                                   VK_LValue, Loc);
12815 
12816         ExprResult Result
12817           = S.PerformCopyInitialization(
12818               InitializedEntity::InitializeBlock(Var->getLocation(),
12819                                                   CaptureType, false),
12820               Loc, DeclRef);
12821 
12822         // Build a full-expression copy expression if initialization
12823         // succeeded and used a non-trivial constructor.  Recover from
12824         // errors by pretending that the copy isn't necessary.
12825         if (!Result.isInvalid() &&
12826             !cast<CXXConstructExpr>(Result.get())->getConstructor()
12827                 ->isTrivial()) {
12828           Result = S.MaybeCreateExprWithCleanups(Result);
12829           CopyExpr = Result.get();
12830         }
12831       }
12832     }
12833   }
12834 
12835   // Actually capture the variable.
12836   if (BuildAndDiagnose)
12837     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
12838                     SourceLocation(), CaptureType, CopyExpr);
12839 
12840   return true;
12841 
12842 }
12843 
12844 
12845 /// \brief Capture the given variable in the captured region.
12846 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
12847                                     VarDecl *Var,
12848                                     SourceLocation Loc,
12849                                     const bool BuildAndDiagnose,
12850                                     QualType &CaptureType,
12851                                     QualType &DeclRefType,
12852                                     const bool RefersToCapturedVariable,
12853                                     Sema &S) {
12854 
12855   // By default, capture variables by reference.
12856   bool ByRef = true;
12857   // Using an LValue reference type is consistent with Lambdas (see below).
12858   if (S.getLangOpts().OpenMP) {
12859     ByRef = S.IsOpenMPCapturedByRef(Var, RSI);
12860     if (S.IsOpenMPCapturedVar(Var))
12861       DeclRefType = DeclRefType.getUnqualifiedType();
12862   }
12863 
12864   if (ByRef)
12865     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12866   else
12867     CaptureType = DeclRefType;
12868 
12869   Expr *CopyExpr = nullptr;
12870   if (BuildAndDiagnose) {
12871     // The current implementation assumes that all variables are captured
12872     // by references. Since there is no capture by copy, no expression
12873     // evaluation will be needed.
12874     RecordDecl *RD = RSI->TheRecordDecl;
12875 
12876     FieldDecl *Field
12877       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
12878                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
12879                           nullptr, false, ICIS_NoInit);
12880     Field->setImplicit(true);
12881     Field->setAccess(AS_private);
12882     RD->addDecl(Field);
12883 
12884     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
12885                                             DeclRefType, VK_LValue, Loc);
12886     Var->setReferenced(true);
12887     Var->markUsed(S.Context);
12888   }
12889 
12890   // Actually capture the variable.
12891   if (BuildAndDiagnose)
12892     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
12893                     SourceLocation(), CaptureType, CopyExpr);
12894 
12895 
12896   return true;
12897 }
12898 
12899 /// \brief Create a field within the lambda class for the variable
12900 /// being captured.
12901 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
12902                                     QualType FieldType, QualType DeclRefType,
12903                                     SourceLocation Loc,
12904                                     bool RefersToCapturedVariable) {
12905   CXXRecordDecl *Lambda = LSI->Lambda;
12906 
12907   // Build the non-static data member.
12908   FieldDecl *Field
12909     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
12910                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
12911                         nullptr, false, ICIS_NoInit);
12912   Field->setImplicit(true);
12913   Field->setAccess(AS_private);
12914   Lambda->addDecl(Field);
12915 }
12916 
12917 /// \brief Capture the given variable in the lambda.
12918 static bool captureInLambda(LambdaScopeInfo *LSI,
12919                             VarDecl *Var,
12920                             SourceLocation Loc,
12921                             const bool BuildAndDiagnose,
12922                             QualType &CaptureType,
12923                             QualType &DeclRefType,
12924                             const bool RefersToCapturedVariable,
12925                             const Sema::TryCaptureKind Kind,
12926                             SourceLocation EllipsisLoc,
12927                             const bool IsTopScope,
12928                             Sema &S) {
12929 
12930   // Determine whether we are capturing by reference or by value.
12931   bool ByRef = false;
12932   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12933     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12934   } else {
12935     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12936   }
12937 
12938   // Compute the type of the field that will capture this variable.
12939   if (ByRef) {
12940     // C++11 [expr.prim.lambda]p15:
12941     //   An entity is captured by reference if it is implicitly or
12942     //   explicitly captured but not captured by copy. It is
12943     //   unspecified whether additional unnamed non-static data
12944     //   members are declared in the closure type for entities
12945     //   captured by reference.
12946     //
12947     // FIXME: It is not clear whether we want to build an lvalue reference
12948     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12949     // to do the former, while EDG does the latter. Core issue 1249 will
12950     // clarify, but for now we follow GCC because it's a more permissive and
12951     // easily defensible position.
12952     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12953   } else {
12954     // C++11 [expr.prim.lambda]p14:
12955     //   For each entity captured by copy, an unnamed non-static
12956     //   data member is declared in the closure type. The
12957     //   declaration order of these members is unspecified. The type
12958     //   of such a data member is the type of the corresponding
12959     //   captured entity if the entity is not a reference to an
12960     //   object, or the referenced type otherwise. [Note: If the
12961     //   captured entity is a reference to a function, the
12962     //   corresponding data member is also a reference to a
12963     //   function. - end note ]
12964     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12965       if (!RefType->getPointeeType()->isFunctionType())
12966         CaptureType = RefType->getPointeeType();
12967     }
12968 
12969     // Forbid the lambda copy-capture of autoreleasing variables.
12970     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12971       if (BuildAndDiagnose) {
12972         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12973         S.Diag(Var->getLocation(), diag::note_previous_decl)
12974           << Var->getDeclName();
12975       }
12976       return false;
12977     }
12978 
12979     // Make sure that by-copy captures are of a complete and non-abstract type.
12980     if (BuildAndDiagnose) {
12981       if (!CaptureType->isDependentType() &&
12982           S.RequireCompleteType(Loc, CaptureType,
12983                                 diag::err_capture_of_incomplete_type,
12984                                 Var->getDeclName()))
12985         return false;
12986 
12987       if (S.RequireNonAbstractType(Loc, CaptureType,
12988                                    diag::err_capture_of_abstract_type))
12989         return false;
12990     }
12991   }
12992 
12993   // Capture this variable in the lambda.
12994   if (BuildAndDiagnose)
12995     addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
12996                             RefersToCapturedVariable);
12997 
12998   // Compute the type of a reference to this captured variable.
12999   if (ByRef)
13000     DeclRefType = CaptureType.getNonReferenceType();
13001   else {
13002     // C++ [expr.prim.lambda]p5:
13003     //   The closure type for a lambda-expression has a public inline
13004     //   function call operator [...]. This function call operator is
13005     //   declared const (9.3.1) if and only if the lambda-expression’s
13006     //   parameter-declaration-clause is not followed by mutable.
13007     DeclRefType = CaptureType.getNonReferenceType();
13008     if (!LSI->Mutable && !CaptureType->isReferenceType())
13009       DeclRefType.addConst();
13010   }
13011 
13012   // Add the capture.
13013   if (BuildAndDiagnose)
13014     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
13015                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
13016 
13017   return true;
13018 }
13019 
13020 bool Sema::tryCaptureVariable(
13021     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
13022     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
13023     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
13024   // An init-capture is notionally from the context surrounding its
13025   // declaration, but its parent DC is the lambda class.
13026   DeclContext *VarDC = Var->getDeclContext();
13027   if (Var->isInitCapture())
13028     VarDC = VarDC->getParent();
13029 
13030   DeclContext *DC = CurContext;
13031   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
13032       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
13033   // We need to sync up the Declaration Context with the
13034   // FunctionScopeIndexToStopAt
13035   if (FunctionScopeIndexToStopAt) {
13036     unsigned FSIndex = FunctionScopes.size() - 1;
13037     while (FSIndex != MaxFunctionScopesIndex) {
13038       DC = getLambdaAwareParentOfDeclContext(DC);
13039       --FSIndex;
13040     }
13041   }
13042 
13043 
13044   // If the variable is declared in the current context, there is no need to
13045   // capture it.
13046   if (VarDC == DC) return true;
13047 
13048   // Capture global variables if it is required to use private copy of this
13049   // variable.
13050   bool IsGlobal = !Var->hasLocalStorage();
13051   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
13052     return true;
13053 
13054   // Walk up the stack to determine whether we can capture the variable,
13055   // performing the "simple" checks that don't depend on type. We stop when
13056   // we've either hit the declared scope of the variable or find an existing
13057   // capture of that variable.  We start from the innermost capturing-entity
13058   // (the DC) and ensure that all intervening capturing-entities
13059   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
13060   // declcontext can either capture the variable or have already captured
13061   // the variable.
13062   CaptureType = Var->getType();
13063   DeclRefType = CaptureType.getNonReferenceType();
13064   bool Nested = false;
13065   bool Explicit = (Kind != TryCapture_Implicit);
13066   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
13067   unsigned OpenMPLevel = 0;
13068   do {
13069     // Only block literals, captured statements, and lambda expressions can
13070     // capture; other scopes don't work.
13071     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
13072                                                               ExprLoc,
13073                                                               BuildAndDiagnose,
13074                                                               *this);
13075     // We need to check for the parent *first* because, if we *have*
13076     // private-captured a global variable, we need to recursively capture it in
13077     // intermediate blocks, lambdas, etc.
13078     if (!ParentDC) {
13079       if (IsGlobal) {
13080         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13081         break;
13082       }
13083       return true;
13084     }
13085 
13086     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13087     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13088 
13089 
13090     // Check whether we've already captured it.
13091     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13092                                              DeclRefType))
13093       break;
13094     // If we are instantiating a generic lambda call operator body,
13095     // we do not want to capture new variables.  What was captured
13096     // during either a lambdas transformation or initial parsing
13097     // should be used.
13098     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13099       if (BuildAndDiagnose) {
13100         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13101         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13102           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13103           Diag(Var->getLocation(), diag::note_previous_decl)
13104              << Var->getDeclName();
13105           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13106         } else
13107           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13108       }
13109       return true;
13110     }
13111     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13112     // certain types of variables (unnamed, variably modified types etc.)
13113     // so check for eligibility.
13114     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13115        return true;
13116 
13117     // Try to capture variable-length arrays types.
13118     if (Var->getType()->isVariablyModifiedType()) {
13119       // We're going to walk down into the type and look for VLA
13120       // expressions.
13121       QualType QTy = Var->getType();
13122       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13123         QTy = PVD->getOriginalType();
13124       do {
13125         const Type *Ty = QTy.getTypePtr();
13126         switch (Ty->getTypeClass()) {
13127 #define TYPE(Class, Base)
13128 #define ABSTRACT_TYPE(Class, Base)
13129 #define NON_CANONICAL_TYPE(Class, Base)
13130 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
13131 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
13132 #include "clang/AST/TypeNodes.def"
13133           QTy = QualType();
13134           break;
13135         // These types are never variably-modified.
13136         case Type::Builtin:
13137         case Type::Complex:
13138         case Type::Vector:
13139         case Type::ExtVector:
13140         case Type::Record:
13141         case Type::Enum:
13142         case Type::Elaborated:
13143         case Type::TemplateSpecialization:
13144         case Type::ObjCObject:
13145         case Type::ObjCInterface:
13146         case Type::ObjCObjectPointer:
13147           llvm_unreachable("type class is never variably-modified!");
13148         case Type::Adjusted:
13149           QTy = cast<AdjustedType>(Ty)->getOriginalType();
13150           break;
13151         case Type::Decayed:
13152           QTy = cast<DecayedType>(Ty)->getPointeeType();
13153           break;
13154         case Type::Pointer:
13155           QTy = cast<PointerType>(Ty)->getPointeeType();
13156           break;
13157         case Type::BlockPointer:
13158           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
13159           break;
13160         case Type::LValueReference:
13161         case Type::RValueReference:
13162           QTy = cast<ReferenceType>(Ty)->getPointeeType();
13163           break;
13164         case Type::MemberPointer:
13165           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
13166           break;
13167         case Type::ConstantArray:
13168         case Type::IncompleteArray:
13169           // Losing element qualification here is fine.
13170           QTy = cast<ArrayType>(Ty)->getElementType();
13171           break;
13172         case Type::VariableArray: {
13173           // Losing element qualification here is fine.
13174           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
13175 
13176           // Unknown size indication requires no size computation.
13177           // Otherwise, evaluate and record it.
13178           if (auto Size = VAT->getSizeExpr()) {
13179             if (!CSI->isVLATypeCaptured(VAT)) {
13180               RecordDecl *CapRecord = nullptr;
13181               if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
13182                 CapRecord = LSI->Lambda;
13183               } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13184                 CapRecord = CRSI->TheRecordDecl;
13185               }
13186               if (CapRecord) {
13187                 auto ExprLoc = Size->getExprLoc();
13188                 auto SizeType = Context.getSizeType();
13189                 // Build the non-static data member.
13190                 auto Field = FieldDecl::Create(
13191                     Context, CapRecord, ExprLoc, ExprLoc,
13192                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
13193                     /*BW*/ nullptr, /*Mutable*/ false,
13194                     /*InitStyle*/ ICIS_NoInit);
13195                 Field->setImplicit(true);
13196                 Field->setAccess(AS_private);
13197                 Field->setCapturedVLAType(VAT);
13198                 CapRecord->addDecl(Field);
13199 
13200                 CSI->addVLATypeCapture(ExprLoc, SizeType);
13201               }
13202             }
13203           }
13204           QTy = VAT->getElementType();
13205           break;
13206         }
13207         case Type::FunctionProto:
13208         case Type::FunctionNoProto:
13209           QTy = cast<FunctionType>(Ty)->getReturnType();
13210           break;
13211         case Type::Paren:
13212         case Type::TypeOf:
13213         case Type::UnaryTransform:
13214         case Type::Attributed:
13215         case Type::SubstTemplateTypeParm:
13216         case Type::PackExpansion:
13217           // Keep walking after single level desugaring.
13218           QTy = QTy.getSingleStepDesugaredType(getASTContext());
13219           break;
13220         case Type::Typedef:
13221           QTy = cast<TypedefType>(Ty)->desugar();
13222           break;
13223         case Type::Decltype:
13224           QTy = cast<DecltypeType>(Ty)->desugar();
13225           break;
13226         case Type::Auto:
13227           QTy = cast<AutoType>(Ty)->getDeducedType();
13228           break;
13229         case Type::TypeOfExpr:
13230           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
13231           break;
13232         case Type::Atomic:
13233           QTy = cast<AtomicType>(Ty)->getValueType();
13234           break;
13235         }
13236       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
13237     }
13238 
13239     if (getLangOpts().OpenMP) {
13240       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13241         // OpenMP private variables should not be captured in outer scope, so
13242         // just break here. Similarly, global variables that are captured in a
13243         // target region should not be captured outside the scope of the region.
13244         if (RSI->CapRegionKind == CR_OpenMP) {
13245           auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel);
13246           // When we detect target captures we are looking from inside the
13247           // target region, therefore we need to propagate the capture from the
13248           // enclosing region. Therefore, the capture is not initially nested.
13249           if (isTargetCap)
13250             FunctionScopesIndex--;
13251 
13252           if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) {
13253             Nested = !isTargetCap;
13254             DeclRefType = DeclRefType.getUnqualifiedType();
13255             CaptureType = Context.getLValueReferenceType(DeclRefType);
13256             break;
13257           }
13258           ++OpenMPLevel;
13259         }
13260       }
13261     }
13262     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13263       // No capture-default, and this is not an explicit capture
13264       // so cannot capture this variable.
13265       if (BuildAndDiagnose) {
13266         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13267         Diag(Var->getLocation(), diag::note_previous_decl)
13268           << Var->getDeclName();
13269         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13270              diag::note_lambda_decl);
13271         // FIXME: If we error out because an outer lambda can not implicitly
13272         // capture a variable that an inner lambda explicitly captures, we
13273         // should have the inner lambda do the explicit capture - because
13274         // it makes for cleaner diagnostics later.  This would purely be done
13275         // so that the diagnostic does not misleadingly claim that a variable
13276         // can not be captured by a lambda implicitly even though it is captured
13277         // explicitly.  Suggestion:
13278         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13279         //    at the function head
13280         //  - cache the StartingDeclContext - this must be a lambda
13281         //  - captureInLambda in the innermost lambda the variable.
13282       }
13283       return true;
13284     }
13285 
13286     FunctionScopesIndex--;
13287     DC = ParentDC;
13288     Explicit = false;
13289   } while (!VarDC->Equals(DC));
13290 
13291   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13292   // computing the type of the capture at each step, checking type-specific
13293   // requirements, and adding captures if requested.
13294   // If the variable had already been captured previously, we start capturing
13295   // at the lambda nested within that one.
13296   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13297        ++I) {
13298     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13299 
13300     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13301       if (!captureInBlock(BSI, Var, ExprLoc,
13302                           BuildAndDiagnose, CaptureType,
13303                           DeclRefType, Nested, *this))
13304         return true;
13305       Nested = true;
13306     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13307       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13308                                    BuildAndDiagnose, CaptureType,
13309                                    DeclRefType, Nested, *this))
13310         return true;
13311       Nested = true;
13312     } else {
13313       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13314       if (!captureInLambda(LSI, Var, ExprLoc,
13315                            BuildAndDiagnose, CaptureType,
13316                            DeclRefType, Nested, Kind, EllipsisLoc,
13317                             /*IsTopScope*/I == N - 1, *this))
13318         return true;
13319       Nested = true;
13320     }
13321   }
13322   return false;
13323 }
13324 
13325 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13326                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13327   QualType CaptureType;
13328   QualType DeclRefType;
13329   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13330                             /*BuildAndDiagnose=*/true, CaptureType,
13331                             DeclRefType, nullptr);
13332 }
13333 
13334 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13335   QualType CaptureType;
13336   QualType DeclRefType;
13337   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13338                              /*BuildAndDiagnose=*/false, CaptureType,
13339                              DeclRefType, nullptr);
13340 }
13341 
13342 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13343   QualType CaptureType;
13344   QualType DeclRefType;
13345 
13346   // Determine whether we can capture this variable.
13347   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13348                          /*BuildAndDiagnose=*/false, CaptureType,
13349                          DeclRefType, nullptr))
13350     return QualType();
13351 
13352   return DeclRefType;
13353 }
13354 
13355 
13356 
13357 // If either the type of the variable or the initializer is dependent,
13358 // return false. Otherwise, determine whether the variable is a constant
13359 // expression. Use this if you need to know if a variable that might or
13360 // might not be dependent is truly a constant expression.
13361 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13362     ASTContext &Context) {
13363 
13364   if (Var->getType()->isDependentType())
13365     return false;
13366   const VarDecl *DefVD = nullptr;
13367   Var->getAnyInitializer(DefVD);
13368   if (!DefVD)
13369     return false;
13370   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13371   Expr *Init = cast<Expr>(Eval->Value);
13372   if (Init->isValueDependent())
13373     return false;
13374   return IsVariableAConstantExpression(Var, Context);
13375 }
13376 
13377 
13378 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13379   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13380   // an object that satisfies the requirements for appearing in a
13381   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13382   // is immediately applied."  This function handles the lvalue-to-rvalue
13383   // conversion part.
13384   MaybeODRUseExprs.erase(E->IgnoreParens());
13385 
13386   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13387   // to a variable that is a constant expression, and if so, identify it as
13388   // a reference to a variable that does not involve an odr-use of that
13389   // variable.
13390   if (LambdaScopeInfo *LSI = getCurLambda()) {
13391     Expr *SansParensExpr = E->IgnoreParens();
13392     VarDecl *Var = nullptr;
13393     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13394       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13395     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13396       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13397 
13398     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13399       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13400   }
13401 }
13402 
13403 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13404   Res = CorrectDelayedTyposInExpr(Res);
13405 
13406   if (!Res.isUsable())
13407     return Res;
13408 
13409   // If a constant-expression is a reference to a variable where we delay
13410   // deciding whether it is an odr-use, just assume we will apply the
13411   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13412   // (a non-type template argument), we have special handling anyway.
13413   UpdateMarkingForLValueToRValue(Res.get());
13414   return Res;
13415 }
13416 
13417 void Sema::CleanupVarDeclMarking() {
13418   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
13419                                         e = MaybeODRUseExprs.end();
13420        i != e; ++i) {
13421     VarDecl *Var;
13422     SourceLocation Loc;
13423     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
13424       Var = cast<VarDecl>(DRE->getDecl());
13425       Loc = DRE->getLocation();
13426     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
13427       Var = cast<VarDecl>(ME->getMemberDecl());
13428       Loc = ME->getMemberLoc();
13429     } else {
13430       llvm_unreachable("Unexpected expression");
13431     }
13432 
13433     MarkVarDeclODRUsed(Var, Loc, *this,
13434                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13435   }
13436 
13437   MaybeODRUseExprs.clear();
13438 }
13439 
13440 
13441 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13442                                     VarDecl *Var, Expr *E) {
13443   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13444          "Invalid Expr argument to DoMarkVarDeclReferenced");
13445   Var->setReferenced();
13446 
13447   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13448   bool MarkODRUsed = true;
13449 
13450   // If the context is not potentially evaluated, this is not an odr-use and
13451   // does not trigger instantiation.
13452   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13453     if (SemaRef.isUnevaluatedContext())
13454       return;
13455 
13456     // If we don't yet know whether this context is going to end up being an
13457     // evaluated context, and we're referencing a variable from an enclosing
13458     // scope, add a potential capture.
13459     //
13460     // FIXME: Is this necessary? These contexts are only used for default
13461     // arguments, where local variables can't be used.
13462     const bool RefersToEnclosingScope =
13463         (SemaRef.CurContext != Var->getDeclContext() &&
13464          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13465     if (RefersToEnclosingScope) {
13466       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13467         // If a variable could potentially be odr-used, defer marking it so
13468         // until we finish analyzing the full expression for any
13469         // lvalue-to-rvalue
13470         // or discarded value conversions that would obviate odr-use.
13471         // Add it to the list of potential captures that will be analyzed
13472         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13473         // unless the variable is a reference that was initialized by a constant
13474         // expression (this will never need to be captured or odr-used).
13475         assert(E && "Capture variable should be used in an expression.");
13476         if (!Var->getType()->isReferenceType() ||
13477             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13478           LSI->addPotentialCapture(E->IgnoreParens());
13479       }
13480     }
13481 
13482     if (!isTemplateInstantiation(TSK))
13483     	return;
13484 
13485     // Instantiate, but do not mark as odr-used, variable templates.
13486     MarkODRUsed = false;
13487   }
13488 
13489   VarTemplateSpecializationDecl *VarSpec =
13490       dyn_cast<VarTemplateSpecializationDecl>(Var);
13491   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13492          "Can't instantiate a partial template specialization.");
13493 
13494   // Perform implicit instantiation of static data members, static data member
13495   // templates of class templates, and variable template specializations. Delay
13496   // instantiations of variable templates, except for those that could be used
13497   // in a constant expression.
13498   if (isTemplateInstantiation(TSK)) {
13499     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13500 
13501     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13502       if (Var->getPointOfInstantiation().isInvalid()) {
13503         // This is a modification of an existing AST node. Notify listeners.
13504         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13505           L->StaticDataMemberInstantiated(Var);
13506       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13507         // Don't bother trying to instantiate it again, unless we might need
13508         // its initializer before we get to the end of the TU.
13509         TryInstantiating = false;
13510     }
13511 
13512     if (Var->getPointOfInstantiation().isInvalid())
13513       Var->setTemplateSpecializationKind(TSK, Loc);
13514 
13515     if (TryInstantiating) {
13516       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13517       bool InstantiationDependent = false;
13518       bool IsNonDependent =
13519           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13520                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13521                   : true;
13522 
13523       // Do not instantiate specializations that are still type-dependent.
13524       if (IsNonDependent) {
13525         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13526           // Do not defer instantiations of variables which could be used in a
13527           // constant expression.
13528           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13529         } else {
13530           SemaRef.PendingInstantiations
13531               .push_back(std::make_pair(Var, PointOfInstantiation));
13532         }
13533       }
13534     }
13535   }
13536 
13537   if(!MarkODRUsed) return;
13538 
13539   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13540   // the requirements for appearing in a constant expression (5.19) and, if
13541   // it is an object, the lvalue-to-rvalue conversion (4.1)
13542   // is immediately applied."  We check the first part here, and
13543   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13544   // Note that we use the C++11 definition everywhere because nothing in
13545   // C++03 depends on whether we get the C++03 version correct. The second
13546   // part does not apply to references, since they are not objects.
13547   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13548     // A reference initialized by a constant expression can never be
13549     // odr-used, so simply ignore it.
13550     if (!Var->getType()->isReferenceType())
13551       SemaRef.MaybeODRUseExprs.insert(E);
13552   } else
13553     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13554                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13555 }
13556 
13557 /// \brief Mark a variable referenced, and check whether it is odr-used
13558 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13559 /// used directly for normal expressions referring to VarDecl.
13560 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13561   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13562 }
13563 
13564 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13565                                Decl *D, Expr *E, bool OdrUse) {
13566   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13567     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13568     return;
13569   }
13570 
13571   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
13572 
13573   // If this is a call to a method via a cast, also mark the method in the
13574   // derived class used in case codegen can devirtualize the call.
13575   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13576   if (!ME)
13577     return;
13578   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13579   if (!MD)
13580     return;
13581   // Only attempt to devirtualize if this is truly a virtual call.
13582   bool IsVirtualCall = MD->isVirtual() &&
13583                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
13584   if (!IsVirtualCall)
13585     return;
13586   const Expr *Base = ME->getBase();
13587   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
13588   if (!MostDerivedClassDecl)
13589     return;
13590   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
13591   if (!DM || DM->isPure())
13592     return;
13593   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
13594 }
13595 
13596 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13597 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
13598   // TODO: update this with DR# once a defect report is filed.
13599   // C++11 defect. The address of a pure member should not be an ODR use, even
13600   // if it's a qualified reference.
13601   bool OdrUse = true;
13602   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
13603     if (Method->isVirtual())
13604       OdrUse = false;
13605   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
13606 }
13607 
13608 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
13609 void Sema::MarkMemberReferenced(MemberExpr *E) {
13610   // C++11 [basic.def.odr]p2:
13611   //   A non-overloaded function whose name appears as a potentially-evaluated
13612   //   expression or a member of a set of candidate functions, if selected by
13613   //   overload resolution when referred to from a potentially-evaluated
13614   //   expression, is odr-used, unless it is a pure virtual function and its
13615   //   name is not explicitly qualified.
13616   bool OdrUse = true;
13617   if (E->performsVirtualDispatch(getLangOpts())) {
13618     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13619       if (Method->isPure())
13620         OdrUse = false;
13621   }
13622   SourceLocation Loc = E->getMemberLoc().isValid() ?
13623                             E->getMemberLoc() : E->getLocStart();
13624   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
13625 }
13626 
13627 /// \brief Perform marking for a reference to an arbitrary declaration.  It
13628 /// marks the declaration referenced, and performs odr-use checking for
13629 /// functions and variables. This method should not be used when building a
13630 /// normal expression which refers to a variable.
13631 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
13632   if (OdrUse) {
13633     if (auto *VD = dyn_cast<VarDecl>(D)) {
13634       MarkVariableReferenced(Loc, VD);
13635       return;
13636     }
13637   }
13638   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13639     MarkFunctionReferenced(Loc, FD, OdrUse);
13640     return;
13641   }
13642   D->setReferenced();
13643 }
13644 
13645 namespace {
13646   // Mark all of the declarations referenced
13647   // FIXME: Not fully implemented yet! We need to have a better understanding
13648   // of when we're entering
13649   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13650     Sema &S;
13651     SourceLocation Loc;
13652 
13653   public:
13654     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
13655 
13656     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
13657 
13658     bool TraverseTemplateArgument(const TemplateArgument &Arg);
13659     bool TraverseRecordType(RecordType *T);
13660   };
13661 }
13662 
13663 bool MarkReferencedDecls::TraverseTemplateArgument(
13664     const TemplateArgument &Arg) {
13665   if (Arg.getKind() == TemplateArgument::Declaration) {
13666     if (Decl *D = Arg.getAsDecl())
13667       S.MarkAnyDeclReferenced(Loc, D, true);
13668   }
13669 
13670   return Inherited::TraverseTemplateArgument(Arg);
13671 }
13672 
13673 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
13674   if (ClassTemplateSpecializationDecl *Spec
13675                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13676     const TemplateArgumentList &Args = Spec->getTemplateArgs();
13677     return TraverseTemplateArguments(Args.data(), Args.size());
13678   }
13679 
13680   return true;
13681 }
13682 
13683 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13684   MarkReferencedDecls Marker(*this, Loc);
13685   Marker.TraverseType(Context.getCanonicalType(T));
13686 }
13687 
13688 namespace {
13689   /// \brief Helper class that marks all of the declarations referenced by
13690   /// potentially-evaluated subexpressions as "referenced".
13691   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13692     Sema &S;
13693     bool SkipLocalVariables;
13694 
13695   public:
13696     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13697 
13698     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
13699       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
13700 
13701     void VisitDeclRefExpr(DeclRefExpr *E) {
13702       // If we were asked not to visit local variables, don't.
13703       if (SkipLocalVariables) {
13704         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13705           if (VD->hasLocalStorage())
13706             return;
13707       }
13708 
13709       S.MarkDeclRefReferenced(E);
13710     }
13711 
13712     void VisitMemberExpr(MemberExpr *E) {
13713       S.MarkMemberReferenced(E);
13714       Inherited::VisitMemberExpr(E);
13715     }
13716 
13717     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13718       S.MarkFunctionReferenced(E->getLocStart(),
13719             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13720       Visit(E->getSubExpr());
13721     }
13722 
13723     void VisitCXXNewExpr(CXXNewExpr *E) {
13724       if (E->getOperatorNew())
13725         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
13726       if (E->getOperatorDelete())
13727         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13728       Inherited::VisitCXXNewExpr(E);
13729     }
13730 
13731     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13732       if (E->getOperatorDelete())
13733         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13734       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13735       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13736         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
13737         S.MarkFunctionReferenced(E->getLocStart(),
13738                                     S.LookupDestructor(Record));
13739       }
13740 
13741       Inherited::VisitCXXDeleteExpr(E);
13742     }
13743 
13744     void VisitCXXConstructExpr(CXXConstructExpr *E) {
13745       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
13746       Inherited::VisitCXXConstructExpr(E);
13747     }
13748 
13749     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
13750       Visit(E->getExpr());
13751     }
13752 
13753     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13754       Inherited::VisitImplicitCastExpr(E);
13755 
13756       if (E->getCastKind() == CK_LValueToRValue)
13757         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
13758     }
13759   };
13760 }
13761 
13762 /// \brief Mark any declarations that appear within this expression or any
13763 /// potentially-evaluated subexpressions as "referenced".
13764 ///
13765 /// \param SkipLocalVariables If true, don't mark local variables as
13766 /// 'referenced'.
13767 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
13768                                             bool SkipLocalVariables) {
13769   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
13770 }
13771 
13772 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
13773 /// of the program being compiled.
13774 ///
13775 /// This routine emits the given diagnostic when the code currently being
13776 /// type-checked is "potentially evaluated", meaning that there is a
13777 /// possibility that the code will actually be executable. Code in sizeof()
13778 /// expressions, code used only during overload resolution, etc., are not
13779 /// potentially evaluated. This routine will suppress such diagnostics or,
13780 /// in the absolutely nutty case of potentially potentially evaluated
13781 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
13782 /// later.
13783 ///
13784 /// This routine should be used for all diagnostics that describe the run-time
13785 /// behavior of a program, such as passing a non-POD value through an ellipsis.
13786 /// Failure to do so will likely result in spurious diagnostics or failures
13787 /// during overload resolution or within sizeof/alignof/typeof/typeid.
13788 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
13789                                const PartialDiagnostic &PD) {
13790   switch (ExprEvalContexts.back().Context) {
13791   case Unevaluated:
13792   case UnevaluatedAbstract:
13793     // The argument will never be evaluated, so don't complain.
13794     break;
13795 
13796   case ConstantEvaluated:
13797     // Relevant diagnostics should be produced by constant evaluation.
13798     break;
13799 
13800   case PotentiallyEvaluated:
13801   case PotentiallyEvaluatedIfUsed:
13802     if (Statement && getCurFunctionOrMethodDecl()) {
13803       FunctionScopes.back()->PossiblyUnreachableDiags.
13804         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
13805     }
13806     else
13807       Diag(Loc, PD);
13808 
13809     return true;
13810   }
13811 
13812   return false;
13813 }
13814 
13815 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
13816                                CallExpr *CE, FunctionDecl *FD) {
13817   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
13818     return false;
13819 
13820   // If we're inside a decltype's expression, don't check for a valid return
13821   // type or construct temporaries until we know whether this is the last call.
13822   if (ExprEvalContexts.back().IsDecltype) {
13823     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
13824     return false;
13825   }
13826 
13827   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
13828     FunctionDecl *FD;
13829     CallExpr *CE;
13830 
13831   public:
13832     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13833       : FD(FD), CE(CE) { }
13834 
13835     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
13836       if (!FD) {
13837         S.Diag(Loc, diag::err_call_incomplete_return)
13838           << T << CE->getSourceRange();
13839         return;
13840       }
13841 
13842       S.Diag(Loc, diag::err_call_function_incomplete_return)
13843         << CE->getSourceRange() << FD->getDeclName() << T;
13844       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13845           << FD->getDeclName();
13846     }
13847   } Diagnoser(FD, CE);
13848 
13849   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
13850     return true;
13851 
13852   return false;
13853 }
13854 
13855 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
13856 // will prevent this condition from triggering, which is what we want.
13857 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13858   SourceLocation Loc;
13859 
13860   unsigned diagnostic = diag::warn_condition_is_assignment;
13861   bool IsOrAssign = false;
13862 
13863   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
13864     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
13865       return;
13866 
13867     IsOrAssign = Op->getOpcode() == BO_OrAssign;
13868 
13869     // Greylist some idioms by putting them into a warning subcategory.
13870     if (ObjCMessageExpr *ME
13871           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13872       Selector Sel = ME->getSelector();
13873 
13874       // self = [<foo> init...]
13875       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
13876         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13877 
13878       // <foo> = [<bar> nextObject]
13879       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
13880         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13881     }
13882 
13883     Loc = Op->getOperatorLoc();
13884   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
13885     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
13886       return;
13887 
13888     IsOrAssign = Op->getOperator() == OO_PipeEqual;
13889     Loc = Op->getOperatorLoc();
13890   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13891     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13892   else {
13893     // Not an assignment.
13894     return;
13895   }
13896 
13897   Diag(Loc, diagnostic) << E->getSourceRange();
13898 
13899   SourceLocation Open = E->getLocStart();
13900   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
13901   Diag(Loc, diag::note_condition_assign_silence)
13902         << FixItHint::CreateInsertion(Open, "(")
13903         << FixItHint::CreateInsertion(Close, ")");
13904 
13905   if (IsOrAssign)
13906     Diag(Loc, diag::note_condition_or_assign_to_comparison)
13907       << FixItHint::CreateReplacement(Loc, "!=");
13908   else
13909     Diag(Loc, diag::note_condition_assign_to_comparison)
13910       << FixItHint::CreateReplacement(Loc, "==");
13911 }
13912 
13913 /// \brief Redundant parentheses over an equality comparison can indicate
13914 /// that the user intended an assignment used as condition.
13915 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
13916   // Don't warn if the parens came from a macro.
13917   SourceLocation parenLoc = ParenE->getLocStart();
13918   if (parenLoc.isInvalid() || parenLoc.isMacroID())
13919     return;
13920   // Don't warn for dependent expressions.
13921   if (ParenE->isTypeDependent())
13922     return;
13923 
13924   Expr *E = ParenE->IgnoreParens();
13925 
13926   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
13927     if (opE->getOpcode() == BO_EQ &&
13928         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13929                                                            == Expr::MLV_Valid) {
13930       SourceLocation Loc = opE->getOperatorLoc();
13931 
13932       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
13933       SourceRange ParenERange = ParenE->getSourceRange();
13934       Diag(Loc, diag::note_equality_comparison_silence)
13935         << FixItHint::CreateRemoval(ParenERange.getBegin())
13936         << FixItHint::CreateRemoval(ParenERange.getEnd());
13937       Diag(Loc, diag::note_equality_comparison_to_assign)
13938         << FixItHint::CreateReplacement(Loc, "=");
13939     }
13940 }
13941 
13942 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
13943   DiagnoseAssignmentAsCondition(E);
13944   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13945     DiagnoseEqualityWithExtraParens(parenE);
13946 
13947   ExprResult result = CheckPlaceholderExpr(E);
13948   if (result.isInvalid()) return ExprError();
13949   E = result.get();
13950 
13951   if (!E->isTypeDependent()) {
13952     if (getLangOpts().CPlusPlus)
13953       return CheckCXXBooleanCondition(E); // C++ 6.4p4
13954 
13955     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13956     if (ERes.isInvalid())
13957       return ExprError();
13958     E = ERes.get();
13959 
13960     QualType T = E->getType();
13961     if (!T->isScalarType()) { // C99 6.8.4.1p1
13962       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13963         << T << E->getSourceRange();
13964       return ExprError();
13965     }
13966     CheckBoolLikeConversion(E, Loc);
13967   }
13968 
13969   return E;
13970 }
13971 
13972 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
13973                                        Expr *SubExpr) {
13974   if (!SubExpr)
13975     return ExprError();
13976 
13977   return CheckBooleanCondition(SubExpr, Loc);
13978 }
13979 
13980 namespace {
13981   /// A visitor for rebuilding a call to an __unknown_any expression
13982   /// to have an appropriate type.
13983   struct RebuildUnknownAnyFunction
13984     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13985 
13986     Sema &S;
13987 
13988     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13989 
13990     ExprResult VisitStmt(Stmt *S) {
13991       llvm_unreachable("unexpected statement!");
13992     }
13993 
13994     ExprResult VisitExpr(Expr *E) {
13995       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13996         << E->getSourceRange();
13997       return ExprError();
13998     }
13999 
14000     /// Rebuild an expression which simply semantically wraps another
14001     /// expression which it shares the type and value kind of.
14002     template <class T> ExprResult rebuildSugarExpr(T *E) {
14003       ExprResult SubResult = Visit(E->getSubExpr());
14004       if (SubResult.isInvalid()) return ExprError();
14005 
14006       Expr *SubExpr = SubResult.get();
14007       E->setSubExpr(SubExpr);
14008       E->setType(SubExpr->getType());
14009       E->setValueKind(SubExpr->getValueKind());
14010       assert(E->getObjectKind() == OK_Ordinary);
14011       return E;
14012     }
14013 
14014     ExprResult VisitParenExpr(ParenExpr *E) {
14015       return rebuildSugarExpr(E);
14016     }
14017 
14018     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14019       return rebuildSugarExpr(E);
14020     }
14021 
14022     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14023       ExprResult SubResult = Visit(E->getSubExpr());
14024       if (SubResult.isInvalid()) return ExprError();
14025 
14026       Expr *SubExpr = SubResult.get();
14027       E->setSubExpr(SubExpr);
14028       E->setType(S.Context.getPointerType(SubExpr->getType()));
14029       assert(E->getValueKind() == VK_RValue);
14030       assert(E->getObjectKind() == OK_Ordinary);
14031       return E;
14032     }
14033 
14034     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
14035       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
14036 
14037       E->setType(VD->getType());
14038 
14039       assert(E->getValueKind() == VK_RValue);
14040       if (S.getLangOpts().CPlusPlus &&
14041           !(isa<CXXMethodDecl>(VD) &&
14042             cast<CXXMethodDecl>(VD)->isInstance()))
14043         E->setValueKind(VK_LValue);
14044 
14045       return E;
14046     }
14047 
14048     ExprResult VisitMemberExpr(MemberExpr *E) {
14049       return resolveDecl(E, E->getMemberDecl());
14050     }
14051 
14052     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14053       return resolveDecl(E, E->getDecl());
14054     }
14055   };
14056 }
14057 
14058 /// Given a function expression of unknown-any type, try to rebuild it
14059 /// to have a function type.
14060 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
14061   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
14062   if (Result.isInvalid()) return ExprError();
14063   return S.DefaultFunctionArrayConversion(Result.get());
14064 }
14065 
14066 namespace {
14067   /// A visitor for rebuilding an expression of type __unknown_anytype
14068   /// into one which resolves the type directly on the referring
14069   /// expression.  Strict preservation of the original source
14070   /// structure is not a goal.
14071   struct RebuildUnknownAnyExpr
14072     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
14073 
14074     Sema &S;
14075 
14076     /// The current destination type.
14077     QualType DestType;
14078 
14079     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14080       : S(S), DestType(CastType) {}
14081 
14082     ExprResult VisitStmt(Stmt *S) {
14083       llvm_unreachable("unexpected statement!");
14084     }
14085 
14086     ExprResult VisitExpr(Expr *E) {
14087       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14088         << E->getSourceRange();
14089       return ExprError();
14090     }
14091 
14092     ExprResult VisitCallExpr(CallExpr *E);
14093     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14094 
14095     /// Rebuild an expression which simply semantically wraps another
14096     /// expression which it shares the type and value kind of.
14097     template <class T> ExprResult rebuildSugarExpr(T *E) {
14098       ExprResult SubResult = Visit(E->getSubExpr());
14099       if (SubResult.isInvalid()) return ExprError();
14100       Expr *SubExpr = SubResult.get();
14101       E->setSubExpr(SubExpr);
14102       E->setType(SubExpr->getType());
14103       E->setValueKind(SubExpr->getValueKind());
14104       assert(E->getObjectKind() == OK_Ordinary);
14105       return E;
14106     }
14107 
14108     ExprResult VisitParenExpr(ParenExpr *E) {
14109       return rebuildSugarExpr(E);
14110     }
14111 
14112     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14113       return rebuildSugarExpr(E);
14114     }
14115 
14116     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14117       const PointerType *Ptr = DestType->getAs<PointerType>();
14118       if (!Ptr) {
14119         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14120           << E->getSourceRange();
14121         return ExprError();
14122       }
14123       assert(E->getValueKind() == VK_RValue);
14124       assert(E->getObjectKind() == OK_Ordinary);
14125       E->setType(DestType);
14126 
14127       // Build the sub-expression as if it were an object of the pointee type.
14128       DestType = Ptr->getPointeeType();
14129       ExprResult SubResult = Visit(E->getSubExpr());
14130       if (SubResult.isInvalid()) return ExprError();
14131       E->setSubExpr(SubResult.get());
14132       return E;
14133     }
14134 
14135     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14136 
14137     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14138 
14139     ExprResult VisitMemberExpr(MemberExpr *E) {
14140       return resolveDecl(E, E->getMemberDecl());
14141     }
14142 
14143     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14144       return resolveDecl(E, E->getDecl());
14145     }
14146   };
14147 }
14148 
14149 /// Rebuilds a call expression which yielded __unknown_anytype.
14150 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14151   Expr *CalleeExpr = E->getCallee();
14152 
14153   enum FnKind {
14154     FK_MemberFunction,
14155     FK_FunctionPointer,
14156     FK_BlockPointer
14157   };
14158 
14159   FnKind Kind;
14160   QualType CalleeType = CalleeExpr->getType();
14161   if (CalleeType == S.Context.BoundMemberTy) {
14162     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14163     Kind = FK_MemberFunction;
14164     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14165   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14166     CalleeType = Ptr->getPointeeType();
14167     Kind = FK_FunctionPointer;
14168   } else {
14169     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14170     Kind = FK_BlockPointer;
14171   }
14172   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14173 
14174   // Verify that this is a legal result type of a function.
14175   if (DestType->isArrayType() || DestType->isFunctionType()) {
14176     unsigned diagID = diag::err_func_returning_array_function;
14177     if (Kind == FK_BlockPointer)
14178       diagID = diag::err_block_returning_array_function;
14179 
14180     S.Diag(E->getExprLoc(), diagID)
14181       << DestType->isFunctionType() << DestType;
14182     return ExprError();
14183   }
14184 
14185   // Otherwise, go ahead and set DestType as the call's result.
14186   E->setType(DestType.getNonLValueExprType(S.Context));
14187   E->setValueKind(Expr::getValueKindForType(DestType));
14188   assert(E->getObjectKind() == OK_Ordinary);
14189 
14190   // Rebuild the function type, replacing the result type with DestType.
14191   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14192   if (Proto) {
14193     // __unknown_anytype(...) is a special case used by the debugger when
14194     // it has no idea what a function's signature is.
14195     //
14196     // We want to build this call essentially under the K&R
14197     // unprototyped rules, but making a FunctionNoProtoType in C++
14198     // would foul up all sorts of assumptions.  However, we cannot
14199     // simply pass all arguments as variadic arguments, nor can we
14200     // portably just call the function under a non-variadic type; see
14201     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14202     // However, it turns out that in practice it is generally safe to
14203     // call a function declared as "A foo(B,C,D);" under the prototype
14204     // "A foo(B,C,D,...);".  The only known exception is with the
14205     // Windows ABI, where any variadic function is implicitly cdecl
14206     // regardless of its normal CC.  Therefore we change the parameter
14207     // types to match the types of the arguments.
14208     //
14209     // This is a hack, but it is far superior to moving the
14210     // corresponding target-specific code from IR-gen to Sema/AST.
14211 
14212     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14213     SmallVector<QualType, 8> ArgTypes;
14214     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14215       ArgTypes.reserve(E->getNumArgs());
14216       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14217         Expr *Arg = E->getArg(i);
14218         QualType ArgType = Arg->getType();
14219         if (E->isLValue()) {
14220           ArgType = S.Context.getLValueReferenceType(ArgType);
14221         } else if (E->isXValue()) {
14222           ArgType = S.Context.getRValueReferenceType(ArgType);
14223         }
14224         ArgTypes.push_back(ArgType);
14225       }
14226       ParamTypes = ArgTypes;
14227     }
14228     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14229                                          Proto->getExtProtoInfo());
14230   } else {
14231     DestType = S.Context.getFunctionNoProtoType(DestType,
14232                                                 FnType->getExtInfo());
14233   }
14234 
14235   // Rebuild the appropriate pointer-to-function type.
14236   switch (Kind) {
14237   case FK_MemberFunction:
14238     // Nothing to do.
14239     break;
14240 
14241   case FK_FunctionPointer:
14242     DestType = S.Context.getPointerType(DestType);
14243     break;
14244 
14245   case FK_BlockPointer:
14246     DestType = S.Context.getBlockPointerType(DestType);
14247     break;
14248   }
14249 
14250   // Finally, we can recurse.
14251   ExprResult CalleeResult = Visit(CalleeExpr);
14252   if (!CalleeResult.isUsable()) return ExprError();
14253   E->setCallee(CalleeResult.get());
14254 
14255   // Bind a temporary if necessary.
14256   return S.MaybeBindToTemporary(E);
14257 }
14258 
14259 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14260   // Verify that this is a legal result type of a call.
14261   if (DestType->isArrayType() || DestType->isFunctionType()) {
14262     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14263       << DestType->isFunctionType() << DestType;
14264     return ExprError();
14265   }
14266 
14267   // Rewrite the method result type if available.
14268   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14269     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14270     Method->setReturnType(DestType);
14271   }
14272 
14273   // Change the type of the message.
14274   E->setType(DestType.getNonReferenceType());
14275   E->setValueKind(Expr::getValueKindForType(DestType));
14276 
14277   return S.MaybeBindToTemporary(E);
14278 }
14279 
14280 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14281   // The only case we should ever see here is a function-to-pointer decay.
14282   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14283     assert(E->getValueKind() == VK_RValue);
14284     assert(E->getObjectKind() == OK_Ordinary);
14285 
14286     E->setType(DestType);
14287 
14288     // Rebuild the sub-expression as the pointee (function) type.
14289     DestType = DestType->castAs<PointerType>()->getPointeeType();
14290 
14291     ExprResult Result = Visit(E->getSubExpr());
14292     if (!Result.isUsable()) return ExprError();
14293 
14294     E->setSubExpr(Result.get());
14295     return E;
14296   } else if (E->getCastKind() == CK_LValueToRValue) {
14297     assert(E->getValueKind() == VK_RValue);
14298     assert(E->getObjectKind() == OK_Ordinary);
14299 
14300     assert(isa<BlockPointerType>(E->getType()));
14301 
14302     E->setType(DestType);
14303 
14304     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14305     DestType = S.Context.getLValueReferenceType(DestType);
14306 
14307     ExprResult Result = Visit(E->getSubExpr());
14308     if (!Result.isUsable()) return ExprError();
14309 
14310     E->setSubExpr(Result.get());
14311     return E;
14312   } else {
14313     llvm_unreachable("Unhandled cast type!");
14314   }
14315 }
14316 
14317 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14318   ExprValueKind ValueKind = VK_LValue;
14319   QualType Type = DestType;
14320 
14321   // We know how to make this work for certain kinds of decls:
14322 
14323   //  - functions
14324   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14325     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14326       DestType = Ptr->getPointeeType();
14327       ExprResult Result = resolveDecl(E, VD);
14328       if (Result.isInvalid()) return ExprError();
14329       return S.ImpCastExprToType(Result.get(), Type,
14330                                  CK_FunctionToPointerDecay, VK_RValue);
14331     }
14332 
14333     if (!Type->isFunctionType()) {
14334       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14335         << VD << E->getSourceRange();
14336       return ExprError();
14337     }
14338     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14339       // We must match the FunctionDecl's type to the hack introduced in
14340       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14341       // type. See the lengthy commentary in that routine.
14342       QualType FDT = FD->getType();
14343       const FunctionType *FnType = FDT->castAs<FunctionType>();
14344       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14345       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14346       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14347         SourceLocation Loc = FD->getLocation();
14348         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14349                                       FD->getDeclContext(),
14350                                       Loc, Loc, FD->getNameInfo().getName(),
14351                                       DestType, FD->getTypeSourceInfo(),
14352                                       SC_None, false/*isInlineSpecified*/,
14353                                       FD->hasPrototype(),
14354                                       false/*isConstexprSpecified*/);
14355 
14356         if (FD->getQualifier())
14357           NewFD->setQualifierInfo(FD->getQualifierLoc());
14358 
14359         SmallVector<ParmVarDecl*, 16> Params;
14360         for (const auto &AI : FT->param_types()) {
14361           ParmVarDecl *Param =
14362             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14363           Param->setScopeInfo(0, Params.size());
14364           Params.push_back(Param);
14365         }
14366         NewFD->setParams(Params);
14367         DRE->setDecl(NewFD);
14368         VD = DRE->getDecl();
14369       }
14370     }
14371 
14372     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14373       if (MD->isInstance()) {
14374         ValueKind = VK_RValue;
14375         Type = S.Context.BoundMemberTy;
14376       }
14377 
14378     // Function references aren't l-values in C.
14379     if (!S.getLangOpts().CPlusPlus)
14380       ValueKind = VK_RValue;
14381 
14382   //  - variables
14383   } else if (isa<VarDecl>(VD)) {
14384     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14385       Type = RefTy->getPointeeType();
14386     } else if (Type->isFunctionType()) {
14387       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14388         << VD << E->getSourceRange();
14389       return ExprError();
14390     }
14391 
14392   //  - nothing else
14393   } else {
14394     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14395       << VD << E->getSourceRange();
14396     return ExprError();
14397   }
14398 
14399   // Modifying the declaration like this is friendly to IR-gen but
14400   // also really dangerous.
14401   VD->setType(DestType);
14402   E->setType(Type);
14403   E->setValueKind(ValueKind);
14404   return E;
14405 }
14406 
14407 /// Check a cast of an unknown-any type.  We intentionally only
14408 /// trigger this for C-style casts.
14409 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14410                                      Expr *CastExpr, CastKind &CastKind,
14411                                      ExprValueKind &VK, CXXCastPath &Path) {
14412   // Rewrite the casted expression from scratch.
14413   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14414   if (!result.isUsable()) return ExprError();
14415 
14416   CastExpr = result.get();
14417   VK = CastExpr->getValueKind();
14418   CastKind = CK_NoOp;
14419 
14420   return CastExpr;
14421 }
14422 
14423 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14424   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14425 }
14426 
14427 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14428                                     Expr *arg, QualType &paramType) {
14429   // If the syntactic form of the argument is not an explicit cast of
14430   // any sort, just do default argument promotion.
14431   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14432   if (!castArg) {
14433     ExprResult result = DefaultArgumentPromotion(arg);
14434     if (result.isInvalid()) return ExprError();
14435     paramType = result.get()->getType();
14436     return result;
14437   }
14438 
14439   // Otherwise, use the type that was written in the explicit cast.
14440   assert(!arg->hasPlaceholderType());
14441   paramType = castArg->getTypeAsWritten();
14442 
14443   // Copy-initialize a parameter of that type.
14444   InitializedEntity entity =
14445     InitializedEntity::InitializeParameter(Context, paramType,
14446                                            /*consumed*/ false);
14447   return PerformCopyInitialization(entity, callLoc, arg);
14448 }
14449 
14450 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14451   Expr *orig = E;
14452   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14453   while (true) {
14454     E = E->IgnoreParenImpCasts();
14455     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14456       E = call->getCallee();
14457       diagID = diag::err_uncasted_call_of_unknown_any;
14458     } else {
14459       break;
14460     }
14461   }
14462 
14463   SourceLocation loc;
14464   NamedDecl *d;
14465   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14466     loc = ref->getLocation();
14467     d = ref->getDecl();
14468   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14469     loc = mem->getMemberLoc();
14470     d = mem->getMemberDecl();
14471   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14472     diagID = diag::err_uncasted_call_of_unknown_any;
14473     loc = msg->getSelectorStartLoc();
14474     d = msg->getMethodDecl();
14475     if (!d) {
14476       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14477         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14478         << orig->getSourceRange();
14479       return ExprError();
14480     }
14481   } else {
14482     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14483       << E->getSourceRange();
14484     return ExprError();
14485   }
14486 
14487   S.Diag(loc, diagID) << d << orig->getSourceRange();
14488 
14489   // Never recoverable.
14490   return ExprError();
14491 }
14492 
14493 /// Check for operands with placeholder types and complain if found.
14494 /// Returns true if there was an error and no recovery was possible.
14495 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14496   if (!getLangOpts().CPlusPlus) {
14497     // C cannot handle TypoExpr nodes on either side of a binop because it
14498     // doesn't handle dependent types properly, so make sure any TypoExprs have
14499     // been dealt with before checking the operands.
14500     ExprResult Result = CorrectDelayedTyposInExpr(E);
14501     if (!Result.isUsable()) return ExprError();
14502     E = Result.get();
14503   }
14504 
14505   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14506   if (!placeholderType) return E;
14507 
14508   switch (placeholderType->getKind()) {
14509 
14510   // Overloaded expressions.
14511   case BuiltinType::Overload: {
14512     // Try to resolve a single function template specialization.
14513     // This is obligatory.
14514     ExprResult result = E;
14515     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14516       return result;
14517 
14518     // If that failed, try to recover with a call.
14519     } else {
14520       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14521                            /*complain*/ true);
14522       return result;
14523     }
14524   }
14525 
14526   // Bound member functions.
14527   case BuiltinType::BoundMember: {
14528     ExprResult result = E;
14529     const Expr *BME = E->IgnoreParens();
14530     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14531     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14532     if (isa<CXXPseudoDestructorExpr>(BME)) {
14533       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14534     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14535       if (ME->getMemberNameInfo().getName().getNameKind() ==
14536           DeclarationName::CXXDestructorName)
14537         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14538     }
14539     tryToRecoverWithCall(result, PD,
14540                          /*complain*/ true);
14541     return result;
14542   }
14543 
14544   // ARC unbridged casts.
14545   case BuiltinType::ARCUnbridgedCast: {
14546     Expr *realCast = stripARCUnbridgedCast(E);
14547     diagnoseARCUnbridgedCast(realCast);
14548     return realCast;
14549   }
14550 
14551   // Expressions of unknown type.
14552   case BuiltinType::UnknownAny:
14553     return diagnoseUnknownAnyExpr(*this, E);
14554 
14555   // Pseudo-objects.
14556   case BuiltinType::PseudoObject:
14557     return checkPseudoObjectRValue(E);
14558 
14559   case BuiltinType::BuiltinFn: {
14560     // Accept __noop without parens by implicitly converting it to a call expr.
14561     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14562     if (DRE) {
14563       auto *FD = cast<FunctionDecl>(DRE->getDecl());
14564       if (FD->getBuiltinID() == Builtin::BI__noop) {
14565         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14566                               CK_BuiltinFnToFnPtr).get();
14567         return new (Context) CallExpr(Context, E, None, Context.IntTy,
14568                                       VK_RValue, SourceLocation());
14569       }
14570     }
14571 
14572     Diag(E->getLocStart(), diag::err_builtin_fn_use);
14573     return ExprError();
14574   }
14575 
14576   // Expressions of unknown type.
14577   case BuiltinType::OMPArraySection:
14578     Diag(E->getLocStart(), diag::err_omp_array_section_use);
14579     return ExprError();
14580 
14581   // Everything else should be impossible.
14582 #define BUILTIN_TYPE(Id, SingletonId) \
14583   case BuiltinType::Id:
14584 #define PLACEHOLDER_TYPE(Id, SingletonId)
14585 #include "clang/AST/BuiltinTypes.def"
14586     break;
14587   }
14588 
14589   llvm_unreachable("invalid placeholder type!");
14590 }
14591 
14592 bool Sema::CheckCaseExpression(Expr *E) {
14593   if (E->isTypeDependent())
14594     return true;
14595   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14596     return E->getType()->isIntegralOrEnumerationType();
14597   return false;
14598 }
14599 
14600 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14601 ExprResult
14602 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14603   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14604          "Unknown Objective-C Boolean value!");
14605   QualType BoolT = Context.ObjCBuiltinBoolTy;
14606   if (!Context.getBOOLDecl()) {
14607     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
14608                         Sema::LookupOrdinaryName);
14609     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
14610       NamedDecl *ND = Result.getFoundDecl();
14611       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
14612         Context.setBOOLDecl(TD);
14613     }
14614   }
14615   if (Context.getBOOLDecl())
14616     BoolT = Context.getBOOLType();
14617   return new (Context)
14618       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
14619 }
14620