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) {
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       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
515       return ExprError();
516     }
517     E = ImpCastExprToType(E, Context.getPointerType(Ty),
518                           CK_FunctionToPointerDecay).get();
519   } else if (Ty->isArrayType()) {
520     // In C90 mode, arrays only promote to pointers if the array expression is
521     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
522     // type 'array of type' is converted to an expression that has type 'pointer
523     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
524     // that has type 'array of type' ...".  The relevant change is "an lvalue"
525     // (C90) to "an expression" (C99).
526     //
527     // C++ 4.2p1:
528     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
529     // T" can be converted to an rvalue of type "pointer to T".
530     //
531     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
532       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
533                             CK_ArrayToPointerDecay).get();
534   }
535   return E;
536 }
537 
538 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
539   // Check to see if we are dereferencing a null pointer.  If so,
540   // and if not volatile-qualified, this is undefined behavior that the
541   // optimizer will delete, so warn about it.  People sometimes try to use this
542   // to get a deterministic trap and are surprised by clang's behavior.  This
543   // only handles the pattern "*null", which is a very syntactic check.
544   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
545     if (UO->getOpcode() == UO_Deref &&
546         UO->getSubExpr()->IgnoreParenCasts()->
547           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
548         !UO->getType().isVolatileQualified()) {
549     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
550                           S.PDiag(diag::warn_indirection_through_null)
551                             << UO->getSubExpr()->getSourceRange());
552     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
553                         S.PDiag(diag::note_indirection_through_null));
554   }
555 }
556 
557 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
558                                     SourceLocation AssignLoc,
559                                     const Expr* RHS) {
560   const ObjCIvarDecl *IV = OIRE->getDecl();
561   if (!IV)
562     return;
563 
564   DeclarationName MemberName = IV->getDeclName();
565   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
566   if (!Member || !Member->isStr("isa"))
567     return;
568 
569   const Expr *Base = OIRE->getBase();
570   QualType BaseType = Base->getType();
571   if (OIRE->isArrow())
572     BaseType = BaseType->getPointeeType();
573   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
574     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
575       ObjCInterfaceDecl *ClassDeclared = nullptr;
576       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
577       if (!ClassDeclared->getSuperClass()
578           && (*ClassDeclared->ivar_begin()) == IV) {
579         if (RHS) {
580           NamedDecl *ObjectSetClass =
581             S.LookupSingleName(S.TUScope,
582                                &S.Context.Idents.get("object_setClass"),
583                                SourceLocation(), S.LookupOrdinaryName);
584           if (ObjectSetClass) {
585             SourceLocation RHSLocEnd = S.getLocForEndOfToken(RHS->getLocEnd());
586             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
587             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
588             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
589                                                      AssignLoc), ",") <<
590             FixItHint::CreateInsertion(RHSLocEnd, ")");
591           }
592           else
593             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
594         } else {
595           NamedDecl *ObjectGetClass =
596             S.LookupSingleName(S.TUScope,
597                                &S.Context.Idents.get("object_getClass"),
598                                SourceLocation(), S.LookupOrdinaryName);
599           if (ObjectGetClass)
600             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
601             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
602             FixItHint::CreateReplacement(
603                                          SourceRange(OIRE->getOpLoc(),
604                                                      OIRE->getLocEnd()), ")");
605           else
606             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
607         }
608         S.Diag(IV->getLocation(), diag::note_ivar_decl);
609       }
610     }
611 }
612 
613 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
614   // Handle any placeholder expressions which made it here.
615   if (E->getType()->isPlaceholderType()) {
616     ExprResult result = CheckPlaceholderExpr(E);
617     if (result.isInvalid()) return ExprError();
618     E = result.get();
619   }
620 
621   // C++ [conv.lval]p1:
622   //   A glvalue of a non-function, non-array type T can be
623   //   converted to a prvalue.
624   if (!E->isGLValue()) return E;
625 
626   QualType T = E->getType();
627   assert(!T.isNull() && "r-value conversion on typeless expression?");
628 
629   // We don't want to throw lvalue-to-rvalue casts on top of
630   // expressions of certain types in C++.
631   if (getLangOpts().CPlusPlus &&
632       (E->getType() == Context.OverloadTy ||
633        T->isDependentType() ||
634        T->isRecordType()))
635     return E;
636 
637   // The C standard is actually really unclear on this point, and
638   // DR106 tells us what the result should be but not why.  It's
639   // generally best to say that void types just doesn't undergo
640   // lvalue-to-rvalue at all.  Note that expressions of unqualified
641   // 'void' type are never l-values, but qualified void can be.
642   if (T->isVoidType())
643     return E;
644 
645   // OpenCL usually rejects direct accesses to values of 'half' type.
646   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
647       T->isHalfType()) {
648     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
649       << 0 << T;
650     return ExprError();
651   }
652 
653   CheckForNullPointerDereference(*this, E);
654   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
655     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
656                                      &Context.Idents.get("object_getClass"),
657                                      SourceLocation(), LookupOrdinaryName);
658     if (ObjectGetClass)
659       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
660         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
661         FixItHint::CreateReplacement(
662                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
663     else
664       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
665   }
666   else if (const ObjCIvarRefExpr *OIRE =
667             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
668     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
669 
670   // C++ [conv.lval]p1:
671   //   [...] If T is a non-class type, the type of the prvalue is the
672   //   cv-unqualified version of T. Otherwise, the type of the
673   //   rvalue is T.
674   //
675   // C99 6.3.2.1p2:
676   //   If the lvalue has qualified type, the value has the unqualified
677   //   version of the type of the lvalue; otherwise, the value has the
678   //   type of the lvalue.
679   if (T.hasQualifiers())
680     T = T.getUnqualifiedType();
681 
682   if (T->isMemberPointerType() &&
683       Context.getTargetInfo().getCXXABI().isMicrosoft())
684     RequireCompleteType(E->getExprLoc(), T, 0);
685 
686   UpdateMarkingForLValueToRValue(E);
687 
688   // Loading a __weak object implicitly retains the value, so we need a cleanup to
689   // balance that.
690   if (getLangOpts().ObjCAutoRefCount &&
691       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
692     ExprNeedsCleanups = true;
693 
694   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
695                                             nullptr, VK_RValue);
696 
697   // C11 6.3.2.1p2:
698   //   ... if the lvalue has atomic type, the value has the non-atomic version
699   //   of the type of the lvalue ...
700   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
701     T = Atomic->getValueType().getUnqualifiedType();
702     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
703                                    nullptr, VK_RValue);
704   }
705 
706   return Res;
707 }
708 
709 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
710   ExprResult Res = DefaultFunctionArrayConversion(E);
711   if (Res.isInvalid())
712     return ExprError();
713   Res = DefaultLvalueConversion(Res.get());
714   if (Res.isInvalid())
715     return ExprError();
716   return Res;
717 }
718 
719 /// CallExprUnaryConversions - a special case of an unary conversion
720 /// performed on a function designator of a call expression.
721 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
722   QualType Ty = E->getType();
723   ExprResult Res = E;
724   // Only do implicit cast for a function type, but not for a pointer
725   // to function type.
726   if (Ty->isFunctionType()) {
727     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
728                             CK_FunctionToPointerDecay).get();
729     if (Res.isInvalid())
730       return ExprError();
731   }
732   Res = DefaultLvalueConversion(Res.get());
733   if (Res.isInvalid())
734     return ExprError();
735   return Res.get();
736 }
737 
738 /// UsualUnaryConversions - Performs various conversions that are common to most
739 /// operators (C99 6.3). The conversions of array and function types are
740 /// sometimes suppressed. For example, the array->pointer conversion doesn't
741 /// apply if the array is an argument to the sizeof or address (&) operators.
742 /// In these instances, this routine should *not* be called.
743 ExprResult Sema::UsualUnaryConversions(Expr *E) {
744   // First, convert to an r-value.
745   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
746   if (Res.isInvalid())
747     return ExprError();
748   E = Res.get();
749 
750   QualType Ty = E->getType();
751   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
752 
753   // Half FP have to be promoted to float unless it is natively supported
754   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
755     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
756 
757   // Try to perform integral promotions if the object has a theoretically
758   // promotable type.
759   if (Ty->isIntegralOrUnscopedEnumerationType()) {
760     // C99 6.3.1.1p2:
761     //
762     //   The following may be used in an expression wherever an int or
763     //   unsigned int may be used:
764     //     - an object or expression with an integer type whose integer
765     //       conversion rank is less than or equal to the rank of int
766     //       and unsigned int.
767     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
768     //
769     //   If an int can represent all values of the original type, the
770     //   value is converted to an int; otherwise, it is converted to an
771     //   unsigned int. These are called the integer promotions. All
772     //   other types are unchanged by the integer promotions.
773 
774     QualType PTy = Context.isPromotableBitField(E);
775     if (!PTy.isNull()) {
776       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
777       return E;
778     }
779     if (Ty->isPromotableIntegerType()) {
780       QualType PT = Context.getPromotedIntegerType(Ty);
781       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
782       return E;
783     }
784   }
785   return E;
786 }
787 
788 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
789 /// do not have a prototype. Arguments that have type float or __fp16
790 /// are promoted to double. All other argument types are converted by
791 /// UsualUnaryConversions().
792 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
793   QualType Ty = E->getType();
794   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
795 
796   ExprResult Res = UsualUnaryConversions(E);
797   if (Res.isInvalid())
798     return ExprError();
799   E = Res.get();
800 
801   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
802   // double.
803   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
804   if (BTy && (BTy->getKind() == BuiltinType::Half ||
805               BTy->getKind() == BuiltinType::Float))
806     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
807 
808   // C++ performs lvalue-to-rvalue conversion as a default argument
809   // promotion, even on class types, but note:
810   //   C++11 [conv.lval]p2:
811   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
812   //     operand or a subexpression thereof the value contained in the
813   //     referenced object is not accessed. Otherwise, if the glvalue
814   //     has a class type, the conversion copy-initializes a temporary
815   //     of type T from the glvalue and the result of the conversion
816   //     is a prvalue for the temporary.
817   // FIXME: add some way to gate this entire thing for correctness in
818   // potentially potentially evaluated contexts.
819   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
820     ExprResult Temp = PerformCopyInitialization(
821                        InitializedEntity::InitializeTemporary(E->getType()),
822                                                 E->getExprLoc(), E);
823     if (Temp.isInvalid())
824       return ExprError();
825     E = Temp.get();
826   }
827 
828   return E;
829 }
830 
831 /// Determine the degree of POD-ness for an expression.
832 /// Incomplete types are considered POD, since this check can be performed
833 /// when we're in an unevaluated context.
834 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
835   if (Ty->isIncompleteType()) {
836     // C++11 [expr.call]p7:
837     //   After these conversions, if the argument does not have arithmetic,
838     //   enumeration, pointer, pointer to member, or class type, the program
839     //   is ill-formed.
840     //
841     // Since we've already performed array-to-pointer and function-to-pointer
842     // decay, the only such type in C++ is cv void. This also handles
843     // initializer lists as variadic arguments.
844     if (Ty->isVoidType())
845       return VAK_Invalid;
846 
847     if (Ty->isObjCObjectType())
848       return VAK_Invalid;
849     return VAK_Valid;
850   }
851 
852   if (Ty.isCXX98PODType(Context))
853     return VAK_Valid;
854 
855   // C++11 [expr.call]p7:
856   //   Passing a potentially-evaluated argument of class type (Clause 9)
857   //   having a non-trivial copy constructor, a non-trivial move constructor,
858   //   or a non-trivial destructor, with no corresponding parameter,
859   //   is conditionally-supported with implementation-defined semantics.
860   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
861     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
862       if (!Record->hasNonTrivialCopyConstructor() &&
863           !Record->hasNonTrivialMoveConstructor() &&
864           !Record->hasNonTrivialDestructor())
865         return VAK_ValidInCXX11;
866 
867   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
868     return VAK_Valid;
869 
870   if (Ty->isObjCObjectType())
871     return VAK_Invalid;
872 
873   if (getLangOpts().MSVCCompat)
874     return VAK_MSVCUndefined;
875 
876   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
877   // permitted to reject them. We should consider doing so.
878   return VAK_Undefined;
879 }
880 
881 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
882   // Don't allow one to pass an Objective-C interface to a vararg.
883   const QualType &Ty = E->getType();
884   VarArgKind VAK = isValidVarArgType(Ty);
885 
886   // Complain about passing non-POD types through varargs.
887   switch (VAK) {
888   case VAK_ValidInCXX11:
889     DiagRuntimeBehavior(
890         E->getLocStart(), nullptr,
891         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
892           << Ty << CT);
893     // Fall through.
894   case VAK_Valid:
895     if (Ty->isRecordType()) {
896       // This is unlikely to be what the user intended. If the class has a
897       // 'c_str' member function, the user probably meant to call that.
898       DiagRuntimeBehavior(E->getLocStart(), nullptr,
899                           PDiag(diag::warn_pass_class_arg_to_vararg)
900                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
901     }
902     break;
903 
904   case VAK_Undefined:
905   case VAK_MSVCUndefined:
906     DiagRuntimeBehavior(
907         E->getLocStart(), nullptr,
908         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
909           << getLangOpts().CPlusPlus11 << Ty << CT);
910     break;
911 
912   case VAK_Invalid:
913     if (Ty->isObjCObjectType())
914       DiagRuntimeBehavior(
915           E->getLocStart(), nullptr,
916           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
917             << Ty << CT);
918     else
919       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
920         << isa<InitListExpr>(E) << Ty << CT;
921     break;
922   }
923 }
924 
925 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
926 /// will create a trap if the resulting type is not a POD type.
927 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
928                                                   FunctionDecl *FDecl) {
929   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
930     // Strip the unbridged-cast placeholder expression off, if applicable.
931     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
932         (CT == VariadicMethod ||
933          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
934       E = stripARCUnbridgedCast(E);
935 
936     // Otherwise, do normal placeholder checking.
937     } else {
938       ExprResult ExprRes = CheckPlaceholderExpr(E);
939       if (ExprRes.isInvalid())
940         return ExprError();
941       E = ExprRes.get();
942     }
943   }
944 
945   ExprResult ExprRes = DefaultArgumentPromotion(E);
946   if (ExprRes.isInvalid())
947     return ExprError();
948   E = ExprRes.get();
949 
950   // Diagnostics regarding non-POD argument types are
951   // emitted along with format string checking in Sema::CheckFunctionCall().
952   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
953     // Turn this into a trap.
954     CXXScopeSpec SS;
955     SourceLocation TemplateKWLoc;
956     UnqualifiedId Name;
957     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
958                        E->getLocStart());
959     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
960                                           Name, true, false);
961     if (TrapFn.isInvalid())
962       return ExprError();
963 
964     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
965                                     E->getLocStart(), None,
966                                     E->getLocEnd());
967     if (Call.isInvalid())
968       return ExprError();
969 
970     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
971                                   Call.get(), E);
972     if (Comma.isInvalid())
973       return ExprError();
974     return Comma.get();
975   }
976 
977   if (!getLangOpts().CPlusPlus &&
978       RequireCompleteType(E->getExprLoc(), E->getType(),
979                           diag::err_call_incomplete_argument))
980     return ExprError();
981 
982   return E;
983 }
984 
985 /// \brief Converts an integer to complex float type.  Helper function of
986 /// UsualArithmeticConversions()
987 ///
988 /// \return false if the integer expression is an integer type and is
989 /// successfully converted to the complex type.
990 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
991                                                   ExprResult &ComplexExpr,
992                                                   QualType IntTy,
993                                                   QualType ComplexTy,
994                                                   bool SkipCast) {
995   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
996   if (SkipCast) return false;
997   if (IntTy->isIntegerType()) {
998     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
999     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
1000     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1001                                   CK_FloatingRealToComplex);
1002   } else {
1003     assert(IntTy->isComplexIntegerType());
1004     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
1005                                   CK_IntegralComplexToFloatingComplex);
1006   }
1007   return false;
1008 }
1009 
1010 /// \brief Handle arithmetic conversion with complex types.  Helper function of
1011 /// UsualArithmeticConversions()
1012 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
1013                                              ExprResult &RHS, QualType LHSType,
1014                                              QualType RHSType,
1015                                              bool IsCompAssign) {
1016   // if we have an integer operand, the result is the complex type.
1017   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
1018                                              /*skipCast*/false))
1019     return LHSType;
1020   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1021                                              /*skipCast*/IsCompAssign))
1022     return RHSType;
1023 
1024   // This handles complex/complex, complex/float, or float/complex.
1025   // When both operands are complex, the shorter operand is converted to the
1026   // type of the longer, and that is the type of the result. This corresponds
1027   // to what is done when combining two real floating-point operands.
1028   // The fun begins when size promotion occur across type domains.
1029   // From H&S 6.3.4: When one operand is complex and the other is a real
1030   // floating-point type, the less precise type is converted, within it's
1031   // real or complex domain, to the precision of the other type. For example,
1032   // when combining a "long double" with a "double _Complex", the
1033   // "double _Complex" is promoted to "long double _Complex".
1034 
1035   // Compute the rank of the two types, regardless of whether they are complex.
1036   int Order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1037 
1038   auto *LHSComplexType = dyn_cast<ComplexType>(LHSType);
1039   auto *RHSComplexType = dyn_cast<ComplexType>(RHSType);
1040   QualType LHSElementType =
1041       LHSComplexType ? LHSComplexType->getElementType() : LHSType;
1042   QualType RHSElementType =
1043       RHSComplexType ? RHSComplexType->getElementType() : RHSType;
1044 
1045   QualType ResultType = S.Context.getComplexType(LHSElementType);
1046   if (Order < 0) {
1047     // Promote the precision of the LHS if not an assignment.
1048     ResultType = S.Context.getComplexType(RHSElementType);
1049     if (!IsCompAssign) {
1050       if (LHSComplexType)
1051         LHS =
1052             S.ImpCastExprToType(LHS.get(), ResultType, CK_FloatingComplexCast);
1053       else
1054         LHS = S.ImpCastExprToType(LHS.get(), RHSElementType, CK_FloatingCast);
1055     }
1056   } else if (Order > 0) {
1057     // Promote the precision of the RHS.
1058     if (RHSComplexType)
1059       RHS = S.ImpCastExprToType(RHS.get(), ResultType, CK_FloatingComplexCast);
1060     else
1061       RHS = S.ImpCastExprToType(RHS.get(), LHSElementType, CK_FloatingCast);
1062   }
1063   return ResultType;
1064 }
1065 
1066 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1067 /// of UsualArithmeticConversions()
1068 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1069                                            ExprResult &IntExpr,
1070                                            QualType FloatTy, QualType IntTy,
1071                                            bool ConvertFloat, bool ConvertInt) {
1072   if (IntTy->isIntegerType()) {
1073     if (ConvertInt)
1074       // Convert intExpr to the lhs floating point type.
1075       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1076                                     CK_IntegralToFloating);
1077     return FloatTy;
1078   }
1079 
1080   // Convert both sides to the appropriate complex float.
1081   assert(IntTy->isComplexIntegerType());
1082   QualType result = S.Context.getComplexType(FloatTy);
1083 
1084   // _Complex int -> _Complex float
1085   if (ConvertInt)
1086     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1087                                   CK_IntegralComplexToFloatingComplex);
1088 
1089   // float -> _Complex float
1090   if (ConvertFloat)
1091     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1092                                     CK_FloatingRealToComplex);
1093 
1094   return result;
1095 }
1096 
1097 /// \brief Handle arithmethic conversion with floating point types.  Helper
1098 /// function of UsualArithmeticConversions()
1099 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1100                                       ExprResult &RHS, QualType LHSType,
1101                                       QualType RHSType, bool IsCompAssign) {
1102   bool LHSFloat = LHSType->isRealFloatingType();
1103   bool RHSFloat = RHSType->isRealFloatingType();
1104 
1105   // If we have two real floating types, convert the smaller operand
1106   // to the bigger result.
1107   if (LHSFloat && RHSFloat) {
1108     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1109     if (order > 0) {
1110       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1111       return LHSType;
1112     }
1113 
1114     assert(order < 0 && "illegal float comparison");
1115     if (!IsCompAssign)
1116       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1117     return RHSType;
1118   }
1119 
1120   if (LHSFloat) {
1121     // Half FP has to be promoted to float unless it is natively supported
1122     if (LHSType->isHalfType() && !S.getLangOpts().NativeHalfType)
1123       LHSType = S.Context.FloatTy;
1124 
1125     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1126                                       /*convertFloat=*/!IsCompAssign,
1127                                       /*convertInt=*/ true);
1128   }
1129   assert(RHSFloat);
1130   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1131                                     /*convertInt=*/ true,
1132                                     /*convertFloat=*/!IsCompAssign);
1133 }
1134 
1135 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1136 
1137 namespace {
1138 /// These helper callbacks are placed in an anonymous namespace to
1139 /// permit their use as function template parameters.
1140 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1141   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1142 }
1143 
1144 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1145   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1146                              CK_IntegralComplexCast);
1147 }
1148 }
1149 
1150 /// \brief Handle integer arithmetic conversions.  Helper function of
1151 /// UsualArithmeticConversions()
1152 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1153 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1154                                         ExprResult &RHS, QualType LHSType,
1155                                         QualType RHSType, bool IsCompAssign) {
1156   // The rules for this case are in C99 6.3.1.8
1157   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1158   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1159   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1160   if (LHSSigned == RHSSigned) {
1161     // Same signedness; use the higher-ranked type
1162     if (order >= 0) {
1163       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1164       return LHSType;
1165     } else if (!IsCompAssign)
1166       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1167     return RHSType;
1168   } else if (order != (LHSSigned ? 1 : -1)) {
1169     // The unsigned type has greater than or equal rank to the
1170     // signed type, so use the unsigned type
1171     if (RHSSigned) {
1172       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1173       return LHSType;
1174     } else if (!IsCompAssign)
1175       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1176     return RHSType;
1177   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1178     // The two types are different widths; if we are here, that
1179     // means the signed type is larger than the unsigned type, so
1180     // use the signed type.
1181     if (LHSSigned) {
1182       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1183       return LHSType;
1184     } else if (!IsCompAssign)
1185       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1186     return RHSType;
1187   } else {
1188     // The signed type is higher-ranked than the unsigned type,
1189     // but isn't actually any bigger (like unsigned int and long
1190     // on most 32-bit systems).  Use the unsigned type corresponding
1191     // to the signed type.
1192     QualType result =
1193       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1194     RHS = (*doRHSCast)(S, RHS.get(), result);
1195     if (!IsCompAssign)
1196       LHS = (*doLHSCast)(S, LHS.get(), result);
1197     return result;
1198   }
1199 }
1200 
1201 /// \brief Handle conversions with GCC complex int extension.  Helper function
1202 /// of UsualArithmeticConversions()
1203 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1204                                            ExprResult &RHS, QualType LHSType,
1205                                            QualType RHSType,
1206                                            bool IsCompAssign) {
1207   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1208   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1209 
1210   if (LHSComplexInt && RHSComplexInt) {
1211     QualType LHSEltType = LHSComplexInt->getElementType();
1212     QualType RHSEltType = RHSComplexInt->getElementType();
1213     QualType ScalarType =
1214       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1215         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1216 
1217     return S.Context.getComplexType(ScalarType);
1218   }
1219 
1220   if (LHSComplexInt) {
1221     QualType LHSEltType = LHSComplexInt->getElementType();
1222     QualType ScalarType =
1223       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1224         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1225     QualType ComplexType = S.Context.getComplexType(ScalarType);
1226     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1227                               CK_IntegralRealToComplex);
1228 
1229     return ComplexType;
1230   }
1231 
1232   assert(RHSComplexInt);
1233 
1234   QualType RHSEltType = RHSComplexInt->getElementType();
1235   QualType ScalarType =
1236     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1237       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1238   QualType ComplexType = S.Context.getComplexType(ScalarType);
1239 
1240   if (!IsCompAssign)
1241     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1242                               CK_IntegralRealToComplex);
1243   return ComplexType;
1244 }
1245 
1246 /// UsualArithmeticConversions - Performs various conversions that are common to
1247 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1248 /// routine returns the first non-arithmetic type found. The client is
1249 /// responsible for emitting appropriate error diagnostics.
1250 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1251                                           bool IsCompAssign) {
1252   if (!IsCompAssign) {
1253     LHS = UsualUnaryConversions(LHS.get());
1254     if (LHS.isInvalid())
1255       return QualType();
1256   }
1257 
1258   RHS = UsualUnaryConversions(RHS.get());
1259   if (RHS.isInvalid())
1260     return QualType();
1261 
1262   // For conversion purposes, we ignore any qualifiers.
1263   // For example, "const float" and "float" are equivalent.
1264   QualType LHSType =
1265     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1266   QualType RHSType =
1267     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1268 
1269   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1270   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1271     LHSType = AtomicLHS->getValueType();
1272 
1273   // If both types are identical, no conversion is needed.
1274   if (LHSType == RHSType)
1275     return LHSType;
1276 
1277   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1278   // The caller can deal with this (e.g. pointer + int).
1279   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1280     return QualType();
1281 
1282   // Apply unary and bitfield promotions to the LHS's type.
1283   QualType LHSUnpromotedType = LHSType;
1284   if (LHSType->isPromotableIntegerType())
1285     LHSType = Context.getPromotedIntegerType(LHSType);
1286   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1287   if (!LHSBitfieldPromoteTy.isNull())
1288     LHSType = LHSBitfieldPromoteTy;
1289   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1290     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1291 
1292   // If both types are identical, no conversion is needed.
1293   if (LHSType == RHSType)
1294     return LHSType;
1295 
1296   // At this point, we have two different arithmetic types.
1297 
1298   // Handle complex types first (C99 6.3.1.8p1).
1299   if (LHSType->isComplexType() || RHSType->isComplexType())
1300     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1301                                         IsCompAssign);
1302 
1303   // Now handle "real" floating types (i.e. float, double, long double).
1304   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1305     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1306                                  IsCompAssign);
1307 
1308   // Handle GCC complex int extension.
1309   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1310     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1311                                       IsCompAssign);
1312 
1313   // Finally, we have two differing integer types.
1314   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1315            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1316 }
1317 
1318 
1319 //===----------------------------------------------------------------------===//
1320 //  Semantic Analysis for various Expression Types
1321 //===----------------------------------------------------------------------===//
1322 
1323 
1324 ExprResult
1325 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1326                                 SourceLocation DefaultLoc,
1327                                 SourceLocation RParenLoc,
1328                                 Expr *ControllingExpr,
1329                                 ArrayRef<ParsedType> ArgTypes,
1330                                 ArrayRef<Expr *> ArgExprs) {
1331   unsigned NumAssocs = ArgTypes.size();
1332   assert(NumAssocs == ArgExprs.size());
1333 
1334   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1335   for (unsigned i = 0; i < NumAssocs; ++i) {
1336     if (ArgTypes[i])
1337       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1338     else
1339       Types[i] = nullptr;
1340   }
1341 
1342   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1343                                              ControllingExpr,
1344                                              llvm::makeArrayRef(Types, NumAssocs),
1345                                              ArgExprs);
1346   delete [] Types;
1347   return ER;
1348 }
1349 
1350 ExprResult
1351 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1352                                  SourceLocation DefaultLoc,
1353                                  SourceLocation RParenLoc,
1354                                  Expr *ControllingExpr,
1355                                  ArrayRef<TypeSourceInfo *> Types,
1356                                  ArrayRef<Expr *> Exprs) {
1357   unsigned NumAssocs = Types.size();
1358   assert(NumAssocs == Exprs.size());
1359 
1360   // Decay and strip qualifiers for the controlling expression type, and handle
1361   // placeholder type replacement. See committee discussion from WG14 DR423.
1362   ExprResult R = DefaultFunctionArrayLvalueConversion(ControllingExpr);
1363   if (R.isInvalid())
1364     return ExprError();
1365   ControllingExpr = R.get();
1366 
1367   // The controlling expression is an unevaluated operand, so side effects are
1368   // likely unintended.
1369   if (ActiveTemplateInstantiations.empty() &&
1370       ControllingExpr->HasSideEffects(Context, false))
1371     Diag(ControllingExpr->getExprLoc(),
1372          diag::warn_side_effects_unevaluated_context);
1373 
1374   bool TypeErrorFound = false,
1375        IsResultDependent = ControllingExpr->isTypeDependent(),
1376        ContainsUnexpandedParameterPack
1377          = ControllingExpr->containsUnexpandedParameterPack();
1378 
1379   for (unsigned i = 0; i < NumAssocs; ++i) {
1380     if (Exprs[i]->containsUnexpandedParameterPack())
1381       ContainsUnexpandedParameterPack = true;
1382 
1383     if (Types[i]) {
1384       if (Types[i]->getType()->containsUnexpandedParameterPack())
1385         ContainsUnexpandedParameterPack = true;
1386 
1387       if (Types[i]->getType()->isDependentType()) {
1388         IsResultDependent = true;
1389       } else {
1390         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1391         // complete object type other than a variably modified type."
1392         unsigned D = 0;
1393         if (Types[i]->getType()->isIncompleteType())
1394           D = diag::err_assoc_type_incomplete;
1395         else if (!Types[i]->getType()->isObjectType())
1396           D = diag::err_assoc_type_nonobject;
1397         else if (Types[i]->getType()->isVariablyModifiedType())
1398           D = diag::err_assoc_type_variably_modified;
1399 
1400         if (D != 0) {
1401           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1402             << Types[i]->getTypeLoc().getSourceRange()
1403             << Types[i]->getType();
1404           TypeErrorFound = true;
1405         }
1406 
1407         // C11 6.5.1.1p2 "No two generic associations in the same generic
1408         // selection shall specify compatible types."
1409         for (unsigned j = i+1; j < NumAssocs; ++j)
1410           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1411               Context.typesAreCompatible(Types[i]->getType(),
1412                                          Types[j]->getType())) {
1413             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1414                  diag::err_assoc_compatible_types)
1415               << Types[j]->getTypeLoc().getSourceRange()
1416               << Types[j]->getType()
1417               << Types[i]->getType();
1418             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1419                  diag::note_compat_assoc)
1420               << Types[i]->getTypeLoc().getSourceRange()
1421               << Types[i]->getType();
1422             TypeErrorFound = true;
1423           }
1424       }
1425     }
1426   }
1427   if (TypeErrorFound)
1428     return ExprError();
1429 
1430   // If we determined that the generic selection is result-dependent, don't
1431   // try to compute the result expression.
1432   if (IsResultDependent)
1433     return new (Context) GenericSelectionExpr(
1434         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1435         ContainsUnexpandedParameterPack);
1436 
1437   SmallVector<unsigned, 1> CompatIndices;
1438   unsigned DefaultIndex = -1U;
1439   for (unsigned i = 0; i < NumAssocs; ++i) {
1440     if (!Types[i])
1441       DefaultIndex = i;
1442     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1443                                         Types[i]->getType()))
1444       CompatIndices.push_back(i);
1445   }
1446 
1447   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1448   // type compatible with at most one of the types named in its generic
1449   // association list."
1450   if (CompatIndices.size() > 1) {
1451     // We strip parens here because the controlling expression is typically
1452     // parenthesized in macro definitions.
1453     ControllingExpr = ControllingExpr->IgnoreParens();
1454     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1455       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1456       << (unsigned) CompatIndices.size();
1457     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1458          E = CompatIndices.end(); I != E; ++I) {
1459       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1460            diag::note_compat_assoc)
1461         << Types[*I]->getTypeLoc().getSourceRange()
1462         << Types[*I]->getType();
1463     }
1464     return ExprError();
1465   }
1466 
1467   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1468   // its controlling expression shall have type compatible with exactly one of
1469   // the types named in its generic association list."
1470   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1471     // We strip parens here because the controlling expression is typically
1472     // parenthesized in macro definitions.
1473     ControllingExpr = ControllingExpr->IgnoreParens();
1474     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1475       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1476     return ExprError();
1477   }
1478 
1479   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1480   // type name that is compatible with the type of the controlling expression,
1481   // then the result expression of the generic selection is the expression
1482   // in that generic association. Otherwise, the result expression of the
1483   // generic selection is the expression in the default generic association."
1484   unsigned ResultIndex =
1485     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1486 
1487   return new (Context) GenericSelectionExpr(
1488       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1489       ContainsUnexpandedParameterPack, ResultIndex);
1490 }
1491 
1492 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1493 /// location of the token and the offset of the ud-suffix within it.
1494 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1495                                      unsigned Offset) {
1496   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1497                                         S.getLangOpts());
1498 }
1499 
1500 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1501 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1502 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1503                                                  IdentifierInfo *UDSuffix,
1504                                                  SourceLocation UDSuffixLoc,
1505                                                  ArrayRef<Expr*> Args,
1506                                                  SourceLocation LitEndLoc) {
1507   assert(Args.size() <= 2 && "too many arguments for literal operator");
1508 
1509   QualType ArgTy[2];
1510   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1511     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1512     if (ArgTy[ArgIdx]->isArrayType())
1513       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1514   }
1515 
1516   DeclarationName OpName =
1517     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1518   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1519   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1520 
1521   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1522   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1523                               /*AllowRaw*/false, /*AllowTemplate*/false,
1524                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1525     return ExprError();
1526 
1527   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1528 }
1529 
1530 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1531 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1532 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1533 /// multiple tokens.  However, the common case is that StringToks points to one
1534 /// string.
1535 ///
1536 ExprResult
1537 Sema::ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope) {
1538   assert(!StringToks.empty() && "Must have at least one string!");
1539 
1540   StringLiteralParser Literal(StringToks, PP);
1541   if (Literal.hadError)
1542     return ExprError();
1543 
1544   SmallVector<SourceLocation, 4> StringTokLocs;
1545   for (unsigned i = 0; i != StringToks.size(); ++i)
1546     StringTokLocs.push_back(StringToks[i].getLocation());
1547 
1548   QualType CharTy = Context.CharTy;
1549   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1550   if (Literal.isWide()) {
1551     CharTy = Context.getWideCharType();
1552     Kind = StringLiteral::Wide;
1553   } else if (Literal.isUTF8()) {
1554     Kind = StringLiteral::UTF8;
1555   } else if (Literal.isUTF16()) {
1556     CharTy = Context.Char16Ty;
1557     Kind = StringLiteral::UTF16;
1558   } else if (Literal.isUTF32()) {
1559     CharTy = Context.Char32Ty;
1560     Kind = StringLiteral::UTF32;
1561   } else if (Literal.isPascal()) {
1562     CharTy = Context.UnsignedCharTy;
1563   }
1564 
1565   QualType CharTyConst = CharTy;
1566   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1567   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1568     CharTyConst.addConst();
1569 
1570   // Get an array type for the string, according to C99 6.4.5.  This includes
1571   // the nul terminator character as well as the string length for pascal
1572   // strings.
1573   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1574                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1575                                  ArrayType::Normal, 0);
1576 
1577   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1578   if (getLangOpts().OpenCL) {
1579     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1580   }
1581 
1582   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1583   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1584                                              Kind, Literal.Pascal, StrTy,
1585                                              &StringTokLocs[0],
1586                                              StringTokLocs.size());
1587   if (Literal.getUDSuffix().empty())
1588     return Lit;
1589 
1590   // We're building a user-defined literal.
1591   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1592   SourceLocation UDSuffixLoc =
1593     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1594                    Literal.getUDSuffixOffset());
1595 
1596   // Make sure we're allowed user-defined literals here.
1597   if (!UDLScope)
1598     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1599 
1600   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1601   //   operator "" X (str, len)
1602   QualType SizeType = Context.getSizeType();
1603 
1604   DeclarationName OpName =
1605     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1606   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1607   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1608 
1609   QualType ArgTy[] = {
1610     Context.getArrayDecayedType(StrTy), SizeType
1611   };
1612 
1613   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1614   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1615                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1616                                 /*AllowStringTemplate*/true)) {
1617 
1618   case LOLR_Cooked: {
1619     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1620     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1621                                                     StringTokLocs[0]);
1622     Expr *Args[] = { Lit, LenArg };
1623 
1624     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1625   }
1626 
1627   case LOLR_StringTemplate: {
1628     TemplateArgumentListInfo ExplicitArgs;
1629 
1630     unsigned CharBits = Context.getIntWidth(CharTy);
1631     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1632     llvm::APSInt Value(CharBits, CharIsUnsigned);
1633 
1634     TemplateArgument TypeArg(CharTy);
1635     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1636     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1637 
1638     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1639       Value = Lit->getCodeUnit(I);
1640       TemplateArgument Arg(Context, Value, CharTy);
1641       TemplateArgumentLocInfo ArgInfo;
1642       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1643     }
1644     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1645                                     &ExplicitArgs);
1646   }
1647   case LOLR_Raw:
1648   case LOLR_Template:
1649     llvm_unreachable("unexpected literal operator lookup result");
1650   case LOLR_Error:
1651     return ExprError();
1652   }
1653   llvm_unreachable("unexpected literal operator lookup result");
1654 }
1655 
1656 ExprResult
1657 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1658                        SourceLocation Loc,
1659                        const CXXScopeSpec *SS) {
1660   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1661   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1662 }
1663 
1664 /// BuildDeclRefExpr - Build an expression that references a
1665 /// declaration that does not require a closure capture.
1666 ExprResult
1667 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1668                        const DeclarationNameInfo &NameInfo,
1669                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1670                        const TemplateArgumentListInfo *TemplateArgs) {
1671   if (getLangOpts().CUDA)
1672     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1673       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1674         if (CheckCUDATarget(Caller, Callee)) {
1675           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1676             << IdentifyCUDATarget(Callee) << D->getIdentifier()
1677             << IdentifyCUDATarget(Caller);
1678           Diag(D->getLocation(), diag::note_previous_decl)
1679             << D->getIdentifier();
1680           return ExprError();
1681         }
1682       }
1683 
1684   bool RefersToCapturedVariable =
1685       isa<VarDecl>(D) &&
1686       NeedToCaptureVariable(cast<VarDecl>(D), NameInfo.getLoc());
1687 
1688   DeclRefExpr *E;
1689   if (isa<VarTemplateSpecializationDecl>(D)) {
1690     VarTemplateSpecializationDecl *VarSpec =
1691         cast<VarTemplateSpecializationDecl>(D);
1692 
1693     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1694                                         : NestedNameSpecifierLoc(),
1695                             VarSpec->getTemplateKeywordLoc(), D,
1696                             RefersToCapturedVariable, NameInfo.getLoc(), Ty, VK,
1697                             FoundD, TemplateArgs);
1698   } else {
1699     assert(!TemplateArgs && "No template arguments for non-variable"
1700                             " template specialization references");
1701     E = DeclRefExpr::Create(Context, SS ? SS->getWithLocInContext(Context)
1702                                         : NestedNameSpecifierLoc(),
1703                             SourceLocation(), D, RefersToCapturedVariable,
1704                             NameInfo, Ty, VK, FoundD);
1705   }
1706 
1707   MarkDeclRefReferenced(E);
1708 
1709   if (getLangOpts().ObjCWeak && isa<VarDecl>(D) &&
1710       Ty.getObjCLifetime() == Qualifiers::OCL_Weak &&
1711       !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, E->getLocStart()))
1712       recordUseOfEvaluatedWeak(E);
1713 
1714   // Just in case we're building an illegal pointer-to-member.
1715   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1716   if (FD && FD->isBitField())
1717     E->setObjectKind(OK_BitField);
1718 
1719   return E;
1720 }
1721 
1722 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1723 /// possibly a list of template arguments.
1724 ///
1725 /// If this produces template arguments, it is permitted to call
1726 /// DecomposeTemplateName.
1727 ///
1728 /// This actually loses a lot of source location information for
1729 /// non-standard name kinds; we should consider preserving that in
1730 /// some way.
1731 void
1732 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1733                              TemplateArgumentListInfo &Buffer,
1734                              DeclarationNameInfo &NameInfo,
1735                              const TemplateArgumentListInfo *&TemplateArgs) {
1736   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1737     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1738     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1739 
1740     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1741                                        Id.TemplateId->NumArgs);
1742     translateTemplateArguments(TemplateArgsPtr, Buffer);
1743 
1744     TemplateName TName = Id.TemplateId->Template.get();
1745     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1746     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1747     TemplateArgs = &Buffer;
1748   } else {
1749     NameInfo = GetNameFromUnqualifiedId(Id);
1750     TemplateArgs = nullptr;
1751   }
1752 }
1753 
1754 static void emitEmptyLookupTypoDiagnostic(
1755     const TypoCorrection &TC, Sema &SemaRef, const CXXScopeSpec &SS,
1756     DeclarationName Typo, SourceLocation TypoLoc, ArrayRef<Expr *> Args,
1757     unsigned DiagnosticID, unsigned DiagnosticSuggestID) {
1758   DeclContext *Ctx =
1759       SS.isEmpty() ? nullptr : SemaRef.computeDeclContext(SS, false);
1760   if (!TC) {
1761     // Emit a special diagnostic for failed member lookups.
1762     // FIXME: computing the declaration context might fail here (?)
1763     if (Ctx)
1764       SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << Ctx
1765                                                  << SS.getRange();
1766     else
1767       SemaRef.Diag(TypoLoc, DiagnosticID) << Typo;
1768     return;
1769   }
1770 
1771   std::string CorrectedStr = TC.getAsString(SemaRef.getLangOpts());
1772   bool DroppedSpecifier =
1773       TC.WillReplaceSpecifier() && Typo.getAsString() == CorrectedStr;
1774   unsigned NoteID =
1775       (TC.getCorrectionDecl() && isa<ImplicitParamDecl>(TC.getCorrectionDecl()))
1776           ? diag::note_implicit_param_decl
1777           : diag::note_previous_decl;
1778   if (!Ctx)
1779     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticSuggestID) << Typo,
1780                          SemaRef.PDiag(NoteID));
1781   else
1782     SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
1783                                  << Typo << Ctx << DroppedSpecifier
1784                                  << SS.getRange(),
1785                          SemaRef.PDiag(NoteID));
1786 }
1787 
1788 /// Diagnose an empty lookup.
1789 ///
1790 /// \return false if new lookup candidates were found
1791 bool
1792 Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1793                           std::unique_ptr<CorrectionCandidateCallback> CCC,
1794                           TemplateArgumentListInfo *ExplicitTemplateArgs,
1795                           ArrayRef<Expr *> Args, TypoExpr **Out) {
1796   DeclarationName Name = R.getLookupName();
1797 
1798   unsigned diagnostic = diag::err_undeclared_var_use;
1799   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1800   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1801       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1802       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1803     diagnostic = diag::err_undeclared_use;
1804     diagnostic_suggest = diag::err_undeclared_use_suggest;
1805   }
1806 
1807   // If the original lookup was an unqualified lookup, fake an
1808   // unqualified lookup.  This is useful when (for example) the
1809   // original lookup would not have found something because it was a
1810   // dependent name.
1811   DeclContext *DC = SS.isEmpty() ? CurContext : nullptr;
1812   while (DC) {
1813     if (isa<CXXRecordDecl>(DC)) {
1814       LookupQualifiedName(R, DC);
1815 
1816       if (!R.empty()) {
1817         // Don't give errors about ambiguities in this lookup.
1818         R.suppressDiagnostics();
1819 
1820         // During a default argument instantiation the CurContext points
1821         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1822         // function parameter list, hence add an explicit check.
1823         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1824                               ActiveTemplateInstantiations.back().Kind ==
1825             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1826         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1827         bool isInstance = CurMethod &&
1828                           CurMethod->isInstance() &&
1829                           DC == CurMethod->getParent() && !isDefaultArgument;
1830 
1831         // Give a code modification hint to insert 'this->'.
1832         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1833         // Actually quite difficult!
1834         if (getLangOpts().MSVCCompat)
1835           diagnostic = diag::ext_found_via_dependent_bases_lookup;
1836         if (isInstance) {
1837           Diag(R.getNameLoc(), diagnostic) << Name
1838             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1839           CheckCXXThisCapture(R.getNameLoc());
1840         } else {
1841           Diag(R.getNameLoc(), diagnostic) << Name;
1842         }
1843 
1844         // Do we really want to note all of these?
1845         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1846           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1847 
1848         // Return true if we are inside a default argument instantiation
1849         // and the found name refers to an instance member function, otherwise
1850         // the function calling DiagnoseEmptyLookup will try to create an
1851         // implicit member call and this is wrong for default argument.
1852         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1853           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1854           return true;
1855         }
1856 
1857         // Tell the callee to try to recover.
1858         return false;
1859       }
1860 
1861       R.clear();
1862     }
1863 
1864     // In Microsoft mode, if we are performing lookup from within a friend
1865     // function definition declared at class scope then we must set
1866     // DC to the lexical parent to be able to search into the parent
1867     // class.
1868     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1869         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1870         DC->getLexicalParent()->isRecord())
1871       DC = DC->getLexicalParent();
1872     else
1873       DC = DC->getParent();
1874   }
1875 
1876   // We didn't find anything, so try to correct for a typo.
1877   TypoCorrection Corrected;
1878   if (S && Out) {
1879     SourceLocation TypoLoc = R.getNameLoc();
1880     assert(!ExplicitTemplateArgs &&
1881            "Diagnosing an empty lookup with explicit template args!");
1882     *Out = CorrectTypoDelayed(
1883         R.getLookupNameInfo(), R.getLookupKind(), S, &SS, std::move(CCC),
1884         [=](const TypoCorrection &TC) {
1885           emitEmptyLookupTypoDiagnostic(TC, *this, SS, Name, TypoLoc, Args,
1886                                         diagnostic, diagnostic_suggest);
1887         },
1888         nullptr, CTK_ErrorRecovery);
1889     if (*Out)
1890       return true;
1891   } else if (S && (Corrected =
1892                        CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S,
1893                                    &SS, std::move(CCC), CTK_ErrorRecovery))) {
1894     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1895     bool DroppedSpecifier =
1896         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1897     R.setLookupName(Corrected.getCorrection());
1898 
1899     bool AcceptableWithRecovery = false;
1900     bool AcceptableWithoutRecovery = false;
1901     NamedDecl *ND = Corrected.getCorrectionDecl();
1902     if (ND) {
1903       if (Corrected.isOverloaded()) {
1904         OverloadCandidateSet OCS(R.getNameLoc(),
1905                                  OverloadCandidateSet::CSK_Normal);
1906         OverloadCandidateSet::iterator Best;
1907         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1908                                         CDEnd = Corrected.end();
1909              CD != CDEnd; ++CD) {
1910           if (FunctionTemplateDecl *FTD =
1911                    dyn_cast<FunctionTemplateDecl>(*CD))
1912             AddTemplateOverloadCandidate(
1913                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1914                 Args, OCS);
1915           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1916             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1917               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1918                                    Args, OCS);
1919         }
1920         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1921         case OR_Success:
1922           ND = Best->Function;
1923           Corrected.setCorrectionDecl(ND);
1924           break;
1925         default:
1926           // FIXME: Arbitrarily pick the first declaration for the note.
1927           Corrected.setCorrectionDecl(ND);
1928           break;
1929         }
1930       }
1931       R.addDecl(ND);
1932       if (getLangOpts().CPlusPlus && ND->isCXXClassMember()) {
1933         CXXRecordDecl *Record = nullptr;
1934         if (Corrected.getCorrectionSpecifier()) {
1935           const Type *Ty = Corrected.getCorrectionSpecifier()->getAsType();
1936           Record = Ty->getAsCXXRecordDecl();
1937         }
1938         if (!Record)
1939           Record = cast<CXXRecordDecl>(
1940               ND->getDeclContext()->getRedeclContext());
1941         R.setNamingClass(Record);
1942       }
1943 
1944       AcceptableWithRecovery =
1945           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1946       // FIXME: If we ended up with a typo for a type name or
1947       // Objective-C class name, we're in trouble because the parser
1948       // is in the wrong place to recover. Suggest the typo
1949       // correction, but don't make it a fix-it since we're not going
1950       // to recover well anyway.
1951       AcceptableWithoutRecovery =
1952           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1953     } else {
1954       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1955       // because we aren't able to recover.
1956       AcceptableWithoutRecovery = true;
1957     }
1958 
1959     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1960       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1961                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1962                             ? diag::note_implicit_param_decl
1963                             : diag::note_previous_decl;
1964       if (SS.isEmpty())
1965         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1966                      PDiag(NoteID), AcceptableWithRecovery);
1967       else
1968         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1969                                   << Name << computeDeclContext(SS, false)
1970                                   << DroppedSpecifier << SS.getRange(),
1971                      PDiag(NoteID), AcceptableWithRecovery);
1972 
1973       // Tell the callee whether to try to recover.
1974       return !AcceptableWithRecovery;
1975     }
1976   }
1977   R.clear();
1978 
1979   // Emit a special diagnostic for failed member lookups.
1980   // FIXME: computing the declaration context might fail here (?)
1981   if (!SS.isEmpty()) {
1982     Diag(R.getNameLoc(), diag::err_no_member)
1983       << Name << computeDeclContext(SS, false)
1984       << SS.getRange();
1985     return true;
1986   }
1987 
1988   // Give up, we can't recover.
1989   Diag(R.getNameLoc(), diagnostic) << Name;
1990   return true;
1991 }
1992 
1993 /// In Microsoft mode, if we are inside a template class whose parent class has
1994 /// dependent base classes, and we can't resolve an unqualified identifier, then
1995 /// assume the identifier is a member of a dependent base class.  We can only
1996 /// recover successfully in static methods, instance methods, and other contexts
1997 /// where 'this' is available.  This doesn't precisely match MSVC's
1998 /// instantiation model, but it's close enough.
1999 static Expr *
2000 recoverFromMSUnqualifiedLookup(Sema &S, ASTContext &Context,
2001                                DeclarationNameInfo &NameInfo,
2002                                SourceLocation TemplateKWLoc,
2003                                const TemplateArgumentListInfo *TemplateArgs) {
2004   // Only try to recover from lookup into dependent bases in static methods or
2005   // contexts where 'this' is available.
2006   QualType ThisType = S.getCurrentThisType();
2007   const CXXRecordDecl *RD = nullptr;
2008   if (!ThisType.isNull())
2009     RD = ThisType->getPointeeType()->getAsCXXRecordDecl();
2010   else if (auto *MD = dyn_cast<CXXMethodDecl>(S.CurContext))
2011     RD = MD->getParent();
2012   if (!RD || !RD->hasAnyDependentBases())
2013     return nullptr;
2014 
2015   // Diagnose this as unqualified lookup into a dependent base class.  If 'this'
2016   // is available, suggest inserting 'this->' as a fixit.
2017   SourceLocation Loc = NameInfo.getLoc();
2018   auto DB = S.Diag(Loc, diag::ext_undeclared_unqual_id_with_dependent_base);
2019   DB << NameInfo.getName() << RD;
2020 
2021   if (!ThisType.isNull()) {
2022     DB << FixItHint::CreateInsertion(Loc, "this->");
2023     return CXXDependentScopeMemberExpr::Create(
2024         Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2025         /*Op=*/SourceLocation(), NestedNameSpecifierLoc(), TemplateKWLoc,
2026         /*FirstQualifierInScope=*/nullptr, NameInfo, TemplateArgs);
2027   }
2028 
2029   // Synthesize a fake NNS that points to the derived class.  This will
2030   // perform name lookup during template instantiation.
2031   CXXScopeSpec SS;
2032   auto *NNS =
2033       NestedNameSpecifier::Create(Context, nullptr, true, RD->getTypeForDecl());
2034   SS.MakeTrivial(Context, NNS, SourceRange(Loc, Loc));
2035   return DependentScopeDeclRefExpr::Create(
2036       Context, SS.getWithLocInContext(Context), TemplateKWLoc, NameInfo,
2037       TemplateArgs);
2038 }
2039 
2040 ExprResult
2041 Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
2042                         SourceLocation TemplateKWLoc, UnqualifiedId &Id,
2043                         bool HasTrailingLParen, bool IsAddressOfOperand,
2044                         std::unique_ptr<CorrectionCandidateCallback> CCC,
2045                         bool IsInlineAsmIdentifier, Token *KeywordReplacement) {
2046   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
2047          "cannot be direct & operand and have a trailing lparen");
2048   if (SS.isInvalid())
2049     return ExprError();
2050 
2051   TemplateArgumentListInfo TemplateArgsBuffer;
2052 
2053   // Decompose the UnqualifiedId into the following data.
2054   DeclarationNameInfo NameInfo;
2055   const TemplateArgumentListInfo *TemplateArgs;
2056   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
2057 
2058   DeclarationName Name = NameInfo.getName();
2059   IdentifierInfo *II = Name.getAsIdentifierInfo();
2060   SourceLocation NameLoc = NameInfo.getLoc();
2061 
2062   // C++ [temp.dep.expr]p3:
2063   //   An id-expression is type-dependent if it contains:
2064   //     -- an identifier that was declared with a dependent type,
2065   //        (note: handled after lookup)
2066   //     -- a template-id that is dependent,
2067   //        (note: handled in BuildTemplateIdExpr)
2068   //     -- a conversion-function-id that specifies a dependent type,
2069   //     -- a nested-name-specifier that contains a class-name that
2070   //        names a dependent type.
2071   // Determine whether this is a member of an unknown specialization;
2072   // we need to handle these differently.
2073   bool DependentID = false;
2074   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
2075       Name.getCXXNameType()->isDependentType()) {
2076     DependentID = true;
2077   } else if (SS.isSet()) {
2078     if (DeclContext *DC = computeDeclContext(SS, false)) {
2079       if (RequireCompleteDeclContext(SS, DC))
2080         return ExprError();
2081     } else {
2082       DependentID = true;
2083     }
2084   }
2085 
2086   if (DependentID)
2087     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2088                                       IsAddressOfOperand, TemplateArgs);
2089 
2090   // Perform the required lookup.
2091   LookupResult R(*this, NameInfo,
2092                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
2093                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
2094   if (TemplateArgs) {
2095     // Lookup the template name again to correctly establish the context in
2096     // which it was found. This is really unfortunate as we already did the
2097     // lookup to determine that it was a template name in the first place. If
2098     // this becomes a performance hit, we can work harder to preserve those
2099     // results until we get here but it's likely not worth it.
2100     bool MemberOfUnknownSpecialization;
2101     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
2102                        MemberOfUnknownSpecialization);
2103 
2104     if (MemberOfUnknownSpecialization ||
2105         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2106       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2107                                         IsAddressOfOperand, TemplateArgs);
2108   } else {
2109     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2110     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2111 
2112     // If the result might be in a dependent base class, this is a dependent
2113     // id-expression.
2114     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2115       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2116                                         IsAddressOfOperand, TemplateArgs);
2117 
2118     // If this reference is in an Objective-C method, then we need to do
2119     // some special Objective-C lookup, too.
2120     if (IvarLookupFollowUp) {
2121       ExprResult E(LookupInObjCMethod(R, S, II, true));
2122       if (E.isInvalid())
2123         return ExprError();
2124 
2125       if (Expr *Ex = E.getAs<Expr>())
2126         return Ex;
2127     }
2128   }
2129 
2130   if (R.isAmbiguous())
2131     return ExprError();
2132 
2133   // This could be an implicitly declared function reference (legal in C90,
2134   // extension in C99, forbidden in C++).
2135   if (R.empty() && HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2136     NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2137     if (D) R.addDecl(D);
2138   }
2139 
2140   // Determine whether this name might be a candidate for
2141   // argument-dependent lookup.
2142   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2143 
2144   if (R.empty() && !ADL) {
2145     if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2146       if (Expr *E = recoverFromMSUnqualifiedLookup(*this, Context, NameInfo,
2147                                                    TemplateKWLoc, TemplateArgs))
2148         return E;
2149     }
2150 
2151     // Don't diagnose an empty lookup for inline assembly.
2152     if (IsInlineAsmIdentifier)
2153       return ExprError();
2154 
2155     // If this name wasn't predeclared and if this is not a function
2156     // call, diagnose the problem.
2157     TypoExpr *TE = nullptr;
2158     auto DefaultValidator = llvm::make_unique<CorrectionCandidateCallback>(
2159         II, SS.isValid() ? SS.getScopeRep() : nullptr);
2160     DefaultValidator->IsAddressOfOperand = IsAddressOfOperand;
2161     assert((!CCC || CCC->IsAddressOfOperand == IsAddressOfOperand) &&
2162            "Typo correction callback misconfigured");
2163     if (CCC) {
2164       // Make sure the callback knows what the typo being diagnosed is.
2165       CCC->setTypoName(II);
2166       if (SS.isValid())
2167         CCC->setTypoNNS(SS.getScopeRep());
2168     }
2169     if (DiagnoseEmptyLookup(S, SS, R,
2170                             CCC ? std::move(CCC) : std::move(DefaultValidator),
2171                             nullptr, None, &TE)) {
2172       if (TE && KeywordReplacement) {
2173         auto &State = getTypoExprState(TE);
2174         auto BestTC = State.Consumer->getNextCorrection();
2175         if (BestTC.isKeyword()) {
2176           auto *II = BestTC.getCorrectionAsIdentifierInfo();
2177           if (State.DiagHandler)
2178             State.DiagHandler(BestTC);
2179           KeywordReplacement->startToken();
2180           KeywordReplacement->setKind(II->getTokenID());
2181           KeywordReplacement->setIdentifierInfo(II);
2182           KeywordReplacement->setLocation(BestTC.getCorrectionRange().getBegin());
2183           // Clean up the state associated with the TypoExpr, since it has
2184           // now been diagnosed (without a call to CorrectDelayedTyposInExpr).
2185           clearDelayedTypo(TE);
2186           // Signal that a correction to a keyword was performed by returning a
2187           // valid-but-null ExprResult.
2188           return (Expr*)nullptr;
2189         }
2190         State.Consumer->resetCorrectionStream();
2191       }
2192       return TE ? TE : ExprError();
2193     }
2194 
2195     assert(!R.empty() &&
2196            "DiagnoseEmptyLookup returned false but added no results");
2197 
2198     // If we found an Objective-C instance variable, let
2199     // LookupInObjCMethod build the appropriate expression to
2200     // reference the ivar.
2201     if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2202       R.clear();
2203       ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2204       // In a hopelessly buggy code, Objective-C instance variable
2205       // lookup fails and no expression will be built to reference it.
2206       if (!E.isInvalid() && !E.get())
2207         return ExprError();
2208       return E;
2209     }
2210   }
2211 
2212   // This is guaranteed from this point on.
2213   assert(!R.empty() || ADL);
2214 
2215   // Check whether this might be a C++ implicit instance member access.
2216   // C++ [class.mfct.non-static]p3:
2217   //   When an id-expression that is not part of a class member access
2218   //   syntax and not used to form a pointer to member is used in the
2219   //   body of a non-static member function of class X, if name lookup
2220   //   resolves the name in the id-expression to a non-static non-type
2221   //   member of some class C, the id-expression is transformed into a
2222   //   class member access expression using (*this) as the
2223   //   postfix-expression to the left of the . operator.
2224   //
2225   // But we don't actually need to do this for '&' operands if R
2226   // resolved to a function or overloaded function set, because the
2227   // expression is ill-formed if it actually works out to be a
2228   // non-static member function:
2229   //
2230   // C++ [expr.ref]p4:
2231   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2232   //   [t]he expression can be used only as the left-hand operand of a
2233   //   member function call.
2234   //
2235   // There are other safeguards against such uses, but it's important
2236   // to get this right here so that we don't end up making a
2237   // spuriously dependent expression if we're inside a dependent
2238   // instance method.
2239   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2240     bool MightBeImplicitMember;
2241     if (!IsAddressOfOperand)
2242       MightBeImplicitMember = true;
2243     else if (!SS.isEmpty())
2244       MightBeImplicitMember = false;
2245     else if (R.isOverloadedResult())
2246       MightBeImplicitMember = false;
2247     else if (R.isUnresolvableResult())
2248       MightBeImplicitMember = true;
2249     else
2250       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2251                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2252                               isa<MSPropertyDecl>(R.getFoundDecl());
2253 
2254     if (MightBeImplicitMember)
2255       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2256                                              R, TemplateArgs, S);
2257   }
2258 
2259   if (TemplateArgs || TemplateKWLoc.isValid()) {
2260 
2261     // In C++1y, if this is a variable template id, then check it
2262     // in BuildTemplateIdExpr().
2263     // The single lookup result must be a variable template declaration.
2264     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2265         Id.TemplateId->Kind == TNK_Var_template) {
2266       assert(R.getAsSingle<VarTemplateDecl>() &&
2267              "There should only be one declaration found.");
2268     }
2269 
2270     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2271   }
2272 
2273   return BuildDeclarationNameExpr(SS, R, ADL);
2274 }
2275 
2276 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2277 /// declaration name, generally during template instantiation.
2278 /// There's a large number of things which don't need to be done along
2279 /// this path.
2280 ExprResult Sema::BuildQualifiedDeclarationNameExpr(
2281     CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo,
2282     bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI) {
2283   DeclContext *DC = computeDeclContext(SS, false);
2284   if (!DC)
2285     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2286                                      NameInfo, /*TemplateArgs=*/nullptr);
2287 
2288   if (RequireCompleteDeclContext(SS, DC))
2289     return ExprError();
2290 
2291   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2292   LookupQualifiedName(R, DC);
2293 
2294   if (R.isAmbiguous())
2295     return ExprError();
2296 
2297   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2298     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2299                                      NameInfo, /*TemplateArgs=*/nullptr);
2300 
2301   if (R.empty()) {
2302     Diag(NameInfo.getLoc(), diag::err_no_member)
2303       << NameInfo.getName() << DC << SS.getRange();
2304     return ExprError();
2305   }
2306 
2307   if (const TypeDecl *TD = R.getAsSingle<TypeDecl>()) {
2308     // Diagnose a missing typename if this resolved unambiguously to a type in
2309     // a dependent context.  If we can recover with a type, downgrade this to
2310     // a warning in Microsoft compatibility mode.
2311     unsigned DiagID = diag::err_typename_missing;
2312     if (RecoveryTSI && getLangOpts().MSVCCompat)
2313       DiagID = diag::ext_typename_missing;
2314     SourceLocation Loc = SS.getBeginLoc();
2315     auto D = Diag(Loc, DiagID);
2316     D << SS.getScopeRep() << NameInfo.getName().getAsString()
2317       << SourceRange(Loc, NameInfo.getEndLoc());
2318 
2319     // Don't recover if the caller isn't expecting us to or if we're in a SFINAE
2320     // context.
2321     if (!RecoveryTSI)
2322       return ExprError();
2323 
2324     // Only issue the fixit if we're prepared to recover.
2325     D << FixItHint::CreateInsertion(Loc, "typename ");
2326 
2327     // Recover by pretending this was an elaborated type.
2328     QualType Ty = Context.getTypeDeclType(TD);
2329     TypeLocBuilder TLB;
2330     TLB.pushTypeSpec(Ty).setNameLoc(NameInfo.getLoc());
2331 
2332     QualType ET = getElaboratedType(ETK_None, SS, Ty);
2333     ElaboratedTypeLoc QTL = TLB.push<ElaboratedTypeLoc>(ET);
2334     QTL.setElaboratedKeywordLoc(SourceLocation());
2335     QTL.setQualifierLoc(SS.getWithLocInContext(Context));
2336 
2337     *RecoveryTSI = TLB.getTypeSourceInfo(Context, ET);
2338 
2339     return ExprEmpty();
2340   }
2341 
2342   // Defend against this resolving to an implicit member access. We usually
2343   // won't get here if this might be a legitimate a class member (we end up in
2344   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2345   // a pointer-to-member or in an unevaluated context in C++11.
2346   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2347     return BuildPossibleImplicitMemberExpr(SS,
2348                                            /*TemplateKWLoc=*/SourceLocation(),
2349                                            R, /*TemplateArgs=*/nullptr, S);
2350 
2351   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2352 }
2353 
2354 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2355 /// detected that we're currently inside an ObjC method.  Perform some
2356 /// additional lookup.
2357 ///
2358 /// Ideally, most of this would be done by lookup, but there's
2359 /// actually quite a lot of extra work involved.
2360 ///
2361 /// Returns a null sentinel to indicate trivial success.
2362 ExprResult
2363 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2364                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2365   SourceLocation Loc = Lookup.getNameLoc();
2366   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2367 
2368   // Check for error condition which is already reported.
2369   if (!CurMethod)
2370     return ExprError();
2371 
2372   // There are two cases to handle here.  1) scoped lookup could have failed,
2373   // in which case we should look for an ivar.  2) scoped lookup could have
2374   // found a decl, but that decl is outside the current instance method (i.e.
2375   // a global variable).  In these two cases, we do a lookup for an ivar with
2376   // this name, if the lookup sucedes, we replace it our current decl.
2377 
2378   // If we're in a class method, we don't normally want to look for
2379   // ivars.  But if we don't find anything else, and there's an
2380   // ivar, that's an error.
2381   bool IsClassMethod = CurMethod->isClassMethod();
2382 
2383   bool LookForIvars;
2384   if (Lookup.empty())
2385     LookForIvars = true;
2386   else if (IsClassMethod)
2387     LookForIvars = false;
2388   else
2389     LookForIvars = (Lookup.isSingleResult() &&
2390                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2391   ObjCInterfaceDecl *IFace = nullptr;
2392   if (LookForIvars) {
2393     IFace = CurMethod->getClassInterface();
2394     ObjCInterfaceDecl *ClassDeclared;
2395     ObjCIvarDecl *IV = nullptr;
2396     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2397       // Diagnose using an ivar in a class method.
2398       if (IsClassMethod)
2399         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2400                          << IV->getDeclName());
2401 
2402       // If we're referencing an invalid decl, just return this as a silent
2403       // error node.  The error diagnostic was already emitted on the decl.
2404       if (IV->isInvalidDecl())
2405         return ExprError();
2406 
2407       // Check if referencing a field with __attribute__((deprecated)).
2408       if (DiagnoseUseOfDecl(IV, Loc))
2409         return ExprError();
2410 
2411       // Diagnose the use of an ivar outside of the declaring class.
2412       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2413           !declaresSameEntity(ClassDeclared, IFace) &&
2414           !getLangOpts().DebuggerSupport)
2415         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2416 
2417       // FIXME: This should use a new expr for a direct reference, don't
2418       // turn this into Self->ivar, just return a BareIVarExpr or something.
2419       IdentifierInfo &II = Context.Idents.get("self");
2420       UnqualifiedId SelfName;
2421       SelfName.setIdentifier(&II, SourceLocation());
2422       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2423       CXXScopeSpec SelfScopeSpec;
2424       SourceLocation TemplateKWLoc;
2425       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2426                                               SelfName, false, false);
2427       if (SelfExpr.isInvalid())
2428         return ExprError();
2429 
2430       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2431       if (SelfExpr.isInvalid())
2432         return ExprError();
2433 
2434       MarkAnyDeclReferenced(Loc, IV, true);
2435 
2436       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2437       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2438           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2439         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2440 
2441       ObjCIvarRefExpr *Result = new (Context)
2442           ObjCIvarRefExpr(IV, IV->getUsageType(SelfExpr.get()->getType()), Loc,
2443                           IV->getLocation(), SelfExpr.get(), true, true);
2444 
2445       if (getLangOpts().ObjCAutoRefCount) {
2446         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2447           if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
2448             recordUseOfEvaluatedWeak(Result);
2449         }
2450         if (CurContext->isClosure())
2451           Diag(Loc, diag::warn_implicitly_retains_self)
2452             << FixItHint::CreateInsertion(Loc, "self->");
2453       }
2454 
2455       return Result;
2456     }
2457   } else if (CurMethod->isInstanceMethod()) {
2458     // We should warn if a local variable hides an ivar.
2459     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2460       ObjCInterfaceDecl *ClassDeclared;
2461       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2462         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2463             declaresSameEntity(IFace, ClassDeclared))
2464           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2465       }
2466     }
2467   } else if (Lookup.isSingleResult() &&
2468              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2469     // If accessing a stand-alone ivar in a class method, this is an error.
2470     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2471       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2472                        << IV->getDeclName());
2473   }
2474 
2475   if (Lookup.empty() && II && AllowBuiltinCreation) {
2476     // FIXME. Consolidate this with similar code in LookupName.
2477     if (unsigned BuiltinID = II->getBuiltinID()) {
2478       if (!(getLangOpts().CPlusPlus &&
2479             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2480         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2481                                            S, Lookup.isForRedeclaration(),
2482                                            Lookup.getNameLoc());
2483         if (D) Lookup.addDecl(D);
2484       }
2485     }
2486   }
2487   // Sentinel value saying that we didn't do anything special.
2488   return ExprResult((Expr *)nullptr);
2489 }
2490 
2491 /// \brief Cast a base object to a member's actual type.
2492 ///
2493 /// Logically this happens in three phases:
2494 ///
2495 /// * First we cast from the base type to the naming class.
2496 ///   The naming class is the class into which we were looking
2497 ///   when we found the member;  it's the qualifier type if a
2498 ///   qualifier was provided, and otherwise it's the base type.
2499 ///
2500 /// * Next we cast from the naming class to the declaring class.
2501 ///   If the member we found was brought into a class's scope by
2502 ///   a using declaration, this is that class;  otherwise it's
2503 ///   the class declaring the member.
2504 ///
2505 /// * Finally we cast from the declaring class to the "true"
2506 ///   declaring class of the member.  This conversion does not
2507 ///   obey access control.
2508 ExprResult
2509 Sema::PerformObjectMemberConversion(Expr *From,
2510                                     NestedNameSpecifier *Qualifier,
2511                                     NamedDecl *FoundDecl,
2512                                     NamedDecl *Member) {
2513   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2514   if (!RD)
2515     return From;
2516 
2517   QualType DestRecordType;
2518   QualType DestType;
2519   QualType FromRecordType;
2520   QualType FromType = From->getType();
2521   bool PointerConversions = false;
2522   if (isa<FieldDecl>(Member)) {
2523     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2524 
2525     if (FromType->getAs<PointerType>()) {
2526       DestType = Context.getPointerType(DestRecordType);
2527       FromRecordType = FromType->getPointeeType();
2528       PointerConversions = true;
2529     } else {
2530       DestType = DestRecordType;
2531       FromRecordType = FromType;
2532     }
2533   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2534     if (Method->isStatic())
2535       return From;
2536 
2537     DestType = Method->getThisType(Context);
2538     DestRecordType = DestType->getPointeeType();
2539 
2540     if (FromType->getAs<PointerType>()) {
2541       FromRecordType = FromType->getPointeeType();
2542       PointerConversions = true;
2543     } else {
2544       FromRecordType = FromType;
2545       DestType = DestRecordType;
2546     }
2547   } else {
2548     // No conversion necessary.
2549     return From;
2550   }
2551 
2552   if (DestType->isDependentType() || FromType->isDependentType())
2553     return From;
2554 
2555   // If the unqualified types are the same, no conversion is necessary.
2556   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2557     return From;
2558 
2559   SourceRange FromRange = From->getSourceRange();
2560   SourceLocation FromLoc = FromRange.getBegin();
2561 
2562   ExprValueKind VK = From->getValueKind();
2563 
2564   // C++ [class.member.lookup]p8:
2565   //   [...] Ambiguities can often be resolved by qualifying a name with its
2566   //   class name.
2567   //
2568   // If the member was a qualified name and the qualified referred to a
2569   // specific base subobject type, we'll cast to that intermediate type
2570   // first and then to the object in which the member is declared. That allows
2571   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2572   //
2573   //   class Base { public: int x; };
2574   //   class Derived1 : public Base { };
2575   //   class Derived2 : public Base { };
2576   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2577   //
2578   //   void VeryDerived::f() {
2579   //     x = 17; // error: ambiguous base subobjects
2580   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2581   //   }
2582   if (Qualifier && Qualifier->getAsType()) {
2583     QualType QType = QualType(Qualifier->getAsType(), 0);
2584     assert(QType->isRecordType() && "lookup done with non-record type");
2585 
2586     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2587 
2588     // In C++98, the qualifier type doesn't actually have to be a base
2589     // type of the object type, in which case we just ignore it.
2590     // Otherwise build the appropriate casts.
2591     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2592       CXXCastPath BasePath;
2593       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2594                                        FromLoc, FromRange, &BasePath))
2595         return ExprError();
2596 
2597       if (PointerConversions)
2598         QType = Context.getPointerType(QType);
2599       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2600                                VK, &BasePath).get();
2601 
2602       FromType = QType;
2603       FromRecordType = QRecordType;
2604 
2605       // If the qualifier type was the same as the destination type,
2606       // we're done.
2607       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2608         return From;
2609     }
2610   }
2611 
2612   bool IgnoreAccess = false;
2613 
2614   // If we actually found the member through a using declaration, cast
2615   // down to the using declaration's type.
2616   //
2617   // Pointer equality is fine here because only one declaration of a
2618   // class ever has member declarations.
2619   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2620     assert(isa<UsingShadowDecl>(FoundDecl));
2621     QualType URecordType = Context.getTypeDeclType(
2622                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2623 
2624     // We only need to do this if the naming-class to declaring-class
2625     // conversion is non-trivial.
2626     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2627       assert(IsDerivedFrom(FromRecordType, URecordType));
2628       CXXCastPath BasePath;
2629       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2630                                        FromLoc, FromRange, &BasePath))
2631         return ExprError();
2632 
2633       QualType UType = URecordType;
2634       if (PointerConversions)
2635         UType = Context.getPointerType(UType);
2636       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2637                                VK, &BasePath).get();
2638       FromType = UType;
2639       FromRecordType = URecordType;
2640     }
2641 
2642     // We don't do access control for the conversion from the
2643     // declaring class to the true declaring class.
2644     IgnoreAccess = true;
2645   }
2646 
2647   CXXCastPath BasePath;
2648   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2649                                    FromLoc, FromRange, &BasePath,
2650                                    IgnoreAccess))
2651     return ExprError();
2652 
2653   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2654                            VK, &BasePath);
2655 }
2656 
2657 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2658                                       const LookupResult &R,
2659                                       bool HasTrailingLParen) {
2660   // Only when used directly as the postfix-expression of a call.
2661   if (!HasTrailingLParen)
2662     return false;
2663 
2664   // Never if a scope specifier was provided.
2665   if (SS.isSet())
2666     return false;
2667 
2668   // Only in C++ or ObjC++.
2669   if (!getLangOpts().CPlusPlus)
2670     return false;
2671 
2672   // Turn off ADL when we find certain kinds of declarations during
2673   // normal lookup:
2674   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2675     NamedDecl *D = *I;
2676 
2677     // C++0x [basic.lookup.argdep]p3:
2678     //     -- a declaration of a class member
2679     // Since using decls preserve this property, we check this on the
2680     // original decl.
2681     if (D->isCXXClassMember())
2682       return false;
2683 
2684     // C++0x [basic.lookup.argdep]p3:
2685     //     -- a block-scope function declaration that is not a
2686     //        using-declaration
2687     // NOTE: we also trigger this for function templates (in fact, we
2688     // don't check the decl type at all, since all other decl types
2689     // turn off ADL anyway).
2690     if (isa<UsingShadowDecl>(D))
2691       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2692     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2693       return false;
2694 
2695     // C++0x [basic.lookup.argdep]p3:
2696     //     -- a declaration that is neither a function or a function
2697     //        template
2698     // And also for builtin functions.
2699     if (isa<FunctionDecl>(D)) {
2700       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2701 
2702       // But also builtin functions.
2703       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2704         return false;
2705     } else if (!isa<FunctionTemplateDecl>(D))
2706       return false;
2707   }
2708 
2709   return true;
2710 }
2711 
2712 
2713 /// Diagnoses obvious problems with the use of the given declaration
2714 /// as an expression.  This is only actually called for lookups that
2715 /// were not overloaded, and it doesn't promise that the declaration
2716 /// will in fact be used.
2717 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2718   if (isa<TypedefNameDecl>(D)) {
2719     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2720     return true;
2721   }
2722 
2723   if (isa<ObjCInterfaceDecl>(D)) {
2724     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2725     return true;
2726   }
2727 
2728   if (isa<NamespaceDecl>(D)) {
2729     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2730     return true;
2731   }
2732 
2733   return false;
2734 }
2735 
2736 ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2737                                           LookupResult &R, bool NeedsADL,
2738                                           bool AcceptInvalidDecl) {
2739   // If this is a single, fully-resolved result and we don't need ADL,
2740   // just build an ordinary singleton decl ref.
2741   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2742     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2743                                     R.getRepresentativeDecl(), nullptr,
2744                                     AcceptInvalidDecl);
2745 
2746   // We only need to check the declaration if there's exactly one
2747   // result, because in the overloaded case the results can only be
2748   // functions and function templates.
2749   if (R.isSingleResult() &&
2750       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2751     return ExprError();
2752 
2753   // Otherwise, just build an unresolved lookup expression.  Suppress
2754   // any lookup-related diagnostics; we'll hash these out later, when
2755   // we've picked a target.
2756   R.suppressDiagnostics();
2757 
2758   UnresolvedLookupExpr *ULE
2759     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2760                                    SS.getWithLocInContext(Context),
2761                                    R.getLookupNameInfo(),
2762                                    NeedsADL, R.isOverloadedResult(),
2763                                    R.begin(), R.end());
2764 
2765   return ULE;
2766 }
2767 
2768 /// \brief Complete semantic analysis for a reference to the given declaration.
2769 ExprResult Sema::BuildDeclarationNameExpr(
2770     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2771     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs,
2772     bool AcceptInvalidDecl) {
2773   assert(D && "Cannot refer to a NULL declaration");
2774   assert(!isa<FunctionTemplateDecl>(D) &&
2775          "Cannot refer unambiguously to a function template");
2776 
2777   SourceLocation Loc = NameInfo.getLoc();
2778   if (CheckDeclInExpr(*this, Loc, D))
2779     return ExprError();
2780 
2781   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2782     // Specifically diagnose references to class templates that are missing
2783     // a template argument list.
2784     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2785                                            << Template << SS.getRange();
2786     Diag(Template->getLocation(), diag::note_template_decl_here);
2787     return ExprError();
2788   }
2789 
2790   // Make sure that we're referring to a value.
2791   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2792   if (!VD) {
2793     Diag(Loc, diag::err_ref_non_value)
2794       << D << SS.getRange();
2795     Diag(D->getLocation(), diag::note_declared_at);
2796     return ExprError();
2797   }
2798 
2799   // Check whether this declaration can be used. Note that we suppress
2800   // this check when we're going to perform argument-dependent lookup
2801   // on this function name, because this might not be the function
2802   // that overload resolution actually selects.
2803   if (DiagnoseUseOfDecl(VD, Loc))
2804     return ExprError();
2805 
2806   // Only create DeclRefExpr's for valid Decl's.
2807   if (VD->isInvalidDecl() && !AcceptInvalidDecl)
2808     return ExprError();
2809 
2810   // Handle members of anonymous structs and unions.  If we got here,
2811   // and the reference is to a class member indirect field, then this
2812   // must be the subject of a pointer-to-member expression.
2813   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2814     if (!indirectField->isCXXClassMember())
2815       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2816                                                       indirectField);
2817 
2818   {
2819     QualType type = VD->getType();
2820     ExprValueKind valueKind = VK_RValue;
2821 
2822     switch (D->getKind()) {
2823     // Ignore all the non-ValueDecl kinds.
2824 #define ABSTRACT_DECL(kind)
2825 #define VALUE(type, base)
2826 #define DECL(type, base) \
2827     case Decl::type:
2828 #include "clang/AST/DeclNodes.inc"
2829       llvm_unreachable("invalid value decl kind");
2830 
2831     // These shouldn't make it here.
2832     case Decl::ObjCAtDefsField:
2833     case Decl::ObjCIvar:
2834       llvm_unreachable("forming non-member reference to ivar?");
2835 
2836     // Enum constants are always r-values and never references.
2837     // Unresolved using declarations are dependent.
2838     case Decl::EnumConstant:
2839     case Decl::UnresolvedUsingValue:
2840       valueKind = VK_RValue;
2841       break;
2842 
2843     // Fields and indirect fields that got here must be for
2844     // pointer-to-member expressions; we just call them l-values for
2845     // internal consistency, because this subexpression doesn't really
2846     // exist in the high-level semantics.
2847     case Decl::Field:
2848     case Decl::IndirectField:
2849       assert(getLangOpts().CPlusPlus &&
2850              "building reference to field in C?");
2851 
2852       // These can't have reference type in well-formed programs, but
2853       // for internal consistency we do this anyway.
2854       type = type.getNonReferenceType();
2855       valueKind = VK_LValue;
2856       break;
2857 
2858     // Non-type template parameters are either l-values or r-values
2859     // depending on the type.
2860     case Decl::NonTypeTemplateParm: {
2861       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2862         type = reftype->getPointeeType();
2863         valueKind = VK_LValue; // even if the parameter is an r-value reference
2864         break;
2865       }
2866 
2867       // For non-references, we need to strip qualifiers just in case
2868       // the template parameter was declared as 'const int' or whatever.
2869       valueKind = VK_RValue;
2870       type = type.getUnqualifiedType();
2871       break;
2872     }
2873 
2874     case Decl::Var:
2875     case Decl::VarTemplateSpecialization:
2876     case Decl::VarTemplatePartialSpecialization:
2877       // In C, "extern void blah;" is valid and is an r-value.
2878       if (!getLangOpts().CPlusPlus &&
2879           !type.hasQualifiers() &&
2880           type->isVoidType()) {
2881         valueKind = VK_RValue;
2882         break;
2883       }
2884       // fallthrough
2885 
2886     case Decl::ImplicitParam:
2887     case Decl::ParmVar: {
2888       // These are always l-values.
2889       valueKind = VK_LValue;
2890       type = type.getNonReferenceType();
2891 
2892       // FIXME: Does the addition of const really only apply in
2893       // potentially-evaluated contexts? Since the variable isn't actually
2894       // captured in an unevaluated context, it seems that the answer is no.
2895       if (!isUnevaluatedContext()) {
2896         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2897         if (!CapturedType.isNull())
2898           type = CapturedType;
2899       }
2900 
2901       break;
2902     }
2903 
2904     case Decl::Function: {
2905       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2906         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2907           type = Context.BuiltinFnTy;
2908           valueKind = VK_RValue;
2909           break;
2910         }
2911       }
2912 
2913       const FunctionType *fty = type->castAs<FunctionType>();
2914 
2915       // If we're referring to a function with an __unknown_anytype
2916       // result type, make the entire expression __unknown_anytype.
2917       if (fty->getReturnType() == Context.UnknownAnyTy) {
2918         type = Context.UnknownAnyTy;
2919         valueKind = VK_RValue;
2920         break;
2921       }
2922 
2923       // Functions are l-values in C++.
2924       if (getLangOpts().CPlusPlus) {
2925         valueKind = VK_LValue;
2926         break;
2927       }
2928 
2929       // C99 DR 316 says that, if a function type comes from a
2930       // function definition (without a prototype), that type is only
2931       // used for checking compatibility. Therefore, when referencing
2932       // the function, we pretend that we don't have the full function
2933       // type.
2934       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2935           isa<FunctionProtoType>(fty))
2936         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2937                                               fty->getExtInfo());
2938 
2939       // Functions are r-values in C.
2940       valueKind = VK_RValue;
2941       break;
2942     }
2943 
2944     case Decl::MSProperty:
2945       valueKind = VK_LValue;
2946       break;
2947 
2948     case Decl::CXXMethod:
2949       // If we're referring to a method with an __unknown_anytype
2950       // result type, make the entire expression __unknown_anytype.
2951       // This should only be possible with a type written directly.
2952       if (const FunctionProtoType *proto
2953             = dyn_cast<FunctionProtoType>(VD->getType()))
2954         if (proto->getReturnType() == Context.UnknownAnyTy) {
2955           type = Context.UnknownAnyTy;
2956           valueKind = VK_RValue;
2957           break;
2958         }
2959 
2960       // C++ methods are l-values if static, r-values if non-static.
2961       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2962         valueKind = VK_LValue;
2963         break;
2964       }
2965       // fallthrough
2966 
2967     case Decl::CXXConversion:
2968     case Decl::CXXDestructor:
2969     case Decl::CXXConstructor:
2970       valueKind = VK_RValue;
2971       break;
2972     }
2973 
2974     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2975                             TemplateArgs);
2976   }
2977 }
2978 
2979 static void ConvertUTF8ToWideString(unsigned CharByteWidth, StringRef Source,
2980                                     SmallString<32> &Target) {
2981   Target.resize(CharByteWidth * (Source.size() + 1));
2982   char *ResultPtr = &Target[0];
2983   const UTF8 *ErrorPtr;
2984   bool success = ConvertUTF8toWide(CharByteWidth, Source, ResultPtr, ErrorPtr);
2985   (void)success;
2986   assert(success);
2987   Target.resize(ResultPtr - &Target[0]);
2988 }
2989 
2990 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2991                                      PredefinedExpr::IdentType IT) {
2992   // Pick the current block, lambda, captured statement or function.
2993   Decl *currentDecl = nullptr;
2994   if (const BlockScopeInfo *BSI = getCurBlock())
2995     currentDecl = BSI->TheDecl;
2996   else if (const LambdaScopeInfo *LSI = getCurLambda())
2997     currentDecl = LSI->CallOperator;
2998   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2999     currentDecl = CSI->TheCapturedDecl;
3000   else
3001     currentDecl = getCurFunctionOrMethodDecl();
3002 
3003   if (!currentDecl) {
3004     Diag(Loc, diag::ext_predef_outside_function);
3005     currentDecl = Context.getTranslationUnitDecl();
3006   }
3007 
3008   QualType ResTy;
3009   StringLiteral *SL = nullptr;
3010   if (cast<DeclContext>(currentDecl)->isDependentContext())
3011     ResTy = Context.DependentTy;
3012   else {
3013     // Pre-defined identifiers are of type char[x], where x is the length of
3014     // the string.
3015     auto Str = PredefinedExpr::ComputeName(IT, currentDecl);
3016     unsigned Length = Str.length();
3017 
3018     llvm::APInt LengthI(32, Length + 1);
3019     if (IT == PredefinedExpr::LFunction) {
3020       ResTy = Context.WideCharTy.withConst();
3021       SmallString<32> RawChars;
3022       ConvertUTF8ToWideString(Context.getTypeSizeInChars(ResTy).getQuantity(),
3023                               Str, RawChars);
3024       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3025                                            /*IndexTypeQuals*/ 0);
3026       SL = StringLiteral::Create(Context, RawChars, StringLiteral::Wide,
3027                                  /*Pascal*/ false, ResTy, Loc);
3028     } else {
3029       ResTy = Context.CharTy.withConst();
3030       ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal,
3031                                            /*IndexTypeQuals*/ 0);
3032       SL = StringLiteral::Create(Context, Str, StringLiteral::Ascii,
3033                                  /*Pascal*/ false, ResTy, Loc);
3034     }
3035   }
3036 
3037   return new (Context) PredefinedExpr(Loc, ResTy, IT, SL);
3038 }
3039 
3040 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
3041   PredefinedExpr::IdentType IT;
3042 
3043   switch (Kind) {
3044   default: llvm_unreachable("Unknown simple primary expr!");
3045   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
3046   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
3047   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
3048   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
3049   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
3050   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
3051   }
3052 
3053   return BuildPredefinedExpr(Loc, IT);
3054 }
3055 
3056 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
3057   SmallString<16> CharBuffer;
3058   bool Invalid = false;
3059   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
3060   if (Invalid)
3061     return ExprError();
3062 
3063   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
3064                             PP, Tok.getKind());
3065   if (Literal.hadError())
3066     return ExprError();
3067 
3068   QualType Ty;
3069   if (Literal.isWide())
3070     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
3071   else if (Literal.isUTF16())
3072     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
3073   else if (Literal.isUTF32())
3074     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
3075   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
3076     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
3077   else
3078     Ty = Context.CharTy;  // 'x' -> char in C++
3079 
3080   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
3081   if (Literal.isWide())
3082     Kind = CharacterLiteral::Wide;
3083   else if (Literal.isUTF16())
3084     Kind = CharacterLiteral::UTF16;
3085   else if (Literal.isUTF32())
3086     Kind = CharacterLiteral::UTF32;
3087 
3088   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
3089                                              Tok.getLocation());
3090 
3091   if (Literal.getUDSuffix().empty())
3092     return Lit;
3093 
3094   // We're building a user-defined literal.
3095   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3096   SourceLocation UDSuffixLoc =
3097     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3098 
3099   // Make sure we're allowed user-defined literals here.
3100   if (!UDLScope)
3101     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
3102 
3103   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
3104   //   operator "" X (ch)
3105   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
3106                                         Lit, Tok.getLocation());
3107 }
3108 
3109 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
3110   unsigned IntSize = Context.getTargetInfo().getIntWidth();
3111   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
3112                                 Context.IntTy, Loc);
3113 }
3114 
3115 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
3116                                   QualType Ty, SourceLocation Loc) {
3117   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
3118 
3119   using llvm::APFloat;
3120   APFloat Val(Format);
3121 
3122   APFloat::opStatus result = Literal.GetFloatValue(Val);
3123 
3124   // Overflow is always an error, but underflow is only an error if
3125   // we underflowed to zero (APFloat reports denormals as underflow).
3126   if ((result & APFloat::opOverflow) ||
3127       ((result & APFloat::opUnderflow) && Val.isZero())) {
3128     unsigned diagnostic;
3129     SmallString<20> buffer;
3130     if (result & APFloat::opOverflow) {
3131       diagnostic = diag::warn_float_overflow;
3132       APFloat::getLargest(Format).toString(buffer);
3133     } else {
3134       diagnostic = diag::warn_float_underflow;
3135       APFloat::getSmallest(Format).toString(buffer);
3136     }
3137 
3138     S.Diag(Loc, diagnostic)
3139       << Ty
3140       << StringRef(buffer.data(), buffer.size());
3141   }
3142 
3143   bool isExact = (result == APFloat::opOK);
3144   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
3145 }
3146 
3147 bool Sema::CheckLoopHintExpr(Expr *E, SourceLocation Loc) {
3148   assert(E && "Invalid expression");
3149 
3150   if (E->isValueDependent())
3151     return false;
3152 
3153   QualType QT = E->getType();
3154   if (!QT->isIntegerType() || QT->isBooleanType() || QT->isCharType()) {
3155     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_type) << QT;
3156     return true;
3157   }
3158 
3159   llvm::APSInt ValueAPS;
3160   ExprResult R = VerifyIntegerConstantExpression(E, &ValueAPS);
3161 
3162   if (R.isInvalid())
3163     return true;
3164 
3165   bool ValueIsPositive = ValueAPS.isStrictlyPositive();
3166   if (!ValueIsPositive || ValueAPS.getActiveBits() > 31) {
3167     Diag(E->getExprLoc(), diag::err_pragma_loop_invalid_argument_value)
3168         << ValueAPS.toString(10) << ValueIsPositive;
3169     return true;
3170   }
3171 
3172   return false;
3173 }
3174 
3175 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
3176   // Fast path for a single digit (which is quite common).  A single digit
3177   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
3178   if (Tok.getLength() == 1) {
3179     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
3180     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
3181   }
3182 
3183   SmallString<128> SpellingBuffer;
3184   // NumericLiteralParser wants to overread by one character.  Add padding to
3185   // the buffer in case the token is copied to the buffer.  If getSpelling()
3186   // returns a StringRef to the memory buffer, it should have a null char at
3187   // the EOF, so it is also safe.
3188   SpellingBuffer.resize(Tok.getLength() + 1);
3189 
3190   // Get the spelling of the token, which eliminates trigraphs, etc.
3191   bool Invalid = false;
3192   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
3193   if (Invalid)
3194     return ExprError();
3195 
3196   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
3197   if (Literal.hadError)
3198     return ExprError();
3199 
3200   if (Literal.hasUDSuffix()) {
3201     // We're building a user-defined literal.
3202     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3203     SourceLocation UDSuffixLoc =
3204       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3205 
3206     // Make sure we're allowed user-defined literals here.
3207     if (!UDLScope)
3208       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3209 
3210     QualType CookedTy;
3211     if (Literal.isFloatingLiteral()) {
3212       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3213       // long double, the literal is treated as a call of the form
3214       //   operator "" X (f L)
3215       CookedTy = Context.LongDoubleTy;
3216     } else {
3217       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3218       // unsigned long long, the literal is treated as a call of the form
3219       //   operator "" X (n ULL)
3220       CookedTy = Context.UnsignedLongLongTy;
3221     }
3222 
3223     DeclarationName OpName =
3224       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3225     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3226     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3227 
3228     SourceLocation TokLoc = Tok.getLocation();
3229 
3230     // Perform literal operator lookup to determine if we're building a raw
3231     // literal or a cooked one.
3232     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3233     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3234                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3235                                   /*AllowStringTemplate*/false)) {
3236     case LOLR_Error:
3237       return ExprError();
3238 
3239     case LOLR_Cooked: {
3240       Expr *Lit;
3241       if (Literal.isFloatingLiteral()) {
3242         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3243       } else {
3244         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3245         if (Literal.GetIntegerValue(ResultVal))
3246           Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3247               << /* Unsigned */ 1;
3248         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3249                                      Tok.getLocation());
3250       }
3251       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3252     }
3253 
3254     case LOLR_Raw: {
3255       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3256       // literal is treated as a call of the form
3257       //   operator "" X ("n")
3258       unsigned Length = Literal.getUDSuffixOffset();
3259       QualType StrTy = Context.getConstantArrayType(
3260           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3261           ArrayType::Normal, 0);
3262       Expr *Lit = StringLiteral::Create(
3263           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3264           /*Pascal*/false, StrTy, &TokLoc, 1);
3265       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3266     }
3267 
3268     case LOLR_Template: {
3269       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3270       // template), L is treated as a call fo the form
3271       //   operator "" X <'c1', 'c2', ... 'ck'>()
3272       // where n is the source character sequence c1 c2 ... ck.
3273       TemplateArgumentListInfo ExplicitArgs;
3274       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3275       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3276       llvm::APSInt Value(CharBits, CharIsUnsigned);
3277       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3278         Value = TokSpelling[I];
3279         TemplateArgument Arg(Context, Value, Context.CharTy);
3280         TemplateArgumentLocInfo ArgInfo;
3281         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3282       }
3283       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3284                                       &ExplicitArgs);
3285     }
3286     case LOLR_StringTemplate:
3287       llvm_unreachable("unexpected literal operator lookup result");
3288     }
3289   }
3290 
3291   Expr *Res;
3292 
3293   if (Literal.isFloatingLiteral()) {
3294     QualType Ty;
3295     if (Literal.isFloat)
3296       Ty = Context.FloatTy;
3297     else if (!Literal.isLong)
3298       Ty = Context.DoubleTy;
3299     else
3300       Ty = Context.LongDoubleTy;
3301 
3302     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3303 
3304     if (Ty == Context.DoubleTy) {
3305       if (getLangOpts().SinglePrecisionConstants) {
3306         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3307       } else if (getLangOpts().OpenCL &&
3308                  !((getLangOpts().OpenCLVersion >= 120) ||
3309                    getOpenCLOptions().cl_khr_fp64)) {
3310         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3311         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3312       }
3313     }
3314   } else if (!Literal.isIntegerLiteral()) {
3315     return ExprError();
3316   } else {
3317     QualType Ty;
3318 
3319     // 'long long' is a C99 or C++11 feature.
3320     if (!getLangOpts().C99 && Literal.isLongLong) {
3321       if (getLangOpts().CPlusPlus)
3322         Diag(Tok.getLocation(),
3323              getLangOpts().CPlusPlus11 ?
3324              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3325       else
3326         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3327     }
3328 
3329     // Get the value in the widest-possible width.
3330     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3331     llvm::APInt ResultVal(MaxWidth, 0);
3332 
3333     if (Literal.GetIntegerValue(ResultVal)) {
3334       // If this value didn't fit into uintmax_t, error and force to ull.
3335       Diag(Tok.getLocation(), diag::err_integer_literal_too_large)
3336           << /* Unsigned */ 1;
3337       Ty = Context.UnsignedLongLongTy;
3338       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3339              "long long is not intmax_t?");
3340     } else {
3341       // If this value fits into a ULL, try to figure out what else it fits into
3342       // according to the rules of C99 6.4.4.1p5.
3343 
3344       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3345       // be an unsigned int.
3346       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3347 
3348       // Check from smallest to largest, picking the smallest type we can.
3349       unsigned Width = 0;
3350 
3351       // Microsoft specific integer suffixes are explicitly sized.
3352       if (Literal.MicrosoftInteger) {
3353         if (Literal.MicrosoftInteger == 8 && !Literal.isUnsigned) {
3354           Width = 8;
3355           Ty = Context.CharTy;
3356         } else {
3357           Width = Literal.MicrosoftInteger;
3358           Ty = Context.getIntTypeForBitwidth(Width,
3359                                              /*Signed=*/!Literal.isUnsigned);
3360         }
3361       }
3362 
3363       if (Ty.isNull() && !Literal.isLong && !Literal.isLongLong) {
3364         // Are int/unsigned possibilities?
3365         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3366 
3367         // Does it fit in a unsigned int?
3368         if (ResultVal.isIntN(IntSize)) {
3369           // Does it fit in a signed int?
3370           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3371             Ty = Context.IntTy;
3372           else if (AllowUnsigned)
3373             Ty = Context.UnsignedIntTy;
3374           Width = IntSize;
3375         }
3376       }
3377 
3378       // Are long/unsigned long possibilities?
3379       if (Ty.isNull() && !Literal.isLongLong) {
3380         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3381 
3382         // Does it fit in a unsigned long?
3383         if (ResultVal.isIntN(LongSize)) {
3384           // Does it fit in a signed long?
3385           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3386             Ty = Context.LongTy;
3387           else if (AllowUnsigned)
3388             Ty = Context.UnsignedLongTy;
3389           // Check according to the rules of C90 6.1.3.2p5. C++03 [lex.icon]p2
3390           // is compatible.
3391           else if (!getLangOpts().C99 && !getLangOpts().CPlusPlus11) {
3392             const unsigned LongLongSize =
3393                 Context.getTargetInfo().getLongLongWidth();
3394             Diag(Tok.getLocation(),
3395                  getLangOpts().CPlusPlus
3396                      ? Literal.isLong
3397                            ? diag::warn_old_implicitly_unsigned_long_cxx
3398                            : /*C++98 UB*/ diag::
3399                                  ext_old_implicitly_unsigned_long_cxx
3400                      : diag::warn_old_implicitly_unsigned_long)
3401                 << (LongLongSize > LongSize ? /*will have type 'long long'*/ 0
3402                                             : /*will be ill-formed*/ 1);
3403             Ty = Context.UnsignedLongTy;
3404           }
3405           Width = LongSize;
3406         }
3407       }
3408 
3409       // Check long long if needed.
3410       if (Ty.isNull()) {
3411         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3412 
3413         // Does it fit in a unsigned long long?
3414         if (ResultVal.isIntN(LongLongSize)) {
3415           // Does it fit in a signed long long?
3416           // To be compatible with MSVC, hex integer literals ending with the
3417           // LL or i64 suffix are always signed in Microsoft mode.
3418           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3419               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3420             Ty = Context.LongLongTy;
3421           else if (AllowUnsigned)
3422             Ty = Context.UnsignedLongLongTy;
3423           Width = LongLongSize;
3424         }
3425       }
3426 
3427       // If we still couldn't decide a type, we probably have something that
3428       // does not fit in a signed long long, but has no U suffix.
3429       if (Ty.isNull()) {
3430         Diag(Tok.getLocation(), diag::ext_integer_literal_too_large_for_signed);
3431         Ty = Context.UnsignedLongLongTy;
3432         Width = Context.getTargetInfo().getLongLongWidth();
3433       }
3434 
3435       if (ResultVal.getBitWidth() != Width)
3436         ResultVal = ResultVal.trunc(Width);
3437     }
3438     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3439   }
3440 
3441   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3442   if (Literal.isImaginary)
3443     Res = new (Context) ImaginaryLiteral(Res,
3444                                         Context.getComplexType(Res->getType()));
3445 
3446   return Res;
3447 }
3448 
3449 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3450   assert(E && "ActOnParenExpr() missing expr");
3451   return new (Context) ParenExpr(L, R, E);
3452 }
3453 
3454 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3455                                          SourceLocation Loc,
3456                                          SourceRange ArgRange) {
3457   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3458   // scalar or vector data type argument..."
3459   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3460   // type (C99 6.2.5p18) or void.
3461   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3462     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3463       << T << ArgRange;
3464     return true;
3465   }
3466 
3467   assert((T->isVoidType() || !T->isIncompleteType()) &&
3468          "Scalar types should always be complete");
3469   return false;
3470 }
3471 
3472 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3473                                            SourceLocation Loc,
3474                                            SourceRange ArgRange,
3475                                            UnaryExprOrTypeTrait TraitKind) {
3476   // Invalid types must be hard errors for SFINAE in C++.
3477   if (S.LangOpts.CPlusPlus)
3478     return true;
3479 
3480   // C99 6.5.3.4p1:
3481   if (T->isFunctionType() &&
3482       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3483     // sizeof(function)/alignof(function) is allowed as an extension.
3484     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3485       << TraitKind << ArgRange;
3486     return false;
3487   }
3488 
3489   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3490   // this is an error (OpenCL v1.1 s6.3.k)
3491   if (T->isVoidType()) {
3492     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3493                                         : diag::ext_sizeof_alignof_void_type;
3494     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3495     return false;
3496   }
3497 
3498   return true;
3499 }
3500 
3501 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3502                                              SourceLocation Loc,
3503                                              SourceRange ArgRange,
3504                                              UnaryExprOrTypeTrait TraitKind) {
3505   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3506   // runtime doesn't allow it.
3507   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3508     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3509       << T << (TraitKind == UETT_SizeOf)
3510       << ArgRange;
3511     return true;
3512   }
3513 
3514   return false;
3515 }
3516 
3517 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3518 /// pointer type is equal to T) and emit a warning if it is.
3519 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3520                                      Expr *E) {
3521   // Don't warn if the operation changed the type.
3522   if (T != E->getType())
3523     return;
3524 
3525   // Now look for array decays.
3526   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3527   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3528     return;
3529 
3530   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3531                                              << ICE->getType()
3532                                              << ICE->getSubExpr()->getType();
3533 }
3534 
3535 /// \brief Check the constraints on expression operands to unary type expression
3536 /// and type traits.
3537 ///
3538 /// Completes any types necessary and validates the constraints on the operand
3539 /// expression. The logic mostly mirrors the type-based overload, but may modify
3540 /// the expression as it completes the type for that expression through template
3541 /// instantiation, etc.
3542 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3543                                             UnaryExprOrTypeTrait ExprKind) {
3544   QualType ExprTy = E->getType();
3545   assert(!ExprTy->isReferenceType());
3546 
3547   if (ExprKind == UETT_VecStep)
3548     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3549                                         E->getSourceRange());
3550 
3551   // Whitelist some types as extensions
3552   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3553                                       E->getSourceRange(), ExprKind))
3554     return false;
3555 
3556   // 'alignof' applied to an expression only requires the base element type of
3557   // the expression to be complete. 'sizeof' requires the expression's type to
3558   // be complete (and will attempt to complete it if it's an array of unknown
3559   // bound).
3560   if (ExprKind == UETT_AlignOf) {
3561     if (RequireCompleteType(E->getExprLoc(),
3562                             Context.getBaseElementType(E->getType()),
3563                             diag::err_sizeof_alignof_incomplete_type, ExprKind,
3564                             E->getSourceRange()))
3565       return true;
3566   } else {
3567     if (RequireCompleteExprType(E, diag::err_sizeof_alignof_incomplete_type,
3568                                 ExprKind, E->getSourceRange()))
3569       return true;
3570   }
3571 
3572   // Completing the expression's type may have changed it.
3573   ExprTy = E->getType();
3574   assert(!ExprTy->isReferenceType());
3575 
3576   if (ExprTy->isFunctionType()) {
3577     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3578       << ExprKind << E->getSourceRange();
3579     return true;
3580   }
3581 
3582   // The operand for sizeof and alignof is in an unevaluated expression context,
3583   // so side effects could result in unintended consequences.
3584   if ((ExprKind == UETT_SizeOf || ExprKind == UETT_AlignOf) &&
3585       ActiveTemplateInstantiations.empty() && E->HasSideEffects(Context, false))
3586     Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
3587 
3588   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3589                                        E->getSourceRange(), ExprKind))
3590     return true;
3591 
3592   if (ExprKind == UETT_SizeOf) {
3593     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3594       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3595         QualType OType = PVD->getOriginalType();
3596         QualType Type = PVD->getType();
3597         if (Type->isPointerType() && OType->isArrayType()) {
3598           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3599             << Type << OType;
3600           Diag(PVD->getLocation(), diag::note_declared_at);
3601         }
3602       }
3603     }
3604 
3605     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3606     // decays into a pointer and returns an unintended result. This is most
3607     // likely a typo for "sizeof(array) op x".
3608     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3609       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3610                                BO->getLHS());
3611       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3612                                BO->getRHS());
3613     }
3614   }
3615 
3616   return false;
3617 }
3618 
3619 /// \brief Check the constraints on operands to unary expression and type
3620 /// traits.
3621 ///
3622 /// This will complete any types necessary, and validate the various constraints
3623 /// on those operands.
3624 ///
3625 /// The UsualUnaryConversions() function is *not* called by this routine.
3626 /// C99 6.3.2.1p[2-4] all state:
3627 ///   Except when it is the operand of the sizeof operator ...
3628 ///
3629 /// C++ [expr.sizeof]p4
3630 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3631 ///   standard conversions are not applied to the operand of sizeof.
3632 ///
3633 /// This policy is followed for all of the unary trait expressions.
3634 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3635                                             SourceLocation OpLoc,
3636                                             SourceRange ExprRange,
3637                                             UnaryExprOrTypeTrait ExprKind) {
3638   if (ExprType->isDependentType())
3639     return false;
3640 
3641   // C++ [expr.sizeof]p2:
3642   //     When applied to a reference or a reference type, the result
3643   //     is the size of the referenced type.
3644   // C++11 [expr.alignof]p3:
3645   //     When alignof is applied to a reference type, the result
3646   //     shall be the alignment of the referenced type.
3647   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3648     ExprType = Ref->getPointeeType();
3649 
3650   // C11 6.5.3.4/3, C++11 [expr.alignof]p3:
3651   //   When alignof or _Alignof is applied to an array type, the result
3652   //   is the alignment of the element type.
3653   if (ExprKind == UETT_AlignOf || ExprKind == UETT_OpenMPRequiredSimdAlign)
3654     ExprType = Context.getBaseElementType(ExprType);
3655 
3656   if (ExprKind == UETT_VecStep)
3657     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3658 
3659   // Whitelist some types as extensions
3660   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3661                                       ExprKind))
3662     return false;
3663 
3664   if (RequireCompleteType(OpLoc, ExprType,
3665                           diag::err_sizeof_alignof_incomplete_type,
3666                           ExprKind, ExprRange))
3667     return true;
3668 
3669   if (ExprType->isFunctionType()) {
3670     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3671       << ExprKind << ExprRange;
3672     return true;
3673   }
3674 
3675   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3676                                        ExprKind))
3677     return true;
3678 
3679   return false;
3680 }
3681 
3682 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3683   E = E->IgnoreParens();
3684 
3685   // Cannot know anything else if the expression is dependent.
3686   if (E->isTypeDependent())
3687     return false;
3688 
3689   if (E->getObjectKind() == OK_BitField) {
3690     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
3691        << 1 << E->getSourceRange();
3692     return true;
3693   }
3694 
3695   ValueDecl *D = nullptr;
3696   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3697     D = DRE->getDecl();
3698   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3699     D = ME->getMemberDecl();
3700   }
3701 
3702   // If it's a field, require the containing struct to have a
3703   // complete definition so that we can compute the layout.
3704   //
3705   // This can happen in C++11 onwards, either by naming the member
3706   // in a way that is not transformed into a member access expression
3707   // (in an unevaluated operand, for instance), or by naming the member
3708   // in a trailing-return-type.
3709   //
3710   // For the record, since __alignof__ on expressions is a GCC
3711   // extension, GCC seems to permit this but always gives the
3712   // nonsensical answer 0.
3713   //
3714   // We don't really need the layout here --- we could instead just
3715   // directly check for all the appropriate alignment-lowing
3716   // attributes --- but that would require duplicating a lot of
3717   // logic that just isn't worth duplicating for such a marginal
3718   // use-case.
3719   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3720     // Fast path this check, since we at least know the record has a
3721     // definition if we can find a member of it.
3722     if (!FD->getParent()->isCompleteDefinition()) {
3723       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3724         << E->getSourceRange();
3725       return true;
3726     }
3727 
3728     // Otherwise, if it's a field, and the field doesn't have
3729     // reference type, then it must have a complete type (or be a
3730     // flexible array member, which we explicitly want to
3731     // white-list anyway), which makes the following checks trivial.
3732     if (!FD->getType()->isReferenceType())
3733       return false;
3734   }
3735 
3736   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3737 }
3738 
3739 bool Sema::CheckVecStepExpr(Expr *E) {
3740   E = E->IgnoreParens();
3741 
3742   // Cannot know anything else if the expression is dependent.
3743   if (E->isTypeDependent())
3744     return false;
3745 
3746   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3747 }
3748 
3749 /// \brief Build a sizeof or alignof expression given a type operand.
3750 ExprResult
3751 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3752                                      SourceLocation OpLoc,
3753                                      UnaryExprOrTypeTrait ExprKind,
3754                                      SourceRange R) {
3755   if (!TInfo)
3756     return ExprError();
3757 
3758   QualType T = TInfo->getType();
3759 
3760   if (!T->isDependentType() &&
3761       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3762     return ExprError();
3763 
3764   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3765   return new (Context) UnaryExprOrTypeTraitExpr(
3766       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3767 }
3768 
3769 /// \brief Build a sizeof or alignof expression given an expression
3770 /// operand.
3771 ExprResult
3772 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3773                                      UnaryExprOrTypeTrait ExprKind) {
3774   ExprResult PE = CheckPlaceholderExpr(E);
3775   if (PE.isInvalid())
3776     return ExprError();
3777 
3778   E = PE.get();
3779 
3780   // Verify that the operand is valid.
3781   bool isInvalid = false;
3782   if (E->isTypeDependent()) {
3783     // Delay type-checking for type-dependent expressions.
3784   } else if (ExprKind == UETT_AlignOf) {
3785     isInvalid = CheckAlignOfExpr(*this, E);
3786   } else if (ExprKind == UETT_VecStep) {
3787     isInvalid = CheckVecStepExpr(E);
3788   } else if (ExprKind == UETT_OpenMPRequiredSimdAlign) {
3789       Diag(E->getExprLoc(), diag::err_openmp_default_simd_align_expr);
3790       isInvalid = true;
3791   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3792     Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 0;
3793     isInvalid = true;
3794   } else {
3795     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3796   }
3797 
3798   if (isInvalid)
3799     return ExprError();
3800 
3801   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3802     PE = TransformToPotentiallyEvaluated(E);
3803     if (PE.isInvalid()) return ExprError();
3804     E = PE.get();
3805   }
3806 
3807   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3808   return new (Context) UnaryExprOrTypeTraitExpr(
3809       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3810 }
3811 
3812 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3813 /// expr and the same for @c alignof and @c __alignof
3814 /// Note that the ArgRange is invalid if isType is false.
3815 ExprResult
3816 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3817                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3818                                     void *TyOrEx, SourceRange ArgRange) {
3819   // If error parsing type, ignore.
3820   if (!TyOrEx) return ExprError();
3821 
3822   if (IsType) {
3823     TypeSourceInfo *TInfo;
3824     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3825     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3826   }
3827 
3828   Expr *ArgEx = (Expr *)TyOrEx;
3829   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3830   return Result;
3831 }
3832 
3833 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3834                                      bool IsReal) {
3835   if (V.get()->isTypeDependent())
3836     return S.Context.DependentTy;
3837 
3838   // _Real and _Imag are only l-values for normal l-values.
3839   if (V.get()->getObjectKind() != OK_Ordinary) {
3840     V = S.DefaultLvalueConversion(V.get());
3841     if (V.isInvalid())
3842       return QualType();
3843   }
3844 
3845   // These operators return the element type of a complex type.
3846   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3847     return CT->getElementType();
3848 
3849   // Otherwise they pass through real integer and floating point types here.
3850   if (V.get()->getType()->isArithmeticType())
3851     return V.get()->getType();
3852 
3853   // Test for placeholders.
3854   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3855   if (PR.isInvalid()) return QualType();
3856   if (PR.get() != V.get()) {
3857     V = PR;
3858     return CheckRealImagOperand(S, V, Loc, IsReal);
3859   }
3860 
3861   // Reject anything else.
3862   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3863     << (IsReal ? "__real" : "__imag");
3864   return QualType();
3865 }
3866 
3867 
3868 
3869 ExprResult
3870 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3871                           tok::TokenKind Kind, Expr *Input) {
3872   UnaryOperatorKind Opc;
3873   switch (Kind) {
3874   default: llvm_unreachable("Unknown unary op!");
3875   case tok::plusplus:   Opc = UO_PostInc; break;
3876   case tok::minusminus: Opc = UO_PostDec; break;
3877   }
3878 
3879   // Since this might is a postfix expression, get rid of ParenListExprs.
3880   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3881   if (Result.isInvalid()) return ExprError();
3882   Input = Result.get();
3883 
3884   return BuildUnaryOp(S, OpLoc, Opc, Input);
3885 }
3886 
3887 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3888 ///
3889 /// \return true on error
3890 static bool checkArithmeticOnObjCPointer(Sema &S,
3891                                          SourceLocation opLoc,
3892                                          Expr *op) {
3893   assert(op->getType()->isObjCObjectPointerType());
3894   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3895       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3896     return false;
3897 
3898   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3899     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3900     << op->getSourceRange();
3901   return true;
3902 }
3903 
3904 ExprResult
3905 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3906                               Expr *idx, SourceLocation rbLoc) {
3907   if (base && !base->getType().isNull() &&
3908       base->getType()->isSpecificPlaceholderType(BuiltinType::OMPArraySection))
3909     return ActOnOMPArraySectionExpr(base, lbLoc, idx, SourceLocation(),
3910                                     /*Length=*/nullptr, rbLoc);
3911 
3912   // Since this might be a postfix expression, get rid of ParenListExprs.
3913   if (isa<ParenListExpr>(base)) {
3914     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3915     if (result.isInvalid()) return ExprError();
3916     base = result.get();
3917   }
3918 
3919   // Handle any non-overload placeholder types in the base and index
3920   // expressions.  We can't handle overloads here because the other
3921   // operand might be an overloadable type, in which case the overload
3922   // resolution for the operator overload should get the first crack
3923   // at the overload.
3924   if (base->getType()->isNonOverloadPlaceholderType()) {
3925     ExprResult result = CheckPlaceholderExpr(base);
3926     if (result.isInvalid()) return ExprError();
3927     base = result.get();
3928   }
3929   if (idx->getType()->isNonOverloadPlaceholderType()) {
3930     ExprResult result = CheckPlaceholderExpr(idx);
3931     if (result.isInvalid()) return ExprError();
3932     idx = result.get();
3933   }
3934 
3935   // Build an unanalyzed expression if either operand is type-dependent.
3936   if (getLangOpts().CPlusPlus &&
3937       (base->isTypeDependent() || idx->isTypeDependent())) {
3938     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3939                                             VK_LValue, OK_Ordinary, rbLoc);
3940   }
3941 
3942   // Use C++ overloaded-operator rules if either operand has record
3943   // type.  The spec says to do this if either type is *overloadable*,
3944   // but enum types can't declare subscript operators or conversion
3945   // operators, so there's nothing interesting for overload resolution
3946   // to do if there aren't any record types involved.
3947   //
3948   // ObjC pointers have their own subscripting logic that is not tied
3949   // to overload resolution and so should not take this path.
3950   if (getLangOpts().CPlusPlus &&
3951       (base->getType()->isRecordType() ||
3952        (!base->getType()->isObjCObjectPointerType() &&
3953         idx->getType()->isRecordType()))) {
3954     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3955   }
3956 
3957   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3958 }
3959 
3960 ExprResult Sema::ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc,
3961                                           Expr *LowerBound,
3962                                           SourceLocation ColonLoc, Expr *Length,
3963                                           SourceLocation RBLoc) {
3964   if (Base->getType()->isPlaceholderType() &&
3965       !Base->getType()->isSpecificPlaceholderType(
3966           BuiltinType::OMPArraySection)) {
3967     ExprResult Result = CheckPlaceholderExpr(Base);
3968     if (Result.isInvalid())
3969       return ExprError();
3970     Base = Result.get();
3971   }
3972   if (LowerBound && LowerBound->getType()->isNonOverloadPlaceholderType()) {
3973     ExprResult Result = CheckPlaceholderExpr(LowerBound);
3974     if (Result.isInvalid())
3975       return ExprError();
3976     LowerBound = Result.get();
3977   }
3978   if (Length && Length->getType()->isNonOverloadPlaceholderType()) {
3979     ExprResult Result = CheckPlaceholderExpr(Length);
3980     if (Result.isInvalid())
3981       return ExprError();
3982     Length = Result.get();
3983   }
3984 
3985   // Build an unanalyzed expression if either operand is type-dependent.
3986   if (Base->isTypeDependent() ||
3987       (LowerBound &&
3988        (LowerBound->isTypeDependent() || LowerBound->isValueDependent())) ||
3989       (Length && (Length->isTypeDependent() || Length->isValueDependent()))) {
3990     return new (Context)
3991         OMPArraySectionExpr(Base, LowerBound, Length, Context.DependentTy,
3992                             VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
3993   }
3994 
3995   // Perform default conversions.
3996   QualType OriginalTy = OMPArraySectionExpr::getBaseOriginalType(Base);
3997   QualType ResultTy;
3998   if (OriginalTy->isAnyPointerType()) {
3999     ResultTy = OriginalTy->getPointeeType();
4000   } else if (OriginalTy->isArrayType()) {
4001     ResultTy = OriginalTy->getAsArrayTypeUnsafe()->getElementType();
4002   } else {
4003     return ExprError(
4004         Diag(Base->getExprLoc(), diag::err_omp_typecheck_section_value)
4005         << Base->getSourceRange());
4006   }
4007   // C99 6.5.2.1p1
4008   if (LowerBound) {
4009     auto Res = PerformOpenMPImplicitIntegerConversion(LowerBound->getExprLoc(),
4010                                                       LowerBound);
4011     if (Res.isInvalid())
4012       return ExprError(Diag(LowerBound->getExprLoc(),
4013                             diag::err_omp_typecheck_section_not_integer)
4014                        << 0 << LowerBound->getSourceRange());
4015     LowerBound = Res.get();
4016 
4017     if (LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4018         LowerBound->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4019       Diag(LowerBound->getExprLoc(), diag::warn_omp_section_is_char)
4020           << 0 << LowerBound->getSourceRange();
4021   }
4022   if (Length) {
4023     auto Res =
4024         PerformOpenMPImplicitIntegerConversion(Length->getExprLoc(), Length);
4025     if (Res.isInvalid())
4026       return ExprError(Diag(Length->getExprLoc(),
4027                             diag::err_omp_typecheck_section_not_integer)
4028                        << 1 << Length->getSourceRange());
4029     Length = Res.get();
4030 
4031     if (Length->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4032         Length->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4033       Diag(Length->getExprLoc(), diag::warn_omp_section_is_char)
4034           << 1 << Length->getSourceRange();
4035   }
4036 
4037   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4038   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4039   // type. Note that functions are not objects, and that (in C99 parlance)
4040   // incomplete types are not object types.
4041   if (ResultTy->isFunctionType()) {
4042     Diag(Base->getExprLoc(), diag::err_omp_section_function_type)
4043         << ResultTy << Base->getSourceRange();
4044     return ExprError();
4045   }
4046 
4047   if (RequireCompleteType(Base->getExprLoc(), ResultTy,
4048                           diag::err_omp_section_incomplete_type, Base))
4049     return ExprError();
4050 
4051   if (LowerBound) {
4052     llvm::APSInt LowerBoundValue;
4053     if (LowerBound->EvaluateAsInt(LowerBoundValue, Context)) {
4054       // OpenMP 4.0, [2.4 Array Sections]
4055       // The lower-bound and length must evaluate to non-negative integers.
4056       if (LowerBoundValue.isNegative()) {
4057         Diag(LowerBound->getExprLoc(), diag::err_omp_section_negative)
4058             << 0 << LowerBoundValue.toString(/*Radix=*/10, /*Signed=*/true)
4059             << LowerBound->getSourceRange();
4060         return ExprError();
4061       }
4062     }
4063   }
4064 
4065   if (Length) {
4066     llvm::APSInt LengthValue;
4067     if (Length->EvaluateAsInt(LengthValue, Context)) {
4068       // OpenMP 4.0, [2.4 Array Sections]
4069       // The lower-bound and length must evaluate to non-negative integers.
4070       if (LengthValue.isNegative()) {
4071         Diag(Length->getExprLoc(), diag::err_omp_section_negative)
4072             << 1 << LengthValue.toString(/*Radix=*/10, /*Signed=*/true)
4073             << Length->getSourceRange();
4074         return ExprError();
4075       }
4076     }
4077   } else if (ColonLoc.isValid() &&
4078              (OriginalTy.isNull() || (!OriginalTy->isConstantArrayType() &&
4079                                       !OriginalTy->isVariableArrayType()))) {
4080     // OpenMP 4.0, [2.4 Array Sections]
4081     // When the size of the array dimension is not known, the length must be
4082     // specified explicitly.
4083     Diag(ColonLoc, diag::err_omp_section_length_undefined)
4084         << (!OriginalTy.isNull() && OriginalTy->isArrayType());
4085     return ExprError();
4086   }
4087 
4088   return new (Context)
4089       OMPArraySectionExpr(Base, LowerBound, Length, Context.OMPArraySectionTy,
4090                           VK_LValue, OK_Ordinary, ColonLoc, RBLoc);
4091 }
4092 
4093 ExprResult
4094 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
4095                                       Expr *Idx, SourceLocation RLoc) {
4096   Expr *LHSExp = Base;
4097   Expr *RHSExp = Idx;
4098 
4099   // Perform default conversions.
4100   if (!LHSExp->getType()->getAs<VectorType>()) {
4101     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
4102     if (Result.isInvalid())
4103       return ExprError();
4104     LHSExp = Result.get();
4105   }
4106   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
4107   if (Result.isInvalid())
4108     return ExprError();
4109   RHSExp = Result.get();
4110 
4111   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
4112   ExprValueKind VK = VK_LValue;
4113   ExprObjectKind OK = OK_Ordinary;
4114 
4115   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
4116   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
4117   // in the subscript position. As a result, we need to derive the array base
4118   // and index from the expression types.
4119   Expr *BaseExpr, *IndexExpr;
4120   QualType ResultType;
4121   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
4122     BaseExpr = LHSExp;
4123     IndexExpr = RHSExp;
4124     ResultType = Context.DependentTy;
4125   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
4126     BaseExpr = LHSExp;
4127     IndexExpr = RHSExp;
4128     ResultType = PTy->getPointeeType();
4129   } else if (const ObjCObjectPointerType *PTy =
4130                LHSTy->getAs<ObjCObjectPointerType>()) {
4131     BaseExpr = LHSExp;
4132     IndexExpr = RHSExp;
4133 
4134     // Use custom logic if this should be the pseudo-object subscript
4135     // expression.
4136     if (!LangOpts.isSubscriptPointerArithmetic())
4137       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
4138                                           nullptr);
4139 
4140     ResultType = PTy->getPointeeType();
4141   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
4142      // Handle the uncommon case of "123[Ptr]".
4143     BaseExpr = RHSExp;
4144     IndexExpr = LHSExp;
4145     ResultType = PTy->getPointeeType();
4146   } else if (const ObjCObjectPointerType *PTy =
4147                RHSTy->getAs<ObjCObjectPointerType>()) {
4148      // Handle the uncommon case of "123[Ptr]".
4149     BaseExpr = RHSExp;
4150     IndexExpr = LHSExp;
4151     ResultType = PTy->getPointeeType();
4152     if (!LangOpts.isSubscriptPointerArithmetic()) {
4153       Diag(LLoc, diag::err_subscript_nonfragile_interface)
4154         << ResultType << BaseExpr->getSourceRange();
4155       return ExprError();
4156     }
4157   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
4158     BaseExpr = LHSExp;    // vectors: V[123]
4159     IndexExpr = RHSExp;
4160     VK = LHSExp->getValueKind();
4161     if (VK != VK_RValue)
4162       OK = OK_VectorComponent;
4163 
4164     // FIXME: need to deal with const...
4165     ResultType = VTy->getElementType();
4166   } else if (LHSTy->isArrayType()) {
4167     // If we see an array that wasn't promoted by
4168     // DefaultFunctionArrayLvalueConversion, it must be an array that
4169     // wasn't promoted because of the C90 rule that doesn't
4170     // allow promoting non-lvalue arrays.  Warn, then
4171     // force the promotion here.
4172     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4173         LHSExp->getSourceRange();
4174     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
4175                                CK_ArrayToPointerDecay).get();
4176     LHSTy = LHSExp->getType();
4177 
4178     BaseExpr = LHSExp;
4179     IndexExpr = RHSExp;
4180     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
4181   } else if (RHSTy->isArrayType()) {
4182     // Same as previous, except for 123[f().a] case
4183     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
4184         RHSExp->getSourceRange();
4185     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
4186                                CK_ArrayToPointerDecay).get();
4187     RHSTy = RHSExp->getType();
4188 
4189     BaseExpr = RHSExp;
4190     IndexExpr = LHSExp;
4191     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
4192   } else {
4193     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
4194        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
4195   }
4196   // C99 6.5.2.1p1
4197   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
4198     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
4199                      << IndexExpr->getSourceRange());
4200 
4201   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
4202        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
4203          && !IndexExpr->isTypeDependent())
4204     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
4205 
4206   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
4207   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
4208   // type. Note that Functions are not objects, and that (in C99 parlance)
4209   // incomplete types are not object types.
4210   if (ResultType->isFunctionType()) {
4211     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
4212       << ResultType << BaseExpr->getSourceRange();
4213     return ExprError();
4214   }
4215 
4216   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
4217     // GNU extension: subscripting on pointer to void
4218     Diag(LLoc, diag::ext_gnu_subscript_void_type)
4219       << BaseExpr->getSourceRange();
4220 
4221     // C forbids expressions of unqualified void type from being l-values.
4222     // See IsCForbiddenLValueType.
4223     if (!ResultType.hasQualifiers()) VK = VK_RValue;
4224   } else if (!ResultType->isDependentType() &&
4225       RequireCompleteType(LLoc, ResultType,
4226                           diag::err_subscript_incomplete_type, BaseExpr))
4227     return ExprError();
4228 
4229   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
4230          !ResultType.isCForbiddenLValueType());
4231 
4232   return new (Context)
4233       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
4234 }
4235 
4236 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
4237                                         FunctionDecl *FD,
4238                                         ParmVarDecl *Param) {
4239   if (Param->hasUnparsedDefaultArg()) {
4240     Diag(CallLoc,
4241          diag::err_use_of_default_argument_to_function_declared_later) <<
4242       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
4243     Diag(UnparsedDefaultArgLocs[Param],
4244          diag::note_default_argument_declared_here);
4245     return ExprError();
4246   }
4247 
4248   if (Param->hasUninstantiatedDefaultArg()) {
4249     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
4250 
4251     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
4252                                                  Param);
4253 
4254     // Instantiate the expression.
4255     MultiLevelTemplateArgumentList MutiLevelArgList
4256       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
4257 
4258     InstantiatingTemplate Inst(*this, CallLoc, Param,
4259                                MutiLevelArgList.getInnermost());
4260     if (Inst.isInvalid())
4261       return ExprError();
4262 
4263     ExprResult Result;
4264     {
4265       // C++ [dcl.fct.default]p5:
4266       //   The names in the [default argument] expression are bound, and
4267       //   the semantic constraints are checked, at the point where the
4268       //   default argument expression appears.
4269       ContextRAII SavedContext(*this, FD);
4270       LocalInstantiationScope Local(*this);
4271       Result = SubstExpr(UninstExpr, MutiLevelArgList);
4272     }
4273     if (Result.isInvalid())
4274       return ExprError();
4275 
4276     // Check the expression as an initializer for the parameter.
4277     InitializedEntity Entity
4278       = InitializedEntity::InitializeParameter(Context, Param);
4279     InitializationKind Kind
4280       = InitializationKind::CreateCopy(Param->getLocation(),
4281              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
4282     Expr *ResultE = Result.getAs<Expr>();
4283 
4284     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
4285     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
4286     if (Result.isInvalid())
4287       return ExprError();
4288 
4289     Expr *Arg = Result.getAs<Expr>();
4290     CheckCompletedExpr(Arg, Param->getOuterLocStart());
4291     // Build the default argument expression.
4292     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
4293   }
4294 
4295   // If the default expression creates temporaries, we need to
4296   // push them to the current stack of expression temporaries so they'll
4297   // be properly destroyed.
4298   // FIXME: We should really be rebuilding the default argument with new
4299   // bound temporaries; see the comment in PR5810.
4300   // We don't need to do that with block decls, though, because
4301   // blocks in default argument expression can never capture anything.
4302   if (isa<ExprWithCleanups>(Param->getInit())) {
4303     // Set the "needs cleanups" bit regardless of whether there are
4304     // any explicit objects.
4305     ExprNeedsCleanups = true;
4306 
4307     // Append all the objects to the cleanup list.  Right now, this
4308     // should always be a no-op, because blocks in default argument
4309     // expressions should never be able to capture anything.
4310     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
4311            "default argument expression has capturing blocks?");
4312   }
4313 
4314   // We already type-checked the argument, so we know it works.
4315   // Just mark all of the declarations in this potentially-evaluated expression
4316   // as being "referenced".
4317   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
4318                                    /*SkipLocalVariables=*/true);
4319   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
4320 }
4321 
4322 
4323 Sema::VariadicCallType
4324 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
4325                           Expr *Fn) {
4326   if (Proto && Proto->isVariadic()) {
4327     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
4328       return VariadicConstructor;
4329     else if (Fn && Fn->getType()->isBlockPointerType())
4330       return VariadicBlock;
4331     else if (FDecl) {
4332       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4333         if (Method->isInstance())
4334           return VariadicMethod;
4335     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
4336       return VariadicMethod;
4337     return VariadicFunction;
4338   }
4339   return VariadicDoesNotApply;
4340 }
4341 
4342 namespace {
4343 class FunctionCallCCC : public FunctionCallFilterCCC {
4344 public:
4345   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
4346                   unsigned NumArgs, MemberExpr *ME)
4347       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
4348         FunctionName(FuncName) {}
4349 
4350   bool ValidateCandidate(const TypoCorrection &candidate) override {
4351     if (!candidate.getCorrectionSpecifier() ||
4352         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
4353       return false;
4354     }
4355 
4356     return FunctionCallFilterCCC::ValidateCandidate(candidate);
4357   }
4358 
4359 private:
4360   const IdentifierInfo *const FunctionName;
4361 };
4362 }
4363 
4364 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
4365                                                FunctionDecl *FDecl,
4366                                                ArrayRef<Expr *> Args) {
4367   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4368   DeclarationName FuncName = FDecl->getDeclName();
4369   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4370 
4371   if (TypoCorrection Corrected = S.CorrectTypo(
4372           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4373           S.getScopeForContext(S.CurContext), nullptr,
4374           llvm::make_unique<FunctionCallCCC>(S, FuncName.getAsIdentifierInfo(),
4375                                              Args.size(), ME),
4376           Sema::CTK_ErrorRecovery)) {
4377     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4378       if (Corrected.isOverloaded()) {
4379         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4380         OverloadCandidateSet::iterator Best;
4381         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4382                                            CDEnd = Corrected.end();
4383              CD != CDEnd; ++CD) {
4384           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4385             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4386                                    OCS);
4387         }
4388         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4389         case OR_Success:
4390           ND = Best->Function;
4391           Corrected.setCorrectionDecl(ND);
4392           break;
4393         default:
4394           break;
4395         }
4396       }
4397       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4398         return Corrected;
4399       }
4400     }
4401   }
4402   return TypoCorrection();
4403 }
4404 
4405 /// ConvertArgumentsForCall - Converts the arguments specified in
4406 /// Args/NumArgs to the parameter types of the function FDecl with
4407 /// function prototype Proto. Call is the call expression itself, and
4408 /// Fn is the function expression. For a C++ member function, this
4409 /// routine does not attempt to convert the object argument. Returns
4410 /// true if the call is ill-formed.
4411 bool
4412 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4413                               FunctionDecl *FDecl,
4414                               const FunctionProtoType *Proto,
4415                               ArrayRef<Expr *> Args,
4416                               SourceLocation RParenLoc,
4417                               bool IsExecConfig) {
4418   // Bail out early if calling a builtin with custom typechecking.
4419   if (FDecl)
4420     if (unsigned ID = FDecl->getBuiltinID())
4421       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4422         return false;
4423 
4424   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4425   // assignment, to the types of the corresponding parameter, ...
4426   unsigned NumParams = Proto->getNumParams();
4427   bool Invalid = false;
4428   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4429   unsigned FnKind = Fn->getType()->isBlockPointerType()
4430                        ? 1 /* block */
4431                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4432                                        : 0 /* function */);
4433 
4434   // If too few arguments are available (and we don't have default
4435   // arguments for the remaining parameters), don't make the call.
4436   if (Args.size() < NumParams) {
4437     if (Args.size() < MinArgs) {
4438       TypoCorrection TC;
4439       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4440         unsigned diag_id =
4441             MinArgs == NumParams && !Proto->isVariadic()
4442                 ? diag::err_typecheck_call_too_few_args_suggest
4443                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4444         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4445                                         << static_cast<unsigned>(Args.size())
4446                                         << TC.getCorrectionRange());
4447       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4448         Diag(RParenLoc,
4449              MinArgs == NumParams && !Proto->isVariadic()
4450                  ? diag::err_typecheck_call_too_few_args_one
4451                  : diag::err_typecheck_call_too_few_args_at_least_one)
4452             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4453       else
4454         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4455                             ? diag::err_typecheck_call_too_few_args
4456                             : diag::err_typecheck_call_too_few_args_at_least)
4457             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4458             << Fn->getSourceRange();
4459 
4460       // Emit the location of the prototype.
4461       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4462         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4463           << FDecl;
4464 
4465       return true;
4466     }
4467     Call->setNumArgs(Context, NumParams);
4468   }
4469 
4470   // If too many are passed and not variadic, error on the extras and drop
4471   // them.
4472   if (Args.size() > NumParams) {
4473     if (!Proto->isVariadic()) {
4474       TypoCorrection TC;
4475       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4476         unsigned diag_id =
4477             MinArgs == NumParams && !Proto->isVariadic()
4478                 ? diag::err_typecheck_call_too_many_args_suggest
4479                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4480         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4481                                         << static_cast<unsigned>(Args.size())
4482                                         << TC.getCorrectionRange());
4483       } else if (NumParams == 1 && FDecl &&
4484                  FDecl->getParamDecl(0)->getDeclName())
4485         Diag(Args[NumParams]->getLocStart(),
4486              MinArgs == NumParams
4487                  ? diag::err_typecheck_call_too_many_args_one
4488                  : diag::err_typecheck_call_too_many_args_at_most_one)
4489             << FnKind << FDecl->getParamDecl(0)
4490             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4491             << SourceRange(Args[NumParams]->getLocStart(),
4492                            Args.back()->getLocEnd());
4493       else
4494         Diag(Args[NumParams]->getLocStart(),
4495              MinArgs == NumParams
4496                  ? diag::err_typecheck_call_too_many_args
4497                  : diag::err_typecheck_call_too_many_args_at_most)
4498             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4499             << Fn->getSourceRange()
4500             << SourceRange(Args[NumParams]->getLocStart(),
4501                            Args.back()->getLocEnd());
4502 
4503       // Emit the location of the prototype.
4504       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4505         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4506           << FDecl;
4507 
4508       // This deletes the extra arguments.
4509       Call->setNumArgs(Context, NumParams);
4510       return true;
4511     }
4512   }
4513   SmallVector<Expr *, 8> AllArgs;
4514   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4515 
4516   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4517                                    Proto, 0, Args, AllArgs, CallType);
4518   if (Invalid)
4519     return true;
4520   unsigned TotalNumArgs = AllArgs.size();
4521   for (unsigned i = 0; i < TotalNumArgs; ++i)
4522     Call->setArg(i, AllArgs[i]);
4523 
4524   return false;
4525 }
4526 
4527 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4528                                   const FunctionProtoType *Proto,
4529                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4530                                   SmallVectorImpl<Expr *> &AllArgs,
4531                                   VariadicCallType CallType, bool AllowExplicit,
4532                                   bool IsListInitialization) {
4533   unsigned NumParams = Proto->getNumParams();
4534   bool Invalid = false;
4535   unsigned ArgIx = 0;
4536   // Continue to check argument types (even if we have too few/many args).
4537   for (unsigned i = FirstParam; i < NumParams; i++) {
4538     QualType ProtoArgType = Proto->getParamType(i);
4539 
4540     Expr *Arg;
4541     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4542     if (ArgIx < Args.size()) {
4543       Arg = Args[ArgIx++];
4544 
4545       if (RequireCompleteType(Arg->getLocStart(),
4546                               ProtoArgType,
4547                               diag::err_call_incomplete_argument, Arg))
4548         return true;
4549 
4550       // Strip the unbridged-cast placeholder expression off, if applicable.
4551       bool CFAudited = false;
4552       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4553           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4554           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4555         Arg = stripARCUnbridgedCast(Arg);
4556       else if (getLangOpts().ObjCAutoRefCount &&
4557                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4558                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4559         CFAudited = true;
4560 
4561       InitializedEntity Entity =
4562           Param ? InitializedEntity::InitializeParameter(Context, Param,
4563                                                          ProtoArgType)
4564                 : InitializedEntity::InitializeParameter(
4565                       Context, ProtoArgType, Proto->isParamConsumed(i));
4566 
4567       // Remember that parameter belongs to a CF audited API.
4568       if (CFAudited)
4569         Entity.setParameterCFAudited();
4570 
4571       ExprResult ArgE = PerformCopyInitialization(
4572           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4573       if (ArgE.isInvalid())
4574         return true;
4575 
4576       Arg = ArgE.getAs<Expr>();
4577     } else {
4578       assert(Param && "can't use default arguments without a known callee");
4579 
4580       ExprResult ArgExpr =
4581         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4582       if (ArgExpr.isInvalid())
4583         return true;
4584 
4585       Arg = ArgExpr.getAs<Expr>();
4586     }
4587 
4588     // Check for array bounds violations for each argument to the call. This
4589     // check only triggers warnings when the argument isn't a more complex Expr
4590     // with its own checking, such as a BinaryOperator.
4591     CheckArrayAccess(Arg);
4592 
4593     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4594     CheckStaticArrayArgument(CallLoc, Param, Arg);
4595 
4596     AllArgs.push_back(Arg);
4597   }
4598 
4599   // If this is a variadic call, handle args passed through "...".
4600   if (CallType != VariadicDoesNotApply) {
4601     // Assume that extern "C" functions with variadic arguments that
4602     // return __unknown_anytype aren't *really* variadic.
4603     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4604         FDecl->isExternC()) {
4605       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4606         QualType paramType; // ignored
4607         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4608         Invalid |= arg.isInvalid();
4609         AllArgs.push_back(arg.get());
4610       }
4611 
4612     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4613     } else {
4614       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4615         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4616                                                           FDecl);
4617         Invalid |= Arg.isInvalid();
4618         AllArgs.push_back(Arg.get());
4619       }
4620     }
4621 
4622     // Check for array bounds violations.
4623     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4624       CheckArrayAccess(Args[i]);
4625   }
4626   return Invalid;
4627 }
4628 
4629 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4630   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4631   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4632     TL = DTL.getOriginalLoc();
4633   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4634     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4635       << ATL.getLocalSourceRange();
4636 }
4637 
4638 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4639 /// array parameter, check that it is non-null, and that if it is formed by
4640 /// array-to-pointer decay, the underlying array is sufficiently large.
4641 ///
4642 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4643 /// array type derivation, then for each call to the function, the value of the
4644 /// corresponding actual argument shall provide access to the first element of
4645 /// an array with at least as many elements as specified by the size expression.
4646 void
4647 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4648                                ParmVarDecl *Param,
4649                                const Expr *ArgExpr) {
4650   // Static array parameters are not supported in C++.
4651   if (!Param || getLangOpts().CPlusPlus)
4652     return;
4653 
4654   QualType OrigTy = Param->getOriginalType();
4655 
4656   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4657   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4658     return;
4659 
4660   if (ArgExpr->isNullPointerConstant(Context,
4661                                      Expr::NPC_NeverValueDependent)) {
4662     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4663     DiagnoseCalleeStaticArrayParam(*this, Param);
4664     return;
4665   }
4666 
4667   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4668   if (!CAT)
4669     return;
4670 
4671   const ConstantArrayType *ArgCAT =
4672     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4673   if (!ArgCAT)
4674     return;
4675 
4676   if (ArgCAT->getSize().ult(CAT->getSize())) {
4677     Diag(CallLoc, diag::warn_static_array_too_small)
4678       << ArgExpr->getSourceRange()
4679       << (unsigned) ArgCAT->getSize().getZExtValue()
4680       << (unsigned) CAT->getSize().getZExtValue();
4681     DiagnoseCalleeStaticArrayParam(*this, Param);
4682   }
4683 }
4684 
4685 /// Given a function expression of unknown-any type, try to rebuild it
4686 /// to have a function type.
4687 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4688 
4689 /// Is the given type a placeholder that we need to lower out
4690 /// immediately during argument processing?
4691 static bool isPlaceholderToRemoveAsArg(QualType type) {
4692   // Placeholders are never sugared.
4693   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4694   if (!placeholder) return false;
4695 
4696   switch (placeholder->getKind()) {
4697   // Ignore all the non-placeholder types.
4698 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4699 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4700 #include "clang/AST/BuiltinTypes.def"
4701     return false;
4702 
4703   // We cannot lower out overload sets; they might validly be resolved
4704   // by the call machinery.
4705   case BuiltinType::Overload:
4706     return false;
4707 
4708   // Unbridged casts in ARC can be handled in some call positions and
4709   // should be left in place.
4710   case BuiltinType::ARCUnbridgedCast:
4711     return false;
4712 
4713   // Pseudo-objects should be converted as soon as possible.
4714   case BuiltinType::PseudoObject:
4715     return true;
4716 
4717   // The debugger mode could theoretically but currently does not try
4718   // to resolve unknown-typed arguments based on known parameter types.
4719   case BuiltinType::UnknownAny:
4720     return true;
4721 
4722   // These are always invalid as call arguments and should be reported.
4723   case BuiltinType::BoundMember:
4724   case BuiltinType::BuiltinFn:
4725   case BuiltinType::OMPArraySection:
4726     return true;
4727 
4728   }
4729   llvm_unreachable("bad builtin type kind");
4730 }
4731 
4732 /// Check an argument list for placeholders that we won't try to
4733 /// handle later.
4734 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4735   // Apply this processing to all the arguments at once instead of
4736   // dying at the first failure.
4737   bool hasInvalid = false;
4738   for (size_t i = 0, e = args.size(); i != e; i++) {
4739     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4740       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4741       if (result.isInvalid()) hasInvalid = true;
4742       else args[i] = result.get();
4743     } else if (hasInvalid) {
4744       (void)S.CorrectDelayedTyposInExpr(args[i]);
4745     }
4746   }
4747   return hasInvalid;
4748 }
4749 
4750 /// If a builtin function has a pointer argument with no explicit address
4751 /// space, than it should be able to accept a pointer to any address
4752 /// space as input.  In order to do this, we need to replace the
4753 /// standard builtin declaration with one that uses the same address space
4754 /// as the call.
4755 ///
4756 /// \returns nullptr If this builtin is not a candidate for a rewrite i.e.
4757 ///                  it does not contain any pointer arguments without
4758 ///                  an address space qualifer.  Otherwise the rewritten
4759 ///                  FunctionDecl is returned.
4760 /// TODO: Handle pointer return types.
4761 static FunctionDecl *rewriteBuiltinFunctionDecl(Sema *Sema, ASTContext &Context,
4762                                                 const FunctionDecl *FDecl,
4763                                                 MultiExprArg ArgExprs) {
4764 
4765   QualType DeclType = FDecl->getType();
4766   const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(DeclType);
4767 
4768   if (!Context.BuiltinInfo.hasPtrArgsOrResult(FDecl->getBuiltinID()) ||
4769       !FT || FT->isVariadic() || ArgExprs.size() != FT->getNumParams())
4770     return nullptr;
4771 
4772   bool NeedsNewDecl = false;
4773   unsigned i = 0;
4774   SmallVector<QualType, 8> OverloadParams;
4775 
4776   for (QualType ParamType : FT->param_types()) {
4777 
4778     // Convert array arguments to pointer to simplify type lookup.
4779     Expr *Arg = Sema->DefaultFunctionArrayLvalueConversion(ArgExprs[i++]).get();
4780     QualType ArgType = Arg->getType();
4781     if (!ParamType->isPointerType() ||
4782         ParamType.getQualifiers().hasAddressSpace() ||
4783         !ArgType->isPointerType() ||
4784         !ArgType->getPointeeType().getQualifiers().hasAddressSpace()) {
4785       OverloadParams.push_back(ParamType);
4786       continue;
4787     }
4788 
4789     NeedsNewDecl = true;
4790     unsigned AS = ArgType->getPointeeType().getQualifiers().getAddressSpace();
4791 
4792     QualType PointeeType = ParamType->getPointeeType();
4793     PointeeType = Context.getAddrSpaceQualType(PointeeType, AS);
4794     OverloadParams.push_back(Context.getPointerType(PointeeType));
4795   }
4796 
4797   if (!NeedsNewDecl)
4798     return nullptr;
4799 
4800   FunctionProtoType::ExtProtoInfo EPI;
4801   QualType OverloadTy = Context.getFunctionType(FT->getReturnType(),
4802                                                 OverloadParams, EPI);
4803   DeclContext *Parent = Context.getTranslationUnitDecl();
4804   FunctionDecl *OverloadDecl = FunctionDecl::Create(Context, Parent,
4805                                                     FDecl->getLocation(),
4806                                                     FDecl->getLocation(),
4807                                                     FDecl->getIdentifier(),
4808                                                     OverloadTy,
4809                                                     /*TInfo=*/nullptr,
4810                                                     SC_Extern, false,
4811                                                     /*hasPrototype=*/true);
4812   SmallVector<ParmVarDecl*, 16> Params;
4813   FT = cast<FunctionProtoType>(OverloadTy);
4814   for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
4815     QualType ParamType = FT->getParamType(i);
4816     ParmVarDecl *Parm =
4817         ParmVarDecl::Create(Context, OverloadDecl, SourceLocation(),
4818                                 SourceLocation(), nullptr, ParamType,
4819                                 /*TInfo=*/nullptr, SC_None, nullptr);
4820     Parm->setScopeInfo(0, i);
4821     Params.push_back(Parm);
4822   }
4823   OverloadDecl->setParams(Params);
4824   return OverloadDecl;
4825 }
4826 
4827 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4828 /// This provides the location of the left/right parens and a list of comma
4829 /// locations.
4830 ExprResult
4831 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4832                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4833                     Expr *ExecConfig, bool IsExecConfig) {
4834   // Since this might be a postfix expression, get rid of ParenListExprs.
4835   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4836   if (Result.isInvalid()) return ExprError();
4837   Fn = Result.get();
4838 
4839   if (checkArgsForPlaceholders(*this, ArgExprs))
4840     return ExprError();
4841 
4842   if (getLangOpts().CPlusPlus) {
4843     // If this is a pseudo-destructor expression, build the call immediately.
4844     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4845       if (!ArgExprs.empty()) {
4846         // Pseudo-destructor calls should not have any arguments.
4847         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4848           << FixItHint::CreateRemoval(
4849                                     SourceRange(ArgExprs.front()->getLocStart(),
4850                                                 ArgExprs.back()->getLocEnd()));
4851       }
4852 
4853       return new (Context)
4854           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4855     }
4856     if (Fn->getType() == Context.PseudoObjectTy) {
4857       ExprResult result = CheckPlaceholderExpr(Fn);
4858       if (result.isInvalid()) return ExprError();
4859       Fn = result.get();
4860     }
4861 
4862     // Determine whether this is a dependent call inside a C++ template,
4863     // in which case we won't do any semantic analysis now.
4864     // FIXME: Will need to cache the results of name lookup (including ADL) in
4865     // Fn.
4866     bool Dependent = false;
4867     if (Fn->isTypeDependent())
4868       Dependent = true;
4869     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4870       Dependent = true;
4871 
4872     if (Dependent) {
4873       if (ExecConfig) {
4874         return new (Context) CUDAKernelCallExpr(
4875             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4876             Context.DependentTy, VK_RValue, RParenLoc);
4877       } else {
4878         return new (Context) CallExpr(
4879             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4880       }
4881     }
4882 
4883     // Determine whether this is a call to an object (C++ [over.call.object]).
4884     if (Fn->getType()->isRecordType())
4885       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4886                                           RParenLoc);
4887 
4888     if (Fn->getType() == Context.UnknownAnyTy) {
4889       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4890       if (result.isInvalid()) return ExprError();
4891       Fn = result.get();
4892     }
4893 
4894     if (Fn->getType() == Context.BoundMemberTy) {
4895       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4896     }
4897   }
4898 
4899   // Check for overloaded calls.  This can happen even in C due to extensions.
4900   if (Fn->getType() == Context.OverloadTy) {
4901     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4902 
4903     // We aren't supposed to apply this logic for if there's an '&' involved.
4904     if (!find.HasFormOfMemberPointer) {
4905       OverloadExpr *ovl = find.Expression;
4906       if (isa<UnresolvedLookupExpr>(ovl)) {
4907         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4908         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4909                                        RParenLoc, ExecConfig);
4910       } else {
4911         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4912                                          RParenLoc);
4913       }
4914     }
4915   }
4916 
4917   // If we're directly calling a function, get the appropriate declaration.
4918   if (Fn->getType() == Context.UnknownAnyTy) {
4919     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4920     if (result.isInvalid()) return ExprError();
4921     Fn = result.get();
4922   }
4923 
4924   Expr *NakedFn = Fn->IgnoreParens();
4925 
4926   NamedDecl *NDecl = nullptr;
4927   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4928     if (UnOp->getOpcode() == UO_AddrOf)
4929       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4930 
4931   if (isa<DeclRefExpr>(NakedFn)) {
4932     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4933 
4934     FunctionDecl *FDecl = dyn_cast<FunctionDecl>(NDecl);
4935     if (FDecl && FDecl->getBuiltinID()) {
4936       // Rewrite the function decl for this builtin by replacing paramaters
4937       // with no explicit address space with the address space of the arguments
4938       // in ArgExprs.
4939       if ((FDecl = rewriteBuiltinFunctionDecl(this, Context, FDecl, ArgExprs))) {
4940         NDecl = FDecl;
4941         Fn = DeclRefExpr::Create(Context, FDecl->getQualifierLoc(),
4942                            SourceLocation(), FDecl, false,
4943                            SourceLocation(), FDecl->getType(),
4944                            Fn->getValueKind(), FDecl);
4945       }
4946     }
4947   } else if (isa<MemberExpr>(NakedFn))
4948     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4949 
4950   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4951     if (FD->hasAttr<EnableIfAttr>()) {
4952       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4953         Diag(Fn->getLocStart(),
4954              isa<CXXMethodDecl>(FD) ?
4955                  diag::err_ovl_no_viable_member_function_in_call :
4956                  diag::err_ovl_no_viable_function_in_call)
4957           << FD << FD->getSourceRange();
4958         Diag(FD->getLocation(),
4959              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4960             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4961       }
4962     }
4963   }
4964 
4965   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4966                                ExecConfig, IsExecConfig);
4967 }
4968 
4969 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4970 ///
4971 /// __builtin_astype( value, dst type )
4972 ///
4973 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4974                                  SourceLocation BuiltinLoc,
4975                                  SourceLocation RParenLoc) {
4976   ExprValueKind VK = VK_RValue;
4977   ExprObjectKind OK = OK_Ordinary;
4978   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4979   QualType SrcTy = E->getType();
4980   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4981     return ExprError(Diag(BuiltinLoc,
4982                           diag::err_invalid_astype_of_different_size)
4983                      << DstTy
4984                      << SrcTy
4985                      << E->getSourceRange());
4986   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4987 }
4988 
4989 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4990 /// provided arguments.
4991 ///
4992 /// __builtin_convertvector( value, dst type )
4993 ///
4994 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4995                                         SourceLocation BuiltinLoc,
4996                                         SourceLocation RParenLoc) {
4997   TypeSourceInfo *TInfo;
4998   GetTypeFromParser(ParsedDestTy, &TInfo);
4999   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
5000 }
5001 
5002 /// BuildResolvedCallExpr - Build a call to a resolved expression,
5003 /// i.e. an expression not of \p OverloadTy.  The expression should
5004 /// unary-convert to an expression of function-pointer or
5005 /// block-pointer type.
5006 ///
5007 /// \param NDecl the declaration being called, if available
5008 ExprResult
5009 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
5010                             SourceLocation LParenLoc,
5011                             ArrayRef<Expr *> Args,
5012                             SourceLocation RParenLoc,
5013                             Expr *Config, bool IsExecConfig) {
5014   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
5015   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
5016 
5017   // Promote the function operand.
5018   // We special-case function promotion here because we only allow promoting
5019   // builtin functions to function pointers in the callee of a call.
5020   ExprResult Result;
5021   if (BuiltinID &&
5022       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
5023     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
5024                                CK_BuiltinFnToFnPtr).get();
5025   } else {
5026     Result = CallExprUnaryConversions(Fn);
5027   }
5028   if (Result.isInvalid())
5029     return ExprError();
5030   Fn = Result.get();
5031 
5032   // Make the call expr early, before semantic checks.  This guarantees cleanup
5033   // of arguments and function on error.
5034   CallExpr *TheCall;
5035   if (Config)
5036     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
5037                                                cast<CallExpr>(Config), Args,
5038                                                Context.BoolTy, VK_RValue,
5039                                                RParenLoc);
5040   else
5041     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
5042                                      VK_RValue, RParenLoc);
5043 
5044   if (!getLangOpts().CPlusPlus) {
5045     // C cannot always handle TypoExpr nodes in builtin calls and direct
5046     // function calls as their argument checking don't necessarily handle
5047     // dependent types properly, so make sure any TypoExprs have been
5048     // dealt with.
5049     ExprResult Result = CorrectDelayedTyposInExpr(TheCall);
5050     if (!Result.isUsable()) return ExprError();
5051     TheCall = dyn_cast<CallExpr>(Result.get());
5052     if (!TheCall) return Result;
5053     Args = llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs());
5054   }
5055 
5056   // Bail out early if calling a builtin with custom typechecking.
5057   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
5058     return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5059 
5060  retry:
5061   const FunctionType *FuncT;
5062   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
5063     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
5064     // have type pointer to function".
5065     FuncT = PT->getPointeeType()->getAs<FunctionType>();
5066     if (!FuncT)
5067       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5068                          << Fn->getType() << Fn->getSourceRange());
5069   } else if (const BlockPointerType *BPT =
5070                Fn->getType()->getAs<BlockPointerType>()) {
5071     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
5072   } else {
5073     // Handle calls to expressions of unknown-any type.
5074     if (Fn->getType() == Context.UnknownAnyTy) {
5075       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
5076       if (rewrite.isInvalid()) return ExprError();
5077       Fn = rewrite.get();
5078       TheCall->setCallee(Fn);
5079       goto retry;
5080     }
5081 
5082     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
5083       << Fn->getType() << Fn->getSourceRange());
5084   }
5085 
5086   if (getLangOpts().CUDA) {
5087     if (Config) {
5088       // CUDA: Kernel calls must be to global functions
5089       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
5090         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
5091             << FDecl->getName() << Fn->getSourceRange());
5092 
5093       // CUDA: Kernel function must have 'void' return type
5094       if (!FuncT->getReturnType()->isVoidType())
5095         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
5096             << Fn->getType() << Fn->getSourceRange());
5097     } else {
5098       // CUDA: Calls to global functions must be configured
5099       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
5100         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
5101             << FDecl->getName() << Fn->getSourceRange());
5102     }
5103   }
5104 
5105   // Check for a valid return type
5106   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
5107                           FDecl))
5108     return ExprError();
5109 
5110   // We know the result type of the call, set it.
5111   TheCall->setType(FuncT->getCallResultType(Context));
5112   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
5113 
5114   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
5115   if (Proto) {
5116     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
5117                                 IsExecConfig))
5118       return ExprError();
5119   } else {
5120     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
5121 
5122     if (FDecl) {
5123       // Check if we have too few/too many template arguments, based
5124       // on our knowledge of the function definition.
5125       const FunctionDecl *Def = nullptr;
5126       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
5127         Proto = Def->getType()->getAs<FunctionProtoType>();
5128        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
5129           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
5130           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
5131       }
5132 
5133       // If the function we're calling isn't a function prototype, but we have
5134       // a function prototype from a prior declaratiom, use that prototype.
5135       if (!FDecl->hasPrototype())
5136         Proto = FDecl->getType()->getAs<FunctionProtoType>();
5137     }
5138 
5139     // Promote the arguments (C99 6.5.2.2p6).
5140     for (unsigned i = 0, e = Args.size(); i != e; i++) {
5141       Expr *Arg = Args[i];
5142 
5143       if (Proto && i < Proto->getNumParams()) {
5144         InitializedEntity Entity = InitializedEntity::InitializeParameter(
5145             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
5146         ExprResult ArgE =
5147             PerformCopyInitialization(Entity, SourceLocation(), Arg);
5148         if (ArgE.isInvalid())
5149           return true;
5150 
5151         Arg = ArgE.getAs<Expr>();
5152 
5153       } else {
5154         ExprResult ArgE = DefaultArgumentPromotion(Arg);
5155 
5156         if (ArgE.isInvalid())
5157           return true;
5158 
5159         Arg = ArgE.getAs<Expr>();
5160       }
5161 
5162       if (RequireCompleteType(Arg->getLocStart(),
5163                               Arg->getType(),
5164                               diag::err_call_incomplete_argument, Arg))
5165         return ExprError();
5166 
5167       TheCall->setArg(i, Arg);
5168     }
5169   }
5170 
5171   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
5172     if (!Method->isStatic())
5173       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
5174         << Fn->getSourceRange());
5175 
5176   // Check for sentinels
5177   if (NDecl)
5178     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
5179 
5180   // Do special checking on direct calls to functions.
5181   if (FDecl) {
5182     if (CheckFunctionCall(FDecl, TheCall, Proto))
5183       return ExprError();
5184 
5185     if (BuiltinID)
5186       return CheckBuiltinFunctionCall(FDecl, BuiltinID, TheCall);
5187   } else if (NDecl) {
5188     if (CheckPointerCall(NDecl, TheCall, Proto))
5189       return ExprError();
5190   } else {
5191     if (CheckOtherCall(TheCall, Proto))
5192       return ExprError();
5193   }
5194 
5195   return MaybeBindToTemporary(TheCall);
5196 }
5197 
5198 ExprResult
5199 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
5200                            SourceLocation RParenLoc, Expr *InitExpr) {
5201   assert(Ty && "ActOnCompoundLiteral(): missing type");
5202   assert(InitExpr && "ActOnCompoundLiteral(): missing expression");
5203 
5204   TypeSourceInfo *TInfo;
5205   QualType literalType = GetTypeFromParser(Ty, &TInfo);
5206   if (!TInfo)
5207     TInfo = Context.getTrivialTypeSourceInfo(literalType);
5208 
5209   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
5210 }
5211 
5212 ExprResult
5213 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
5214                                SourceLocation RParenLoc, Expr *LiteralExpr) {
5215   QualType literalType = TInfo->getType();
5216 
5217   if (literalType->isArrayType()) {
5218     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
5219           diag::err_illegal_decl_array_incomplete_type,
5220           SourceRange(LParenLoc,
5221                       LiteralExpr->getSourceRange().getEnd())))
5222       return ExprError();
5223     if (literalType->isVariableArrayType())
5224       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
5225         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
5226   } else if (!literalType->isDependentType() &&
5227              RequireCompleteType(LParenLoc, literalType,
5228                diag::err_typecheck_decl_incomplete_type,
5229                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
5230     return ExprError();
5231 
5232   InitializedEntity Entity
5233     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
5234   InitializationKind Kind
5235     = InitializationKind::CreateCStyleCast(LParenLoc,
5236                                            SourceRange(LParenLoc, RParenLoc),
5237                                            /*InitList=*/true);
5238   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
5239   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
5240                                       &literalType);
5241   if (Result.isInvalid())
5242     return ExprError();
5243   LiteralExpr = Result.get();
5244 
5245   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
5246   if (isFileScope &&
5247       !LiteralExpr->isTypeDependent() &&
5248       !LiteralExpr->isValueDependent() &&
5249       !literalType->isDependentType()) { // 6.5.2.5p3
5250     if (CheckForConstantInitializer(LiteralExpr, literalType))
5251       return ExprError();
5252   }
5253 
5254   // In C, compound literals are l-values for some reason.
5255   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
5256 
5257   return MaybeBindToTemporary(
5258            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
5259                                              VK, LiteralExpr, isFileScope));
5260 }
5261 
5262 ExprResult
5263 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
5264                     SourceLocation RBraceLoc) {
5265   // Immediately handle non-overload placeholders.  Overloads can be
5266   // resolved contextually, but everything else here can't.
5267   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
5268     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
5269       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
5270 
5271       // Ignore failures; dropping the entire initializer list because
5272       // of one failure would be terrible for indexing/etc.
5273       if (result.isInvalid()) continue;
5274 
5275       InitArgList[I] = result.get();
5276     }
5277   }
5278 
5279   // Semantic analysis for initializers is done by ActOnDeclarator() and
5280   // CheckInitializer() - it requires knowledge of the object being intialized.
5281 
5282   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
5283                                                RBraceLoc);
5284   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
5285   return E;
5286 }
5287 
5288 /// Do an explicit extend of the given block pointer if we're in ARC.
5289 void Sema::maybeExtendBlockObject(ExprResult &E) {
5290   assert(E.get()->getType()->isBlockPointerType());
5291   assert(E.get()->isRValue());
5292 
5293   // Only do this in an r-value context.
5294   if (!getLangOpts().ObjCAutoRefCount) return;
5295 
5296   E = ImplicitCastExpr::Create(Context, E.get()->getType(),
5297                                CK_ARCExtendBlockObject, E.get(),
5298                                /*base path*/ nullptr, VK_RValue);
5299   ExprNeedsCleanups = true;
5300 }
5301 
5302 /// Prepare a conversion of the given expression to an ObjC object
5303 /// pointer type.
5304 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
5305   QualType type = E.get()->getType();
5306   if (type->isObjCObjectPointerType()) {
5307     return CK_BitCast;
5308   } else if (type->isBlockPointerType()) {
5309     maybeExtendBlockObject(E);
5310     return CK_BlockPointerToObjCPointerCast;
5311   } else {
5312     assert(type->isPointerType());
5313     return CK_CPointerToObjCPointerCast;
5314   }
5315 }
5316 
5317 /// Prepares for a scalar cast, performing all the necessary stages
5318 /// except the final cast and returning the kind required.
5319 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
5320   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
5321   // Also, callers should have filtered out the invalid cases with
5322   // pointers.  Everything else should be possible.
5323 
5324   QualType SrcTy = Src.get()->getType();
5325   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
5326     return CK_NoOp;
5327 
5328   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
5329   case Type::STK_MemberPointer:
5330     llvm_unreachable("member pointer type in C");
5331 
5332   case Type::STK_CPointer:
5333   case Type::STK_BlockPointer:
5334   case Type::STK_ObjCObjectPointer:
5335     switch (DestTy->getScalarTypeKind()) {
5336     case Type::STK_CPointer: {
5337       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
5338       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
5339       if (SrcAS != DestAS)
5340         return CK_AddressSpaceConversion;
5341       return CK_BitCast;
5342     }
5343     case Type::STK_BlockPointer:
5344       return (SrcKind == Type::STK_BlockPointer
5345                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
5346     case Type::STK_ObjCObjectPointer:
5347       if (SrcKind == Type::STK_ObjCObjectPointer)
5348         return CK_BitCast;
5349       if (SrcKind == Type::STK_CPointer)
5350         return CK_CPointerToObjCPointerCast;
5351       maybeExtendBlockObject(Src);
5352       return CK_BlockPointerToObjCPointerCast;
5353     case Type::STK_Bool:
5354       return CK_PointerToBoolean;
5355     case Type::STK_Integral:
5356       return CK_PointerToIntegral;
5357     case Type::STK_Floating:
5358     case Type::STK_FloatingComplex:
5359     case Type::STK_IntegralComplex:
5360     case Type::STK_MemberPointer:
5361       llvm_unreachable("illegal cast from pointer");
5362     }
5363     llvm_unreachable("Should have returned before this");
5364 
5365   case Type::STK_Bool: // casting from bool is like casting from an integer
5366   case Type::STK_Integral:
5367     switch (DestTy->getScalarTypeKind()) {
5368     case Type::STK_CPointer:
5369     case Type::STK_ObjCObjectPointer:
5370     case Type::STK_BlockPointer:
5371       if (Src.get()->isNullPointerConstant(Context,
5372                                            Expr::NPC_ValueDependentIsNull))
5373         return CK_NullToPointer;
5374       return CK_IntegralToPointer;
5375     case Type::STK_Bool:
5376       return CK_IntegralToBoolean;
5377     case Type::STK_Integral:
5378       return CK_IntegralCast;
5379     case Type::STK_Floating:
5380       return CK_IntegralToFloating;
5381     case Type::STK_IntegralComplex:
5382       Src = ImpCastExprToType(Src.get(),
5383                       DestTy->castAs<ComplexType>()->getElementType(),
5384                       CK_IntegralCast);
5385       return CK_IntegralRealToComplex;
5386     case Type::STK_FloatingComplex:
5387       Src = ImpCastExprToType(Src.get(),
5388                       DestTy->castAs<ComplexType>()->getElementType(),
5389                       CK_IntegralToFloating);
5390       return CK_FloatingRealToComplex;
5391     case Type::STK_MemberPointer:
5392       llvm_unreachable("member pointer type in C");
5393     }
5394     llvm_unreachable("Should have returned before this");
5395 
5396   case Type::STK_Floating:
5397     switch (DestTy->getScalarTypeKind()) {
5398     case Type::STK_Floating:
5399       return CK_FloatingCast;
5400     case Type::STK_Bool:
5401       return CK_FloatingToBoolean;
5402     case Type::STK_Integral:
5403       return CK_FloatingToIntegral;
5404     case Type::STK_FloatingComplex:
5405       Src = ImpCastExprToType(Src.get(),
5406                               DestTy->castAs<ComplexType>()->getElementType(),
5407                               CK_FloatingCast);
5408       return CK_FloatingRealToComplex;
5409     case Type::STK_IntegralComplex:
5410       Src = ImpCastExprToType(Src.get(),
5411                               DestTy->castAs<ComplexType>()->getElementType(),
5412                               CK_FloatingToIntegral);
5413       return CK_IntegralRealToComplex;
5414     case Type::STK_CPointer:
5415     case Type::STK_ObjCObjectPointer:
5416     case Type::STK_BlockPointer:
5417       llvm_unreachable("valid float->pointer cast?");
5418     case Type::STK_MemberPointer:
5419       llvm_unreachable("member pointer type in C");
5420     }
5421     llvm_unreachable("Should have returned before this");
5422 
5423   case Type::STK_FloatingComplex:
5424     switch (DestTy->getScalarTypeKind()) {
5425     case Type::STK_FloatingComplex:
5426       return CK_FloatingComplexCast;
5427     case Type::STK_IntegralComplex:
5428       return CK_FloatingComplexToIntegralComplex;
5429     case Type::STK_Floating: {
5430       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5431       if (Context.hasSameType(ET, DestTy))
5432         return CK_FloatingComplexToReal;
5433       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
5434       return CK_FloatingCast;
5435     }
5436     case Type::STK_Bool:
5437       return CK_FloatingComplexToBoolean;
5438     case Type::STK_Integral:
5439       Src = ImpCastExprToType(Src.get(),
5440                               SrcTy->castAs<ComplexType>()->getElementType(),
5441                               CK_FloatingComplexToReal);
5442       return CK_FloatingToIntegral;
5443     case Type::STK_CPointer:
5444     case Type::STK_ObjCObjectPointer:
5445     case Type::STK_BlockPointer:
5446       llvm_unreachable("valid complex float->pointer cast?");
5447     case Type::STK_MemberPointer:
5448       llvm_unreachable("member pointer type in C");
5449     }
5450     llvm_unreachable("Should have returned before this");
5451 
5452   case Type::STK_IntegralComplex:
5453     switch (DestTy->getScalarTypeKind()) {
5454     case Type::STK_FloatingComplex:
5455       return CK_IntegralComplexToFloatingComplex;
5456     case Type::STK_IntegralComplex:
5457       return CK_IntegralComplexCast;
5458     case Type::STK_Integral: {
5459       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5460       if (Context.hasSameType(ET, DestTy))
5461         return CK_IntegralComplexToReal;
5462       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
5463       return CK_IntegralCast;
5464     }
5465     case Type::STK_Bool:
5466       return CK_IntegralComplexToBoolean;
5467     case Type::STK_Floating:
5468       Src = ImpCastExprToType(Src.get(),
5469                               SrcTy->castAs<ComplexType>()->getElementType(),
5470                               CK_IntegralComplexToReal);
5471       return CK_IntegralToFloating;
5472     case Type::STK_CPointer:
5473     case Type::STK_ObjCObjectPointer:
5474     case Type::STK_BlockPointer:
5475       llvm_unreachable("valid complex int->pointer cast?");
5476     case Type::STK_MemberPointer:
5477       llvm_unreachable("member pointer type in C");
5478     }
5479     llvm_unreachable("Should have returned before this");
5480   }
5481 
5482   llvm_unreachable("Unhandled scalar cast");
5483 }
5484 
5485 static bool breakDownVectorType(QualType type, uint64_t &len,
5486                                 QualType &eltType) {
5487   // Vectors are simple.
5488   if (const VectorType *vecType = type->getAs<VectorType>()) {
5489     len = vecType->getNumElements();
5490     eltType = vecType->getElementType();
5491     assert(eltType->isScalarType());
5492     return true;
5493   }
5494 
5495   // We allow lax conversion to and from non-vector types, but only if
5496   // they're real types (i.e. non-complex, non-pointer scalar types).
5497   if (!type->isRealType()) return false;
5498 
5499   len = 1;
5500   eltType = type;
5501   return true;
5502 }
5503 
5504 /// Are the two types lax-compatible vector types?  That is, given
5505 /// that one of them is a vector, do they have equal storage sizes,
5506 /// where the storage size is the number of elements times the element
5507 /// size?
5508 ///
5509 /// This will also return false if either of the types is neither a
5510 /// vector nor a real type.
5511 bool Sema::areLaxCompatibleVectorTypes(QualType srcTy, QualType destTy) {
5512   assert(destTy->isVectorType() || srcTy->isVectorType());
5513 
5514   // Disallow lax conversions between scalars and ExtVectors (these
5515   // conversions are allowed for other vector types because common headers
5516   // depend on them).  Most scalar OP ExtVector cases are handled by the
5517   // splat path anyway, which does what we want (convert, not bitcast).
5518   // What this rules out for ExtVectors is crazy things like char4*float.
5519   if (srcTy->isScalarType() && destTy->isExtVectorType()) return false;
5520   if (destTy->isScalarType() && srcTy->isExtVectorType()) return false;
5521 
5522   uint64_t srcLen, destLen;
5523   QualType srcEltTy, destEltTy;
5524   if (!breakDownVectorType(srcTy, srcLen, srcEltTy)) return false;
5525   if (!breakDownVectorType(destTy, destLen, destEltTy)) return false;
5526 
5527   // ASTContext::getTypeSize will return the size rounded up to a
5528   // power of 2, so instead of using that, we need to use the raw
5529   // element size multiplied by the element count.
5530   uint64_t srcEltSize = Context.getTypeSize(srcEltTy);
5531   uint64_t destEltSize = Context.getTypeSize(destEltTy);
5532 
5533   return (srcLen * srcEltSize == destLen * destEltSize);
5534 }
5535 
5536 /// Is this a legal conversion between two types, one of which is
5537 /// known to be a vector type?
5538 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5539   assert(destTy->isVectorType() || srcTy->isVectorType());
5540 
5541   if (!Context.getLangOpts().LaxVectorConversions)
5542     return false;
5543   return areLaxCompatibleVectorTypes(srcTy, destTy);
5544 }
5545 
5546 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5547                            CastKind &Kind) {
5548   assert(VectorTy->isVectorType() && "Not a vector type!");
5549 
5550   if (Ty->isVectorType() || Ty->isIntegralType(Context)) {
5551     if (!areLaxCompatibleVectorTypes(Ty, VectorTy))
5552       return Diag(R.getBegin(),
5553                   Ty->isVectorType() ?
5554                   diag::err_invalid_conversion_between_vectors :
5555                   diag::err_invalid_conversion_between_vector_and_integer)
5556         << VectorTy << Ty << R;
5557   } else
5558     return Diag(R.getBegin(),
5559                 diag::err_invalid_conversion_between_vector_and_scalar)
5560       << VectorTy << Ty << R;
5561 
5562   Kind = CK_BitCast;
5563   return false;
5564 }
5565 
5566 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5567                                     Expr *CastExpr, CastKind &Kind) {
5568   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5569 
5570   QualType SrcTy = CastExpr->getType();
5571 
5572   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5573   // an ExtVectorType.
5574   // In OpenCL, casts between vectors of different types are not allowed.
5575   // (See OpenCL 6.2).
5576   if (SrcTy->isVectorType()) {
5577     if (!areLaxCompatibleVectorTypes(SrcTy, DestTy)
5578         || (getLangOpts().OpenCL &&
5579             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5580       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5581         << DestTy << SrcTy << R;
5582       return ExprError();
5583     }
5584     Kind = CK_BitCast;
5585     return CastExpr;
5586   }
5587 
5588   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5589   // conversion will take place first from scalar to elt type, and then
5590   // splat from elt type to vector.
5591   if (SrcTy->isPointerType())
5592     return Diag(R.getBegin(),
5593                 diag::err_invalid_conversion_between_vector_and_scalar)
5594       << DestTy << SrcTy << R;
5595 
5596   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5597   ExprResult CastExprRes = CastExpr;
5598   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5599   if (CastExprRes.isInvalid())
5600     return ExprError();
5601   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5602 
5603   Kind = CK_VectorSplat;
5604   return CastExpr;
5605 }
5606 
5607 ExprResult
5608 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5609                     Declarator &D, ParsedType &Ty,
5610                     SourceLocation RParenLoc, Expr *CastExpr) {
5611   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5612          "ActOnCastExpr(): missing type or expr");
5613 
5614   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5615   if (D.isInvalidType())
5616     return ExprError();
5617 
5618   if (getLangOpts().CPlusPlus) {
5619     // Check that there are no default arguments (C++ only).
5620     CheckExtraCXXDefaultArguments(D);
5621   } else {
5622     // Make sure any TypoExprs have been dealt with.
5623     ExprResult Res = CorrectDelayedTyposInExpr(CastExpr);
5624     if (!Res.isUsable())
5625       return ExprError();
5626     CastExpr = Res.get();
5627   }
5628 
5629   checkUnusedDeclAttributes(D);
5630 
5631   QualType castType = castTInfo->getType();
5632   Ty = CreateParsedType(castType, castTInfo);
5633 
5634   bool isVectorLiteral = false;
5635 
5636   // Check for an altivec or OpenCL literal,
5637   // i.e. all the elements are integer constants.
5638   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5639   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5640   if ((getLangOpts().AltiVec || getLangOpts().ZVector || getLangOpts().OpenCL)
5641        && castType->isVectorType() && (PE || PLE)) {
5642     if (PLE && PLE->getNumExprs() == 0) {
5643       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5644       return ExprError();
5645     }
5646     if (PE || PLE->getNumExprs() == 1) {
5647       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5648       if (!E->getType()->isVectorType())
5649         isVectorLiteral = true;
5650     }
5651     else
5652       isVectorLiteral = true;
5653   }
5654 
5655   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5656   // then handle it as such.
5657   if (isVectorLiteral)
5658     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5659 
5660   // If the Expr being casted is a ParenListExpr, handle it specially.
5661   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5662   // sequence of BinOp comma operators.
5663   if (isa<ParenListExpr>(CastExpr)) {
5664     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5665     if (Result.isInvalid()) return ExprError();
5666     CastExpr = Result.get();
5667   }
5668 
5669   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5670       !getSourceManager().isInSystemMacro(LParenLoc))
5671     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5672 
5673   CheckTollFreeBridgeCast(castType, CastExpr);
5674 
5675   CheckObjCBridgeRelatedCast(castType, CastExpr);
5676 
5677   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5678 }
5679 
5680 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5681                                     SourceLocation RParenLoc, Expr *E,
5682                                     TypeSourceInfo *TInfo) {
5683   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5684          "Expected paren or paren list expression");
5685 
5686   Expr **exprs;
5687   unsigned numExprs;
5688   Expr *subExpr;
5689   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5690   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5691     LiteralLParenLoc = PE->getLParenLoc();
5692     LiteralRParenLoc = PE->getRParenLoc();
5693     exprs = PE->getExprs();
5694     numExprs = PE->getNumExprs();
5695   } else { // isa<ParenExpr> by assertion at function entrance
5696     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5697     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5698     subExpr = cast<ParenExpr>(E)->getSubExpr();
5699     exprs = &subExpr;
5700     numExprs = 1;
5701   }
5702 
5703   QualType Ty = TInfo->getType();
5704   assert(Ty->isVectorType() && "Expected vector type");
5705 
5706   SmallVector<Expr *, 8> initExprs;
5707   const VectorType *VTy = Ty->getAs<VectorType>();
5708   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5709 
5710   // '(...)' form of vector initialization in AltiVec: the number of
5711   // initializers must be one or must match the size of the vector.
5712   // If a single value is specified in the initializer then it will be
5713   // replicated to all the components of the vector
5714   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5715     // The number of initializers must be one or must match the size of the
5716     // vector. If a single value is specified in the initializer then it will
5717     // be replicated to all the components of the vector
5718     if (numExprs == 1) {
5719       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5720       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5721       if (Literal.isInvalid())
5722         return ExprError();
5723       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5724                                   PrepareScalarCast(Literal, ElemTy));
5725       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5726     }
5727     else if (numExprs < numElems) {
5728       Diag(E->getExprLoc(),
5729            diag::err_incorrect_number_of_vector_initializers);
5730       return ExprError();
5731     }
5732     else
5733       initExprs.append(exprs, exprs + numExprs);
5734   }
5735   else {
5736     // For OpenCL, when the number of initializers is a single value,
5737     // it will be replicated to all components of the vector.
5738     if (getLangOpts().OpenCL &&
5739         VTy->getVectorKind() == VectorType::GenericVector &&
5740         numExprs == 1) {
5741         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5742         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5743         if (Literal.isInvalid())
5744           return ExprError();
5745         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5746                                     PrepareScalarCast(Literal, ElemTy));
5747         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5748     }
5749 
5750     initExprs.append(exprs, exprs + numExprs);
5751   }
5752   // FIXME: This means that pretty-printing the final AST will produce curly
5753   // braces instead of the original commas.
5754   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5755                                                    initExprs, LiteralRParenLoc);
5756   initE->setType(Ty);
5757   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5758 }
5759 
5760 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5761 /// the ParenListExpr into a sequence of comma binary operators.
5762 ExprResult
5763 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5764   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5765   if (!E)
5766     return OrigExpr;
5767 
5768   ExprResult Result(E->getExpr(0));
5769 
5770   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5771     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5772                         E->getExpr(i));
5773 
5774   if (Result.isInvalid()) return ExprError();
5775 
5776   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5777 }
5778 
5779 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5780                                     SourceLocation R,
5781                                     MultiExprArg Val) {
5782   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5783   return expr;
5784 }
5785 
5786 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5787 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5788 /// emitted.
5789 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5790                                       SourceLocation QuestionLoc) {
5791   Expr *NullExpr = LHSExpr;
5792   Expr *NonPointerExpr = RHSExpr;
5793   Expr::NullPointerConstantKind NullKind =
5794       NullExpr->isNullPointerConstant(Context,
5795                                       Expr::NPC_ValueDependentIsNotNull);
5796 
5797   if (NullKind == Expr::NPCK_NotNull) {
5798     NullExpr = RHSExpr;
5799     NonPointerExpr = LHSExpr;
5800     NullKind =
5801         NullExpr->isNullPointerConstant(Context,
5802                                         Expr::NPC_ValueDependentIsNotNull);
5803   }
5804 
5805   if (NullKind == Expr::NPCK_NotNull)
5806     return false;
5807 
5808   if (NullKind == Expr::NPCK_ZeroExpression)
5809     return false;
5810 
5811   if (NullKind == Expr::NPCK_ZeroLiteral) {
5812     // In this case, check to make sure that we got here from a "NULL"
5813     // string in the source code.
5814     NullExpr = NullExpr->IgnoreParenImpCasts();
5815     SourceLocation loc = NullExpr->getExprLoc();
5816     if (!findMacroSpelling(loc, "NULL"))
5817       return false;
5818   }
5819 
5820   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5821   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5822       << NonPointerExpr->getType() << DiagType
5823       << NonPointerExpr->getSourceRange();
5824   return true;
5825 }
5826 
5827 /// \brief Return false if the condition expression is valid, true otherwise.
5828 static bool checkCondition(Sema &S, Expr *Cond, SourceLocation QuestionLoc) {
5829   QualType CondTy = Cond->getType();
5830 
5831   // OpenCL v1.1 s6.3.i says the condition cannot be a floating point type.
5832   if (S.getLangOpts().OpenCL && CondTy->isFloatingType()) {
5833     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
5834       << CondTy << Cond->getSourceRange();
5835     return true;
5836   }
5837 
5838   // C99 6.5.15p2
5839   if (CondTy->isScalarType()) return false;
5840 
5841   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_scalar)
5842     << CondTy << Cond->getSourceRange();
5843   return true;
5844 }
5845 
5846 /// \brief Handle when one or both operands are void type.
5847 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5848                                          ExprResult &RHS) {
5849     Expr *LHSExpr = LHS.get();
5850     Expr *RHSExpr = RHS.get();
5851 
5852     if (!LHSExpr->getType()->isVoidType())
5853       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5854         << RHSExpr->getSourceRange();
5855     if (!RHSExpr->getType()->isVoidType())
5856       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5857         << LHSExpr->getSourceRange();
5858     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5859     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5860     return S.Context.VoidTy;
5861 }
5862 
5863 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5864 /// true otherwise.
5865 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5866                                         QualType PointerTy) {
5867   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5868       !NullExpr.get()->isNullPointerConstant(S.Context,
5869                                             Expr::NPC_ValueDependentIsNull))
5870     return true;
5871 
5872   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5873   return false;
5874 }
5875 
5876 /// \brief Checks compatibility between two pointers and return the resulting
5877 /// type.
5878 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5879                                                      ExprResult &RHS,
5880                                                      SourceLocation Loc) {
5881   QualType LHSTy = LHS.get()->getType();
5882   QualType RHSTy = RHS.get()->getType();
5883 
5884   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5885     // Two identical pointers types are always compatible.
5886     return LHSTy;
5887   }
5888 
5889   QualType lhptee, rhptee;
5890 
5891   // Get the pointee types.
5892   bool IsBlockPointer = false;
5893   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5894     lhptee = LHSBTy->getPointeeType();
5895     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5896     IsBlockPointer = true;
5897   } else {
5898     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5899     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5900   }
5901 
5902   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5903   // differently qualified versions of compatible types, the result type is
5904   // a pointer to an appropriately qualified version of the composite
5905   // type.
5906 
5907   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5908   // clause doesn't make sense for our extensions. E.g. address space 2 should
5909   // be incompatible with address space 3: they may live on different devices or
5910   // anything.
5911   Qualifiers lhQual = lhptee.getQualifiers();
5912   Qualifiers rhQual = rhptee.getQualifiers();
5913 
5914   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5915   lhQual.removeCVRQualifiers();
5916   rhQual.removeCVRQualifiers();
5917 
5918   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5919   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5920 
5921   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5922 
5923   if (CompositeTy.isNull()) {
5924     S.Diag(Loc, diag::ext_typecheck_cond_incompatible_pointers)
5925       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5926       << RHS.get()->getSourceRange();
5927     // In this situation, we assume void* type. No especially good
5928     // reason, but this is what gcc does, and we do have to pick
5929     // to get a consistent AST.
5930     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5931     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5932     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5933     return incompatTy;
5934   }
5935 
5936   // The pointer types are compatible.
5937   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5938   if (IsBlockPointer)
5939     ResultTy = S.Context.getBlockPointerType(ResultTy);
5940   else
5941     ResultTy = S.Context.getPointerType(ResultTy);
5942 
5943   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5944   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5945   return ResultTy;
5946 }
5947 
5948 /// \brief Return the resulting type when the operands are both block pointers.
5949 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5950                                                           ExprResult &LHS,
5951                                                           ExprResult &RHS,
5952                                                           SourceLocation Loc) {
5953   QualType LHSTy = LHS.get()->getType();
5954   QualType RHSTy = RHS.get()->getType();
5955 
5956   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5957     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5958       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5959       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5960       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5961       return destType;
5962     }
5963     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5964       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5965       << RHS.get()->getSourceRange();
5966     return QualType();
5967   }
5968 
5969   // We have 2 block pointer types.
5970   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5971 }
5972 
5973 /// \brief Return the resulting type when the operands are both pointers.
5974 static QualType
5975 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5976                                             ExprResult &RHS,
5977                                             SourceLocation Loc) {
5978   // get the pointer types
5979   QualType LHSTy = LHS.get()->getType();
5980   QualType RHSTy = RHS.get()->getType();
5981 
5982   // get the "pointed to" types
5983   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5984   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5985 
5986   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5987   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5988     // Figure out necessary qualifiers (C99 6.5.15p6)
5989     QualType destPointee
5990       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5991     QualType destType = S.Context.getPointerType(destPointee);
5992     // Add qualifiers if necessary.
5993     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5994     // Promote to void*.
5995     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5996     return destType;
5997   }
5998   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5999     QualType destPointee
6000       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6001     QualType destType = S.Context.getPointerType(destPointee);
6002     // Add qualifiers if necessary.
6003     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6004     // Promote to void*.
6005     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6006     return destType;
6007   }
6008 
6009   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
6010 }
6011 
6012 /// \brief Return false if the first expression is not an integer and the second
6013 /// expression is not a pointer, true otherwise.
6014 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
6015                                         Expr* PointerExpr, SourceLocation Loc,
6016                                         bool IsIntFirstExpr) {
6017   if (!PointerExpr->getType()->isPointerType() ||
6018       !Int.get()->getType()->isIntegerType())
6019     return false;
6020 
6021   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
6022   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
6023 
6024   S.Diag(Loc, diag::ext_typecheck_cond_pointer_integer_mismatch)
6025     << Expr1->getType() << Expr2->getType()
6026     << Expr1->getSourceRange() << Expr2->getSourceRange();
6027   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
6028                             CK_IntegralToPointer);
6029   return true;
6030 }
6031 
6032 /// \brief Simple conversion between integer and floating point types.
6033 ///
6034 /// Used when handling the OpenCL conditional operator where the
6035 /// condition is a vector while the other operands are scalar.
6036 ///
6037 /// OpenCL v1.1 s6.3.i and s6.11.6 together require that the scalar
6038 /// types are either integer or floating type. Between the two
6039 /// operands, the type with the higher rank is defined as the "result
6040 /// type". The other operand needs to be promoted to the same type. No
6041 /// other type promotion is allowed. We cannot use
6042 /// UsualArithmeticConversions() for this purpose, since it always
6043 /// promotes promotable types.
6044 static QualType OpenCLArithmeticConversions(Sema &S, ExprResult &LHS,
6045                                             ExprResult &RHS,
6046                                             SourceLocation QuestionLoc) {
6047   LHS = S.DefaultFunctionArrayLvalueConversion(LHS.get());
6048   if (LHS.isInvalid())
6049     return QualType();
6050   RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
6051   if (RHS.isInvalid())
6052     return QualType();
6053 
6054   // For conversion purposes, we ignore any qualifiers.
6055   // For example, "const float" and "float" are equivalent.
6056   QualType LHSType =
6057     S.Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6058   QualType RHSType =
6059     S.Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6060 
6061   if (!LHSType->isIntegerType() && !LHSType->isRealFloatingType()) {
6062     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6063       << LHSType << LHS.get()->getSourceRange();
6064     return QualType();
6065   }
6066 
6067   if (!RHSType->isIntegerType() && !RHSType->isRealFloatingType()) {
6068     S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_int_float)
6069       << RHSType << RHS.get()->getSourceRange();
6070     return QualType();
6071   }
6072 
6073   // If both types are identical, no conversion is needed.
6074   if (LHSType == RHSType)
6075     return LHSType;
6076 
6077   // Now handle "real" floating types (i.e. float, double, long double).
6078   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
6079     return handleFloatConversion(S, LHS, RHS, LHSType, RHSType,
6080                                  /*IsCompAssign = */ false);
6081 
6082   // Finally, we have two differing integer types.
6083   return handleIntegerConversion<doIntegralCast, doIntegralCast>
6084   (S, LHS, RHS, LHSType, RHSType, /*IsCompAssign = */ false);
6085 }
6086 
6087 /// \brief Convert scalar operands to a vector that matches the
6088 ///        condition in length.
6089 ///
6090 /// Used when handling the OpenCL conditional operator where the
6091 /// condition is a vector while the other operands are scalar.
6092 ///
6093 /// We first compute the "result type" for the scalar operands
6094 /// according to OpenCL v1.1 s6.3.i. Both operands are then converted
6095 /// into a vector of that type where the length matches the condition
6096 /// vector type. s6.11.6 requires that the element types of the result
6097 /// and the condition must have the same number of bits.
6098 static QualType
6099 OpenCLConvertScalarsToVectors(Sema &S, ExprResult &LHS, ExprResult &RHS,
6100                               QualType CondTy, SourceLocation QuestionLoc) {
6101   QualType ResTy = OpenCLArithmeticConversions(S, LHS, RHS, QuestionLoc);
6102   if (ResTy.isNull()) return QualType();
6103 
6104   const VectorType *CV = CondTy->getAs<VectorType>();
6105   assert(CV);
6106 
6107   // Determine the vector result type
6108   unsigned NumElements = CV->getNumElements();
6109   QualType VectorTy = S.Context.getExtVectorType(ResTy, NumElements);
6110 
6111   // Ensure that all types have the same number of bits
6112   if (S.Context.getTypeSize(CV->getElementType())
6113       != S.Context.getTypeSize(ResTy)) {
6114     // Since VectorTy is created internally, it does not pretty print
6115     // with an OpenCL name. Instead, we just print a description.
6116     std::string EleTyName = ResTy.getUnqualifiedType().getAsString();
6117     SmallString<64> Str;
6118     llvm::raw_svector_ostream OS(Str);
6119     OS << "(vector of " << NumElements << " '" << EleTyName << "' values)";
6120     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6121       << CondTy << OS.str();
6122     return QualType();
6123   }
6124 
6125   // Convert operands to the vector result type
6126   LHS = S.ImpCastExprToType(LHS.get(), VectorTy, CK_VectorSplat);
6127   RHS = S.ImpCastExprToType(RHS.get(), VectorTy, CK_VectorSplat);
6128 
6129   return VectorTy;
6130 }
6131 
6132 /// \brief Return false if this is a valid OpenCL condition vector
6133 static bool checkOpenCLConditionVector(Sema &S, Expr *Cond,
6134                                        SourceLocation QuestionLoc) {
6135   // OpenCL v1.1 s6.11.6 says the elements of the vector must be of
6136   // integral type.
6137   const VectorType *CondTy = Cond->getType()->getAs<VectorType>();
6138   assert(CondTy);
6139   QualType EleTy = CondTy->getElementType();
6140   if (EleTy->isIntegerType()) return false;
6141 
6142   S.Diag(QuestionLoc, diag::err_typecheck_cond_expect_nonfloat)
6143     << Cond->getType() << Cond->getSourceRange();
6144   return true;
6145 }
6146 
6147 /// \brief Return false if the vector condition type and the vector
6148 ///        result type are compatible.
6149 ///
6150 /// OpenCL v1.1 s6.11.6 requires that both vector types have the same
6151 /// number of elements, and their element types have the same number
6152 /// of bits.
6153 static bool checkVectorResult(Sema &S, QualType CondTy, QualType VecResTy,
6154                               SourceLocation QuestionLoc) {
6155   const VectorType *CV = CondTy->getAs<VectorType>();
6156   const VectorType *RV = VecResTy->getAs<VectorType>();
6157   assert(CV && RV);
6158 
6159   if (CV->getNumElements() != RV->getNumElements()) {
6160     S.Diag(QuestionLoc, diag::err_conditional_vector_size)
6161       << CondTy << VecResTy;
6162     return true;
6163   }
6164 
6165   QualType CVE = CV->getElementType();
6166   QualType RVE = RV->getElementType();
6167 
6168   if (S.Context.getTypeSize(CVE) != S.Context.getTypeSize(RVE)) {
6169     S.Diag(QuestionLoc, diag::err_conditional_vector_element_size)
6170       << CondTy << VecResTy;
6171     return true;
6172   }
6173 
6174   return false;
6175 }
6176 
6177 /// \brief Return the resulting type for the conditional operator in
6178 ///        OpenCL (aka "ternary selection operator", OpenCL v1.1
6179 ///        s6.3.i) when the condition is a vector type.
6180 static QualType
6181 OpenCLCheckVectorConditional(Sema &S, ExprResult &Cond,
6182                              ExprResult &LHS, ExprResult &RHS,
6183                              SourceLocation QuestionLoc) {
6184   Cond = S.DefaultFunctionArrayLvalueConversion(Cond.get());
6185   if (Cond.isInvalid())
6186     return QualType();
6187   QualType CondTy = Cond.get()->getType();
6188 
6189   if (checkOpenCLConditionVector(S, Cond.get(), QuestionLoc))
6190     return QualType();
6191 
6192   // If either operand is a vector then find the vector type of the
6193   // result as specified in OpenCL v1.1 s6.3.i.
6194   if (LHS.get()->getType()->isVectorType() ||
6195       RHS.get()->getType()->isVectorType()) {
6196     QualType VecResTy = S.CheckVectorOperands(LHS, RHS, QuestionLoc,
6197                                               /*isCompAssign*/false,
6198                                               /*AllowBothBool*/true,
6199                                               /*AllowBoolConversions*/false);
6200     if (VecResTy.isNull()) return QualType();
6201     // The result type must match the condition type as specified in
6202     // OpenCL v1.1 s6.11.6.
6203     if (checkVectorResult(S, CondTy, VecResTy, QuestionLoc))
6204       return QualType();
6205     return VecResTy;
6206   }
6207 
6208   // Both operands are scalar.
6209   return OpenCLConvertScalarsToVectors(S, LHS, RHS, CondTy, QuestionLoc);
6210 }
6211 
6212 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
6213 /// In that case, LHS = cond.
6214 /// C99 6.5.15
6215 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
6216                                         ExprResult &RHS, ExprValueKind &VK,
6217                                         ExprObjectKind &OK,
6218                                         SourceLocation QuestionLoc) {
6219 
6220   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
6221   if (!LHSResult.isUsable()) return QualType();
6222   LHS = LHSResult;
6223 
6224   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
6225   if (!RHSResult.isUsable()) return QualType();
6226   RHS = RHSResult;
6227 
6228   // C++ is sufficiently different to merit its own checker.
6229   if (getLangOpts().CPlusPlus)
6230     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
6231 
6232   VK = VK_RValue;
6233   OK = OK_Ordinary;
6234 
6235   // The OpenCL operator with a vector condition is sufficiently
6236   // different to merit its own checker.
6237   if (getLangOpts().OpenCL && Cond.get()->getType()->isVectorType())
6238     return OpenCLCheckVectorConditional(*this, Cond, LHS, RHS, QuestionLoc);
6239 
6240   // First, check the condition.
6241   Cond = UsualUnaryConversions(Cond.get());
6242   if (Cond.isInvalid())
6243     return QualType();
6244   if (checkCondition(*this, Cond.get(), QuestionLoc))
6245     return QualType();
6246 
6247   // Now check the two expressions.
6248   if (LHS.get()->getType()->isVectorType() ||
6249       RHS.get()->getType()->isVectorType())
6250     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
6251                                /*AllowBothBool*/true,
6252                                /*AllowBoolConversions*/false);
6253 
6254   QualType ResTy = UsualArithmeticConversions(LHS, RHS);
6255   if (LHS.isInvalid() || RHS.isInvalid())
6256     return QualType();
6257 
6258   QualType LHSTy = LHS.get()->getType();
6259   QualType RHSTy = RHS.get()->getType();
6260 
6261   // If both operands have arithmetic type, do the usual arithmetic conversions
6262   // to find a common type: C99 6.5.15p3,5.
6263   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
6264     LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
6265     RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
6266 
6267     return ResTy;
6268   }
6269 
6270   // If both operands are the same structure or union type, the result is that
6271   // type.
6272   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
6273     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
6274       if (LHSRT->getDecl() == RHSRT->getDecl())
6275         // "If both the operands have structure or union type, the result has
6276         // that type."  This implies that CV qualifiers are dropped.
6277         return LHSTy.getUnqualifiedType();
6278     // FIXME: Type of conditional expression must be complete in C mode.
6279   }
6280 
6281   // C99 6.5.15p5: "If both operands have void type, the result has void type."
6282   // The following || allows only one side to be void (a GCC-ism).
6283   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
6284     return checkConditionalVoidType(*this, LHS, RHS);
6285   }
6286 
6287   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
6288   // the type of the other operand."
6289   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
6290   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
6291 
6292   // All objective-c pointer type analysis is done here.
6293   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
6294                                                         QuestionLoc);
6295   if (LHS.isInvalid() || RHS.isInvalid())
6296     return QualType();
6297   if (!compositeType.isNull())
6298     return compositeType;
6299 
6300 
6301   // Handle block pointer types.
6302   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
6303     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
6304                                                      QuestionLoc);
6305 
6306   // Check constraints for C object pointers types (C99 6.5.15p3,6).
6307   if (LHSTy->isPointerType() && RHSTy->isPointerType())
6308     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
6309                                                        QuestionLoc);
6310 
6311   // GCC compatibility: soften pointer/integer mismatch.  Note that
6312   // null pointers have been filtered out by this point.
6313   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
6314       /*isIntFirstExpr=*/true))
6315     return RHSTy;
6316   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
6317       /*isIntFirstExpr=*/false))
6318     return LHSTy;
6319 
6320   // Emit a better diagnostic if one of the expressions is a null pointer
6321   // constant and the other is not a pointer type. In this case, the user most
6322   // likely forgot to take the address of the other expression.
6323   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
6324     return QualType();
6325 
6326   // Otherwise, the operands are not compatible.
6327   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
6328     << LHSTy << RHSTy << LHS.get()->getSourceRange()
6329     << RHS.get()->getSourceRange();
6330   return QualType();
6331 }
6332 
6333 /// FindCompositeObjCPointerType - Helper method to find composite type of
6334 /// two objective-c pointer types of the two input expressions.
6335 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
6336                                             SourceLocation QuestionLoc) {
6337   QualType LHSTy = LHS.get()->getType();
6338   QualType RHSTy = RHS.get()->getType();
6339 
6340   // Handle things like Class and struct objc_class*.  Here we case the result
6341   // to the pseudo-builtin, because that will be implicitly cast back to the
6342   // redefinition type if an attempt is made to access its fields.
6343   if (LHSTy->isObjCClassType() &&
6344       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
6345     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6346     return LHSTy;
6347   }
6348   if (RHSTy->isObjCClassType() &&
6349       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
6350     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6351     return RHSTy;
6352   }
6353   // And the same for struct objc_object* / id
6354   if (LHSTy->isObjCIdType() &&
6355       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
6356     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
6357     return LHSTy;
6358   }
6359   if (RHSTy->isObjCIdType() &&
6360       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
6361     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
6362     return RHSTy;
6363   }
6364   // And the same for struct objc_selector* / SEL
6365   if (Context.isObjCSelType(LHSTy) &&
6366       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
6367     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
6368     return LHSTy;
6369   }
6370   if (Context.isObjCSelType(RHSTy) &&
6371       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
6372     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
6373     return RHSTy;
6374   }
6375   // Check constraints for Objective-C object pointers types.
6376   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
6377 
6378     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
6379       // Two identical object pointer types are always compatible.
6380       return LHSTy;
6381     }
6382     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
6383     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
6384     QualType compositeType = LHSTy;
6385 
6386     // If both operands are interfaces and either operand can be
6387     // assigned to the other, use that type as the composite
6388     // type. This allows
6389     //   xxx ? (A*) a : (B*) b
6390     // where B is a subclass of A.
6391     //
6392     // Additionally, as for assignment, if either type is 'id'
6393     // allow silent coercion. Finally, if the types are
6394     // incompatible then make sure to use 'id' as the composite
6395     // type so the result is acceptable for sending messages to.
6396 
6397     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
6398     // It could return the composite type.
6399     if (!(compositeType =
6400           Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull()) {
6401       // Nothing more to do.
6402     } else if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
6403       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
6404     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
6405       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
6406     } else if ((LHSTy->isObjCQualifiedIdType() ||
6407                 RHSTy->isObjCQualifiedIdType()) &&
6408                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
6409       // Need to handle "id<xx>" explicitly.
6410       // GCC allows qualified id and any Objective-C type to devolve to
6411       // id. Currently localizing to here until clear this should be
6412       // part of ObjCQualifiedIdTypesAreCompatible.
6413       compositeType = Context.getObjCIdType();
6414     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
6415       compositeType = Context.getObjCIdType();
6416     } else {
6417       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
6418       << LHSTy << RHSTy
6419       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6420       QualType incompatTy = Context.getObjCIdType();
6421       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
6422       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
6423       return incompatTy;
6424     }
6425     // The object pointer types are compatible.
6426     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
6427     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
6428     return compositeType;
6429   }
6430   // Check Objective-C object pointer types and 'void *'
6431   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
6432     if (getLangOpts().ObjCAutoRefCount) {
6433       // ARC forbids the implicit conversion of object pointers to 'void *',
6434       // so these types are not compatible.
6435       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6436           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6437       LHS = RHS = true;
6438       return QualType();
6439     }
6440     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
6441     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6442     QualType destPointee
6443     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
6444     QualType destType = Context.getPointerType(destPointee);
6445     // Add qualifiers if necessary.
6446     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
6447     // Promote to void*.
6448     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
6449     return destType;
6450   }
6451   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
6452     if (getLangOpts().ObjCAutoRefCount) {
6453       // ARC forbids the implicit conversion of object pointers to 'void *',
6454       // so these types are not compatible.
6455       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
6456           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6457       LHS = RHS = true;
6458       return QualType();
6459     }
6460     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
6461     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
6462     QualType destPointee
6463     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
6464     QualType destType = Context.getPointerType(destPointee);
6465     // Add qualifiers if necessary.
6466     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
6467     // Promote to void*.
6468     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
6469     return destType;
6470   }
6471   return QualType();
6472 }
6473 
6474 /// SuggestParentheses - Emit a note with a fixit hint that wraps
6475 /// ParenRange in parentheses.
6476 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6477                                const PartialDiagnostic &Note,
6478                                SourceRange ParenRange) {
6479   SourceLocation EndLoc = Self.getLocForEndOfToken(ParenRange.getEnd());
6480   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
6481       EndLoc.isValid()) {
6482     Self.Diag(Loc, Note)
6483       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
6484       << FixItHint::CreateInsertion(EndLoc, ")");
6485   } else {
6486     // We can't display the parentheses, so just show the bare note.
6487     Self.Diag(Loc, Note) << ParenRange;
6488   }
6489 }
6490 
6491 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
6492   return Opc >= BO_Mul && Opc <= BO_Shr;
6493 }
6494 
6495 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
6496 /// expression, either using a built-in or overloaded operator,
6497 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
6498 /// expression.
6499 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
6500                                    Expr **RHSExprs) {
6501   // Don't strip parenthesis: we should not warn if E is in parenthesis.
6502   E = E->IgnoreImpCasts();
6503   E = E->IgnoreConversionOperator();
6504   E = E->IgnoreImpCasts();
6505 
6506   // Built-in binary operator.
6507   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
6508     if (IsArithmeticOp(OP->getOpcode())) {
6509       *Opcode = OP->getOpcode();
6510       *RHSExprs = OP->getRHS();
6511       return true;
6512     }
6513   }
6514 
6515   // Overloaded operator.
6516   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
6517     if (Call->getNumArgs() != 2)
6518       return false;
6519 
6520     // Make sure this is really a binary operator that is safe to pass into
6521     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
6522     OverloadedOperatorKind OO = Call->getOperator();
6523     if (OO < OO_Plus || OO > OO_Arrow ||
6524         OO == OO_PlusPlus || OO == OO_MinusMinus)
6525       return false;
6526 
6527     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
6528     if (IsArithmeticOp(OpKind)) {
6529       *Opcode = OpKind;
6530       *RHSExprs = Call->getArg(1);
6531       return true;
6532     }
6533   }
6534 
6535   return false;
6536 }
6537 
6538 static bool IsLogicOp(BinaryOperatorKind Opc) {
6539   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
6540 }
6541 
6542 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
6543 /// or is a logical expression such as (x==y) which has int type, but is
6544 /// commonly interpreted as boolean.
6545 static bool ExprLooksBoolean(Expr *E) {
6546   E = E->IgnoreParenImpCasts();
6547 
6548   if (E->getType()->isBooleanType())
6549     return true;
6550   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
6551     return IsLogicOp(OP->getOpcode());
6552   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
6553     return OP->getOpcode() == UO_LNot;
6554   if (E->getType()->isPointerType())
6555     return true;
6556 
6557   return false;
6558 }
6559 
6560 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
6561 /// and binary operator are mixed in a way that suggests the programmer assumed
6562 /// the conditional operator has higher precedence, for example:
6563 /// "int x = a + someBinaryCondition ? 1 : 2".
6564 static void DiagnoseConditionalPrecedence(Sema &Self,
6565                                           SourceLocation OpLoc,
6566                                           Expr *Condition,
6567                                           Expr *LHSExpr,
6568                                           Expr *RHSExpr) {
6569   BinaryOperatorKind CondOpcode;
6570   Expr *CondRHS;
6571 
6572   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
6573     return;
6574   if (!ExprLooksBoolean(CondRHS))
6575     return;
6576 
6577   // The condition is an arithmetic binary expression, with a right-
6578   // hand side that looks boolean, so warn.
6579 
6580   Self.Diag(OpLoc, diag::warn_precedence_conditional)
6581       << Condition->getSourceRange()
6582       << BinaryOperator::getOpcodeStr(CondOpcode);
6583 
6584   SuggestParentheses(Self, OpLoc,
6585     Self.PDiag(diag::note_precedence_silence)
6586       << BinaryOperator::getOpcodeStr(CondOpcode),
6587     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
6588 
6589   SuggestParentheses(Self, OpLoc,
6590     Self.PDiag(diag::note_precedence_conditional_first),
6591     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
6592 }
6593 
6594 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
6595 /// in the case of a the GNU conditional expr extension.
6596 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
6597                                     SourceLocation ColonLoc,
6598                                     Expr *CondExpr, Expr *LHSExpr,
6599                                     Expr *RHSExpr) {
6600   if (!getLangOpts().CPlusPlus) {
6601     // C cannot handle TypoExpr nodes in the condition because it
6602     // doesn't handle dependent types properly, so make sure any TypoExprs have
6603     // been dealt with before checking the operands.
6604     ExprResult CondResult = CorrectDelayedTyposInExpr(CondExpr);
6605     if (!CondResult.isUsable()) return ExprError();
6606     CondExpr = CondResult.get();
6607   }
6608 
6609   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
6610   // was the condition.
6611   OpaqueValueExpr *opaqueValue = nullptr;
6612   Expr *commonExpr = nullptr;
6613   if (!LHSExpr) {
6614     commonExpr = CondExpr;
6615     // Lower out placeholder types first.  This is important so that we don't
6616     // try to capture a placeholder. This happens in few cases in C++; such
6617     // as Objective-C++'s dictionary subscripting syntax.
6618     if (commonExpr->hasPlaceholderType()) {
6619       ExprResult result = CheckPlaceholderExpr(commonExpr);
6620       if (!result.isUsable()) return ExprError();
6621       commonExpr = result.get();
6622     }
6623     // We usually want to apply unary conversions *before* saving, except
6624     // in the special case of a C++ l-value conditional.
6625     if (!(getLangOpts().CPlusPlus
6626           && !commonExpr->isTypeDependent()
6627           && commonExpr->getValueKind() == RHSExpr->getValueKind()
6628           && commonExpr->isGLValue()
6629           && commonExpr->isOrdinaryOrBitFieldObject()
6630           && RHSExpr->isOrdinaryOrBitFieldObject()
6631           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6632       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6633       if (commonRes.isInvalid())
6634         return ExprError();
6635       commonExpr = commonRes.get();
6636     }
6637 
6638     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6639                                                 commonExpr->getType(),
6640                                                 commonExpr->getValueKind(),
6641                                                 commonExpr->getObjectKind(),
6642                                                 commonExpr);
6643     LHSExpr = CondExpr = opaqueValue;
6644   }
6645 
6646   ExprValueKind VK = VK_RValue;
6647   ExprObjectKind OK = OK_Ordinary;
6648   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6649   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6650                                              VK, OK, QuestionLoc);
6651   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6652       RHS.isInvalid())
6653     return ExprError();
6654 
6655   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6656                                 RHS.get());
6657 
6658   CheckBoolLikeConversion(Cond.get(), QuestionLoc);
6659 
6660   if (!commonExpr)
6661     return new (Context)
6662         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6663                             RHS.get(), result, VK, OK);
6664 
6665   return new (Context) BinaryConditionalOperator(
6666       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6667       ColonLoc, result, VK, OK);
6668 }
6669 
6670 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6671 // being closely modeled after the C99 spec:-). The odd characteristic of this
6672 // routine is it effectively iqnores the qualifiers on the top level pointee.
6673 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6674 // FIXME: add a couple examples in this comment.
6675 static Sema::AssignConvertType
6676 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6677   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6678   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6679 
6680   // get the "pointed to" type (ignoring qualifiers at the top level)
6681   const Type *lhptee, *rhptee;
6682   Qualifiers lhq, rhq;
6683   std::tie(lhptee, lhq) =
6684       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6685   std::tie(rhptee, rhq) =
6686       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6687 
6688   Sema::AssignConvertType ConvTy = Sema::Compatible;
6689 
6690   // C99 6.5.16.1p1: This following citation is common to constraints
6691   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6692   // qualifiers of the type *pointed to* by the right;
6693 
6694   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6695   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6696       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6697     // Ignore lifetime for further calculation.
6698     lhq.removeObjCLifetime();
6699     rhq.removeObjCLifetime();
6700   }
6701 
6702   if (!lhq.compatiblyIncludes(rhq)) {
6703     // Treat address-space mismatches as fatal.  TODO: address subspaces
6704     if (!lhq.isAddressSpaceSupersetOf(rhq))
6705       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6706 
6707     // It's okay to add or remove GC or lifetime qualifiers when converting to
6708     // and from void*.
6709     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6710                         .compatiblyIncludes(
6711                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6712              && (lhptee->isVoidType() || rhptee->isVoidType()))
6713       ; // keep old
6714 
6715     // Treat lifetime mismatches as fatal.
6716     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6717       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6718 
6719     // For GCC compatibility, other qualifier mismatches are treated
6720     // as still compatible in C.
6721     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6722   }
6723 
6724   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6725   // incomplete type and the other is a pointer to a qualified or unqualified
6726   // version of void...
6727   if (lhptee->isVoidType()) {
6728     if (rhptee->isIncompleteOrObjectType())
6729       return ConvTy;
6730 
6731     // As an extension, we allow cast to/from void* to function pointer.
6732     assert(rhptee->isFunctionType());
6733     return Sema::FunctionVoidPointer;
6734   }
6735 
6736   if (rhptee->isVoidType()) {
6737     if (lhptee->isIncompleteOrObjectType())
6738       return ConvTy;
6739 
6740     // As an extension, we allow cast to/from void* to function pointer.
6741     assert(lhptee->isFunctionType());
6742     return Sema::FunctionVoidPointer;
6743   }
6744 
6745   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6746   // unqualified versions of compatible types, ...
6747   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6748   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6749     // Check if the pointee types are compatible ignoring the sign.
6750     // We explicitly check for char so that we catch "char" vs
6751     // "unsigned char" on systems where "char" is unsigned.
6752     if (lhptee->isCharType())
6753       ltrans = S.Context.UnsignedCharTy;
6754     else if (lhptee->hasSignedIntegerRepresentation())
6755       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6756 
6757     if (rhptee->isCharType())
6758       rtrans = S.Context.UnsignedCharTy;
6759     else if (rhptee->hasSignedIntegerRepresentation())
6760       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6761 
6762     if (ltrans == rtrans) {
6763       // Types are compatible ignoring the sign. Qualifier incompatibility
6764       // takes priority over sign incompatibility because the sign
6765       // warning can be disabled.
6766       if (ConvTy != Sema::Compatible)
6767         return ConvTy;
6768 
6769       return Sema::IncompatiblePointerSign;
6770     }
6771 
6772     // If we are a multi-level pointer, it's possible that our issue is simply
6773     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6774     // the eventual target type is the same and the pointers have the same
6775     // level of indirection, this must be the issue.
6776     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6777       do {
6778         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6779         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6780       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6781 
6782       if (lhptee == rhptee)
6783         return Sema::IncompatibleNestedPointerQualifiers;
6784     }
6785 
6786     // General pointer incompatibility takes priority over qualifiers.
6787     return Sema::IncompatiblePointer;
6788   }
6789   if (!S.getLangOpts().CPlusPlus &&
6790       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6791     return Sema::IncompatiblePointer;
6792   return ConvTy;
6793 }
6794 
6795 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6796 /// block pointer types are compatible or whether a block and normal pointer
6797 /// are compatible. It is more restrict than comparing two function pointer
6798 // types.
6799 static Sema::AssignConvertType
6800 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6801                                     QualType RHSType) {
6802   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6803   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6804 
6805   QualType lhptee, rhptee;
6806 
6807   // get the "pointed to" type (ignoring qualifiers at the top level)
6808   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6809   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6810 
6811   // In C++, the types have to match exactly.
6812   if (S.getLangOpts().CPlusPlus)
6813     return Sema::IncompatibleBlockPointer;
6814 
6815   Sema::AssignConvertType ConvTy = Sema::Compatible;
6816 
6817   // For blocks we enforce that qualifiers are identical.
6818   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6819     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6820 
6821   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6822     return Sema::IncompatibleBlockPointer;
6823 
6824   return ConvTy;
6825 }
6826 
6827 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6828 /// for assignment compatibility.
6829 static Sema::AssignConvertType
6830 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6831                                    QualType RHSType) {
6832   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6833   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6834 
6835   if (LHSType->isObjCBuiltinType()) {
6836     // Class is not compatible with ObjC object pointers.
6837     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6838         !RHSType->isObjCQualifiedClassType())
6839       return Sema::IncompatiblePointer;
6840     return Sema::Compatible;
6841   }
6842   if (RHSType->isObjCBuiltinType()) {
6843     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6844         !LHSType->isObjCQualifiedClassType())
6845       return Sema::IncompatiblePointer;
6846     return Sema::Compatible;
6847   }
6848   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6849   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6850 
6851   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6852       // make an exception for id<P>
6853       !LHSType->isObjCQualifiedIdType())
6854     return Sema::CompatiblePointerDiscardsQualifiers;
6855 
6856   if (S.Context.typesAreCompatible(LHSType, RHSType))
6857     return Sema::Compatible;
6858   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6859     return Sema::IncompatibleObjCQualifiedId;
6860   return Sema::IncompatiblePointer;
6861 }
6862 
6863 Sema::AssignConvertType
6864 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6865                                  QualType LHSType, QualType RHSType) {
6866   // Fake up an opaque expression.  We don't actually care about what
6867   // cast operations are required, so if CheckAssignmentConstraints
6868   // adds casts to this they'll be wasted, but fortunately that doesn't
6869   // usually happen on valid code.
6870   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6871   ExprResult RHSPtr = &RHSExpr;
6872   CastKind K = CK_Invalid;
6873 
6874   return CheckAssignmentConstraints(LHSType, RHSPtr, K, /*ConvertRHS=*/false);
6875 }
6876 
6877 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6878 /// has code to accommodate several GCC extensions when type checking
6879 /// pointers. Here are some objectionable examples that GCC considers warnings:
6880 ///
6881 ///  int a, *pint;
6882 ///  short *pshort;
6883 ///  struct foo *pfoo;
6884 ///
6885 ///  pint = pshort; // warning: assignment from incompatible pointer type
6886 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6887 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6888 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6889 ///
6890 /// As a result, the code for dealing with pointers is more complex than the
6891 /// C99 spec dictates.
6892 ///
6893 /// Sets 'Kind' for any result kind except Incompatible.
6894 Sema::AssignConvertType
6895 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6896                                  CastKind &Kind, bool ConvertRHS) {
6897   QualType RHSType = RHS.get()->getType();
6898   QualType OrigLHSType = LHSType;
6899 
6900   // Get canonical types.  We're not formatting these types, just comparing
6901   // them.
6902   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6903   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6904 
6905   // Common case: no conversion required.
6906   if (LHSType == RHSType) {
6907     Kind = CK_NoOp;
6908     return Compatible;
6909   }
6910 
6911   // If we have an atomic type, try a non-atomic assignment, then just add an
6912   // atomic qualification step.
6913   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6914     Sema::AssignConvertType result =
6915       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6916     if (result != Compatible)
6917       return result;
6918     if (Kind != CK_NoOp && ConvertRHS)
6919       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6920     Kind = CK_NonAtomicToAtomic;
6921     return Compatible;
6922   }
6923 
6924   // If the left-hand side is a reference type, then we are in a
6925   // (rare!) case where we've allowed the use of references in C,
6926   // e.g., as a parameter type in a built-in function. In this case,
6927   // just make sure that the type referenced is compatible with the
6928   // right-hand side type. The caller is responsible for adjusting
6929   // LHSType so that the resulting expression does not have reference
6930   // type.
6931   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6932     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6933       Kind = CK_LValueBitCast;
6934       return Compatible;
6935     }
6936     return Incompatible;
6937   }
6938 
6939   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6940   // to the same ExtVector type.
6941   if (LHSType->isExtVectorType()) {
6942     if (RHSType->isExtVectorType())
6943       return Incompatible;
6944     if (RHSType->isArithmeticType()) {
6945       // CK_VectorSplat does T -> vector T, so first cast to the
6946       // element type.
6947       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6948       if (elType != RHSType && ConvertRHS) {
6949         Kind = PrepareScalarCast(RHS, elType);
6950         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6951       }
6952       Kind = CK_VectorSplat;
6953       return Compatible;
6954     }
6955   }
6956 
6957   // Conversions to or from vector type.
6958   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6959     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6960       // Allow assignments of an AltiVec vector type to an equivalent GCC
6961       // vector type and vice versa
6962       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6963         Kind = CK_BitCast;
6964         return Compatible;
6965       }
6966 
6967       // If we are allowing lax vector conversions, and LHS and RHS are both
6968       // vectors, the total size only needs to be the same. This is a bitcast;
6969       // no bits are changed but the result type is different.
6970       if (isLaxVectorConversion(RHSType, LHSType)) {
6971         Kind = CK_BitCast;
6972         return IncompatibleVectors;
6973       }
6974     }
6975     return Incompatible;
6976   }
6977 
6978   // Arithmetic conversions.
6979   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6980       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6981     if (ConvertRHS)
6982       Kind = PrepareScalarCast(RHS, LHSType);
6983     return Compatible;
6984   }
6985 
6986   // Conversions to normal pointers.
6987   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6988     // U* -> T*
6989     if (isa<PointerType>(RHSType)) {
6990       unsigned AddrSpaceL = LHSPointer->getPointeeType().getAddressSpace();
6991       unsigned AddrSpaceR = RHSType->getPointeeType().getAddressSpace();
6992       Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast;
6993       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6994     }
6995 
6996     // int -> T*
6997     if (RHSType->isIntegerType()) {
6998       Kind = CK_IntegralToPointer; // FIXME: null?
6999       return IntToPointer;
7000     }
7001 
7002     // C pointers are not compatible with ObjC object pointers,
7003     // with two exceptions:
7004     if (isa<ObjCObjectPointerType>(RHSType)) {
7005       //  - conversions to void*
7006       if (LHSPointer->getPointeeType()->isVoidType()) {
7007         Kind = CK_BitCast;
7008         return Compatible;
7009       }
7010 
7011       //  - conversions from 'Class' to the redefinition type
7012       if (RHSType->isObjCClassType() &&
7013           Context.hasSameType(LHSType,
7014                               Context.getObjCClassRedefinitionType())) {
7015         Kind = CK_BitCast;
7016         return Compatible;
7017       }
7018 
7019       Kind = CK_BitCast;
7020       return IncompatiblePointer;
7021     }
7022 
7023     // U^ -> void*
7024     if (RHSType->getAs<BlockPointerType>()) {
7025       if (LHSPointer->getPointeeType()->isVoidType()) {
7026         Kind = CK_BitCast;
7027         return Compatible;
7028       }
7029     }
7030 
7031     return Incompatible;
7032   }
7033 
7034   // Conversions to block pointers.
7035   if (isa<BlockPointerType>(LHSType)) {
7036     // U^ -> T^
7037     if (RHSType->isBlockPointerType()) {
7038       Kind = CK_BitCast;
7039       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
7040     }
7041 
7042     // int or null -> T^
7043     if (RHSType->isIntegerType()) {
7044       Kind = CK_IntegralToPointer; // FIXME: null
7045       return IntToBlockPointer;
7046     }
7047 
7048     // id -> T^
7049     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
7050       Kind = CK_AnyPointerToBlockPointerCast;
7051       return Compatible;
7052     }
7053 
7054     // void* -> T^
7055     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
7056       if (RHSPT->getPointeeType()->isVoidType()) {
7057         Kind = CK_AnyPointerToBlockPointerCast;
7058         return Compatible;
7059       }
7060 
7061     return Incompatible;
7062   }
7063 
7064   // Conversions to Objective-C pointers.
7065   if (isa<ObjCObjectPointerType>(LHSType)) {
7066     // A* -> B*
7067     if (RHSType->isObjCObjectPointerType()) {
7068       Kind = CK_BitCast;
7069       Sema::AssignConvertType result =
7070         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
7071       if (getLangOpts().ObjCAutoRefCount &&
7072           result == Compatible &&
7073           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
7074         result = IncompatibleObjCWeakRef;
7075       return result;
7076     }
7077 
7078     // int or null -> A*
7079     if (RHSType->isIntegerType()) {
7080       Kind = CK_IntegralToPointer; // FIXME: null
7081       return IntToPointer;
7082     }
7083 
7084     // In general, C pointers are not compatible with ObjC object pointers,
7085     // with two exceptions:
7086     if (isa<PointerType>(RHSType)) {
7087       Kind = CK_CPointerToObjCPointerCast;
7088 
7089       //  - conversions from 'void*'
7090       if (RHSType->isVoidPointerType()) {
7091         return Compatible;
7092       }
7093 
7094       //  - conversions to 'Class' from its redefinition type
7095       if (LHSType->isObjCClassType() &&
7096           Context.hasSameType(RHSType,
7097                               Context.getObjCClassRedefinitionType())) {
7098         return Compatible;
7099       }
7100 
7101       return IncompatiblePointer;
7102     }
7103 
7104     // Only under strict condition T^ is compatible with an Objective-C pointer.
7105     if (RHSType->isBlockPointerType() &&
7106         LHSType->isBlockCompatibleObjCPointerType(Context)) {
7107       if (ConvertRHS)
7108         maybeExtendBlockObject(RHS);
7109       Kind = CK_BlockPointerToObjCPointerCast;
7110       return Compatible;
7111     }
7112 
7113     return Incompatible;
7114   }
7115 
7116   // Conversions from pointers that are not covered by the above.
7117   if (isa<PointerType>(RHSType)) {
7118     // T* -> _Bool
7119     if (LHSType == Context.BoolTy) {
7120       Kind = CK_PointerToBoolean;
7121       return Compatible;
7122     }
7123 
7124     // T* -> int
7125     if (LHSType->isIntegerType()) {
7126       Kind = CK_PointerToIntegral;
7127       return PointerToInt;
7128     }
7129 
7130     return Incompatible;
7131   }
7132 
7133   // Conversions from Objective-C pointers that are not covered by the above.
7134   if (isa<ObjCObjectPointerType>(RHSType)) {
7135     // T* -> _Bool
7136     if (LHSType == Context.BoolTy) {
7137       Kind = CK_PointerToBoolean;
7138       return Compatible;
7139     }
7140 
7141     // T* -> int
7142     if (LHSType->isIntegerType()) {
7143       Kind = CK_PointerToIntegral;
7144       return PointerToInt;
7145     }
7146 
7147     return Incompatible;
7148   }
7149 
7150   // struct A -> struct B
7151   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
7152     if (Context.typesAreCompatible(LHSType, RHSType)) {
7153       Kind = CK_NoOp;
7154       return Compatible;
7155     }
7156   }
7157 
7158   return Incompatible;
7159 }
7160 
7161 /// \brief Constructs a transparent union from an expression that is
7162 /// used to initialize the transparent union.
7163 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
7164                                       ExprResult &EResult, QualType UnionType,
7165                                       FieldDecl *Field) {
7166   // Build an initializer list that designates the appropriate member
7167   // of the transparent union.
7168   Expr *E = EResult.get();
7169   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
7170                                                    E, SourceLocation());
7171   Initializer->setType(UnionType);
7172   Initializer->setInitializedFieldInUnion(Field);
7173 
7174   // Build a compound literal constructing a value of the transparent
7175   // union type from this initializer list.
7176   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
7177   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
7178                                         VK_RValue, Initializer, false);
7179 }
7180 
7181 Sema::AssignConvertType
7182 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
7183                                                ExprResult &RHS) {
7184   QualType RHSType = RHS.get()->getType();
7185 
7186   // If the ArgType is a Union type, we want to handle a potential
7187   // transparent_union GCC extension.
7188   const RecordType *UT = ArgType->getAsUnionType();
7189   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
7190     return Incompatible;
7191 
7192   // The field to initialize within the transparent union.
7193   RecordDecl *UD = UT->getDecl();
7194   FieldDecl *InitField = nullptr;
7195   // It's compatible if the expression matches any of the fields.
7196   for (auto *it : UD->fields()) {
7197     if (it->getType()->isPointerType()) {
7198       // If the transparent union contains a pointer type, we allow:
7199       // 1) void pointer
7200       // 2) null pointer constant
7201       if (RHSType->isPointerType())
7202         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
7203           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
7204           InitField = it;
7205           break;
7206         }
7207 
7208       if (RHS.get()->isNullPointerConstant(Context,
7209                                            Expr::NPC_ValueDependentIsNull)) {
7210         RHS = ImpCastExprToType(RHS.get(), it->getType(),
7211                                 CK_NullToPointer);
7212         InitField = it;
7213         break;
7214       }
7215     }
7216 
7217     CastKind Kind = CK_Invalid;
7218     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
7219           == Compatible) {
7220       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
7221       InitField = it;
7222       break;
7223     }
7224   }
7225 
7226   if (!InitField)
7227     return Incompatible;
7228 
7229   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
7230   return Compatible;
7231 }
7232 
7233 Sema::AssignConvertType
7234 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &CallerRHS,
7235                                        bool Diagnose,
7236                                        bool DiagnoseCFAudited,
7237                                        bool ConvertRHS) {
7238   // If ConvertRHS is false, we want to leave the caller's RHS untouched. Sadly,
7239   // we can't avoid *all* modifications at the moment, so we need some somewhere
7240   // to put the updated value.
7241   ExprResult LocalRHS = CallerRHS;
7242   ExprResult &RHS = ConvertRHS ? CallerRHS : LocalRHS;
7243 
7244   if (getLangOpts().CPlusPlus) {
7245     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
7246       // C++ 5.17p3: If the left operand is not of class type, the
7247       // expression is implicitly converted (C++ 4) to the
7248       // cv-unqualified type of the left operand.
7249       ExprResult Res;
7250       if (Diagnose) {
7251         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7252                                         AA_Assigning);
7253       } else {
7254         ImplicitConversionSequence ICS =
7255             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7256                                   /*SuppressUserConversions=*/false,
7257                                   /*AllowExplicit=*/false,
7258                                   /*InOverloadResolution=*/false,
7259                                   /*CStyle=*/false,
7260                                   /*AllowObjCWritebackConversion=*/false);
7261         if (ICS.isFailure())
7262           return Incompatible;
7263         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
7264                                         ICS, AA_Assigning);
7265       }
7266       if (Res.isInvalid())
7267         return Incompatible;
7268       Sema::AssignConvertType result = Compatible;
7269       if (getLangOpts().ObjCAutoRefCount &&
7270           !CheckObjCARCUnavailableWeakConversion(LHSType,
7271                                                  RHS.get()->getType()))
7272         result = IncompatibleObjCWeakRef;
7273       RHS = Res;
7274       return result;
7275     }
7276 
7277     // FIXME: Currently, we fall through and treat C++ classes like C
7278     // structures.
7279     // FIXME: We also fall through for atomics; not sure what should
7280     // happen there, though.
7281   } else if (RHS.get()->getType() == Context.OverloadTy) {
7282     // As a set of extensions to C, we support overloading on functions. These
7283     // functions need to be resolved here.
7284     DeclAccessPair DAP;
7285     if (FunctionDecl *FD = ResolveAddressOfOverloadedFunction(
7286             RHS.get(), LHSType, /*Complain=*/false, DAP))
7287       RHS = FixOverloadedFunctionReference(RHS.get(), DAP, FD);
7288     else
7289       return Incompatible;
7290   }
7291 
7292   // C99 6.5.16.1p1: the left operand is a pointer and the right is
7293   // a null pointer constant.
7294   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
7295        LHSType->isBlockPointerType()) &&
7296       RHS.get()->isNullPointerConstant(Context,
7297                                        Expr::NPC_ValueDependentIsNull)) {
7298     CastKind Kind;
7299     CXXCastPath Path;
7300     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
7301     if (ConvertRHS)
7302       RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
7303     return Compatible;
7304   }
7305 
7306   // This check seems unnatural, however it is necessary to ensure the proper
7307   // conversion of functions/arrays. If the conversion were done for all
7308   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
7309   // expressions that suppress this implicit conversion (&, sizeof).
7310   //
7311   // Suppress this for references: C++ 8.5.3p5.
7312   if (!LHSType->isReferenceType()) {
7313     // FIXME: We potentially allocate here even if ConvertRHS is false.
7314     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7315     if (RHS.isInvalid())
7316       return Incompatible;
7317   }
7318 
7319   Expr *PRE = RHS.get()->IgnoreParenCasts();
7320   if (ObjCProtocolExpr *OPE = dyn_cast<ObjCProtocolExpr>(PRE)) {
7321     ObjCProtocolDecl *PDecl = OPE->getProtocol();
7322     if (PDecl && !PDecl->hasDefinition()) {
7323       Diag(PRE->getExprLoc(), diag::warn_atprotocol_protocol) << PDecl->getName();
7324       Diag(PDecl->getLocation(), diag::note_entity_declared_at) << PDecl;
7325     }
7326   }
7327 
7328   CastKind Kind = CK_Invalid;
7329   Sema::AssignConvertType result =
7330     CheckAssignmentConstraints(LHSType, RHS, Kind, ConvertRHS);
7331 
7332   // C99 6.5.16.1p2: The value of the right operand is converted to the
7333   // type of the assignment expression.
7334   // CheckAssignmentConstraints allows the left-hand side to be a reference,
7335   // so that we can use references in built-in functions even in C.
7336   // The getNonReferenceType() call makes sure that the resulting expression
7337   // does not have reference type.
7338   if (result != Incompatible && RHS.get()->getType() != LHSType) {
7339     QualType Ty = LHSType.getNonLValueExprType(Context);
7340     Expr *E = RHS.get();
7341     if (getLangOpts().ObjCAutoRefCount)
7342       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
7343                              DiagnoseCFAudited);
7344     if (getLangOpts().ObjC1 &&
7345         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
7346                                           LHSType, E->getType(), E) ||
7347          ConversionToObjCStringLiteralCheck(LHSType, E))) {
7348       RHS = E;
7349       return Compatible;
7350     }
7351 
7352     if (ConvertRHS)
7353       RHS = ImpCastExprToType(E, Ty, Kind);
7354   }
7355   return result;
7356 }
7357 
7358 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
7359                                ExprResult &RHS) {
7360   Diag(Loc, diag::err_typecheck_invalid_operands)
7361     << LHS.get()->getType() << RHS.get()->getType()
7362     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7363   return QualType();
7364 }
7365 
7366 /// Try to convert a value of non-vector type to a vector type by converting
7367 /// the type to the element type of the vector and then performing a splat.
7368 /// If the language is OpenCL, we only use conversions that promote scalar
7369 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
7370 /// for float->int.
7371 ///
7372 /// \param scalar - if non-null, actually perform the conversions
7373 /// \return true if the operation fails (but without diagnosing the failure)
7374 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
7375                                      QualType scalarTy,
7376                                      QualType vectorEltTy,
7377                                      QualType vectorTy) {
7378   // The conversion to apply to the scalar before splatting it,
7379   // if necessary.
7380   CastKind scalarCast = CK_Invalid;
7381 
7382   if (vectorEltTy->isIntegralType(S.Context)) {
7383     if (!scalarTy->isIntegralType(S.Context))
7384       return true;
7385     if (S.getLangOpts().OpenCL &&
7386         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
7387       return true;
7388     scalarCast = CK_IntegralCast;
7389   } else if (vectorEltTy->isRealFloatingType()) {
7390     if (scalarTy->isRealFloatingType()) {
7391       if (S.getLangOpts().OpenCL &&
7392           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
7393         return true;
7394       scalarCast = CK_FloatingCast;
7395     }
7396     else if (scalarTy->isIntegralType(S.Context))
7397       scalarCast = CK_IntegralToFloating;
7398     else
7399       return true;
7400   } else {
7401     return true;
7402   }
7403 
7404   // Adjust scalar if desired.
7405   if (scalar) {
7406     if (scalarCast != CK_Invalid)
7407       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
7408     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
7409   }
7410   return false;
7411 }
7412 
7413 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
7414                                    SourceLocation Loc, bool IsCompAssign,
7415                                    bool AllowBothBool,
7416                                    bool AllowBoolConversions) {
7417   if (!IsCompAssign) {
7418     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
7419     if (LHS.isInvalid())
7420       return QualType();
7421   }
7422   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
7423   if (RHS.isInvalid())
7424     return QualType();
7425 
7426   // For conversion purposes, we ignore any qualifiers.
7427   // For example, "const float" and "float" are equivalent.
7428   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
7429   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
7430 
7431   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
7432   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
7433   assert(LHSVecType || RHSVecType);
7434 
7435   // AltiVec-style "vector bool op vector bool" combinations are allowed
7436   // for some operators but not others.
7437   if (!AllowBothBool &&
7438       LHSVecType && LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7439       RHSVecType && RHSVecType->getVectorKind() == VectorType::AltiVecBool)
7440     return InvalidOperands(Loc, LHS, RHS);
7441 
7442   // If the vector types are identical, return.
7443   if (Context.hasSameType(LHSType, RHSType))
7444     return LHSType;
7445 
7446   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
7447   if (LHSVecType && RHSVecType &&
7448       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
7449     if (isa<ExtVectorType>(LHSVecType)) {
7450       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7451       return LHSType;
7452     }
7453 
7454     if (!IsCompAssign)
7455       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7456     return RHSType;
7457   }
7458 
7459   // AllowBoolConversions says that bool and non-bool AltiVec vectors
7460   // can be mixed, with the result being the non-bool type.  The non-bool
7461   // operand must have integer element type.
7462   if (AllowBoolConversions && LHSVecType && RHSVecType &&
7463       LHSVecType->getNumElements() == RHSVecType->getNumElements() &&
7464       (Context.getTypeSize(LHSVecType->getElementType()) ==
7465        Context.getTypeSize(RHSVecType->getElementType()))) {
7466     if (LHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7467         LHSVecType->getElementType()->isIntegerType() &&
7468         RHSVecType->getVectorKind() == VectorType::AltiVecBool) {
7469       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7470       return LHSType;
7471     }
7472     if (!IsCompAssign &&
7473         LHSVecType->getVectorKind() == VectorType::AltiVecBool &&
7474         RHSVecType->getVectorKind() == VectorType::AltiVecVector &&
7475         RHSVecType->getElementType()->isIntegerType()) {
7476       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
7477       return RHSType;
7478     }
7479   }
7480 
7481   // If there's an ext-vector type and a scalar, try to convert the scalar to
7482   // the vector element type and splat.
7483   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
7484     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
7485                                   LHSVecType->getElementType(), LHSType))
7486       return LHSType;
7487   }
7488   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
7489     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
7490                                   LHSType, RHSVecType->getElementType(),
7491                                   RHSType))
7492       return RHSType;
7493   }
7494 
7495   // If we're allowing lax vector conversions, only the total (data) size
7496   // needs to be the same.
7497   // FIXME: Should we really be allowing this?
7498   // FIXME: We really just pick the LHS type arbitrarily?
7499   if (isLaxVectorConversion(RHSType, LHSType)) {
7500     QualType resultType = LHSType;
7501     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
7502     return resultType;
7503   }
7504 
7505   // Okay, the expression is invalid.
7506 
7507   // If there's a non-vector, non-real operand, diagnose that.
7508   if ((!RHSVecType && !RHSType->isRealType()) ||
7509       (!LHSVecType && !LHSType->isRealType())) {
7510     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
7511       << LHSType << RHSType
7512       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7513     return QualType();
7514   }
7515 
7516   // OpenCL V1.1 6.2.6.p1:
7517   // If the operands are of more than one vector type, then an error shall
7518   // occur. Implicit conversions between vector types are not permitted, per
7519   // section 6.2.1.
7520   if (getLangOpts().OpenCL &&
7521       RHSVecType && isa<ExtVectorType>(RHSVecType) &&
7522       LHSVecType && isa<ExtVectorType>(LHSVecType)) {
7523     Diag(Loc, diag::err_opencl_implicit_vector_conversion) << LHSType
7524                                                            << RHSType;
7525     return QualType();
7526   }
7527 
7528   // Otherwise, use the generic diagnostic.
7529   Diag(Loc, diag::err_typecheck_vector_not_convertable)
7530     << LHSType << RHSType
7531     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7532   return QualType();
7533 }
7534 
7535 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
7536 // expression.  These are mainly cases where the null pointer is used as an
7537 // integer instead of a pointer.
7538 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
7539                                 SourceLocation Loc, bool IsCompare) {
7540   // The canonical way to check for a GNU null is with isNullPointerConstant,
7541   // but we use a bit of a hack here for speed; this is a relatively
7542   // hot path, and isNullPointerConstant is slow.
7543   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
7544   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
7545 
7546   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
7547 
7548   // Avoid analyzing cases where the result will either be invalid (and
7549   // diagnosed as such) or entirely valid and not something to warn about.
7550   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
7551       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
7552     return;
7553 
7554   // Comparison operations would not make sense with a null pointer no matter
7555   // what the other expression is.
7556   if (!IsCompare) {
7557     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
7558         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
7559         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
7560     return;
7561   }
7562 
7563   // The rest of the operations only make sense with a null pointer
7564   // if the other expression is a pointer.
7565   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
7566       NonNullType->canDecayToPointerType())
7567     return;
7568 
7569   S.Diag(Loc, diag::warn_null_in_comparison_operation)
7570       << LHSNull /* LHS is NULL */ << NonNullType
7571       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7572 }
7573 
7574 static void DiagnoseBadDivideOrRemainderValues(Sema& S, ExprResult &LHS,
7575                                                ExprResult &RHS,
7576                                                SourceLocation Loc, bool IsDiv) {
7577   // Check for division/remainder by zero.
7578   llvm::APSInt RHSValue;
7579   if (!RHS.get()->isValueDependent() &&
7580       RHS.get()->EvaluateAsInt(RHSValue, S.Context) && RHSValue == 0)
7581     S.DiagRuntimeBehavior(Loc, RHS.get(),
7582                           S.PDiag(diag::warn_remainder_division_by_zero)
7583                             << IsDiv << RHS.get()->getSourceRange());
7584 }
7585 
7586 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
7587                                            SourceLocation Loc,
7588                                            bool IsCompAssign, bool IsDiv) {
7589   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7590 
7591   if (LHS.get()->getType()->isVectorType() ||
7592       RHS.get()->getType()->isVectorType())
7593     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7594                                /*AllowBothBool*/getLangOpts().AltiVec,
7595                                /*AllowBoolConversions*/false);
7596 
7597   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7598   if (LHS.isInvalid() || RHS.isInvalid())
7599     return QualType();
7600 
7601 
7602   if (compType.isNull() || !compType->isArithmeticType())
7603     return InvalidOperands(Loc, LHS, RHS);
7604   if (IsDiv)
7605     DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, IsDiv);
7606   return compType;
7607 }
7608 
7609 QualType Sema::CheckRemainderOperands(
7610   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7611   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7612 
7613   if (LHS.get()->getType()->isVectorType() ||
7614       RHS.get()->getType()->isVectorType()) {
7615     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7616         RHS.get()->getType()->hasIntegerRepresentation())
7617       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
7618                                  /*AllowBothBool*/getLangOpts().AltiVec,
7619                                  /*AllowBoolConversions*/false);
7620     return InvalidOperands(Loc, LHS, RHS);
7621   }
7622 
7623   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
7624   if (LHS.isInvalid() || RHS.isInvalid())
7625     return QualType();
7626 
7627   if (compType.isNull() || !compType->isIntegerType())
7628     return InvalidOperands(Loc, LHS, RHS);
7629   DiagnoseBadDivideOrRemainderValues(*this, LHS, RHS, Loc, false /* IsDiv */);
7630   return compType;
7631 }
7632 
7633 /// \brief Diagnose invalid arithmetic on two void pointers.
7634 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
7635                                                 Expr *LHSExpr, Expr *RHSExpr) {
7636   S.Diag(Loc, S.getLangOpts().CPlusPlus
7637                 ? diag::err_typecheck_pointer_arith_void_type
7638                 : diag::ext_gnu_void_ptr)
7639     << 1 /* two pointers */ << LHSExpr->getSourceRange()
7640                             << RHSExpr->getSourceRange();
7641 }
7642 
7643 /// \brief Diagnose invalid arithmetic on a void pointer.
7644 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
7645                                             Expr *Pointer) {
7646   S.Diag(Loc, S.getLangOpts().CPlusPlus
7647                 ? diag::err_typecheck_pointer_arith_void_type
7648                 : diag::ext_gnu_void_ptr)
7649     << 0 /* one pointer */ << Pointer->getSourceRange();
7650 }
7651 
7652 /// \brief Diagnose invalid arithmetic on two function pointers.
7653 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
7654                                                     Expr *LHS, Expr *RHS) {
7655   assert(LHS->getType()->isAnyPointerType());
7656   assert(RHS->getType()->isAnyPointerType());
7657   S.Diag(Loc, S.getLangOpts().CPlusPlus
7658                 ? diag::err_typecheck_pointer_arith_function_type
7659                 : diag::ext_gnu_ptr_func_arith)
7660     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
7661     // We only show the second type if it differs from the first.
7662     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
7663                                                    RHS->getType())
7664     << RHS->getType()->getPointeeType()
7665     << LHS->getSourceRange() << RHS->getSourceRange();
7666 }
7667 
7668 /// \brief Diagnose invalid arithmetic on a function pointer.
7669 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
7670                                                 Expr *Pointer) {
7671   assert(Pointer->getType()->isAnyPointerType());
7672   S.Diag(Loc, S.getLangOpts().CPlusPlus
7673                 ? diag::err_typecheck_pointer_arith_function_type
7674                 : diag::ext_gnu_ptr_func_arith)
7675     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
7676     << 0 /* one pointer, so only one type */
7677     << Pointer->getSourceRange();
7678 }
7679 
7680 /// \brief Emit error if Operand is incomplete pointer type
7681 ///
7682 /// \returns True if pointer has incomplete type
7683 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
7684                                                  Expr *Operand) {
7685   QualType ResType = Operand->getType();
7686   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7687     ResType = ResAtomicType->getValueType();
7688 
7689   assert(ResType->isAnyPointerType() && !ResType->isDependentType());
7690   QualType PointeeTy = ResType->getPointeeType();
7691   return S.RequireCompleteType(Loc, PointeeTy,
7692                                diag::err_typecheck_arithmetic_incomplete_type,
7693                                PointeeTy, Operand->getSourceRange());
7694 }
7695 
7696 /// \brief Check the validity of an arithmetic pointer operand.
7697 ///
7698 /// If the operand has pointer type, this code will check for pointer types
7699 /// which are invalid in arithmetic operations. These will be diagnosed
7700 /// appropriately, including whether or not the use is supported as an
7701 /// extension.
7702 ///
7703 /// \returns True when the operand is valid to use (even if as an extension).
7704 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
7705                                             Expr *Operand) {
7706   QualType ResType = Operand->getType();
7707   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7708     ResType = ResAtomicType->getValueType();
7709 
7710   if (!ResType->isAnyPointerType()) return true;
7711 
7712   QualType PointeeTy = ResType->getPointeeType();
7713   if (PointeeTy->isVoidType()) {
7714     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
7715     return !S.getLangOpts().CPlusPlus;
7716   }
7717   if (PointeeTy->isFunctionType()) {
7718     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7719     return !S.getLangOpts().CPlusPlus;
7720   }
7721 
7722   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7723 
7724   return true;
7725 }
7726 
7727 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7728 /// operands.
7729 ///
7730 /// This routine will diagnose any invalid arithmetic on pointer operands much
7731 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7732 /// for emitting a single diagnostic even for operations where both LHS and RHS
7733 /// are (potentially problematic) pointers.
7734 ///
7735 /// \returns True when the operand is valid to use (even if as an extension).
7736 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7737                                                 Expr *LHSExpr, Expr *RHSExpr) {
7738   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7739   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7740   if (!isLHSPointer && !isRHSPointer) return true;
7741 
7742   QualType LHSPointeeTy, RHSPointeeTy;
7743   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7744   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7745 
7746   // if both are pointers check if operation is valid wrt address spaces
7747   if (S.getLangOpts().OpenCL && isLHSPointer && isRHSPointer) {
7748     const PointerType *lhsPtr = LHSExpr->getType()->getAs<PointerType>();
7749     const PointerType *rhsPtr = RHSExpr->getType()->getAs<PointerType>();
7750     if (!lhsPtr->isAddressSpaceOverlapping(*rhsPtr)) {
7751       S.Diag(Loc,
7752              diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
7753           << LHSExpr->getType() << RHSExpr->getType() << 1 /*arithmetic op*/
7754           << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7755       return false;
7756     }
7757   }
7758 
7759   // Check for arithmetic on pointers to incomplete types.
7760   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7761   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7762   if (isLHSVoidPtr || isRHSVoidPtr) {
7763     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7764     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7765     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7766 
7767     return !S.getLangOpts().CPlusPlus;
7768   }
7769 
7770   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7771   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7772   if (isLHSFuncPtr || isRHSFuncPtr) {
7773     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7774     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7775                                                                 RHSExpr);
7776     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7777 
7778     return !S.getLangOpts().CPlusPlus;
7779   }
7780 
7781   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7782     return false;
7783   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7784     return false;
7785 
7786   return true;
7787 }
7788 
7789 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7790 /// literal.
7791 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7792                                   Expr *LHSExpr, Expr *RHSExpr) {
7793   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7794   Expr* IndexExpr = RHSExpr;
7795   if (!StrExpr) {
7796     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7797     IndexExpr = LHSExpr;
7798   }
7799 
7800   bool IsStringPlusInt = StrExpr &&
7801       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7802   if (!IsStringPlusInt || IndexExpr->isValueDependent())
7803     return;
7804 
7805   llvm::APSInt index;
7806   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7807     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7808     if (index.isNonNegative() &&
7809         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7810                               index.isUnsigned()))
7811       return;
7812   }
7813 
7814   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7815   Self.Diag(OpLoc, diag::warn_string_plus_int)
7816       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7817 
7818   // Only print a fixit for "str" + int, not for int + "str".
7819   if (IndexExpr == RHSExpr) {
7820     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
7821     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7822         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7823         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7824         << FixItHint::CreateInsertion(EndLoc, "]");
7825   } else
7826     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7827 }
7828 
7829 /// \brief Emit a warning when adding a char literal to a string.
7830 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7831                                    Expr *LHSExpr, Expr *RHSExpr) {
7832   const Expr *StringRefExpr = LHSExpr;
7833   const CharacterLiteral *CharExpr =
7834       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7835 
7836   if (!CharExpr) {
7837     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7838     StringRefExpr = RHSExpr;
7839   }
7840 
7841   if (!CharExpr || !StringRefExpr)
7842     return;
7843 
7844   const QualType StringType = StringRefExpr->getType();
7845 
7846   // Return if not a PointerType.
7847   if (!StringType->isAnyPointerType())
7848     return;
7849 
7850   // Return if not a CharacterType.
7851   if (!StringType->getPointeeType()->isAnyCharacterType())
7852     return;
7853 
7854   ASTContext &Ctx = Self.getASTContext();
7855   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7856 
7857   const QualType CharType = CharExpr->getType();
7858   if (!CharType->isAnyCharacterType() &&
7859       CharType->isIntegerType() &&
7860       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7861     Self.Diag(OpLoc, diag::warn_string_plus_char)
7862         << DiagRange << Ctx.CharTy;
7863   } else {
7864     Self.Diag(OpLoc, diag::warn_string_plus_char)
7865         << DiagRange << CharExpr->getType();
7866   }
7867 
7868   // Only print a fixit for str + char, not for char + str.
7869   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7870     SourceLocation EndLoc = Self.getLocForEndOfToken(RHSExpr->getLocEnd());
7871     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7872         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7873         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7874         << FixItHint::CreateInsertion(EndLoc, "]");
7875   } else {
7876     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7877   }
7878 }
7879 
7880 /// \brief Emit error when two pointers are incompatible.
7881 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7882                                            Expr *LHSExpr, Expr *RHSExpr) {
7883   assert(LHSExpr->getType()->isAnyPointerType());
7884   assert(RHSExpr->getType()->isAnyPointerType());
7885   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7886     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7887     << RHSExpr->getSourceRange();
7888 }
7889 
7890 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7891     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7892     QualType* CompLHSTy) {
7893   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7894 
7895   if (LHS.get()->getType()->isVectorType() ||
7896       RHS.get()->getType()->isVectorType()) {
7897     QualType compType = CheckVectorOperands(
7898         LHS, RHS, Loc, CompLHSTy,
7899         /*AllowBothBool*/getLangOpts().AltiVec,
7900         /*AllowBoolConversions*/getLangOpts().ZVector);
7901     if (CompLHSTy) *CompLHSTy = compType;
7902     return compType;
7903   }
7904 
7905   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7906   if (LHS.isInvalid() || RHS.isInvalid())
7907     return QualType();
7908 
7909   // Diagnose "string literal" '+' int and string '+' "char literal".
7910   if (Opc == BO_Add) {
7911     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7912     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7913   }
7914 
7915   // handle the common case first (both operands are arithmetic).
7916   if (!compType.isNull() && compType->isArithmeticType()) {
7917     if (CompLHSTy) *CompLHSTy = compType;
7918     return compType;
7919   }
7920 
7921   // Type-checking.  Ultimately the pointer's going to be in PExp;
7922   // note that we bias towards the LHS being the pointer.
7923   Expr *PExp = LHS.get(), *IExp = RHS.get();
7924 
7925   bool isObjCPointer;
7926   if (PExp->getType()->isPointerType()) {
7927     isObjCPointer = false;
7928   } else if (PExp->getType()->isObjCObjectPointerType()) {
7929     isObjCPointer = true;
7930   } else {
7931     std::swap(PExp, IExp);
7932     if (PExp->getType()->isPointerType()) {
7933       isObjCPointer = false;
7934     } else if (PExp->getType()->isObjCObjectPointerType()) {
7935       isObjCPointer = true;
7936     } else {
7937       return InvalidOperands(Loc, LHS, RHS);
7938     }
7939   }
7940   assert(PExp->getType()->isAnyPointerType());
7941 
7942   if (!IExp->getType()->isIntegerType())
7943     return InvalidOperands(Loc, LHS, RHS);
7944 
7945   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7946     return QualType();
7947 
7948   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7949     return QualType();
7950 
7951   // Check array bounds for pointer arithemtic
7952   CheckArrayAccess(PExp, IExp);
7953 
7954   if (CompLHSTy) {
7955     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7956     if (LHSTy.isNull()) {
7957       LHSTy = LHS.get()->getType();
7958       if (LHSTy->isPromotableIntegerType())
7959         LHSTy = Context.getPromotedIntegerType(LHSTy);
7960     }
7961     *CompLHSTy = LHSTy;
7962   }
7963 
7964   return PExp->getType();
7965 }
7966 
7967 // C99 6.5.6
7968 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7969                                         SourceLocation Loc,
7970                                         QualType* CompLHSTy) {
7971   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7972 
7973   if (LHS.get()->getType()->isVectorType() ||
7974       RHS.get()->getType()->isVectorType()) {
7975     QualType compType = CheckVectorOperands(
7976         LHS, RHS, Loc, CompLHSTy,
7977         /*AllowBothBool*/getLangOpts().AltiVec,
7978         /*AllowBoolConversions*/getLangOpts().ZVector);
7979     if (CompLHSTy) *CompLHSTy = compType;
7980     return compType;
7981   }
7982 
7983   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7984   if (LHS.isInvalid() || RHS.isInvalid())
7985     return QualType();
7986 
7987   // Enforce type constraints: C99 6.5.6p3.
7988 
7989   // Handle the common case first (both operands are arithmetic).
7990   if (!compType.isNull() && compType->isArithmeticType()) {
7991     if (CompLHSTy) *CompLHSTy = compType;
7992     return compType;
7993   }
7994 
7995   // Either ptr - int   or   ptr - ptr.
7996   if (LHS.get()->getType()->isAnyPointerType()) {
7997     QualType lpointee = LHS.get()->getType()->getPointeeType();
7998 
7999     // Diagnose bad cases where we step over interface counts.
8000     if (LHS.get()->getType()->isObjCObjectPointerType() &&
8001         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
8002       return QualType();
8003 
8004     // The result type of a pointer-int computation is the pointer type.
8005     if (RHS.get()->getType()->isIntegerType()) {
8006       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
8007         return QualType();
8008 
8009       // Check array bounds for pointer arithemtic
8010       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
8011                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
8012 
8013       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8014       return LHS.get()->getType();
8015     }
8016 
8017     // Handle pointer-pointer subtractions.
8018     if (const PointerType *RHSPTy
8019           = RHS.get()->getType()->getAs<PointerType>()) {
8020       QualType rpointee = RHSPTy->getPointeeType();
8021 
8022       if (getLangOpts().CPlusPlus) {
8023         // Pointee types must be the same: C++ [expr.add]
8024         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
8025           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8026         }
8027       } else {
8028         // Pointee types must be compatible C99 6.5.6p3
8029         if (!Context.typesAreCompatible(
8030                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
8031                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
8032           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
8033           return QualType();
8034         }
8035       }
8036 
8037       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
8038                                                LHS.get(), RHS.get()))
8039         return QualType();
8040 
8041       // The pointee type may have zero size.  As an extension, a structure or
8042       // union may have zero size or an array may have zero length.  In this
8043       // case subtraction does not make sense.
8044       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
8045         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
8046         if (ElementSize.isZero()) {
8047           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
8048             << rpointee.getUnqualifiedType()
8049             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8050         }
8051       }
8052 
8053       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
8054       return Context.getPointerDiffType();
8055     }
8056   }
8057 
8058   return InvalidOperands(Loc, LHS, RHS);
8059 }
8060 
8061 static bool isScopedEnumerationType(QualType T) {
8062   if (const EnumType *ET = T->getAs<EnumType>())
8063     return ET->getDecl()->isScoped();
8064   return false;
8065 }
8066 
8067 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
8068                                    SourceLocation Loc, unsigned Opc,
8069                                    QualType LHSType) {
8070   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
8071   // so skip remaining warnings as we don't want to modify values within Sema.
8072   if (S.getLangOpts().OpenCL)
8073     return;
8074 
8075   llvm::APSInt Right;
8076   // Check right/shifter operand
8077   if (RHS.get()->isValueDependent() ||
8078       !RHS.get()->EvaluateAsInt(Right, S.Context))
8079     return;
8080 
8081   if (Right.isNegative()) {
8082     S.DiagRuntimeBehavior(Loc, RHS.get(),
8083                           S.PDiag(diag::warn_shift_negative)
8084                             << RHS.get()->getSourceRange());
8085     return;
8086   }
8087   llvm::APInt LeftBits(Right.getBitWidth(),
8088                        S.Context.getTypeSize(LHS.get()->getType()));
8089   if (Right.uge(LeftBits)) {
8090     S.DiagRuntimeBehavior(Loc, RHS.get(),
8091                           S.PDiag(diag::warn_shift_gt_typewidth)
8092                             << RHS.get()->getSourceRange());
8093     return;
8094   }
8095   if (Opc != BO_Shl)
8096     return;
8097 
8098   // When left shifting an ICE which is signed, we can check for overflow which
8099   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
8100   // integers have defined behavior modulo one more than the maximum value
8101   // representable in the result type, so never warn for those.
8102   llvm::APSInt Left;
8103   if (LHS.get()->isValueDependent() ||
8104       LHSType->hasUnsignedIntegerRepresentation() ||
8105       !LHS.get()->EvaluateAsInt(Left, S.Context))
8106     return;
8107 
8108   // If LHS does not have a signed type and non-negative value
8109   // then, the behavior is undefined. Warn about it.
8110   if (Left.isNegative()) {
8111     S.DiagRuntimeBehavior(Loc, LHS.get(),
8112                           S.PDiag(diag::warn_shift_lhs_negative)
8113                             << LHS.get()->getSourceRange());
8114     return;
8115   }
8116 
8117   llvm::APInt ResultBits =
8118       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
8119   if (LeftBits.uge(ResultBits))
8120     return;
8121   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
8122   Result = Result.shl(Right);
8123 
8124   // Print the bit representation of the signed integer as an unsigned
8125   // hexadecimal number.
8126   SmallString<40> HexResult;
8127   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
8128 
8129   // If we are only missing a sign bit, this is less likely to result in actual
8130   // bugs -- if the result is cast back to an unsigned type, it will have the
8131   // expected value. Thus we place this behind a different warning that can be
8132   // turned off separately if needed.
8133   if (LeftBits == ResultBits - 1) {
8134     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
8135         << HexResult << LHSType
8136         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8137     return;
8138   }
8139 
8140   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
8141     << HexResult.str() << Result.getMinSignedBits() << LHSType
8142     << Left.getBitWidth() << LHS.get()->getSourceRange()
8143     << RHS.get()->getSourceRange();
8144 }
8145 
8146 /// \brief Return the resulting type when an OpenCL vector is shifted
8147 ///        by a scalar or vector shift amount.
8148 static QualType checkOpenCLVectorShift(Sema &S,
8149                                        ExprResult &LHS, ExprResult &RHS,
8150                                        SourceLocation Loc, bool IsCompAssign) {
8151   // OpenCL v1.1 s6.3.j says RHS can be a vector only if LHS is a vector.
8152   if (!LHS.get()->getType()->isVectorType()) {
8153     S.Diag(Loc, diag::err_shift_rhs_only_vector)
8154       << RHS.get()->getType() << LHS.get()->getType()
8155       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8156     return QualType();
8157   }
8158 
8159   if (!IsCompAssign) {
8160     LHS = S.UsualUnaryConversions(LHS.get());
8161     if (LHS.isInvalid()) return QualType();
8162   }
8163 
8164   RHS = S.UsualUnaryConversions(RHS.get());
8165   if (RHS.isInvalid()) return QualType();
8166 
8167   QualType LHSType = LHS.get()->getType();
8168   const VectorType *LHSVecTy = LHSType->getAs<VectorType>();
8169   QualType LHSEleType = LHSVecTy->getElementType();
8170 
8171   // Note that RHS might not be a vector.
8172   QualType RHSType = RHS.get()->getType();
8173   const VectorType *RHSVecTy = RHSType->getAs<VectorType>();
8174   QualType RHSEleType = RHSVecTy ? RHSVecTy->getElementType() : RHSType;
8175 
8176   // OpenCL v1.1 s6.3.j says that the operands need to be integers.
8177   if (!LHSEleType->isIntegerType()) {
8178     S.Diag(Loc, diag::err_typecheck_expect_int)
8179       << LHS.get()->getType() << LHS.get()->getSourceRange();
8180     return QualType();
8181   }
8182 
8183   if (!RHSEleType->isIntegerType()) {
8184     S.Diag(Loc, diag::err_typecheck_expect_int)
8185       << RHS.get()->getType() << RHS.get()->getSourceRange();
8186     return QualType();
8187   }
8188 
8189   if (RHSVecTy) {
8190     // OpenCL v1.1 s6.3.j says that for vector types, the operators
8191     // are applied component-wise. So if RHS is a vector, then ensure
8192     // that the number of elements is the same as LHS...
8193     if (RHSVecTy->getNumElements() != LHSVecTy->getNumElements()) {
8194       S.Diag(Loc, diag::err_typecheck_vector_lengths_not_equal)
8195         << LHS.get()->getType() << RHS.get()->getType()
8196         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8197       return QualType();
8198     }
8199   } else {
8200     // ...else expand RHS to match the number of elements in LHS.
8201     QualType VecTy =
8202       S.Context.getExtVectorType(RHSEleType, LHSVecTy->getNumElements());
8203     RHS = S.ImpCastExprToType(RHS.get(), VecTy, CK_VectorSplat);
8204   }
8205 
8206   return LHSType;
8207 }
8208 
8209 // C99 6.5.7
8210 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
8211                                   SourceLocation Loc, unsigned Opc,
8212                                   bool IsCompAssign) {
8213   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8214 
8215   // Vector shifts promote their scalar inputs to vector type.
8216   if (LHS.get()->getType()->isVectorType() ||
8217       RHS.get()->getType()->isVectorType()) {
8218     if (LangOpts.OpenCL)
8219       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8220     if (LangOpts.ZVector) {
8221       // The shift operators for the z vector extensions work basically
8222       // like OpenCL shifts, except that neither the LHS nor the RHS is
8223       // allowed to be a "vector bool".
8224       if (auto LHSVecType = LHS.get()->getType()->getAs<VectorType>())
8225         if (LHSVecType->getVectorKind() == VectorType::AltiVecBool)
8226           return InvalidOperands(Loc, LHS, RHS);
8227       if (auto RHSVecType = RHS.get()->getType()->getAs<VectorType>())
8228         if (RHSVecType->getVectorKind() == VectorType::AltiVecBool)
8229           return InvalidOperands(Loc, LHS, RHS);
8230       return checkOpenCLVectorShift(*this, LHS, RHS, Loc, IsCompAssign);
8231     }
8232     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
8233                                /*AllowBothBool*/true,
8234                                /*AllowBoolConversions*/false);
8235   }
8236 
8237   // Shifts don't perform usual arithmetic conversions, they just do integer
8238   // promotions on each operand. C99 6.5.7p3
8239 
8240   // For the LHS, do usual unary conversions, but then reset them away
8241   // if this is a compound assignment.
8242   ExprResult OldLHS = LHS;
8243   LHS = UsualUnaryConversions(LHS.get());
8244   if (LHS.isInvalid())
8245     return QualType();
8246   QualType LHSType = LHS.get()->getType();
8247   if (IsCompAssign) LHS = OldLHS;
8248 
8249   // The RHS is simpler.
8250   RHS = UsualUnaryConversions(RHS.get());
8251   if (RHS.isInvalid())
8252     return QualType();
8253   QualType RHSType = RHS.get()->getType();
8254 
8255   // C99 6.5.7p2: Each of the operands shall have integer type.
8256   if (!LHSType->hasIntegerRepresentation() ||
8257       !RHSType->hasIntegerRepresentation())
8258     return InvalidOperands(Loc, LHS, RHS);
8259 
8260   // C++0x: Don't allow scoped enums. FIXME: Use something better than
8261   // hasIntegerRepresentation() above instead of this.
8262   if (isScopedEnumerationType(LHSType) ||
8263       isScopedEnumerationType(RHSType)) {
8264     return InvalidOperands(Loc, LHS, RHS);
8265   }
8266   // Sanity-check shift operands
8267   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
8268 
8269   // "The type of the result is that of the promoted left operand."
8270   return LHSType;
8271 }
8272 
8273 static bool IsWithinTemplateSpecialization(Decl *D) {
8274   if (DeclContext *DC = D->getDeclContext()) {
8275     if (isa<ClassTemplateSpecializationDecl>(DC))
8276       return true;
8277     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
8278       return FD->isFunctionTemplateSpecialization();
8279   }
8280   return false;
8281 }
8282 
8283 /// If two different enums are compared, raise a warning.
8284 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
8285                                 Expr *RHS) {
8286   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
8287   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
8288 
8289   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
8290   if (!LHSEnumType)
8291     return;
8292   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
8293   if (!RHSEnumType)
8294     return;
8295 
8296   // Ignore anonymous enums.
8297   if (!LHSEnumType->getDecl()->getIdentifier())
8298     return;
8299   if (!RHSEnumType->getDecl()->getIdentifier())
8300     return;
8301 
8302   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
8303     return;
8304 
8305   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
8306       << LHSStrippedType << RHSStrippedType
8307       << LHS->getSourceRange() << RHS->getSourceRange();
8308 }
8309 
8310 /// \brief Diagnose bad pointer comparisons.
8311 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
8312                                               ExprResult &LHS, ExprResult &RHS,
8313                                               bool IsError) {
8314   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
8315                       : diag::ext_typecheck_comparison_of_distinct_pointers)
8316     << LHS.get()->getType() << RHS.get()->getType()
8317     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8318 }
8319 
8320 /// \brief Returns false if the pointers are converted to a composite type,
8321 /// true otherwise.
8322 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
8323                                            ExprResult &LHS, ExprResult &RHS) {
8324   // C++ [expr.rel]p2:
8325   //   [...] Pointer conversions (4.10) and qualification
8326   //   conversions (4.4) are performed on pointer operands (or on
8327   //   a pointer operand and a null pointer constant) to bring
8328   //   them to their composite pointer type. [...]
8329   //
8330   // C++ [expr.eq]p1 uses the same notion for (in)equality
8331   // comparisons of pointers.
8332 
8333   // C++ [expr.eq]p2:
8334   //   In addition, pointers to members can be compared, or a pointer to
8335   //   member and a null pointer constant. Pointer to member conversions
8336   //   (4.11) and qualification conversions (4.4) are performed to bring
8337   //   them to a common type. If one operand is a null pointer constant,
8338   //   the common type is the type of the other operand. Otherwise, the
8339   //   common type is a pointer to member type similar (4.4) to the type
8340   //   of one of the operands, with a cv-qualification signature (4.4)
8341   //   that is the union of the cv-qualification signatures of the operand
8342   //   types.
8343 
8344   QualType LHSType = LHS.get()->getType();
8345   QualType RHSType = RHS.get()->getType();
8346   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
8347          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
8348 
8349   bool NonStandardCompositeType = false;
8350   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
8351   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
8352   if (T.isNull()) {
8353     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
8354     return true;
8355   }
8356 
8357   if (NonStandardCompositeType)
8358     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
8359       << LHSType << RHSType << T << LHS.get()->getSourceRange()
8360       << RHS.get()->getSourceRange();
8361 
8362   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
8363   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
8364   return false;
8365 }
8366 
8367 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
8368                                                     ExprResult &LHS,
8369                                                     ExprResult &RHS,
8370                                                     bool IsError) {
8371   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
8372                       : diag::ext_typecheck_comparison_of_fptr_to_void)
8373     << LHS.get()->getType() << RHS.get()->getType()
8374     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8375 }
8376 
8377 static bool isObjCObjectLiteral(ExprResult &E) {
8378   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
8379   case Stmt::ObjCArrayLiteralClass:
8380   case Stmt::ObjCDictionaryLiteralClass:
8381   case Stmt::ObjCStringLiteralClass:
8382   case Stmt::ObjCBoxedExprClass:
8383     return true;
8384   default:
8385     // Note that ObjCBoolLiteral is NOT an object literal!
8386     return false;
8387   }
8388 }
8389 
8390 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
8391   const ObjCObjectPointerType *Type =
8392     LHS->getType()->getAs<ObjCObjectPointerType>();
8393 
8394   // If this is not actually an Objective-C object, bail out.
8395   if (!Type)
8396     return false;
8397 
8398   // Get the LHS object's interface type.
8399   QualType InterfaceType = Type->getPointeeType();
8400 
8401   // If the RHS isn't an Objective-C object, bail out.
8402   if (!RHS->getType()->isObjCObjectPointerType())
8403     return false;
8404 
8405   // Try to find the -isEqual: method.
8406   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
8407   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
8408                                                       InterfaceType,
8409                                                       /*instance=*/true);
8410   if (!Method) {
8411     if (Type->isObjCIdType()) {
8412       // For 'id', just check the global pool.
8413       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
8414                                                   /*receiverId=*/true);
8415     } else {
8416       // Check protocols.
8417       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
8418                                              /*instance=*/true);
8419     }
8420   }
8421 
8422   if (!Method)
8423     return false;
8424 
8425   QualType T = Method->parameters()[0]->getType();
8426   if (!T->isObjCObjectPointerType())
8427     return false;
8428 
8429   QualType R = Method->getReturnType();
8430   if (!R->isScalarType())
8431     return false;
8432 
8433   return true;
8434 }
8435 
8436 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
8437   FromE = FromE->IgnoreParenImpCasts();
8438   switch (FromE->getStmtClass()) {
8439     default:
8440       break;
8441     case Stmt::ObjCStringLiteralClass:
8442       // "string literal"
8443       return LK_String;
8444     case Stmt::ObjCArrayLiteralClass:
8445       // "array literal"
8446       return LK_Array;
8447     case Stmt::ObjCDictionaryLiteralClass:
8448       // "dictionary literal"
8449       return LK_Dictionary;
8450     case Stmt::BlockExprClass:
8451       return LK_Block;
8452     case Stmt::ObjCBoxedExprClass: {
8453       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
8454       switch (Inner->getStmtClass()) {
8455         case Stmt::IntegerLiteralClass:
8456         case Stmt::FloatingLiteralClass:
8457         case Stmt::CharacterLiteralClass:
8458         case Stmt::ObjCBoolLiteralExprClass:
8459         case Stmt::CXXBoolLiteralExprClass:
8460           // "numeric literal"
8461           return LK_Numeric;
8462         case Stmt::ImplicitCastExprClass: {
8463           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
8464           // Boolean literals can be represented by implicit casts.
8465           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
8466             return LK_Numeric;
8467           break;
8468         }
8469         default:
8470           break;
8471       }
8472       return LK_Boxed;
8473     }
8474   }
8475   return LK_None;
8476 }
8477 
8478 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
8479                                           ExprResult &LHS, ExprResult &RHS,
8480                                           BinaryOperator::Opcode Opc){
8481   Expr *Literal;
8482   Expr *Other;
8483   if (isObjCObjectLiteral(LHS)) {
8484     Literal = LHS.get();
8485     Other = RHS.get();
8486   } else {
8487     Literal = RHS.get();
8488     Other = LHS.get();
8489   }
8490 
8491   // Don't warn on comparisons against nil.
8492   Other = Other->IgnoreParenCasts();
8493   if (Other->isNullPointerConstant(S.getASTContext(),
8494                                    Expr::NPC_ValueDependentIsNotNull))
8495     return;
8496 
8497   // This should be kept in sync with warn_objc_literal_comparison.
8498   // LK_String should always be after the other literals, since it has its own
8499   // warning flag.
8500   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
8501   assert(LiteralKind != Sema::LK_Block);
8502   if (LiteralKind == Sema::LK_None) {
8503     llvm_unreachable("Unknown Objective-C object literal kind");
8504   }
8505 
8506   if (LiteralKind == Sema::LK_String)
8507     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
8508       << Literal->getSourceRange();
8509   else
8510     S.Diag(Loc, diag::warn_objc_literal_comparison)
8511       << LiteralKind << Literal->getSourceRange();
8512 
8513   if (BinaryOperator::isEqualityOp(Opc) &&
8514       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
8515     SourceLocation Start = LHS.get()->getLocStart();
8516     SourceLocation End = S.getLocForEndOfToken(RHS.get()->getLocEnd());
8517     CharSourceRange OpRange =
8518       CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc));
8519 
8520     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
8521       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
8522       << FixItHint::CreateReplacement(OpRange, " isEqual:")
8523       << FixItHint::CreateInsertion(End, "]");
8524   }
8525 }
8526 
8527 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
8528                                                 ExprResult &RHS,
8529                                                 SourceLocation Loc,
8530                                                 unsigned OpaqueOpc) {
8531   // Check that left hand side is !something.
8532   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
8533   if (!UO || UO->getOpcode() != UO_LNot) return;
8534 
8535   // Only check if the right hand side is non-bool arithmetic type.
8536   if (RHS.get()->isKnownToHaveBooleanValue()) return;
8537 
8538   // Make sure that the something in !something is not bool.
8539   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
8540   if (SubExpr->isKnownToHaveBooleanValue()) return;
8541 
8542   // Emit warning.
8543   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
8544       << Loc;
8545 
8546   // First note suggest !(x < y)
8547   SourceLocation FirstOpen = SubExpr->getLocStart();
8548   SourceLocation FirstClose = RHS.get()->getLocEnd();
8549   FirstClose = S.getLocForEndOfToken(FirstClose);
8550   if (FirstClose.isInvalid())
8551     FirstOpen = SourceLocation();
8552   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
8553       << FixItHint::CreateInsertion(FirstOpen, "(")
8554       << FixItHint::CreateInsertion(FirstClose, ")");
8555 
8556   // Second note suggests (!x) < y
8557   SourceLocation SecondOpen = LHS.get()->getLocStart();
8558   SourceLocation SecondClose = LHS.get()->getLocEnd();
8559   SecondClose = S.getLocForEndOfToken(SecondClose);
8560   if (SecondClose.isInvalid())
8561     SecondOpen = SourceLocation();
8562   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
8563       << FixItHint::CreateInsertion(SecondOpen, "(")
8564       << FixItHint::CreateInsertion(SecondClose, ")");
8565 }
8566 
8567 // Get the decl for a simple expression: a reference to a variable,
8568 // an implicit C++ field reference, or an implicit ObjC ivar reference.
8569 static ValueDecl *getCompareDecl(Expr *E) {
8570   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
8571     return DR->getDecl();
8572   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
8573     if (Ivar->isFreeIvar())
8574       return Ivar->getDecl();
8575   }
8576   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
8577     if (Mem->isImplicitAccess())
8578       return Mem->getMemberDecl();
8579   }
8580   return nullptr;
8581 }
8582 
8583 // C99 6.5.8, C++ [expr.rel]
8584 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
8585                                     SourceLocation Loc, unsigned OpaqueOpc,
8586                                     bool IsRelational) {
8587   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
8588 
8589   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
8590 
8591   // Handle vector comparisons separately.
8592   if (LHS.get()->getType()->isVectorType() ||
8593       RHS.get()->getType()->isVectorType())
8594     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
8595 
8596   QualType LHSType = LHS.get()->getType();
8597   QualType RHSType = RHS.get()->getType();
8598 
8599   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
8600   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
8601 
8602   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
8603   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
8604 
8605   if (!LHSType->hasFloatingRepresentation() &&
8606       !(LHSType->isBlockPointerType() && IsRelational) &&
8607       !LHS.get()->getLocStart().isMacroID() &&
8608       !RHS.get()->getLocStart().isMacroID() &&
8609       ActiveTemplateInstantiations.empty()) {
8610     // For non-floating point types, check for self-comparisons of the form
8611     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8612     // often indicate logic errors in the program.
8613     //
8614     // NOTE: Don't warn about comparison expressions resulting from macro
8615     // expansion. Also don't warn about comparisons which are only self
8616     // comparisons within a template specialization. The warnings should catch
8617     // obvious cases in the definition of the template anyways. The idea is to
8618     // warn when the typed comparison operator will always evaluate to the same
8619     // result.
8620     ValueDecl *DL = getCompareDecl(LHSStripped);
8621     ValueDecl *DR = getCompareDecl(RHSStripped);
8622     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
8623       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8624                           << 0 // self-
8625                           << (Opc == BO_EQ
8626                               || Opc == BO_LE
8627                               || Opc == BO_GE));
8628     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
8629                !DL->getType()->isReferenceType() &&
8630                !DR->getType()->isReferenceType()) {
8631         // what is it always going to eval to?
8632         char always_evals_to;
8633         switch(Opc) {
8634         case BO_EQ: // e.g. array1 == array2
8635           always_evals_to = 0; // false
8636           break;
8637         case BO_NE: // e.g. array1 != array2
8638           always_evals_to = 1; // true
8639           break;
8640         default:
8641           // best we can say is 'a constant'
8642           always_evals_to = 2; // e.g. array1 <= array2
8643           break;
8644         }
8645         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
8646                             << 1 // array
8647                             << always_evals_to);
8648     }
8649 
8650     if (isa<CastExpr>(LHSStripped))
8651       LHSStripped = LHSStripped->IgnoreParenCasts();
8652     if (isa<CastExpr>(RHSStripped))
8653       RHSStripped = RHSStripped->IgnoreParenCasts();
8654 
8655     // Warn about comparisons against a string constant (unless the other
8656     // operand is null), the user probably wants strcmp.
8657     Expr *literalString = nullptr;
8658     Expr *literalStringStripped = nullptr;
8659     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
8660         !RHSStripped->isNullPointerConstant(Context,
8661                                             Expr::NPC_ValueDependentIsNull)) {
8662       literalString = LHS.get();
8663       literalStringStripped = LHSStripped;
8664     } else if ((isa<StringLiteral>(RHSStripped) ||
8665                 isa<ObjCEncodeExpr>(RHSStripped)) &&
8666                !LHSStripped->isNullPointerConstant(Context,
8667                                             Expr::NPC_ValueDependentIsNull)) {
8668       literalString = RHS.get();
8669       literalStringStripped = RHSStripped;
8670     }
8671 
8672     if (literalString) {
8673       DiagRuntimeBehavior(Loc, nullptr,
8674         PDiag(diag::warn_stringcompare)
8675           << isa<ObjCEncodeExpr>(literalStringStripped)
8676           << literalString->getSourceRange());
8677     }
8678   }
8679 
8680   // C99 6.5.8p3 / C99 6.5.9p4
8681   UsualArithmeticConversions(LHS, RHS);
8682   if (LHS.isInvalid() || RHS.isInvalid())
8683     return QualType();
8684 
8685   LHSType = LHS.get()->getType();
8686   RHSType = RHS.get()->getType();
8687 
8688   // The result of comparisons is 'bool' in C++, 'int' in C.
8689   QualType ResultTy = Context.getLogicalOperationType();
8690 
8691   if (IsRelational) {
8692     if (LHSType->isRealType() && RHSType->isRealType())
8693       return ResultTy;
8694   } else {
8695     // Check for comparisons of floating point operands using != and ==.
8696     if (LHSType->hasFloatingRepresentation())
8697       CheckFloatComparison(Loc, LHS.get(), RHS.get());
8698 
8699     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
8700       return ResultTy;
8701   }
8702 
8703   const Expr::NullPointerConstantKind LHSNullKind =
8704       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8705   const Expr::NullPointerConstantKind RHSNullKind =
8706       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
8707   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
8708   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
8709 
8710   if (!IsRelational && LHSIsNull != RHSIsNull) {
8711     bool IsEquality = Opc == BO_EQ;
8712     if (RHSIsNull)
8713       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
8714                                    RHS.get()->getSourceRange());
8715     else
8716       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
8717                                    LHS.get()->getSourceRange());
8718   }
8719 
8720   // All of the following pointer-related warnings are GCC extensions, except
8721   // when handling null pointer constants.
8722   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
8723     QualType LCanPointeeTy =
8724       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8725     QualType RCanPointeeTy =
8726       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
8727 
8728     if (getLangOpts().CPlusPlus) {
8729       if (LCanPointeeTy == RCanPointeeTy)
8730         return ResultTy;
8731       if (!IsRelational &&
8732           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8733         // Valid unless comparison between non-null pointer and function pointer
8734         // This is a gcc extension compatibility comparison.
8735         // In a SFINAE context, we treat this as a hard error to maintain
8736         // conformance with the C++ standard.
8737         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8738             && !LHSIsNull && !RHSIsNull) {
8739           diagnoseFunctionPointerToVoidComparison(
8740               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
8741 
8742           if (isSFINAEContext())
8743             return QualType();
8744 
8745           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8746           return ResultTy;
8747         }
8748       }
8749 
8750       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8751         return QualType();
8752       else
8753         return ResultTy;
8754     }
8755     // C99 6.5.9p2 and C99 6.5.8p2
8756     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
8757                                    RCanPointeeTy.getUnqualifiedType())) {
8758       // Valid unless a relational comparison of function pointers
8759       if (IsRelational && LCanPointeeTy->isFunctionType()) {
8760         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
8761           << LHSType << RHSType << LHS.get()->getSourceRange()
8762           << RHS.get()->getSourceRange();
8763       }
8764     } else if (!IsRelational &&
8765                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
8766       // Valid unless comparison between non-null pointer and function pointer
8767       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
8768           && !LHSIsNull && !RHSIsNull)
8769         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
8770                                                 /*isError*/false);
8771     } else {
8772       // Invalid
8773       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
8774     }
8775     if (LCanPointeeTy != RCanPointeeTy) {
8776       if (getLangOpts().OpenCL) {
8777         const PointerType *LHSPtr = LHSType->getAs<PointerType>();
8778         if (!LHSPtr->isAddressSpaceOverlapping(*RHSType->getAs<PointerType>())) {
8779           Diag(Loc,
8780                diag::err_typecheck_op_on_nonoverlapping_address_space_pointers)
8781               << LHSType << RHSType << 0 /* comparison */
8782               << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
8783         }
8784       }
8785       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
8786       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
8787       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
8788                                                : CK_BitCast;
8789       if (LHSIsNull && !RHSIsNull)
8790         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
8791       else
8792         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
8793     }
8794     return ResultTy;
8795   }
8796 
8797   if (getLangOpts().CPlusPlus) {
8798     // Comparison of nullptr_t with itself.
8799     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
8800       return ResultTy;
8801 
8802     // Comparison of pointers with null pointer constants and equality
8803     // comparisons of member pointers to null pointer constants.
8804     if (RHSIsNull &&
8805         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
8806          (!IsRelational &&
8807           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
8808       RHS = ImpCastExprToType(RHS.get(), LHSType,
8809                         LHSType->isMemberPointerType()
8810                           ? CK_NullToMemberPointer
8811                           : CK_NullToPointer);
8812       return ResultTy;
8813     }
8814     if (LHSIsNull &&
8815         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
8816          (!IsRelational &&
8817           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
8818       LHS = ImpCastExprToType(LHS.get(), RHSType,
8819                         RHSType->isMemberPointerType()
8820                           ? CK_NullToMemberPointer
8821                           : CK_NullToPointer);
8822       return ResultTy;
8823     }
8824 
8825     // Comparison of member pointers.
8826     if (!IsRelational &&
8827         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8828       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8829         return QualType();
8830       else
8831         return ResultTy;
8832     }
8833 
8834     // Handle scoped enumeration types specifically, since they don't promote
8835     // to integers.
8836     if (LHS.get()->getType()->isEnumeralType() &&
8837         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8838                                        RHS.get()->getType()))
8839       return ResultTy;
8840   }
8841 
8842   // Handle block pointer types.
8843   if (!IsRelational && LHSType->isBlockPointerType() &&
8844       RHSType->isBlockPointerType()) {
8845     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8846     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8847 
8848     if (!LHSIsNull && !RHSIsNull &&
8849         !Context.typesAreCompatible(lpointee, rpointee)) {
8850       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8851         << LHSType << RHSType << LHS.get()->getSourceRange()
8852         << RHS.get()->getSourceRange();
8853     }
8854     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8855     return ResultTy;
8856   }
8857 
8858   // Allow block pointers to be compared with null pointer constants.
8859   if (!IsRelational
8860       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8861           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8862     if (!LHSIsNull && !RHSIsNull) {
8863       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8864              ->getPointeeType()->isVoidType())
8865             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8866                 ->getPointeeType()->isVoidType())))
8867         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8868           << LHSType << RHSType << LHS.get()->getSourceRange()
8869           << RHS.get()->getSourceRange();
8870     }
8871     if (LHSIsNull && !RHSIsNull)
8872       LHS = ImpCastExprToType(LHS.get(), RHSType,
8873                               RHSType->isPointerType() ? CK_BitCast
8874                                 : CK_AnyPointerToBlockPointerCast);
8875     else
8876       RHS = ImpCastExprToType(RHS.get(), LHSType,
8877                               LHSType->isPointerType() ? CK_BitCast
8878                                 : CK_AnyPointerToBlockPointerCast);
8879     return ResultTy;
8880   }
8881 
8882   if (LHSType->isObjCObjectPointerType() ||
8883       RHSType->isObjCObjectPointerType()) {
8884     const PointerType *LPT = LHSType->getAs<PointerType>();
8885     const PointerType *RPT = RHSType->getAs<PointerType>();
8886     if (LPT || RPT) {
8887       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8888       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8889 
8890       if (!LPtrToVoid && !RPtrToVoid &&
8891           !Context.typesAreCompatible(LHSType, RHSType)) {
8892         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8893                                           /*isError*/false);
8894       }
8895       if (LHSIsNull && !RHSIsNull) {
8896         Expr *E = LHS.get();
8897         if (getLangOpts().ObjCAutoRefCount)
8898           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8899         LHS = ImpCastExprToType(E, RHSType,
8900                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8901       }
8902       else {
8903         Expr *E = RHS.get();
8904         if (getLangOpts().ObjCAutoRefCount)
8905           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion, false,
8906                                  Opc);
8907         RHS = ImpCastExprToType(E, LHSType,
8908                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8909       }
8910       return ResultTy;
8911     }
8912     if (LHSType->isObjCObjectPointerType() &&
8913         RHSType->isObjCObjectPointerType()) {
8914       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8915         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8916                                           /*isError*/false);
8917       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8918         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8919 
8920       if (LHSIsNull && !RHSIsNull)
8921         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8922       else
8923         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8924       return ResultTy;
8925     }
8926   }
8927   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8928       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8929     unsigned DiagID = 0;
8930     bool isError = false;
8931     if (LangOpts.DebuggerSupport) {
8932       // Under a debugger, allow the comparison of pointers to integers,
8933       // since users tend to want to compare addresses.
8934     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8935         (RHSIsNull && RHSType->isIntegerType())) {
8936       if (IsRelational && !getLangOpts().CPlusPlus)
8937         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8938     } else if (IsRelational && !getLangOpts().CPlusPlus)
8939       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8940     else if (getLangOpts().CPlusPlus) {
8941       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8942       isError = true;
8943     } else
8944       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8945 
8946     if (DiagID) {
8947       Diag(Loc, DiagID)
8948         << LHSType << RHSType << LHS.get()->getSourceRange()
8949         << RHS.get()->getSourceRange();
8950       if (isError)
8951         return QualType();
8952     }
8953 
8954     if (LHSType->isIntegerType())
8955       LHS = ImpCastExprToType(LHS.get(), RHSType,
8956                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8957     else
8958       RHS = ImpCastExprToType(RHS.get(), LHSType,
8959                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8960     return ResultTy;
8961   }
8962 
8963   // Handle block pointers.
8964   if (!IsRelational && RHSIsNull
8965       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8966     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8967     return ResultTy;
8968   }
8969   if (!IsRelational && LHSIsNull
8970       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8971     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8972     return ResultTy;
8973   }
8974 
8975   return InvalidOperands(Loc, LHS, RHS);
8976 }
8977 
8978 
8979 // Return a signed type that is of identical size and number of elements.
8980 // For floating point vectors, return an integer type of identical size
8981 // and number of elements.
8982 QualType Sema::GetSignedVectorType(QualType V) {
8983   const VectorType *VTy = V->getAs<VectorType>();
8984   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8985   if (TypeSize == Context.getTypeSize(Context.CharTy))
8986     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8987   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8988     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8989   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8990     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8991   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8992     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8993   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8994          "Unhandled vector element size in vector compare");
8995   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8996 }
8997 
8998 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8999 /// operates on extended vector types.  Instead of producing an IntTy result,
9000 /// like a scalar comparison, a vector comparison produces a vector of integer
9001 /// types.
9002 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
9003                                           SourceLocation Loc,
9004                                           bool IsRelational) {
9005   // Check to make sure we're operating on vectors of the same type and width,
9006   // Allowing one side to be a scalar of element type.
9007   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false,
9008                               /*AllowBothBool*/true,
9009                               /*AllowBoolConversions*/getLangOpts().ZVector);
9010   if (vType.isNull())
9011     return vType;
9012 
9013   QualType LHSType = LHS.get()->getType();
9014 
9015   // If AltiVec, the comparison results in a numeric type, i.e.
9016   // bool for C++, int for C
9017   if (getLangOpts().AltiVec &&
9018       vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
9019     return Context.getLogicalOperationType();
9020 
9021   // For non-floating point types, check for self-comparisons of the form
9022   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
9023   // often indicate logic errors in the program.
9024   if (!LHSType->hasFloatingRepresentation() &&
9025       ActiveTemplateInstantiations.empty()) {
9026     if (DeclRefExpr* DRL
9027           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
9028       if (DeclRefExpr* DRR
9029             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
9030         if (DRL->getDecl() == DRR->getDecl())
9031           DiagRuntimeBehavior(Loc, nullptr,
9032                               PDiag(diag::warn_comparison_always)
9033                                 << 0 // self-
9034                                 << 2 // "a constant"
9035                               );
9036   }
9037 
9038   // Check for comparisons of floating point operands using != and ==.
9039   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
9040     assert (RHS.get()->getType()->hasFloatingRepresentation());
9041     CheckFloatComparison(Loc, LHS.get(), RHS.get());
9042   }
9043 
9044   // Return a signed type for the vector.
9045   return GetSignedVectorType(LHSType);
9046 }
9047 
9048 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
9049                                           SourceLocation Loc) {
9050   // Ensure that either both operands are of the same vector type, or
9051   // one operand is of a vector type and the other is of its element type.
9052   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false,
9053                                        /*AllowBothBool*/true,
9054                                        /*AllowBoolConversions*/false);
9055   if (vType.isNull())
9056     return InvalidOperands(Loc, LHS, RHS);
9057   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
9058       vType->hasFloatingRepresentation())
9059     return InvalidOperands(Loc, LHS, RHS);
9060 
9061   return GetSignedVectorType(LHS.get()->getType());
9062 }
9063 
9064 inline QualType Sema::CheckBitwiseOperands(
9065   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
9066   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
9067 
9068   if (LHS.get()->getType()->isVectorType() ||
9069       RHS.get()->getType()->isVectorType()) {
9070     if (LHS.get()->getType()->hasIntegerRepresentation() &&
9071         RHS.get()->getType()->hasIntegerRepresentation())
9072       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign,
9073                         /*AllowBothBool*/true,
9074                         /*AllowBoolConversions*/getLangOpts().ZVector);
9075     return InvalidOperands(Loc, LHS, RHS);
9076   }
9077 
9078   ExprResult LHSResult = LHS, RHSResult = RHS;
9079   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
9080                                                  IsCompAssign);
9081   if (LHSResult.isInvalid() || RHSResult.isInvalid())
9082     return QualType();
9083   LHS = LHSResult.get();
9084   RHS = RHSResult.get();
9085 
9086   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
9087     return compType;
9088   return InvalidOperands(Loc, LHS, RHS);
9089 }
9090 
9091 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
9092   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
9093 
9094   // Check vector operands differently.
9095   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
9096     return CheckVectorLogicalOperands(LHS, RHS, Loc);
9097 
9098   // Diagnose cases where the user write a logical and/or but probably meant a
9099   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
9100   // is a constant.
9101   if (LHS.get()->getType()->isIntegerType() &&
9102       !LHS.get()->getType()->isBooleanType() &&
9103       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
9104       // Don't warn in macros or template instantiations.
9105       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
9106     // If the RHS can be constant folded, and if it constant folds to something
9107     // that isn't 0 or 1 (which indicate a potential logical operation that
9108     // happened to fold to true/false) then warn.
9109     // Parens on the RHS are ignored.
9110     llvm::APSInt Result;
9111     if (RHS.get()->EvaluateAsInt(Result, Context))
9112       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
9113            !RHS.get()->getExprLoc().isMacroID()) ||
9114           (Result != 0 && Result != 1)) {
9115         Diag(Loc, diag::warn_logical_instead_of_bitwise)
9116           << RHS.get()->getSourceRange()
9117           << (Opc == BO_LAnd ? "&&" : "||");
9118         // Suggest replacing the logical operator with the bitwise version
9119         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
9120             << (Opc == BO_LAnd ? "&" : "|")
9121             << FixItHint::CreateReplacement(SourceRange(
9122                                                  Loc, getLocForEndOfToken(Loc)),
9123                                             Opc == BO_LAnd ? "&" : "|");
9124         if (Opc == BO_LAnd)
9125           // Suggest replacing "Foo() && kNonZero" with "Foo()"
9126           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
9127               << FixItHint::CreateRemoval(
9128                   SourceRange(getLocForEndOfToken(LHS.get()->getLocEnd()),
9129                               RHS.get()->getLocEnd()));
9130       }
9131   }
9132 
9133   if (!Context.getLangOpts().CPlusPlus) {
9134     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
9135     // not operate on the built-in scalar and vector float types.
9136     if (Context.getLangOpts().OpenCL &&
9137         Context.getLangOpts().OpenCLVersion < 120) {
9138       if (LHS.get()->getType()->isFloatingType() ||
9139           RHS.get()->getType()->isFloatingType())
9140         return InvalidOperands(Loc, LHS, RHS);
9141     }
9142 
9143     LHS = UsualUnaryConversions(LHS.get());
9144     if (LHS.isInvalid())
9145       return QualType();
9146 
9147     RHS = UsualUnaryConversions(RHS.get());
9148     if (RHS.isInvalid())
9149       return QualType();
9150 
9151     if (!LHS.get()->getType()->isScalarType() ||
9152         !RHS.get()->getType()->isScalarType())
9153       return InvalidOperands(Loc, LHS, RHS);
9154 
9155     return Context.IntTy;
9156   }
9157 
9158   // The following is safe because we only use this method for
9159   // non-overloadable operands.
9160 
9161   // C++ [expr.log.and]p1
9162   // C++ [expr.log.or]p1
9163   // The operands are both contextually converted to type bool.
9164   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
9165   if (LHSRes.isInvalid())
9166     return InvalidOperands(Loc, LHS, RHS);
9167   LHS = LHSRes;
9168 
9169   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
9170   if (RHSRes.isInvalid())
9171     return InvalidOperands(Loc, LHS, RHS);
9172   RHS = RHSRes;
9173 
9174   // C++ [expr.log.and]p2
9175   // C++ [expr.log.or]p2
9176   // The result is a bool.
9177   return Context.BoolTy;
9178 }
9179 
9180 static bool IsReadonlyMessage(Expr *E, Sema &S) {
9181   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
9182   if (!ME) return false;
9183   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
9184   ObjCMessageExpr *Base =
9185     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
9186   if (!Base) return false;
9187   return Base->getMethodDecl() != nullptr;
9188 }
9189 
9190 /// Is the given expression (which must be 'const') a reference to a
9191 /// variable which was originally non-const, but which has become
9192 /// 'const' due to being captured within a block?
9193 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
9194 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
9195   assert(E->isLValue() && E->getType().isConstQualified());
9196   E = E->IgnoreParens();
9197 
9198   // Must be a reference to a declaration from an enclosing scope.
9199   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
9200   if (!DRE) return NCCK_None;
9201   if (!DRE->refersToEnclosingVariableOrCapture()) return NCCK_None;
9202 
9203   // The declaration must be a variable which is not declared 'const'.
9204   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
9205   if (!var) return NCCK_None;
9206   if (var->getType().isConstQualified()) return NCCK_None;
9207   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
9208 
9209   // Decide whether the first capture was for a block or a lambda.
9210   DeclContext *DC = S.CurContext, *Prev = nullptr;
9211   while (DC != var->getDeclContext()) {
9212     Prev = DC;
9213     DC = DC->getParent();
9214   }
9215   // Unless we have an init-capture, we've gone one step too far.
9216   if (!var->isInitCapture())
9217     DC = Prev;
9218   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
9219 }
9220 
9221 static bool IsTypeModifiable(QualType Ty, bool IsDereference) {
9222   Ty = Ty.getNonReferenceType();
9223   if (IsDereference && Ty->isPointerType())
9224     Ty = Ty->getPointeeType();
9225   return !Ty.isConstQualified();
9226 }
9227 
9228 /// Emit the "read-only variable not assignable" error and print notes to give
9229 /// more information about why the variable is not assignable, such as pointing
9230 /// to the declaration of a const variable, showing that a method is const, or
9231 /// that the function is returning a const reference.
9232 static void DiagnoseConstAssignment(Sema &S, const Expr *E,
9233                                     SourceLocation Loc) {
9234   // Update err_typecheck_assign_const and note_typecheck_assign_const
9235   // when this enum is changed.
9236   enum {
9237     ConstFunction,
9238     ConstVariable,
9239     ConstMember,
9240     ConstMethod,
9241     ConstUnknown,  // Keep as last element
9242   };
9243 
9244   SourceRange ExprRange = E->getSourceRange();
9245 
9246   // Only emit one error on the first const found.  All other consts will emit
9247   // a note to the error.
9248   bool DiagnosticEmitted = false;
9249 
9250   // Track if the current expression is the result of a derefence, and if the
9251   // next checked expression is the result of a derefence.
9252   bool IsDereference = false;
9253   bool NextIsDereference = false;
9254 
9255   // Loop to process MemberExpr chains.
9256   while (true) {
9257     IsDereference = NextIsDereference;
9258     NextIsDereference = false;
9259 
9260     E = E->IgnoreParenImpCasts();
9261     if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
9262       NextIsDereference = ME->isArrow();
9263       const ValueDecl *VD = ME->getMemberDecl();
9264       if (const FieldDecl *Field = dyn_cast<FieldDecl>(VD)) {
9265         // Mutable fields can be modified even if the class is const.
9266         if (Field->isMutable()) {
9267           assert(DiagnosticEmitted && "Expected diagnostic not emitted.");
9268           break;
9269         }
9270 
9271         if (!IsTypeModifiable(Field->getType(), IsDereference)) {
9272           if (!DiagnosticEmitted) {
9273             S.Diag(Loc, diag::err_typecheck_assign_const)
9274                 << ExprRange << ConstMember << false /*static*/ << Field
9275                 << Field->getType();
9276             DiagnosticEmitted = true;
9277           }
9278           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9279               << ConstMember << false /*static*/ << Field << Field->getType()
9280               << Field->getSourceRange();
9281         }
9282         E = ME->getBase();
9283         continue;
9284       } else if (const VarDecl *VDecl = dyn_cast<VarDecl>(VD)) {
9285         if (VDecl->getType().isConstQualified()) {
9286           if (!DiagnosticEmitted) {
9287             S.Diag(Loc, diag::err_typecheck_assign_const)
9288                 << ExprRange << ConstMember << true /*static*/ << VDecl
9289                 << VDecl->getType();
9290             DiagnosticEmitted = true;
9291           }
9292           S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9293               << ConstMember << true /*static*/ << VDecl << VDecl->getType()
9294               << VDecl->getSourceRange();
9295         }
9296         // Static fields do not inherit constness from parents.
9297         break;
9298       }
9299       break;
9300     } // End MemberExpr
9301     break;
9302   }
9303 
9304   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
9305     // Function calls
9306     const FunctionDecl *FD = CE->getDirectCallee();
9307     if (FD && !IsTypeModifiable(FD->getReturnType(), IsDereference)) {
9308       if (!DiagnosticEmitted) {
9309         S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9310                                                       << ConstFunction << FD;
9311         DiagnosticEmitted = true;
9312       }
9313       S.Diag(FD->getReturnTypeSourceRange().getBegin(),
9314              diag::note_typecheck_assign_const)
9315           << ConstFunction << FD << FD->getReturnType()
9316           << FD->getReturnTypeSourceRange();
9317     }
9318   } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9319     // Point to variable declaration.
9320     if (const ValueDecl *VD = DRE->getDecl()) {
9321       if (!IsTypeModifiable(VD->getType(), IsDereference)) {
9322         if (!DiagnosticEmitted) {
9323           S.Diag(Loc, diag::err_typecheck_assign_const)
9324               << ExprRange << ConstVariable << VD << VD->getType();
9325           DiagnosticEmitted = true;
9326         }
9327         S.Diag(VD->getLocation(), diag::note_typecheck_assign_const)
9328             << ConstVariable << VD << VD->getType() << VD->getSourceRange();
9329       }
9330     }
9331   } else if (isa<CXXThisExpr>(E)) {
9332     if (const DeclContext *DC = S.getFunctionLevelDeclContext()) {
9333       if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
9334         if (MD->isConst()) {
9335           if (!DiagnosticEmitted) {
9336             S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange
9337                                                           << ConstMethod << MD;
9338             DiagnosticEmitted = true;
9339           }
9340           S.Diag(MD->getLocation(), diag::note_typecheck_assign_const)
9341               << ConstMethod << MD << MD->getSourceRange();
9342         }
9343       }
9344     }
9345   }
9346 
9347   if (DiagnosticEmitted)
9348     return;
9349 
9350   // Can't determine a more specific message, so display the generic error.
9351   S.Diag(Loc, diag::err_typecheck_assign_const) << ExprRange << ConstUnknown;
9352 }
9353 
9354 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
9355 /// emit an error and return true.  If so, return false.
9356 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
9357   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
9358   SourceLocation OrigLoc = Loc;
9359   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
9360                                                               &Loc);
9361   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
9362     IsLV = Expr::MLV_InvalidMessageExpression;
9363   if (IsLV == Expr::MLV_Valid)
9364     return false;
9365 
9366   unsigned DiagID = 0;
9367   bool NeedType = false;
9368   switch (IsLV) { // C99 6.5.16p2
9369   case Expr::MLV_ConstQualified:
9370     // Use a specialized diagnostic when we're assigning to an object
9371     // from an enclosing function or block.
9372     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
9373       if (NCCK == NCCK_Block)
9374         DiagID = diag::err_block_decl_ref_not_modifiable_lvalue;
9375       else
9376         DiagID = diag::err_lambda_decl_ref_not_modifiable_lvalue;
9377       break;
9378     }
9379 
9380     // In ARC, use some specialized diagnostics for occasions where we
9381     // infer 'const'.  These are always pseudo-strong variables.
9382     if (S.getLangOpts().ObjCAutoRefCount) {
9383       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
9384       if (declRef && isa<VarDecl>(declRef->getDecl())) {
9385         VarDecl *var = cast<VarDecl>(declRef->getDecl());
9386 
9387         // Use the normal diagnostic if it's pseudo-__strong but the
9388         // user actually wrote 'const'.
9389         if (var->isARCPseudoStrong() &&
9390             (!var->getTypeSourceInfo() ||
9391              !var->getTypeSourceInfo()->getType().isConstQualified())) {
9392           // There are two pseudo-strong cases:
9393           //  - self
9394           ObjCMethodDecl *method = S.getCurMethodDecl();
9395           if (method && var == method->getSelfDecl())
9396             DiagID = method->isClassMethod()
9397               ? diag::err_typecheck_arc_assign_self_class_method
9398               : diag::err_typecheck_arc_assign_self;
9399 
9400           //  - fast enumeration variables
9401           else
9402             DiagID = diag::err_typecheck_arr_assign_enumeration;
9403 
9404           SourceRange Assign;
9405           if (Loc != OrigLoc)
9406             Assign = SourceRange(OrigLoc, OrigLoc);
9407           S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9408           // We need to preserve the AST regardless, so migration tool
9409           // can do its job.
9410           return false;
9411         }
9412       }
9413     }
9414 
9415     // If none of the special cases above are triggered, then this is a
9416     // simple const assignment.
9417     if (DiagID == 0) {
9418       DiagnoseConstAssignment(S, E, Loc);
9419       return true;
9420     }
9421 
9422     break;
9423   case Expr::MLV_ConstAddrSpace:
9424     DiagnoseConstAssignment(S, E, Loc);
9425     return true;
9426   case Expr::MLV_ArrayType:
9427   case Expr::MLV_ArrayTemporary:
9428     DiagID = diag::err_typecheck_array_not_modifiable_lvalue;
9429     NeedType = true;
9430     break;
9431   case Expr::MLV_NotObjectType:
9432     DiagID = diag::err_typecheck_non_object_not_modifiable_lvalue;
9433     NeedType = true;
9434     break;
9435   case Expr::MLV_LValueCast:
9436     DiagID = diag::err_typecheck_lvalue_casts_not_supported;
9437     break;
9438   case Expr::MLV_Valid:
9439     llvm_unreachable("did not take early return for MLV_Valid");
9440   case Expr::MLV_InvalidExpression:
9441   case Expr::MLV_MemberFunction:
9442   case Expr::MLV_ClassTemporary:
9443     DiagID = diag::err_typecheck_expression_not_modifiable_lvalue;
9444     break;
9445   case Expr::MLV_IncompleteType:
9446   case Expr::MLV_IncompleteVoidType:
9447     return S.RequireCompleteType(Loc, E->getType(),
9448              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
9449   case Expr::MLV_DuplicateVectorComponents:
9450     DiagID = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
9451     break;
9452   case Expr::MLV_NoSetterProperty:
9453     llvm_unreachable("readonly properties should be processed differently");
9454   case Expr::MLV_InvalidMessageExpression:
9455     DiagID = diag::error_readonly_message_assignment;
9456     break;
9457   case Expr::MLV_SubObjCPropertySetting:
9458     DiagID = diag::error_no_subobject_property_setting;
9459     break;
9460   }
9461 
9462   SourceRange Assign;
9463   if (Loc != OrigLoc)
9464     Assign = SourceRange(OrigLoc, OrigLoc);
9465   if (NeedType)
9466     S.Diag(Loc, DiagID) << E->getType() << E->getSourceRange() << Assign;
9467   else
9468     S.Diag(Loc, DiagID) << E->getSourceRange() << Assign;
9469   return true;
9470 }
9471 
9472 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
9473                                          SourceLocation Loc,
9474                                          Sema &Sema) {
9475   // C / C++ fields
9476   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
9477   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
9478   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
9479     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
9480       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
9481   }
9482 
9483   // Objective-C instance variables
9484   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
9485   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
9486   if (OL && OR && OL->getDecl() == OR->getDecl()) {
9487     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
9488     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
9489     if (RL && RR && RL->getDecl() == RR->getDecl())
9490       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
9491   }
9492 }
9493 
9494 // C99 6.5.16.1
9495 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
9496                                        SourceLocation Loc,
9497                                        QualType CompoundType) {
9498   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
9499 
9500   // Verify that LHS is a modifiable lvalue, and emit error if not.
9501   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
9502     return QualType();
9503 
9504   QualType LHSType = LHSExpr->getType();
9505   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
9506                                              CompoundType;
9507   AssignConvertType ConvTy;
9508   if (CompoundType.isNull()) {
9509     Expr *RHSCheck = RHS.get();
9510 
9511     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
9512 
9513     QualType LHSTy(LHSType);
9514     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
9515     if (RHS.isInvalid())
9516       return QualType();
9517     // Special case of NSObject attributes on c-style pointer types.
9518     if (ConvTy == IncompatiblePointer &&
9519         ((Context.isObjCNSObjectType(LHSType) &&
9520           RHSType->isObjCObjectPointerType()) ||
9521          (Context.isObjCNSObjectType(RHSType) &&
9522           LHSType->isObjCObjectPointerType())))
9523       ConvTy = Compatible;
9524 
9525     if (ConvTy == Compatible &&
9526         LHSType->isObjCObjectType())
9527         Diag(Loc, diag::err_objc_object_assignment)
9528           << LHSType;
9529 
9530     // If the RHS is a unary plus or minus, check to see if they = and + are
9531     // right next to each other.  If so, the user may have typo'd "x =+ 4"
9532     // instead of "x += 4".
9533     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
9534       RHSCheck = ICE->getSubExpr();
9535     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
9536       if ((UO->getOpcode() == UO_Plus ||
9537            UO->getOpcode() == UO_Minus) &&
9538           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
9539           // Only if the two operators are exactly adjacent.
9540           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
9541           // And there is a space or other character before the subexpr of the
9542           // unary +/-.  We don't want to warn on "x=-1".
9543           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
9544           UO->getSubExpr()->getLocStart().isFileID()) {
9545         Diag(Loc, diag::warn_not_compound_assign)
9546           << (UO->getOpcode() == UO_Plus ? "+" : "-")
9547           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
9548       }
9549     }
9550 
9551     if (ConvTy == Compatible) {
9552       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
9553         // Warn about retain cycles where a block captures the LHS, but
9554         // not if the LHS is a simple variable into which the block is
9555         // being stored...unless that variable can be captured by reference!
9556         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
9557         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
9558         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
9559           checkRetainCycles(LHSExpr, RHS.get());
9560 
9561         // It is safe to assign a weak reference into a strong variable.
9562         // Although this code can still have problems:
9563         //   id x = self.weakProp;
9564         //   id y = self.weakProp;
9565         // we do not warn to warn spuriously when 'x' and 'y' are on separate
9566         // paths through the function. This should be revisited if
9567         // -Wrepeated-use-of-weak is made flow-sensitive.
9568         if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9569                              RHS.get()->getLocStart()))
9570           getCurFunction()->markSafeWeakUse(RHS.get());
9571 
9572       } else if (getLangOpts().ObjCAutoRefCount) {
9573         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
9574       }
9575     }
9576   } else {
9577     // Compound assignment "x += y"
9578     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
9579   }
9580 
9581   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
9582                                RHS.get(), AA_Assigning))
9583     return QualType();
9584 
9585   CheckForNullPointerDereference(*this, LHSExpr);
9586 
9587   // C99 6.5.16p3: The type of an assignment expression is the type of the
9588   // left operand unless the left operand has qualified type, in which case
9589   // it is the unqualified version of the type of the left operand.
9590   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
9591   // is converted to the type of the assignment expression (above).
9592   // C++ 5.17p1: the type of the assignment expression is that of its left
9593   // operand.
9594   return (getLangOpts().CPlusPlus
9595           ? LHSType : LHSType.getUnqualifiedType());
9596 }
9597 
9598 // C99 6.5.17
9599 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
9600                                    SourceLocation Loc) {
9601   LHS = S.CheckPlaceholderExpr(LHS.get());
9602   RHS = S.CheckPlaceholderExpr(RHS.get());
9603   if (LHS.isInvalid() || RHS.isInvalid())
9604     return QualType();
9605 
9606   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
9607   // operands, but not unary promotions.
9608   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
9609 
9610   // So we treat the LHS as a ignored value, and in C++ we allow the
9611   // containing site to determine what should be done with the RHS.
9612   LHS = S.IgnoredValueConversions(LHS.get());
9613   if (LHS.isInvalid())
9614     return QualType();
9615 
9616   S.DiagnoseUnusedExprResult(LHS.get());
9617 
9618   if (!S.getLangOpts().CPlusPlus) {
9619     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
9620     if (RHS.isInvalid())
9621       return QualType();
9622     if (!RHS.get()->getType()->isVoidType())
9623       S.RequireCompleteType(Loc, RHS.get()->getType(),
9624                             diag::err_incomplete_type);
9625   }
9626 
9627   return RHS.get()->getType();
9628 }
9629 
9630 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
9631 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
9632 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
9633                                                ExprValueKind &VK,
9634                                                ExprObjectKind &OK,
9635                                                SourceLocation OpLoc,
9636                                                bool IsInc, bool IsPrefix) {
9637   if (Op->isTypeDependent())
9638     return S.Context.DependentTy;
9639 
9640   QualType ResType = Op->getType();
9641   // Atomic types can be used for increment / decrement where the non-atomic
9642   // versions can, so ignore the _Atomic() specifier for the purpose of
9643   // checking.
9644   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
9645     ResType = ResAtomicType->getValueType();
9646 
9647   assert(!ResType.isNull() && "no type for increment/decrement expression");
9648 
9649   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
9650     // Decrement of bool is not allowed.
9651     if (!IsInc) {
9652       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
9653       return QualType();
9654     }
9655     // Increment of bool sets it to true, but is deprecated.
9656     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
9657   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
9658     // Error on enum increments and decrements in C++ mode
9659     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
9660     return QualType();
9661   } else if (ResType->isRealType()) {
9662     // OK!
9663   } else if (ResType->isPointerType()) {
9664     // C99 6.5.2.4p2, 6.5.6p2
9665     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
9666       return QualType();
9667   } else if (ResType->isObjCObjectPointerType()) {
9668     // On modern runtimes, ObjC pointer arithmetic is forbidden.
9669     // Otherwise, we just need a complete type.
9670     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
9671         checkArithmeticOnObjCPointer(S, OpLoc, Op))
9672       return QualType();
9673   } else if (ResType->isAnyComplexType()) {
9674     // C99 does not support ++/-- on complex types, we allow as an extension.
9675     S.Diag(OpLoc, diag::ext_integer_increment_complex)
9676       << ResType << Op->getSourceRange();
9677   } else if (ResType->isPlaceholderType()) {
9678     ExprResult PR = S.CheckPlaceholderExpr(Op);
9679     if (PR.isInvalid()) return QualType();
9680     return CheckIncrementDecrementOperand(S, PR.get(), VK, OK, OpLoc,
9681                                           IsInc, IsPrefix);
9682   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
9683     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
9684   } else if (S.getLangOpts().ZVector && ResType->isVectorType() &&
9685              (ResType->getAs<VectorType>()->getVectorKind() !=
9686               VectorType::AltiVecBool)) {
9687     // The z vector extensions allow ++ and -- for non-bool vectors.
9688   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
9689             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
9690     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
9691   } else {
9692     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
9693       << ResType << int(IsInc) << Op->getSourceRange();
9694     return QualType();
9695   }
9696   // At this point, we know we have a real, complex or pointer type.
9697   // Now make sure the operand is a modifiable lvalue.
9698   if (CheckForModifiableLvalue(Op, OpLoc, S))
9699     return QualType();
9700   // In C++, a prefix increment is the same type as the operand. Otherwise
9701   // (in C or with postfix), the increment is the unqualified type of the
9702   // operand.
9703   if (IsPrefix && S.getLangOpts().CPlusPlus) {
9704     VK = VK_LValue;
9705     OK = Op->getObjectKind();
9706     return ResType;
9707   } else {
9708     VK = VK_RValue;
9709     return ResType.getUnqualifiedType();
9710   }
9711 }
9712 
9713 
9714 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
9715 /// This routine allows us to typecheck complex/recursive expressions
9716 /// where the declaration is needed for type checking. We only need to
9717 /// handle cases when the expression references a function designator
9718 /// or is an lvalue. Here are some examples:
9719 ///  - &(x) => x
9720 ///  - &*****f => f for f a function designator.
9721 ///  - &s.xx => s
9722 ///  - &s.zz[1].yy -> s, if zz is an array
9723 ///  - *(x + 1) -> x, if x is an array
9724 ///  - &"123"[2] -> 0
9725 ///  - & __real__ x -> x
9726 static ValueDecl *getPrimaryDecl(Expr *E) {
9727   switch (E->getStmtClass()) {
9728   case Stmt::DeclRefExprClass:
9729     return cast<DeclRefExpr>(E)->getDecl();
9730   case Stmt::MemberExprClass:
9731     // If this is an arrow operator, the address is an offset from
9732     // the base's value, so the object the base refers to is
9733     // irrelevant.
9734     if (cast<MemberExpr>(E)->isArrow())
9735       return nullptr;
9736     // Otherwise, the expression refers to a part of the base
9737     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
9738   case Stmt::ArraySubscriptExprClass: {
9739     // FIXME: This code shouldn't be necessary!  We should catch the implicit
9740     // promotion of register arrays earlier.
9741     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
9742     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
9743       if (ICE->getSubExpr()->getType()->isArrayType())
9744         return getPrimaryDecl(ICE->getSubExpr());
9745     }
9746     return nullptr;
9747   }
9748   case Stmt::UnaryOperatorClass: {
9749     UnaryOperator *UO = cast<UnaryOperator>(E);
9750 
9751     switch(UO->getOpcode()) {
9752     case UO_Real:
9753     case UO_Imag:
9754     case UO_Extension:
9755       return getPrimaryDecl(UO->getSubExpr());
9756     default:
9757       return nullptr;
9758     }
9759   }
9760   case Stmt::ParenExprClass:
9761     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
9762   case Stmt::ImplicitCastExprClass:
9763     // If the result of an implicit cast is an l-value, we care about
9764     // the sub-expression; otherwise, the result here doesn't matter.
9765     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
9766   default:
9767     return nullptr;
9768   }
9769 }
9770 
9771 namespace {
9772   enum {
9773     AO_Bit_Field = 0,
9774     AO_Vector_Element = 1,
9775     AO_Property_Expansion = 2,
9776     AO_Register_Variable = 3,
9777     AO_No_Error = 4
9778   };
9779 }
9780 /// \brief Diagnose invalid operand for address of operations.
9781 ///
9782 /// \param Type The type of operand which cannot have its address taken.
9783 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
9784                                          Expr *E, unsigned Type) {
9785   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
9786 }
9787 
9788 /// CheckAddressOfOperand - The operand of & must be either a function
9789 /// designator or an lvalue designating an object. If it is an lvalue, the
9790 /// object cannot be declared with storage class register or be a bit field.
9791 /// Note: The usual conversions are *not* applied to the operand of the &
9792 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
9793 /// In C++, the operand might be an overloaded function name, in which case
9794 /// we allow the '&' but retain the overloaded-function type.
9795 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
9796   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
9797     if (PTy->getKind() == BuiltinType::Overload) {
9798       Expr *E = OrigOp.get()->IgnoreParens();
9799       if (!isa<OverloadExpr>(E)) {
9800         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
9801         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
9802           << OrigOp.get()->getSourceRange();
9803         return QualType();
9804       }
9805 
9806       OverloadExpr *Ovl = cast<OverloadExpr>(E);
9807       if (isa<UnresolvedMemberExpr>(Ovl))
9808         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
9809           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9810             << OrigOp.get()->getSourceRange();
9811           return QualType();
9812         }
9813 
9814       return Context.OverloadTy;
9815     }
9816 
9817     if (PTy->getKind() == BuiltinType::UnknownAny)
9818       return Context.UnknownAnyTy;
9819 
9820     if (PTy->getKind() == BuiltinType::BoundMember) {
9821       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9822         << OrigOp.get()->getSourceRange();
9823       return QualType();
9824     }
9825 
9826     OrigOp = CheckPlaceholderExpr(OrigOp.get());
9827     if (OrigOp.isInvalid()) return QualType();
9828   }
9829 
9830   if (OrigOp.get()->isTypeDependent())
9831     return Context.DependentTy;
9832 
9833   assert(!OrigOp.get()->getType()->isPlaceholderType());
9834 
9835   // Make sure to ignore parentheses in subsequent checks
9836   Expr *op = OrigOp.get()->IgnoreParens();
9837 
9838   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
9839   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
9840     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
9841     return QualType();
9842   }
9843 
9844   if (getLangOpts().C99) {
9845     // Implement C99-only parts of addressof rules.
9846     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
9847       if (uOp->getOpcode() == UO_Deref)
9848         // Per C99 6.5.3.2, the address of a deref always returns a valid result
9849         // (assuming the deref expression is valid).
9850         return uOp->getSubExpr()->getType();
9851     }
9852     // Technically, there should be a check for array subscript
9853     // expressions here, but the result of one is always an lvalue anyway.
9854   }
9855   ValueDecl *dcl = getPrimaryDecl(op);
9856   Expr::LValueClassification lval = op->ClassifyLValue(Context);
9857   unsigned AddressOfError = AO_No_Error;
9858 
9859   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
9860     bool sfinae = (bool)isSFINAEContext();
9861     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
9862                                   : diag::ext_typecheck_addrof_temporary)
9863       << op->getType() << op->getSourceRange();
9864     if (sfinae)
9865       return QualType();
9866     // Materialize the temporary as an lvalue so that we can take its address.
9867     OrigOp = op = new (Context)
9868         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
9869   } else if (isa<ObjCSelectorExpr>(op)) {
9870     return Context.getPointerType(op->getType());
9871   } else if (lval == Expr::LV_MemberFunction) {
9872     // If it's an instance method, make a member pointer.
9873     // The expression must have exactly the form &A::foo.
9874 
9875     // If the underlying expression isn't a decl ref, give up.
9876     if (!isa<DeclRefExpr>(op)) {
9877       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
9878         << OrigOp.get()->getSourceRange();
9879       return QualType();
9880     }
9881     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
9882     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
9883 
9884     // The id-expression was parenthesized.
9885     if (OrigOp.get() != DRE) {
9886       Diag(OpLoc, diag::err_parens_pointer_member_function)
9887         << OrigOp.get()->getSourceRange();
9888 
9889     // The method was named without a qualifier.
9890     } else if (!DRE->getQualifier()) {
9891       if (MD->getParent()->getName().empty())
9892         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9893           << op->getSourceRange();
9894       else {
9895         SmallString<32> Str;
9896         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
9897         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
9898           << op->getSourceRange()
9899           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
9900       }
9901     }
9902 
9903     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
9904     if (isa<CXXDestructorDecl>(MD))
9905       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
9906 
9907     QualType MPTy = Context.getMemberPointerType(
9908         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
9909     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9910       RequireCompleteType(OpLoc, MPTy, 0);
9911     return MPTy;
9912   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
9913     // C99 6.5.3.2p1
9914     // The operand must be either an l-value or a function designator
9915     if (!op->getType()->isFunctionType()) {
9916       // Use a special diagnostic for loads from property references.
9917       if (isa<PseudoObjectExpr>(op)) {
9918         AddressOfError = AO_Property_Expansion;
9919       } else {
9920         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
9921           << op->getType() << op->getSourceRange();
9922         return QualType();
9923       }
9924     }
9925   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
9926     // The operand cannot be a bit-field
9927     AddressOfError = AO_Bit_Field;
9928   } else if (op->getObjectKind() == OK_VectorComponent) {
9929     // The operand cannot be an element of a vector
9930     AddressOfError = AO_Vector_Element;
9931   } else if (dcl) { // C99 6.5.3.2p1
9932     // We have an lvalue with a decl. Make sure the decl is not declared
9933     // with the register storage-class specifier.
9934     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
9935       // in C++ it is not error to take address of a register
9936       // variable (c++03 7.1.1P3)
9937       if (vd->getStorageClass() == SC_Register &&
9938           !getLangOpts().CPlusPlus) {
9939         AddressOfError = AO_Register_Variable;
9940       }
9941     } else if (isa<MSPropertyDecl>(dcl)) {
9942       AddressOfError = AO_Property_Expansion;
9943     } else if (isa<FunctionTemplateDecl>(dcl)) {
9944       return Context.OverloadTy;
9945     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
9946       // Okay: we can take the address of a field.
9947       // Could be a pointer to member, though, if there is an explicit
9948       // scope qualifier for the class.
9949       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
9950         DeclContext *Ctx = dcl->getDeclContext();
9951         if (Ctx && Ctx->isRecord()) {
9952           if (dcl->getType()->isReferenceType()) {
9953             Diag(OpLoc,
9954                  diag::err_cannot_form_pointer_to_member_of_reference_type)
9955               << dcl->getDeclName() << dcl->getType();
9956             return QualType();
9957           }
9958 
9959           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
9960             Ctx = Ctx->getParent();
9961 
9962           QualType MPTy = Context.getMemberPointerType(
9963               op->getType(),
9964               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
9965           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
9966             RequireCompleteType(OpLoc, MPTy, 0);
9967           return MPTy;
9968         }
9969       }
9970     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
9971       llvm_unreachable("Unknown/unexpected decl type");
9972   }
9973 
9974   if (AddressOfError != AO_No_Error) {
9975     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
9976     return QualType();
9977   }
9978 
9979   if (lval == Expr::LV_IncompleteVoidType) {
9980     // Taking the address of a void variable is technically illegal, but we
9981     // allow it in cases which are otherwise valid.
9982     // Example: "extern void x; void* y = &x;".
9983     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9984   }
9985 
9986   // If the operand has type "type", the result has type "pointer to type".
9987   if (op->getType()->isObjCObjectType())
9988     return Context.getObjCObjectPointerType(op->getType());
9989   return Context.getPointerType(op->getType());
9990 }
9991 
9992 static void RecordModifiableNonNullParam(Sema &S, const Expr *Exp) {
9993   const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Exp);
9994   if (!DRE)
9995     return;
9996   const Decl *D = DRE->getDecl();
9997   if (!D)
9998     return;
9999   const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D);
10000   if (!Param)
10001     return;
10002   if (const FunctionDecl* FD = dyn_cast<FunctionDecl>(Param->getDeclContext()))
10003     if (!FD->hasAttr<NonNullAttr>() && !Param->hasAttr<NonNullAttr>())
10004       return;
10005   if (FunctionScopeInfo *FD = S.getCurFunction())
10006     if (!FD->ModifiedNonNullParams.count(Param))
10007       FD->ModifiedNonNullParams.insert(Param);
10008 }
10009 
10010 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
10011 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
10012                                         SourceLocation OpLoc) {
10013   if (Op->isTypeDependent())
10014     return S.Context.DependentTy;
10015 
10016   ExprResult ConvResult = S.UsualUnaryConversions(Op);
10017   if (ConvResult.isInvalid())
10018     return QualType();
10019   Op = ConvResult.get();
10020   QualType OpTy = Op->getType();
10021   QualType Result;
10022 
10023   if (isa<CXXReinterpretCastExpr>(Op)) {
10024     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
10025     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
10026                                      Op->getSourceRange());
10027   }
10028 
10029   if (const PointerType *PT = OpTy->getAs<PointerType>())
10030     Result = PT->getPointeeType();
10031   else if (const ObjCObjectPointerType *OPT =
10032              OpTy->getAs<ObjCObjectPointerType>())
10033     Result = OPT->getPointeeType();
10034   else {
10035     ExprResult PR = S.CheckPlaceholderExpr(Op);
10036     if (PR.isInvalid()) return QualType();
10037     if (PR.get() != Op)
10038       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
10039   }
10040 
10041   if (Result.isNull()) {
10042     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
10043       << OpTy << Op->getSourceRange();
10044     return QualType();
10045   }
10046 
10047   // Note that per both C89 and C99, indirection is always legal, even if Result
10048   // is an incomplete type or void.  It would be possible to warn about
10049   // dereferencing a void pointer, but it's completely well-defined, and such a
10050   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
10051   // for pointers to 'void' but is fine for any other pointer type:
10052   //
10053   // C++ [expr.unary.op]p1:
10054   //   [...] the expression to which [the unary * operator] is applied shall
10055   //   be a pointer to an object type, or a pointer to a function type
10056   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
10057     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
10058       << OpTy << Op->getSourceRange();
10059 
10060   // Dereferences are usually l-values...
10061   VK = VK_LValue;
10062 
10063   // ...except that certain expressions are never l-values in C.
10064   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
10065     VK = VK_RValue;
10066 
10067   return Result;
10068 }
10069 
10070 BinaryOperatorKind Sema::ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind) {
10071   BinaryOperatorKind Opc;
10072   switch (Kind) {
10073   default: llvm_unreachable("Unknown binop!");
10074   case tok::periodstar:           Opc = BO_PtrMemD; break;
10075   case tok::arrowstar:            Opc = BO_PtrMemI; break;
10076   case tok::star:                 Opc = BO_Mul; break;
10077   case tok::slash:                Opc = BO_Div; break;
10078   case tok::percent:              Opc = BO_Rem; break;
10079   case tok::plus:                 Opc = BO_Add; break;
10080   case tok::minus:                Opc = BO_Sub; break;
10081   case tok::lessless:             Opc = BO_Shl; break;
10082   case tok::greatergreater:       Opc = BO_Shr; break;
10083   case tok::lessequal:            Opc = BO_LE; break;
10084   case tok::less:                 Opc = BO_LT; break;
10085   case tok::greaterequal:         Opc = BO_GE; break;
10086   case tok::greater:              Opc = BO_GT; break;
10087   case tok::exclaimequal:         Opc = BO_NE; break;
10088   case tok::equalequal:           Opc = BO_EQ; break;
10089   case tok::amp:                  Opc = BO_And; break;
10090   case tok::caret:                Opc = BO_Xor; break;
10091   case tok::pipe:                 Opc = BO_Or; break;
10092   case tok::ampamp:               Opc = BO_LAnd; break;
10093   case tok::pipepipe:             Opc = BO_LOr; break;
10094   case tok::equal:                Opc = BO_Assign; break;
10095   case tok::starequal:            Opc = BO_MulAssign; break;
10096   case tok::slashequal:           Opc = BO_DivAssign; break;
10097   case tok::percentequal:         Opc = BO_RemAssign; break;
10098   case tok::plusequal:            Opc = BO_AddAssign; break;
10099   case tok::minusequal:           Opc = BO_SubAssign; break;
10100   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
10101   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
10102   case tok::ampequal:             Opc = BO_AndAssign; break;
10103   case tok::caretequal:           Opc = BO_XorAssign; break;
10104   case tok::pipeequal:            Opc = BO_OrAssign; break;
10105   case tok::comma:                Opc = BO_Comma; break;
10106   }
10107   return Opc;
10108 }
10109 
10110 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
10111   tok::TokenKind Kind) {
10112   UnaryOperatorKind Opc;
10113   switch (Kind) {
10114   default: llvm_unreachable("Unknown unary op!");
10115   case tok::plusplus:     Opc = UO_PreInc; break;
10116   case tok::minusminus:   Opc = UO_PreDec; break;
10117   case tok::amp:          Opc = UO_AddrOf; break;
10118   case tok::star:         Opc = UO_Deref; break;
10119   case tok::plus:         Opc = UO_Plus; break;
10120   case tok::minus:        Opc = UO_Minus; break;
10121   case tok::tilde:        Opc = UO_Not; break;
10122   case tok::exclaim:      Opc = UO_LNot; break;
10123   case tok::kw___real:    Opc = UO_Real; break;
10124   case tok::kw___imag:    Opc = UO_Imag; break;
10125   case tok::kw___extension__: Opc = UO_Extension; break;
10126   }
10127   return Opc;
10128 }
10129 
10130 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
10131 /// This warning is only emitted for builtin assignment operations. It is also
10132 /// suppressed in the event of macro expansions.
10133 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
10134                                    SourceLocation OpLoc) {
10135   if (!S.ActiveTemplateInstantiations.empty())
10136     return;
10137   if (OpLoc.isInvalid() || OpLoc.isMacroID())
10138     return;
10139   LHSExpr = LHSExpr->IgnoreParenImpCasts();
10140   RHSExpr = RHSExpr->IgnoreParenImpCasts();
10141   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
10142   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
10143   if (!LHSDeclRef || !RHSDeclRef ||
10144       LHSDeclRef->getLocation().isMacroID() ||
10145       RHSDeclRef->getLocation().isMacroID())
10146     return;
10147   const ValueDecl *LHSDecl =
10148     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
10149   const ValueDecl *RHSDecl =
10150     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
10151   if (LHSDecl != RHSDecl)
10152     return;
10153   if (LHSDecl->getType().isVolatileQualified())
10154     return;
10155   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
10156     if (RefTy->getPointeeType().isVolatileQualified())
10157       return;
10158 
10159   S.Diag(OpLoc, diag::warn_self_assignment)
10160       << LHSDeclRef->getType()
10161       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
10162 }
10163 
10164 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
10165 /// is usually indicative of introspection within the Objective-C pointer.
10166 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
10167                                           SourceLocation OpLoc) {
10168   if (!S.getLangOpts().ObjC1)
10169     return;
10170 
10171   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
10172   const Expr *LHS = L.get();
10173   const Expr *RHS = R.get();
10174 
10175   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10176     ObjCPointerExpr = LHS;
10177     OtherExpr = RHS;
10178   }
10179   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
10180     ObjCPointerExpr = RHS;
10181     OtherExpr = LHS;
10182   }
10183 
10184   // This warning is deliberately made very specific to reduce false
10185   // positives with logic that uses '&' for hashing.  This logic mainly
10186   // looks for code trying to introspect into tagged pointers, which
10187   // code should generally never do.
10188   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
10189     unsigned Diag = diag::warn_objc_pointer_masking;
10190     // Determine if we are introspecting the result of performSelectorXXX.
10191     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
10192     // Special case messages to -performSelector and friends, which
10193     // can return non-pointer values boxed in a pointer value.
10194     // Some clients may wish to silence warnings in this subcase.
10195     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
10196       Selector S = ME->getSelector();
10197       StringRef SelArg0 = S.getNameForSlot(0);
10198       if (SelArg0.startswith("performSelector"))
10199         Diag = diag::warn_objc_pointer_masking_performSelector;
10200     }
10201 
10202     S.Diag(OpLoc, Diag)
10203       << ObjCPointerExpr->getSourceRange();
10204   }
10205 }
10206 
10207 static NamedDecl *getDeclFromExpr(Expr *E) {
10208   if (!E)
10209     return nullptr;
10210   if (auto *DRE = dyn_cast<DeclRefExpr>(E))
10211     return DRE->getDecl();
10212   if (auto *ME = dyn_cast<MemberExpr>(E))
10213     return ME->getMemberDecl();
10214   if (auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
10215     return IRE->getDecl();
10216   return nullptr;
10217 }
10218 
10219 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
10220 /// operator @p Opc at location @c TokLoc. This routine only supports
10221 /// built-in operations; ActOnBinOp handles overloaded operators.
10222 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
10223                                     BinaryOperatorKind Opc,
10224                                     Expr *LHSExpr, Expr *RHSExpr) {
10225   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
10226     // The syntax only allows initializer lists on the RHS of assignment,
10227     // so we don't need to worry about accepting invalid code for
10228     // non-assignment operators.
10229     // C++11 5.17p9:
10230     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
10231     //   of x = {} is x = T().
10232     InitializationKind Kind =
10233         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
10234     InitializedEntity Entity =
10235         InitializedEntity::InitializeTemporary(LHSExpr->getType());
10236     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
10237     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
10238     if (Init.isInvalid())
10239       return Init;
10240     RHSExpr = Init.get();
10241   }
10242 
10243   ExprResult LHS = LHSExpr, RHS = RHSExpr;
10244   QualType ResultTy;     // Result type of the binary operator.
10245   // The following two variables are used for compound assignment operators
10246   QualType CompLHSTy;    // Type of LHS after promotions for computation
10247   QualType CompResultTy; // Type of computation result
10248   ExprValueKind VK = VK_RValue;
10249   ExprObjectKind OK = OK_Ordinary;
10250 
10251   if (!getLangOpts().CPlusPlus) {
10252     // C cannot handle TypoExpr nodes on either side of a binop because it
10253     // doesn't handle dependent types properly, so make sure any TypoExprs have
10254     // been dealt with before checking the operands.
10255     LHS = CorrectDelayedTyposInExpr(LHSExpr);
10256     RHS = CorrectDelayedTyposInExpr(RHSExpr, [Opc, LHS](Expr *E) {
10257       if (Opc != BO_Assign)
10258         return ExprResult(E);
10259       // Avoid correcting the RHS to the same Expr as the LHS.
10260       Decl *D = getDeclFromExpr(E);
10261       return (D && D == getDeclFromExpr(LHS.get())) ? ExprError() : E;
10262     });
10263     if (!LHS.isUsable() || !RHS.isUsable())
10264       return ExprError();
10265   }
10266 
10267   if (getLangOpts().OpenCL) {
10268     // OpenCLC v2.0 s6.13.11.1 allows atomic variables to be initialized by
10269     // the ATOMIC_VAR_INIT macro.
10270     if (LHSExpr->getType()->isAtomicType() ||
10271         RHSExpr->getType()->isAtomicType()) {
10272       SourceRange SR(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
10273       if (BO_Assign == Opc)
10274         Diag(OpLoc, diag::err_atomic_init_constant) << SR;
10275       else
10276         ResultTy = InvalidOperands(OpLoc, LHS, RHS);
10277       return ExprError();
10278     }
10279   }
10280 
10281   switch (Opc) {
10282   case BO_Assign:
10283     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
10284     if (getLangOpts().CPlusPlus &&
10285         LHS.get()->getObjectKind() != OK_ObjCProperty) {
10286       VK = LHS.get()->getValueKind();
10287       OK = LHS.get()->getObjectKind();
10288     }
10289     if (!ResultTy.isNull()) {
10290       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10291       DiagnoseSelfMove(LHS.get(), RHS.get(), OpLoc);
10292     }
10293     RecordModifiableNonNullParam(*this, LHS.get());
10294     break;
10295   case BO_PtrMemD:
10296   case BO_PtrMemI:
10297     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
10298                                             Opc == BO_PtrMemI);
10299     break;
10300   case BO_Mul:
10301   case BO_Div:
10302     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
10303                                            Opc == BO_Div);
10304     break;
10305   case BO_Rem:
10306     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
10307     break;
10308   case BO_Add:
10309     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
10310     break;
10311   case BO_Sub:
10312     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
10313     break;
10314   case BO_Shl:
10315   case BO_Shr:
10316     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
10317     break;
10318   case BO_LE:
10319   case BO_LT:
10320   case BO_GE:
10321   case BO_GT:
10322     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
10323     break;
10324   case BO_EQ:
10325   case BO_NE:
10326     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
10327     break;
10328   case BO_And:
10329     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
10330   case BO_Xor:
10331   case BO_Or:
10332     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
10333     break;
10334   case BO_LAnd:
10335   case BO_LOr:
10336     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
10337     break;
10338   case BO_MulAssign:
10339   case BO_DivAssign:
10340     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
10341                                                Opc == BO_DivAssign);
10342     CompLHSTy = CompResultTy;
10343     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10344       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10345     break;
10346   case BO_RemAssign:
10347     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
10348     CompLHSTy = CompResultTy;
10349     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10350       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10351     break;
10352   case BO_AddAssign:
10353     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
10354     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10355       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10356     break;
10357   case BO_SubAssign:
10358     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
10359     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10360       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10361     break;
10362   case BO_ShlAssign:
10363   case BO_ShrAssign:
10364     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
10365     CompLHSTy = CompResultTy;
10366     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10367       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10368     break;
10369   case BO_AndAssign:
10370   case BO_OrAssign: // fallthrough
10371 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
10372   case BO_XorAssign:
10373     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
10374     CompLHSTy = CompResultTy;
10375     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
10376       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
10377     break;
10378   case BO_Comma:
10379     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
10380     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
10381       VK = RHS.get()->getValueKind();
10382       OK = RHS.get()->getObjectKind();
10383     }
10384     break;
10385   }
10386   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
10387     return ExprError();
10388 
10389   // Check for array bounds violations for both sides of the BinaryOperator
10390   CheckArrayAccess(LHS.get());
10391   CheckArrayAccess(RHS.get());
10392 
10393   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
10394     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
10395                                                  &Context.Idents.get("object_setClass"),
10396                                                  SourceLocation(), LookupOrdinaryName);
10397     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
10398       SourceLocation RHSLocEnd = getLocForEndOfToken(RHS.get()->getLocEnd());
10399       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
10400       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
10401       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
10402       FixItHint::CreateInsertion(RHSLocEnd, ")");
10403     }
10404     else
10405       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
10406   }
10407   else if (const ObjCIvarRefExpr *OIRE =
10408            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
10409     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
10410 
10411   if (CompResultTy.isNull())
10412     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
10413                                         OK, OpLoc, FPFeatures.fp_contract);
10414   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
10415       OK_ObjCProperty) {
10416     VK = VK_LValue;
10417     OK = LHS.get()->getObjectKind();
10418   }
10419   return new (Context) CompoundAssignOperator(
10420       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
10421       OpLoc, FPFeatures.fp_contract);
10422 }
10423 
10424 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
10425 /// operators are mixed in a way that suggests that the programmer forgot that
10426 /// comparison operators have higher precedence. The most typical example of
10427 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
10428 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
10429                                       SourceLocation OpLoc, Expr *LHSExpr,
10430                                       Expr *RHSExpr) {
10431   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
10432   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
10433 
10434   // Check that one of the sides is a comparison operator.
10435   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
10436   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
10437   if (!isLeftComp && !isRightComp)
10438     return;
10439 
10440   // Bitwise operations are sometimes used as eager logical ops.
10441   // Don't diagnose this.
10442   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
10443   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
10444   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
10445     return;
10446 
10447   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
10448                                                    OpLoc)
10449                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
10450   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
10451   SourceRange ParensRange = isLeftComp ?
10452       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
10453     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocEnd());
10454 
10455   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
10456     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
10457   SuggestParentheses(Self, OpLoc,
10458     Self.PDiag(diag::note_precedence_silence) << OpStr,
10459     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
10460   SuggestParentheses(Self, OpLoc,
10461     Self.PDiag(diag::note_precedence_bitwise_first)
10462       << BinaryOperator::getOpcodeStr(Opc),
10463     ParensRange);
10464 }
10465 
10466 /// \brief It accepts a '&' expr that is inside a '|' one.
10467 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
10468 /// in parentheses.
10469 static void
10470 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
10471                                        BinaryOperator *Bop) {
10472   assert(Bop->getOpcode() == BO_And);
10473   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
10474       << Bop->getSourceRange() << OpLoc;
10475   SuggestParentheses(Self, Bop->getOperatorLoc(),
10476     Self.PDiag(diag::note_precedence_silence)
10477       << Bop->getOpcodeStr(),
10478     Bop->getSourceRange());
10479 }
10480 
10481 /// \brief It accepts a '&&' expr that is inside a '||' one.
10482 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
10483 /// in parentheses.
10484 static void
10485 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
10486                                        BinaryOperator *Bop) {
10487   assert(Bop->getOpcode() == BO_LAnd);
10488   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
10489       << Bop->getSourceRange() << OpLoc;
10490   SuggestParentheses(Self, Bop->getOperatorLoc(),
10491     Self.PDiag(diag::note_precedence_silence)
10492       << Bop->getOpcodeStr(),
10493     Bop->getSourceRange());
10494 }
10495 
10496 /// \brief Returns true if the given expression can be evaluated as a constant
10497 /// 'true'.
10498 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
10499   bool Res;
10500   return !E->isValueDependent() &&
10501          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
10502 }
10503 
10504 /// \brief Returns true if the given expression can be evaluated as a constant
10505 /// 'false'.
10506 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
10507   bool Res;
10508   return !E->isValueDependent() &&
10509          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
10510 }
10511 
10512 /// \brief Look for '&&' in the left hand of a '||' expr.
10513 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
10514                                              Expr *LHSExpr, Expr *RHSExpr) {
10515   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
10516     if (Bop->getOpcode() == BO_LAnd) {
10517       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
10518       if (EvaluatesAsFalse(S, RHSExpr))
10519         return;
10520       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
10521       if (!EvaluatesAsTrue(S, Bop->getLHS()))
10522         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10523     } else if (Bop->getOpcode() == BO_LOr) {
10524       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
10525         // If it's "a || b && 1 || c" we didn't warn earlier for
10526         // "a || b && 1", but warn now.
10527         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
10528           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
10529       }
10530     }
10531   }
10532 }
10533 
10534 /// \brief Look for '&&' in the right hand of a '||' expr.
10535 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
10536                                              Expr *LHSExpr, Expr *RHSExpr) {
10537   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
10538     if (Bop->getOpcode() == BO_LAnd) {
10539       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
10540       if (EvaluatesAsFalse(S, LHSExpr))
10541         return;
10542       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
10543       if (!EvaluatesAsTrue(S, Bop->getRHS()))
10544         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
10545     }
10546   }
10547 }
10548 
10549 /// \brief Look for '&' in the left or right hand of a '|' expr.
10550 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
10551                                              Expr *OrArg) {
10552   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
10553     if (Bop->getOpcode() == BO_And)
10554       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
10555   }
10556 }
10557 
10558 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
10559                                     Expr *SubExpr, StringRef Shift) {
10560   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
10561     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
10562       StringRef Op = Bop->getOpcodeStr();
10563       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
10564           << Bop->getSourceRange() << OpLoc << Shift << Op;
10565       SuggestParentheses(S, Bop->getOperatorLoc(),
10566           S.PDiag(diag::note_precedence_silence) << Op,
10567           Bop->getSourceRange());
10568     }
10569   }
10570 }
10571 
10572 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
10573                                  Expr *LHSExpr, Expr *RHSExpr) {
10574   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
10575   if (!OCE)
10576     return;
10577 
10578   FunctionDecl *FD = OCE->getDirectCallee();
10579   if (!FD || !FD->isOverloadedOperator())
10580     return;
10581 
10582   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
10583   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
10584     return;
10585 
10586   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
10587       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
10588       << (Kind == OO_LessLess);
10589   SuggestParentheses(S, OCE->getOperatorLoc(),
10590                      S.PDiag(diag::note_precedence_silence)
10591                          << (Kind == OO_LessLess ? "<<" : ">>"),
10592                      OCE->getSourceRange());
10593   SuggestParentheses(S, OpLoc,
10594                      S.PDiag(diag::note_evaluate_comparison_first),
10595                      SourceRange(OCE->getArg(1)->getLocStart(),
10596                                  RHSExpr->getLocEnd()));
10597 }
10598 
10599 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
10600 /// precedence.
10601 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
10602                                     SourceLocation OpLoc, Expr *LHSExpr,
10603                                     Expr *RHSExpr){
10604   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
10605   if (BinaryOperator::isBitwiseOp(Opc))
10606     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
10607 
10608   // Diagnose "arg1 & arg2 | arg3"
10609   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10610     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
10611     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
10612   }
10613 
10614   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
10615   // We don't warn for 'assert(a || b && "bad")' since this is safe.
10616   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
10617     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
10618     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
10619   }
10620 
10621   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
10622       || Opc == BO_Shr) {
10623     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
10624     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
10625     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
10626   }
10627 
10628   // Warn on overloaded shift operators and comparisons, such as:
10629   // cout << 5 == 4;
10630   if (BinaryOperator::isComparisonOp(Opc))
10631     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
10632 }
10633 
10634 // Binary Operators.  'Tok' is the token for the operator.
10635 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
10636                             tok::TokenKind Kind,
10637                             Expr *LHSExpr, Expr *RHSExpr) {
10638   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
10639   assert(LHSExpr && "ActOnBinOp(): missing left expression");
10640   assert(RHSExpr && "ActOnBinOp(): missing right expression");
10641 
10642   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
10643   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
10644 
10645   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
10646 }
10647 
10648 /// Build an overloaded binary operator expression in the given scope.
10649 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
10650                                        BinaryOperatorKind Opc,
10651                                        Expr *LHS, Expr *RHS) {
10652   // Find all of the overloaded operators visible from this
10653   // point. We perform both an operator-name lookup from the local
10654   // scope and an argument-dependent lookup based on the types of
10655   // the arguments.
10656   UnresolvedSet<16> Functions;
10657   OverloadedOperatorKind OverOp
10658     = BinaryOperator::getOverloadedOperator(Opc);
10659   if (Sc && OverOp != OO_None && OverOp != OO_Equal)
10660     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
10661                                    RHS->getType(), Functions);
10662 
10663   // Build the (potentially-overloaded, potentially-dependent)
10664   // binary operation.
10665   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
10666 }
10667 
10668 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
10669                             BinaryOperatorKind Opc,
10670                             Expr *LHSExpr, Expr *RHSExpr) {
10671   // We want to end up calling one of checkPseudoObjectAssignment
10672   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
10673   // both expressions are overloadable or either is type-dependent),
10674   // or CreateBuiltinBinOp (in any other case).  We also want to get
10675   // any placeholder types out of the way.
10676 
10677   // Handle pseudo-objects in the LHS.
10678   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
10679     // Assignments with a pseudo-object l-value need special analysis.
10680     if (pty->getKind() == BuiltinType::PseudoObject &&
10681         BinaryOperator::isAssignmentOp(Opc))
10682       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
10683 
10684     // Don't resolve overloads if the other type is overloadable.
10685     if (pty->getKind() == BuiltinType::Overload) {
10686       // We can't actually test that if we still have a placeholder,
10687       // though.  Fortunately, none of the exceptions we see in that
10688       // code below are valid when the LHS is an overload set.  Note
10689       // that an overload set can be dependently-typed, but it never
10690       // instantiates to having an overloadable type.
10691       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10692       if (resolvedRHS.isInvalid()) return ExprError();
10693       RHSExpr = resolvedRHS.get();
10694 
10695       if (RHSExpr->isTypeDependent() ||
10696           RHSExpr->getType()->isOverloadableType())
10697         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10698     }
10699 
10700     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
10701     if (LHS.isInvalid()) return ExprError();
10702     LHSExpr = LHS.get();
10703   }
10704 
10705   // Handle pseudo-objects in the RHS.
10706   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
10707     // An overload in the RHS can potentially be resolved by the type
10708     // being assigned to.
10709     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
10710       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10711         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10712 
10713       if (LHSExpr->getType()->isOverloadableType())
10714         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10715 
10716       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10717     }
10718 
10719     // Don't resolve overloads if the other type is overloadable.
10720     if (pty->getKind() == BuiltinType::Overload &&
10721         LHSExpr->getType()->isOverloadableType())
10722       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10723 
10724     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
10725     if (!resolvedRHS.isUsable()) return ExprError();
10726     RHSExpr = resolvedRHS.get();
10727   }
10728 
10729   if (getLangOpts().CPlusPlus) {
10730     // If either expression is type-dependent, always build an
10731     // overloaded op.
10732     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
10733       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10734 
10735     // Otherwise, build an overloaded op if either expression has an
10736     // overloadable type.
10737     if (LHSExpr->getType()->isOverloadableType() ||
10738         RHSExpr->getType()->isOverloadableType())
10739       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
10740   }
10741 
10742   // Build a built-in binary operation.
10743   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
10744 }
10745 
10746 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
10747                                       UnaryOperatorKind Opc,
10748                                       Expr *InputExpr) {
10749   ExprResult Input = InputExpr;
10750   ExprValueKind VK = VK_RValue;
10751   ExprObjectKind OK = OK_Ordinary;
10752   QualType resultType;
10753   if (getLangOpts().OpenCL) {
10754     // The only legal unary operation for atomics is '&'.
10755     if (Opc != UO_AddrOf && InputExpr->getType()->isAtomicType()) {
10756       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10757                        << InputExpr->getType()
10758                        << Input.get()->getSourceRange());
10759     }
10760   }
10761   switch (Opc) {
10762   case UO_PreInc:
10763   case UO_PreDec:
10764   case UO_PostInc:
10765   case UO_PostDec:
10766     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OK,
10767                                                 OpLoc,
10768                                                 Opc == UO_PreInc ||
10769                                                 Opc == UO_PostInc,
10770                                                 Opc == UO_PreInc ||
10771                                                 Opc == UO_PreDec);
10772     break;
10773   case UO_AddrOf:
10774     resultType = CheckAddressOfOperand(Input, OpLoc);
10775     RecordModifiableNonNullParam(*this, InputExpr);
10776     break;
10777   case UO_Deref: {
10778     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10779     if (Input.isInvalid()) return ExprError();
10780     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
10781     break;
10782   }
10783   case UO_Plus:
10784   case UO_Minus:
10785     Input = UsualUnaryConversions(Input.get());
10786     if (Input.isInvalid()) return ExprError();
10787     resultType = Input.get()->getType();
10788     if (resultType->isDependentType())
10789       break;
10790     if (resultType->isArithmeticType()) // C99 6.5.3.3p1
10791       break;
10792     else if (resultType->isVectorType() &&
10793              // The z vector extensions don't allow + or - with bool vectors.
10794              (!Context.getLangOpts().ZVector ||
10795               resultType->getAs<VectorType>()->getVectorKind() !=
10796               VectorType::AltiVecBool))
10797       break;
10798     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
10799              Opc == UO_Plus &&
10800              resultType->isPointerType())
10801       break;
10802 
10803     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10804       << resultType << Input.get()->getSourceRange());
10805 
10806   case UO_Not: // bitwise complement
10807     Input = UsualUnaryConversions(Input.get());
10808     if (Input.isInvalid())
10809       return ExprError();
10810     resultType = Input.get()->getType();
10811     if (resultType->isDependentType())
10812       break;
10813     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
10814     if (resultType->isComplexType() || resultType->isComplexIntegerType())
10815       // C99 does not support '~' for complex conjugation.
10816       Diag(OpLoc, diag::ext_integer_complement_complex)
10817           << resultType << Input.get()->getSourceRange();
10818     else if (resultType->hasIntegerRepresentation())
10819       break;
10820     else if (resultType->isExtVectorType()) {
10821       if (Context.getLangOpts().OpenCL) {
10822         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
10823         // on vector float types.
10824         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10825         if (!T->isIntegerType())
10826           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10827                            << resultType << Input.get()->getSourceRange());
10828       }
10829       break;
10830     } else {
10831       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10832                        << resultType << Input.get()->getSourceRange());
10833     }
10834     break;
10835 
10836   case UO_LNot: // logical negation
10837     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
10838     Input = DefaultFunctionArrayLvalueConversion(Input.get());
10839     if (Input.isInvalid()) return ExprError();
10840     resultType = Input.get()->getType();
10841 
10842     // Though we still have to promote half FP to float...
10843     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
10844       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
10845       resultType = Context.FloatTy;
10846     }
10847 
10848     if (resultType->isDependentType())
10849       break;
10850     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
10851       // C99 6.5.3.3p1: ok, fallthrough;
10852       if (Context.getLangOpts().CPlusPlus) {
10853         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
10854         // operand contextually converted to bool.
10855         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
10856                                   ScalarTypeToBooleanCastKind(resultType));
10857       } else if (Context.getLangOpts().OpenCL &&
10858                  Context.getLangOpts().OpenCLVersion < 120) {
10859         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10860         // operate on scalar float types.
10861         if (!resultType->isIntegerType())
10862           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10863                            << resultType << Input.get()->getSourceRange());
10864       }
10865     } else if (resultType->isExtVectorType()) {
10866       if (Context.getLangOpts().OpenCL &&
10867           Context.getLangOpts().OpenCLVersion < 120) {
10868         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
10869         // operate on vector float types.
10870         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
10871         if (!T->isIntegerType())
10872           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10873                            << resultType << Input.get()->getSourceRange());
10874       }
10875       // Vector logical not returns the signed variant of the operand type.
10876       resultType = GetSignedVectorType(resultType);
10877       break;
10878     } else {
10879       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
10880         << resultType << Input.get()->getSourceRange());
10881     }
10882 
10883     // LNot always has type int. C99 6.5.3.3p5.
10884     // In C++, it's bool. C++ 5.3.1p8
10885     resultType = Context.getLogicalOperationType();
10886     break;
10887   case UO_Real:
10888   case UO_Imag:
10889     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
10890     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
10891     // complex l-values to ordinary l-values and all other values to r-values.
10892     if (Input.isInvalid()) return ExprError();
10893     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
10894       if (Input.get()->getValueKind() != VK_RValue &&
10895           Input.get()->getObjectKind() == OK_Ordinary)
10896         VK = Input.get()->getValueKind();
10897     } else if (!getLangOpts().CPlusPlus) {
10898       // In C, a volatile scalar is read by __imag. In C++, it is not.
10899       Input = DefaultLvalueConversion(Input.get());
10900     }
10901     break;
10902   case UO_Extension:
10903   case UO_Coawait:
10904     resultType = Input.get()->getType();
10905     VK = Input.get()->getValueKind();
10906     OK = Input.get()->getObjectKind();
10907     break;
10908   }
10909   if (resultType.isNull() || Input.isInvalid())
10910     return ExprError();
10911 
10912   // Check for array bounds violations in the operand of the UnaryOperator,
10913   // except for the '*' and '&' operators that have to be handled specially
10914   // by CheckArrayAccess (as there are special cases like &array[arraysize]
10915   // that are explicitly defined as valid by the standard).
10916   if (Opc != UO_AddrOf && Opc != UO_Deref)
10917     CheckArrayAccess(Input.get());
10918 
10919   return new (Context)
10920       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
10921 }
10922 
10923 /// \brief Determine whether the given expression is a qualified member
10924 /// access expression, of a form that could be turned into a pointer to member
10925 /// with the address-of operator.
10926 static bool isQualifiedMemberAccess(Expr *E) {
10927   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
10928     if (!DRE->getQualifier())
10929       return false;
10930 
10931     ValueDecl *VD = DRE->getDecl();
10932     if (!VD->isCXXClassMember())
10933       return false;
10934 
10935     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
10936       return true;
10937     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
10938       return Method->isInstance();
10939 
10940     return false;
10941   }
10942 
10943   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
10944     if (!ULE->getQualifier())
10945       return false;
10946 
10947     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
10948                                            DEnd = ULE->decls_end();
10949          D != DEnd; ++D) {
10950       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
10951         if (Method->isInstance())
10952           return true;
10953       } else {
10954         // Overload set does not contain methods.
10955         break;
10956       }
10957     }
10958 
10959     return false;
10960   }
10961 
10962   return false;
10963 }
10964 
10965 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
10966                               UnaryOperatorKind Opc, Expr *Input) {
10967   // First things first: handle placeholders so that the
10968   // overloaded-operator check considers the right type.
10969   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
10970     // Increment and decrement of pseudo-object references.
10971     if (pty->getKind() == BuiltinType::PseudoObject &&
10972         UnaryOperator::isIncrementDecrementOp(Opc))
10973       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
10974 
10975     // extension is always a builtin operator.
10976     if (Opc == UO_Extension)
10977       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10978 
10979     // & gets special logic for several kinds of placeholder.
10980     // The builtin code knows what to do.
10981     if (Opc == UO_AddrOf &&
10982         (pty->getKind() == BuiltinType::Overload ||
10983          pty->getKind() == BuiltinType::UnknownAny ||
10984          pty->getKind() == BuiltinType::BoundMember))
10985       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10986 
10987     // Anything else needs to be handled now.
10988     ExprResult Result = CheckPlaceholderExpr(Input);
10989     if (Result.isInvalid()) return ExprError();
10990     Input = Result.get();
10991   }
10992 
10993   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
10994       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
10995       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
10996     // Find all of the overloaded operators visible from this
10997     // point. We perform both an operator-name lookup from the local
10998     // scope and an argument-dependent lookup based on the types of
10999     // the arguments.
11000     UnresolvedSet<16> Functions;
11001     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
11002     if (S && OverOp != OO_None)
11003       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
11004                                    Functions);
11005 
11006     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
11007   }
11008 
11009   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
11010 }
11011 
11012 // Unary Operators.  'Tok' is the token for the operator.
11013 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
11014                               tok::TokenKind Op, Expr *Input) {
11015   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
11016 }
11017 
11018 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
11019 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
11020                                 LabelDecl *TheDecl) {
11021   TheDecl->markUsed(Context);
11022   // Create the AST node.  The address of a label always has type 'void*'.
11023   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
11024                                      Context.getPointerType(Context.VoidTy));
11025 }
11026 
11027 /// Given the last statement in a statement-expression, check whether
11028 /// the result is a producing expression (like a call to an
11029 /// ns_returns_retained function) and, if so, rebuild it to hoist the
11030 /// release out of the full-expression.  Otherwise, return null.
11031 /// Cannot fail.
11032 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
11033   // Should always be wrapped with one of these.
11034   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
11035   if (!cleanups) return nullptr;
11036 
11037   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
11038   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
11039     return nullptr;
11040 
11041   // Splice out the cast.  This shouldn't modify any interesting
11042   // features of the statement.
11043   Expr *producer = cast->getSubExpr();
11044   assert(producer->getType() == cast->getType());
11045   assert(producer->getValueKind() == cast->getValueKind());
11046   cleanups->setSubExpr(producer);
11047   return cleanups;
11048 }
11049 
11050 void Sema::ActOnStartStmtExpr() {
11051   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
11052 }
11053 
11054 void Sema::ActOnStmtExprError() {
11055   // Note that function is also called by TreeTransform when leaving a
11056   // StmtExpr scope without rebuilding anything.
11057 
11058   DiscardCleanupsInEvaluationContext();
11059   PopExpressionEvaluationContext();
11060 }
11061 
11062 ExprResult
11063 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
11064                     SourceLocation RPLoc) { // "({..})"
11065   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
11066   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
11067 
11068   if (hasAnyUnrecoverableErrorsInThisFunction())
11069     DiscardCleanupsInEvaluationContext();
11070   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
11071   PopExpressionEvaluationContext();
11072 
11073   // FIXME: there are a variety of strange constraints to enforce here, for
11074   // example, it is not possible to goto into a stmt expression apparently.
11075   // More semantic analysis is needed.
11076 
11077   // If there are sub-stmts in the compound stmt, take the type of the last one
11078   // as the type of the stmtexpr.
11079   QualType Ty = Context.VoidTy;
11080   bool StmtExprMayBindToTemp = false;
11081   if (!Compound->body_empty()) {
11082     Stmt *LastStmt = Compound->body_back();
11083     LabelStmt *LastLabelStmt = nullptr;
11084     // If LastStmt is a label, skip down through into the body.
11085     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
11086       LastLabelStmt = Label;
11087       LastStmt = Label->getSubStmt();
11088     }
11089 
11090     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
11091       // Do function/array conversion on the last expression, but not
11092       // lvalue-to-rvalue.  However, initialize an unqualified type.
11093       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
11094       if (LastExpr.isInvalid())
11095         return ExprError();
11096       Ty = LastExpr.get()->getType().getUnqualifiedType();
11097 
11098       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
11099         // In ARC, if the final expression ends in a consume, splice
11100         // the consume out and bind it later.  In the alternate case
11101         // (when dealing with a retainable type), the result
11102         // initialization will create a produce.  In both cases the
11103         // result will be +1, and we'll need to balance that out with
11104         // a bind.
11105         if (Expr *rebuiltLastStmt
11106               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
11107           LastExpr = rebuiltLastStmt;
11108         } else {
11109           LastExpr = PerformCopyInitialization(
11110                             InitializedEntity::InitializeResult(LPLoc,
11111                                                                 Ty,
11112                                                                 false),
11113                                                    SourceLocation(),
11114                                                LastExpr);
11115         }
11116 
11117         if (LastExpr.isInvalid())
11118           return ExprError();
11119         if (LastExpr.get() != nullptr) {
11120           if (!LastLabelStmt)
11121             Compound->setLastStmt(LastExpr.get());
11122           else
11123             LastLabelStmt->setSubStmt(LastExpr.get());
11124           StmtExprMayBindToTemp = true;
11125         }
11126       }
11127     }
11128   }
11129 
11130   // FIXME: Check that expression type is complete/non-abstract; statement
11131   // expressions are not lvalues.
11132   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
11133   if (StmtExprMayBindToTemp)
11134     return MaybeBindToTemporary(ResStmtExpr);
11135   return ResStmtExpr;
11136 }
11137 
11138 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
11139                                       TypeSourceInfo *TInfo,
11140                                       ArrayRef<OffsetOfComponent> Components,
11141                                       SourceLocation RParenLoc) {
11142   QualType ArgTy = TInfo->getType();
11143   bool Dependent = ArgTy->isDependentType();
11144   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
11145 
11146   // We must have at least one component that refers to the type, and the first
11147   // one is known to be a field designator.  Verify that the ArgTy represents
11148   // a struct/union/class.
11149   if (!Dependent && !ArgTy->isRecordType())
11150     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
11151                        << ArgTy << TypeRange);
11152 
11153   // Type must be complete per C99 7.17p3 because a declaring a variable
11154   // with an incomplete type would be ill-formed.
11155   if (!Dependent
11156       && RequireCompleteType(BuiltinLoc, ArgTy,
11157                              diag::err_offsetof_incomplete_type, TypeRange))
11158     return ExprError();
11159 
11160   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
11161   // GCC extension, diagnose them.
11162   // FIXME: This diagnostic isn't actually visible because the location is in
11163   // a system header!
11164   if (Components.size() != 1)
11165     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
11166       << SourceRange(Components[1].LocStart, Components.back().LocEnd);
11167 
11168   bool DidWarnAboutNonPOD = false;
11169   QualType CurrentType = ArgTy;
11170   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
11171   SmallVector<OffsetOfNode, 4> Comps;
11172   SmallVector<Expr*, 4> Exprs;
11173   for (const OffsetOfComponent &OC : Components) {
11174     if (OC.isBrackets) {
11175       // Offset of an array sub-field.  TODO: Should we allow vector elements?
11176       if (!CurrentType->isDependentType()) {
11177         const ArrayType *AT = Context.getAsArrayType(CurrentType);
11178         if(!AT)
11179           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
11180                            << CurrentType);
11181         CurrentType = AT->getElementType();
11182       } else
11183         CurrentType = Context.DependentTy;
11184 
11185       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
11186       if (IdxRval.isInvalid())
11187         return ExprError();
11188       Expr *Idx = IdxRval.get();
11189 
11190       // The expression must be an integral expression.
11191       // FIXME: An integral constant expression?
11192       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
11193           !Idx->getType()->isIntegerType())
11194         return ExprError(Diag(Idx->getLocStart(),
11195                               diag::err_typecheck_subscript_not_integer)
11196                          << Idx->getSourceRange());
11197 
11198       // Record this array index.
11199       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
11200       Exprs.push_back(Idx);
11201       continue;
11202     }
11203 
11204     // Offset of a field.
11205     if (CurrentType->isDependentType()) {
11206       // We have the offset of a field, but we can't look into the dependent
11207       // type. Just record the identifier of the field.
11208       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
11209       CurrentType = Context.DependentTy;
11210       continue;
11211     }
11212 
11213     // We need to have a complete type to look into.
11214     if (RequireCompleteType(OC.LocStart, CurrentType,
11215                             diag::err_offsetof_incomplete_type))
11216       return ExprError();
11217 
11218     // Look for the designated field.
11219     const RecordType *RC = CurrentType->getAs<RecordType>();
11220     if (!RC)
11221       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
11222                        << CurrentType);
11223     RecordDecl *RD = RC->getDecl();
11224 
11225     // C++ [lib.support.types]p5:
11226     //   The macro offsetof accepts a restricted set of type arguments in this
11227     //   International Standard. type shall be a POD structure or a POD union
11228     //   (clause 9).
11229     // C++11 [support.types]p4:
11230     //   If type is not a standard-layout class (Clause 9), the results are
11231     //   undefined.
11232     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
11233       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
11234       unsigned DiagID =
11235         LangOpts.CPlusPlus11? diag::ext_offsetof_non_standardlayout_type
11236                             : diag::ext_offsetof_non_pod_type;
11237 
11238       if (!IsSafe && !DidWarnAboutNonPOD &&
11239           DiagRuntimeBehavior(BuiltinLoc, nullptr,
11240                               PDiag(DiagID)
11241                               << SourceRange(Components[0].LocStart, OC.LocEnd)
11242                               << CurrentType))
11243         DidWarnAboutNonPOD = true;
11244     }
11245 
11246     // Look for the field.
11247     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
11248     LookupQualifiedName(R, RD);
11249     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
11250     IndirectFieldDecl *IndirectMemberDecl = nullptr;
11251     if (!MemberDecl) {
11252       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
11253         MemberDecl = IndirectMemberDecl->getAnonField();
11254     }
11255 
11256     if (!MemberDecl)
11257       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
11258                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
11259                                                               OC.LocEnd));
11260 
11261     // C99 7.17p3:
11262     //   (If the specified member is a bit-field, the behavior is undefined.)
11263     //
11264     // We diagnose this as an error.
11265     if (MemberDecl->isBitField()) {
11266       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
11267         << MemberDecl->getDeclName()
11268         << SourceRange(BuiltinLoc, RParenLoc);
11269       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
11270       return ExprError();
11271     }
11272 
11273     RecordDecl *Parent = MemberDecl->getParent();
11274     if (IndirectMemberDecl)
11275       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
11276 
11277     // If the member was found in a base class, introduce OffsetOfNodes for
11278     // the base class indirections.
11279     CXXBasePaths Paths;
11280     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
11281       if (Paths.getDetectedVirtual()) {
11282         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
11283           << MemberDecl->getDeclName()
11284           << SourceRange(BuiltinLoc, RParenLoc);
11285         return ExprError();
11286       }
11287 
11288       CXXBasePath &Path = Paths.front();
11289       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
11290            B != BEnd; ++B)
11291         Comps.push_back(OffsetOfNode(B->Base));
11292     }
11293 
11294     if (IndirectMemberDecl) {
11295       for (auto *FI : IndirectMemberDecl->chain()) {
11296         assert(isa<FieldDecl>(FI));
11297         Comps.push_back(OffsetOfNode(OC.LocStart,
11298                                      cast<FieldDecl>(FI), OC.LocEnd));
11299       }
11300     } else
11301       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
11302 
11303     CurrentType = MemberDecl->getType().getNonReferenceType();
11304   }
11305 
11306   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
11307                               Comps, Exprs, RParenLoc);
11308 }
11309 
11310 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
11311                                       SourceLocation BuiltinLoc,
11312                                       SourceLocation TypeLoc,
11313                                       ParsedType ParsedArgTy,
11314                                       ArrayRef<OffsetOfComponent> Components,
11315                                       SourceLocation RParenLoc) {
11316 
11317   TypeSourceInfo *ArgTInfo;
11318   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
11319   if (ArgTy.isNull())
11320     return ExprError();
11321 
11322   if (!ArgTInfo)
11323     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
11324 
11325   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, Components, RParenLoc);
11326 }
11327 
11328 
11329 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
11330                                  Expr *CondExpr,
11331                                  Expr *LHSExpr, Expr *RHSExpr,
11332                                  SourceLocation RPLoc) {
11333   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
11334 
11335   ExprValueKind VK = VK_RValue;
11336   ExprObjectKind OK = OK_Ordinary;
11337   QualType resType;
11338   bool ValueDependent = false;
11339   bool CondIsTrue = false;
11340   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
11341     resType = Context.DependentTy;
11342     ValueDependent = true;
11343   } else {
11344     // The conditional expression is required to be a constant expression.
11345     llvm::APSInt condEval(32);
11346     ExprResult CondICE
11347       = VerifyIntegerConstantExpression(CondExpr, &condEval,
11348           diag::err_typecheck_choose_expr_requires_constant, false);
11349     if (CondICE.isInvalid())
11350       return ExprError();
11351     CondExpr = CondICE.get();
11352     CondIsTrue = condEval.getZExtValue();
11353 
11354     // If the condition is > zero, then the AST type is the same as the LSHExpr.
11355     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
11356 
11357     resType = ActiveExpr->getType();
11358     ValueDependent = ActiveExpr->isValueDependent();
11359     VK = ActiveExpr->getValueKind();
11360     OK = ActiveExpr->getObjectKind();
11361   }
11362 
11363   return new (Context)
11364       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
11365                  CondIsTrue, resType->isDependentType(), ValueDependent);
11366 }
11367 
11368 //===----------------------------------------------------------------------===//
11369 // Clang Extensions.
11370 //===----------------------------------------------------------------------===//
11371 
11372 /// ActOnBlockStart - This callback is invoked when a block literal is started.
11373 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
11374   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
11375 
11376   if (LangOpts.CPlusPlus) {
11377     Decl *ManglingContextDecl;
11378     if (MangleNumberingContext *MCtx =
11379             getCurrentMangleNumberContext(Block->getDeclContext(),
11380                                           ManglingContextDecl)) {
11381       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
11382       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
11383     }
11384   }
11385 
11386   PushBlockScope(CurScope, Block);
11387   CurContext->addDecl(Block);
11388   if (CurScope)
11389     PushDeclContext(CurScope, Block);
11390   else
11391     CurContext = Block;
11392 
11393   getCurBlock()->HasImplicitReturnType = true;
11394 
11395   // Enter a new evaluation context to insulate the block from any
11396   // cleanups from the enclosing full-expression.
11397   PushExpressionEvaluationContext(PotentiallyEvaluated);
11398 }
11399 
11400 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
11401                                Scope *CurScope) {
11402   assert(ParamInfo.getIdentifier() == nullptr &&
11403          "block-id should have no identifier!");
11404   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
11405   BlockScopeInfo *CurBlock = getCurBlock();
11406 
11407   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
11408   QualType T = Sig->getType();
11409 
11410   // FIXME: We should allow unexpanded parameter packs here, but that would,
11411   // in turn, make the block expression contain unexpanded parameter packs.
11412   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
11413     // Drop the parameters.
11414     FunctionProtoType::ExtProtoInfo EPI;
11415     EPI.HasTrailingReturn = false;
11416     EPI.TypeQuals |= DeclSpec::TQ_const;
11417     T = Context.getFunctionType(Context.DependentTy, None, EPI);
11418     Sig = Context.getTrivialTypeSourceInfo(T);
11419   }
11420 
11421   // GetTypeForDeclarator always produces a function type for a block
11422   // literal signature.  Furthermore, it is always a FunctionProtoType
11423   // unless the function was written with a typedef.
11424   assert(T->isFunctionType() &&
11425          "GetTypeForDeclarator made a non-function block signature");
11426 
11427   // Look for an explicit signature in that function type.
11428   FunctionProtoTypeLoc ExplicitSignature;
11429 
11430   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
11431   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
11432 
11433     // Check whether that explicit signature was synthesized by
11434     // GetTypeForDeclarator.  If so, don't save that as part of the
11435     // written signature.
11436     if (ExplicitSignature.getLocalRangeBegin() ==
11437         ExplicitSignature.getLocalRangeEnd()) {
11438       // This would be much cheaper if we stored TypeLocs instead of
11439       // TypeSourceInfos.
11440       TypeLoc Result = ExplicitSignature.getReturnLoc();
11441       unsigned Size = Result.getFullDataSize();
11442       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
11443       Sig->getTypeLoc().initializeFullCopy(Result, Size);
11444 
11445       ExplicitSignature = FunctionProtoTypeLoc();
11446     }
11447   }
11448 
11449   CurBlock->TheDecl->setSignatureAsWritten(Sig);
11450   CurBlock->FunctionType = T;
11451 
11452   const FunctionType *Fn = T->getAs<FunctionType>();
11453   QualType RetTy = Fn->getReturnType();
11454   bool isVariadic =
11455     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
11456 
11457   CurBlock->TheDecl->setIsVariadic(isVariadic);
11458 
11459   // Context.DependentTy is used as a placeholder for a missing block
11460   // return type.  TODO:  what should we do with declarators like:
11461   //   ^ * { ... }
11462   // If the answer is "apply template argument deduction"....
11463   if (RetTy != Context.DependentTy) {
11464     CurBlock->ReturnType = RetTy;
11465     CurBlock->TheDecl->setBlockMissingReturnType(false);
11466     CurBlock->HasImplicitReturnType = false;
11467   }
11468 
11469   // Push block parameters from the declarator if we had them.
11470   SmallVector<ParmVarDecl*, 8> Params;
11471   if (ExplicitSignature) {
11472     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
11473       ParmVarDecl *Param = ExplicitSignature.getParam(I);
11474       if (Param->getIdentifier() == nullptr &&
11475           !Param->isImplicit() &&
11476           !Param->isInvalidDecl() &&
11477           !getLangOpts().CPlusPlus)
11478         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
11479       Params.push_back(Param);
11480     }
11481 
11482   // Fake up parameter variables if we have a typedef, like
11483   //   ^ fntype { ... }
11484   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
11485     for (const auto &I : Fn->param_types()) {
11486       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
11487           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
11488       Params.push_back(Param);
11489     }
11490   }
11491 
11492   // Set the parameters on the block decl.
11493   if (!Params.empty()) {
11494     CurBlock->TheDecl->setParams(Params);
11495     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
11496                              CurBlock->TheDecl->param_end(),
11497                              /*CheckParameterNames=*/false);
11498   }
11499 
11500   // Finally we can process decl attributes.
11501   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
11502 
11503   // Put the parameter variables in scope.
11504   for (auto AI : CurBlock->TheDecl->params()) {
11505     AI->setOwningFunction(CurBlock->TheDecl);
11506 
11507     // If this has an identifier, add it to the scope stack.
11508     if (AI->getIdentifier()) {
11509       CheckShadow(CurBlock->TheScope, AI);
11510 
11511       PushOnScopeChains(AI, CurBlock->TheScope);
11512     }
11513   }
11514 }
11515 
11516 /// ActOnBlockError - If there is an error parsing a block, this callback
11517 /// is invoked to pop the information about the block from the action impl.
11518 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
11519   // Leave the expression-evaluation context.
11520   DiscardCleanupsInEvaluationContext();
11521   PopExpressionEvaluationContext();
11522 
11523   // Pop off CurBlock, handle nested blocks.
11524   PopDeclContext();
11525   PopFunctionScopeInfo();
11526 }
11527 
11528 /// ActOnBlockStmtExpr - This is called when the body of a block statement
11529 /// literal was successfully completed.  ^(int x){...}
11530 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
11531                                     Stmt *Body, Scope *CurScope) {
11532   // If blocks are disabled, emit an error.
11533   if (!LangOpts.Blocks)
11534     Diag(CaretLoc, diag::err_blocks_disable);
11535 
11536   // Leave the expression-evaluation context.
11537   if (hasAnyUnrecoverableErrorsInThisFunction())
11538     DiscardCleanupsInEvaluationContext();
11539   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
11540   PopExpressionEvaluationContext();
11541 
11542   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
11543 
11544   if (BSI->HasImplicitReturnType)
11545     deduceClosureReturnType(*BSI);
11546 
11547   PopDeclContext();
11548 
11549   QualType RetTy = Context.VoidTy;
11550   if (!BSI->ReturnType.isNull())
11551     RetTy = BSI->ReturnType;
11552 
11553   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
11554   QualType BlockTy;
11555 
11556   // Set the captured variables on the block.
11557   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
11558   SmallVector<BlockDecl::Capture, 4> Captures;
11559   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
11560     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
11561     if (Cap.isThisCapture())
11562       continue;
11563     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
11564                               Cap.isNested(), Cap.getInitExpr());
11565     Captures.push_back(NewCap);
11566   }
11567   BSI->TheDecl->setCaptures(Context, Captures, BSI->CXXThisCaptureIndex != 0);
11568 
11569   // If the user wrote a function type in some form, try to use that.
11570   if (!BSI->FunctionType.isNull()) {
11571     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
11572 
11573     FunctionType::ExtInfo Ext = FTy->getExtInfo();
11574     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
11575 
11576     // Turn protoless block types into nullary block types.
11577     if (isa<FunctionNoProtoType>(FTy)) {
11578       FunctionProtoType::ExtProtoInfo EPI;
11579       EPI.ExtInfo = Ext;
11580       BlockTy = Context.getFunctionType(RetTy, None, EPI);
11581 
11582     // Otherwise, if we don't need to change anything about the function type,
11583     // preserve its sugar structure.
11584     } else if (FTy->getReturnType() == RetTy &&
11585                (!NoReturn || FTy->getNoReturnAttr())) {
11586       BlockTy = BSI->FunctionType;
11587 
11588     // Otherwise, make the minimal modifications to the function type.
11589     } else {
11590       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
11591       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
11592       EPI.TypeQuals = 0; // FIXME: silently?
11593       EPI.ExtInfo = Ext;
11594       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
11595     }
11596 
11597   // If we don't have a function type, just build one from nothing.
11598   } else {
11599     FunctionProtoType::ExtProtoInfo EPI;
11600     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
11601     BlockTy = Context.getFunctionType(RetTy, None, EPI);
11602   }
11603 
11604   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
11605                            BSI->TheDecl->param_end());
11606   BlockTy = Context.getBlockPointerType(BlockTy);
11607 
11608   // If needed, diagnose invalid gotos and switches in the block.
11609   if (getCurFunction()->NeedsScopeChecking() &&
11610       !PP.isCodeCompletionEnabled())
11611     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
11612 
11613   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
11614 
11615   // Try to apply the named return value optimization. We have to check again
11616   // if we can do this, though, because blocks keep return statements around
11617   // to deduce an implicit return type.
11618   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
11619       !BSI->TheDecl->isDependentContext())
11620     computeNRVO(Body, BSI);
11621 
11622   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
11623   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11624   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
11625 
11626   // If the block isn't obviously global, i.e. it captures anything at
11627   // all, then we need to do a few things in the surrounding context:
11628   if (Result->getBlockDecl()->hasCaptures()) {
11629     // First, this expression has a new cleanup object.
11630     ExprCleanupObjects.push_back(Result->getBlockDecl());
11631     ExprNeedsCleanups = true;
11632 
11633     // It also gets a branch-protected scope if any of the captured
11634     // variables needs destruction.
11635     for (const auto &CI : Result->getBlockDecl()->captures()) {
11636       const VarDecl *var = CI.getVariable();
11637       if (var->getType().isDestructedType() != QualType::DK_none) {
11638         getCurFunction()->setHasBranchProtectedScope();
11639         break;
11640       }
11641     }
11642   }
11643 
11644   return Result;
11645 }
11646 
11647 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
11648                                         Expr *E, ParsedType Ty,
11649                                         SourceLocation RPLoc) {
11650   TypeSourceInfo *TInfo;
11651   GetTypeFromParser(Ty, &TInfo);
11652   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
11653 }
11654 
11655 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
11656                                 Expr *E, TypeSourceInfo *TInfo,
11657                                 SourceLocation RPLoc) {
11658   Expr *OrigExpr = E;
11659   bool IsMS = false;
11660 
11661   // It might be a __builtin_ms_va_list. (But don't ever mark a va_arg()
11662   // as Microsoft ABI on an actual Microsoft platform, where
11663   // __builtin_ms_va_list and __builtin_va_list are the same.)
11664   if (!E->isTypeDependent() && Context.getTargetInfo().hasBuiltinMSVaList() &&
11665       Context.getTargetInfo().getBuiltinVaListKind() != TargetInfo::CharPtrBuiltinVaList) {
11666     QualType MSVaListType = Context.getBuiltinMSVaListType();
11667     if (Context.hasSameType(MSVaListType, E->getType())) {
11668       if (CheckForModifiableLvalue(E, BuiltinLoc, *this))
11669         return ExprError();
11670       IsMS = true;
11671     }
11672   }
11673 
11674   // Get the va_list type
11675   QualType VaListType = Context.getBuiltinVaListType();
11676   if (!IsMS) {
11677     if (VaListType->isArrayType()) {
11678       // Deal with implicit array decay; for example, on x86-64,
11679       // va_list is an array, but it's supposed to decay to
11680       // a pointer for va_arg.
11681       VaListType = Context.getArrayDecayedType(VaListType);
11682       // Make sure the input expression also decays appropriately.
11683       ExprResult Result = UsualUnaryConversions(E);
11684       if (Result.isInvalid())
11685         return ExprError();
11686       E = Result.get();
11687     } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
11688       // If va_list is a record type and we are compiling in C++ mode,
11689       // check the argument using reference binding.
11690       InitializedEntity Entity = InitializedEntity::InitializeParameter(
11691           Context, Context.getLValueReferenceType(VaListType), false);
11692       ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
11693       if (Init.isInvalid())
11694         return ExprError();
11695       E = Init.getAs<Expr>();
11696     } else {
11697       // Otherwise, the va_list argument must be an l-value because
11698       // it is modified by va_arg.
11699       if (!E->isTypeDependent() &&
11700           CheckForModifiableLvalue(E, BuiltinLoc, *this))
11701         return ExprError();
11702     }
11703   }
11704 
11705   if (!IsMS && !E->isTypeDependent() &&
11706       !Context.hasSameType(VaListType, E->getType()))
11707     return ExprError(Diag(E->getLocStart(),
11708                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
11709       << OrigExpr->getType() << E->getSourceRange());
11710 
11711   if (!TInfo->getType()->isDependentType()) {
11712     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
11713                             diag::err_second_parameter_to_va_arg_incomplete,
11714                             TInfo->getTypeLoc()))
11715       return ExprError();
11716 
11717     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
11718                                TInfo->getType(),
11719                                diag::err_second_parameter_to_va_arg_abstract,
11720                                TInfo->getTypeLoc()))
11721       return ExprError();
11722 
11723     if (!TInfo->getType().isPODType(Context)) {
11724       Diag(TInfo->getTypeLoc().getBeginLoc(),
11725            TInfo->getType()->isObjCLifetimeType()
11726              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
11727              : diag::warn_second_parameter_to_va_arg_not_pod)
11728         << TInfo->getType()
11729         << TInfo->getTypeLoc().getSourceRange();
11730     }
11731 
11732     // Check for va_arg where arguments of the given type will be promoted
11733     // (i.e. this va_arg is guaranteed to have undefined behavior).
11734     QualType PromoteType;
11735     if (TInfo->getType()->isPromotableIntegerType()) {
11736       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
11737       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
11738         PromoteType = QualType();
11739     }
11740     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
11741       PromoteType = Context.DoubleTy;
11742     if (!PromoteType.isNull())
11743       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
11744                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
11745                           << TInfo->getType()
11746                           << PromoteType
11747                           << TInfo->getTypeLoc().getSourceRange());
11748   }
11749 
11750   QualType T = TInfo->getType().getNonLValueExprType(Context);
11751   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T, IsMS);
11752 }
11753 
11754 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
11755   // The type of __null will be int or long, depending on the size of
11756   // pointers on the target.
11757   QualType Ty;
11758   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
11759   if (pw == Context.getTargetInfo().getIntWidth())
11760     Ty = Context.IntTy;
11761   else if (pw == Context.getTargetInfo().getLongWidth())
11762     Ty = Context.LongTy;
11763   else if (pw == Context.getTargetInfo().getLongLongWidth())
11764     Ty = Context.LongLongTy;
11765   else {
11766     llvm_unreachable("I don't know size of pointer!");
11767   }
11768 
11769   return new (Context) GNUNullExpr(Ty, TokenLoc);
11770 }
11771 
11772 bool
11773 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
11774   if (!getLangOpts().ObjC1)
11775     return false;
11776 
11777   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
11778   if (!PT)
11779     return false;
11780 
11781   if (!PT->isObjCIdType()) {
11782     // Check if the destination is the 'NSString' interface.
11783     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
11784     if (!ID || !ID->getIdentifier()->isStr("NSString"))
11785       return false;
11786   }
11787 
11788   // Ignore any parens, implicit casts (should only be
11789   // array-to-pointer decays), and not-so-opaque values.  The last is
11790   // important for making this trigger for property assignments.
11791   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
11792   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
11793     if (OV->getSourceExpr())
11794       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
11795 
11796   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
11797   if (!SL || !SL->isAscii())
11798     return false;
11799   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
11800     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
11801   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
11802   return true;
11803 }
11804 
11805 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
11806                                     SourceLocation Loc,
11807                                     QualType DstType, QualType SrcType,
11808                                     Expr *SrcExpr, AssignmentAction Action,
11809                                     bool *Complained) {
11810   if (Complained)
11811     *Complained = false;
11812 
11813   // Decode the result (notice that AST's are still created for extensions).
11814   bool CheckInferredResultType = false;
11815   bool isInvalid = false;
11816   unsigned DiagKind = 0;
11817   FixItHint Hint;
11818   ConversionFixItGenerator ConvHints;
11819   bool MayHaveConvFixit = false;
11820   bool MayHaveFunctionDiff = false;
11821   const ObjCInterfaceDecl *IFace = nullptr;
11822   const ObjCProtocolDecl *PDecl = nullptr;
11823 
11824   switch (ConvTy) {
11825   case Compatible:
11826       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
11827       return false;
11828 
11829   case PointerToInt:
11830     DiagKind = diag::ext_typecheck_convert_pointer_int;
11831     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11832     MayHaveConvFixit = true;
11833     break;
11834   case IntToPointer:
11835     DiagKind = diag::ext_typecheck_convert_int_pointer;
11836     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11837     MayHaveConvFixit = true;
11838     break;
11839   case IncompatiblePointer:
11840       DiagKind =
11841         (Action == AA_Passing_CFAudited ?
11842           diag::err_arc_typecheck_convert_incompatible_pointer :
11843           diag::ext_typecheck_convert_incompatible_pointer);
11844     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
11845       SrcType->isObjCObjectPointerType();
11846     if (Hint.isNull() && !CheckInferredResultType) {
11847       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11848     }
11849     else if (CheckInferredResultType) {
11850       SrcType = SrcType.getUnqualifiedType();
11851       DstType = DstType.getUnqualifiedType();
11852     }
11853     MayHaveConvFixit = true;
11854     break;
11855   case IncompatiblePointerSign:
11856     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
11857     break;
11858   case FunctionVoidPointer:
11859     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
11860     break;
11861   case IncompatiblePointerDiscardsQualifiers: {
11862     // Perform array-to-pointer decay if necessary.
11863     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
11864 
11865     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
11866     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
11867     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
11868       DiagKind = diag::err_typecheck_incompatible_address_space;
11869       break;
11870 
11871 
11872     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
11873       DiagKind = diag::err_typecheck_incompatible_ownership;
11874       break;
11875     }
11876 
11877     llvm_unreachable("unknown error case for discarding qualifiers!");
11878     // fallthrough
11879   }
11880   case CompatiblePointerDiscardsQualifiers:
11881     // If the qualifiers lost were because we were applying the
11882     // (deprecated) C++ conversion from a string literal to a char*
11883     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
11884     // Ideally, this check would be performed in
11885     // checkPointerTypesForAssignment. However, that would require a
11886     // bit of refactoring (so that the second argument is an
11887     // expression, rather than a type), which should be done as part
11888     // of a larger effort to fix checkPointerTypesForAssignment for
11889     // C++ semantics.
11890     if (getLangOpts().CPlusPlus &&
11891         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
11892       return false;
11893     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
11894     break;
11895   case IncompatibleNestedPointerQualifiers:
11896     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
11897     break;
11898   case IntToBlockPointer:
11899     DiagKind = diag::err_int_to_block_pointer;
11900     break;
11901   case IncompatibleBlockPointer:
11902     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
11903     break;
11904   case IncompatibleObjCQualifiedId: {
11905     if (SrcType->isObjCQualifiedIdType()) {
11906       const ObjCObjectPointerType *srcOPT =
11907                 SrcType->getAs<ObjCObjectPointerType>();
11908       for (auto *srcProto : srcOPT->quals()) {
11909         PDecl = srcProto;
11910         break;
11911       }
11912       if (const ObjCInterfaceType *IFaceT =
11913             DstType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11914         IFace = IFaceT->getDecl();
11915     }
11916     else if (DstType->isObjCQualifiedIdType()) {
11917       const ObjCObjectPointerType *dstOPT =
11918         DstType->getAs<ObjCObjectPointerType>();
11919       for (auto *dstProto : dstOPT->quals()) {
11920         PDecl = dstProto;
11921         break;
11922       }
11923       if (const ObjCInterfaceType *IFaceT =
11924             SrcType->getAs<ObjCObjectPointerType>()->getInterfaceType())
11925         IFace = IFaceT->getDecl();
11926     }
11927     DiagKind = diag::warn_incompatible_qualified_id;
11928     break;
11929   }
11930   case IncompatibleVectors:
11931     DiagKind = diag::warn_incompatible_vectors;
11932     break;
11933   case IncompatibleObjCWeakRef:
11934     DiagKind = diag::err_arc_weak_unavailable_assign;
11935     break;
11936   case Incompatible:
11937     DiagKind = diag::err_typecheck_convert_incompatible;
11938     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
11939     MayHaveConvFixit = true;
11940     isInvalid = true;
11941     MayHaveFunctionDiff = true;
11942     break;
11943   }
11944 
11945   QualType FirstType, SecondType;
11946   switch (Action) {
11947   case AA_Assigning:
11948   case AA_Initializing:
11949     // The destination type comes first.
11950     FirstType = DstType;
11951     SecondType = SrcType;
11952     break;
11953 
11954   case AA_Returning:
11955   case AA_Passing:
11956   case AA_Passing_CFAudited:
11957   case AA_Converting:
11958   case AA_Sending:
11959   case AA_Casting:
11960     // The source type comes first.
11961     FirstType = SrcType;
11962     SecondType = DstType;
11963     break;
11964   }
11965 
11966   PartialDiagnostic FDiag = PDiag(DiagKind);
11967   if (Action == AA_Passing_CFAudited)
11968     FDiag << FirstType << SecondType << AA_Passing << SrcExpr->getSourceRange();
11969   else
11970     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
11971 
11972   // If we can fix the conversion, suggest the FixIts.
11973   assert(ConvHints.isNull() || Hint.isNull());
11974   if (!ConvHints.isNull()) {
11975     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
11976          HE = ConvHints.Hints.end(); HI != HE; ++HI)
11977       FDiag << *HI;
11978   } else {
11979     FDiag << Hint;
11980   }
11981   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
11982 
11983   if (MayHaveFunctionDiff)
11984     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
11985 
11986   Diag(Loc, FDiag);
11987   if (DiagKind == diag::warn_incompatible_qualified_id &&
11988       PDecl && IFace && !IFace->hasDefinition())
11989       Diag(IFace->getLocation(), diag::not_incomplete_class_and_qualified_id)
11990         << IFace->getName() << PDecl->getName();
11991 
11992   if (SecondType == Context.OverloadTy)
11993     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
11994                               FirstType, /*TakingAddress=*/true);
11995 
11996   if (CheckInferredResultType)
11997     EmitRelatedResultTypeNote(SrcExpr);
11998 
11999   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
12000     EmitRelatedResultTypeNoteForReturn(DstType);
12001 
12002   if (Complained)
12003     *Complained = true;
12004   return isInvalid;
12005 }
12006 
12007 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12008                                                  llvm::APSInt *Result) {
12009   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
12010   public:
12011     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12012       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
12013     }
12014   } Diagnoser;
12015 
12016   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
12017 }
12018 
12019 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
12020                                                  llvm::APSInt *Result,
12021                                                  unsigned DiagID,
12022                                                  bool AllowFold) {
12023   class IDDiagnoser : public VerifyICEDiagnoser {
12024     unsigned DiagID;
12025 
12026   public:
12027     IDDiagnoser(unsigned DiagID)
12028       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
12029 
12030     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
12031       S.Diag(Loc, DiagID) << SR;
12032     }
12033   } Diagnoser(DiagID);
12034 
12035   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
12036 }
12037 
12038 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
12039                                             SourceRange SR) {
12040   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
12041 }
12042 
12043 ExprResult
12044 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
12045                                       VerifyICEDiagnoser &Diagnoser,
12046                                       bool AllowFold) {
12047   SourceLocation DiagLoc = E->getLocStart();
12048 
12049   if (getLangOpts().CPlusPlus11) {
12050     // C++11 [expr.const]p5:
12051     //   If an expression of literal class type is used in a context where an
12052     //   integral constant expression is required, then that class type shall
12053     //   have a single non-explicit conversion function to an integral or
12054     //   unscoped enumeration type
12055     ExprResult Converted;
12056     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
12057     public:
12058       CXX11ConvertDiagnoser(bool Silent)
12059           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
12060                                 Silent, true) {}
12061 
12062       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
12063                                            QualType T) override {
12064         return S.Diag(Loc, diag::err_ice_not_integral) << T;
12065       }
12066 
12067       SemaDiagnosticBuilder diagnoseIncomplete(
12068           Sema &S, SourceLocation Loc, QualType T) override {
12069         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
12070       }
12071 
12072       SemaDiagnosticBuilder diagnoseExplicitConv(
12073           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12074         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
12075       }
12076 
12077       SemaDiagnosticBuilder noteExplicitConv(
12078           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12079         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12080                  << ConvTy->isEnumeralType() << ConvTy;
12081       }
12082 
12083       SemaDiagnosticBuilder diagnoseAmbiguous(
12084           Sema &S, SourceLocation Loc, QualType T) override {
12085         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
12086       }
12087 
12088       SemaDiagnosticBuilder noteAmbiguous(
12089           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
12090         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
12091                  << ConvTy->isEnumeralType() << ConvTy;
12092       }
12093 
12094       SemaDiagnosticBuilder diagnoseConversion(
12095           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
12096         llvm_unreachable("conversion functions are permitted");
12097       }
12098     } ConvertDiagnoser(Diagnoser.Suppress);
12099 
12100     Converted = PerformContextualImplicitConversion(DiagLoc, E,
12101                                                     ConvertDiagnoser);
12102     if (Converted.isInvalid())
12103       return Converted;
12104     E = Converted.get();
12105     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
12106       return ExprError();
12107   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12108     // An ICE must be of integral or unscoped enumeration type.
12109     if (!Diagnoser.Suppress)
12110       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12111     return ExprError();
12112   }
12113 
12114   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
12115   // in the non-ICE case.
12116   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
12117     if (Result)
12118       *Result = E->EvaluateKnownConstInt(Context);
12119     return E;
12120   }
12121 
12122   Expr::EvalResult EvalResult;
12123   SmallVector<PartialDiagnosticAt, 8> Notes;
12124   EvalResult.Diag = &Notes;
12125 
12126   // Try to evaluate the expression, and produce diagnostics explaining why it's
12127   // not a constant expression as a side-effect.
12128   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
12129                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
12130 
12131   // In C++11, we can rely on diagnostics being produced for any expression
12132   // which is not a constant expression. If no diagnostics were produced, then
12133   // this is a constant expression.
12134   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
12135     if (Result)
12136       *Result = EvalResult.Val.getInt();
12137     return E;
12138   }
12139 
12140   // If our only note is the usual "invalid subexpression" note, just point
12141   // the caret at its location rather than producing an essentially
12142   // redundant note.
12143   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12144         diag::note_invalid_subexpr_in_const_expr) {
12145     DiagLoc = Notes[0].first;
12146     Notes.clear();
12147   }
12148 
12149   if (!Folded || !AllowFold) {
12150     if (!Diagnoser.Suppress) {
12151       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
12152       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12153         Diag(Notes[I].first, Notes[I].second);
12154     }
12155 
12156     return ExprError();
12157   }
12158 
12159   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
12160   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12161     Diag(Notes[I].first, Notes[I].second);
12162 
12163   if (Result)
12164     *Result = EvalResult.Val.getInt();
12165   return E;
12166 }
12167 
12168 namespace {
12169   // Handle the case where we conclude a expression which we speculatively
12170   // considered to be unevaluated is actually evaluated.
12171   class TransformToPE : public TreeTransform<TransformToPE> {
12172     typedef TreeTransform<TransformToPE> BaseTransform;
12173 
12174   public:
12175     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
12176 
12177     // Make sure we redo semantic analysis
12178     bool AlwaysRebuild() { return true; }
12179 
12180     // Make sure we handle LabelStmts correctly.
12181     // FIXME: This does the right thing, but maybe we need a more general
12182     // fix to TreeTransform?
12183     StmtResult TransformLabelStmt(LabelStmt *S) {
12184       S->getDecl()->setStmt(nullptr);
12185       return BaseTransform::TransformLabelStmt(S);
12186     }
12187 
12188     // We need to special-case DeclRefExprs referring to FieldDecls which
12189     // are not part of a member pointer formation; normal TreeTransforming
12190     // doesn't catch this case because of the way we represent them in the AST.
12191     // FIXME: This is a bit ugly; is it really the best way to handle this
12192     // case?
12193     //
12194     // Error on DeclRefExprs referring to FieldDecls.
12195     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
12196       if (isa<FieldDecl>(E->getDecl()) &&
12197           !SemaRef.isUnevaluatedContext())
12198         return SemaRef.Diag(E->getLocation(),
12199                             diag::err_invalid_non_static_member_use)
12200             << E->getDecl() << E->getSourceRange();
12201 
12202       return BaseTransform::TransformDeclRefExpr(E);
12203     }
12204 
12205     // Exception: filter out member pointer formation
12206     ExprResult TransformUnaryOperator(UnaryOperator *E) {
12207       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
12208         return E;
12209 
12210       return BaseTransform::TransformUnaryOperator(E);
12211     }
12212 
12213     ExprResult TransformLambdaExpr(LambdaExpr *E) {
12214       // Lambdas never need to be transformed.
12215       return E;
12216     }
12217   };
12218 }
12219 
12220 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
12221   assert(isUnevaluatedContext() &&
12222          "Should only transform unevaluated expressions");
12223   ExprEvalContexts.back().Context =
12224       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
12225   if (isUnevaluatedContext())
12226     return E;
12227   return TransformToPE(*this).TransformExpr(E);
12228 }
12229 
12230 void
12231 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12232                                       Decl *LambdaContextDecl,
12233                                       bool IsDecltype) {
12234   ExprEvalContexts.emplace_back(NewContext, ExprCleanupObjects.size(),
12235                                 ExprNeedsCleanups, LambdaContextDecl,
12236                                 IsDecltype);
12237   ExprNeedsCleanups = false;
12238   if (!MaybeODRUseExprs.empty())
12239     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
12240 }
12241 
12242 void
12243 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
12244                                       ReuseLambdaContextDecl_t,
12245                                       bool IsDecltype) {
12246   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
12247   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
12248 }
12249 
12250 void Sema::PopExpressionEvaluationContext() {
12251   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
12252   unsigned NumTypos = Rec.NumTypos;
12253 
12254   if (!Rec.Lambdas.empty()) {
12255     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12256       unsigned D;
12257       if (Rec.isUnevaluated()) {
12258         // C++11 [expr.prim.lambda]p2:
12259         //   A lambda-expression shall not appear in an unevaluated operand
12260         //   (Clause 5).
12261         D = diag::err_lambda_unevaluated_operand;
12262       } else {
12263         // C++1y [expr.const]p2:
12264         //   A conditional-expression e is a core constant expression unless the
12265         //   evaluation of e, following the rules of the abstract machine, would
12266         //   evaluate [...] a lambda-expression.
12267         D = diag::err_lambda_in_constant_expression;
12268       }
12269       for (const auto *L : Rec.Lambdas)
12270         Diag(L->getLocStart(), D);
12271     } else {
12272       // Mark the capture expressions odr-used. This was deferred
12273       // during lambda expression creation.
12274       for (auto *Lambda : Rec.Lambdas) {
12275         for (auto *C : Lambda->capture_inits())
12276           MarkDeclarationsReferencedInExpr(C);
12277       }
12278     }
12279   }
12280 
12281   // When are coming out of an unevaluated context, clear out any
12282   // temporaries that we may have created as part of the evaluation of
12283   // the expression in that context: they aren't relevant because they
12284   // will never be constructed.
12285   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
12286     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
12287                              ExprCleanupObjects.end());
12288     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
12289     CleanupVarDeclMarking();
12290     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
12291   // Otherwise, merge the contexts together.
12292   } else {
12293     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
12294     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
12295                             Rec.SavedMaybeODRUseExprs.end());
12296   }
12297 
12298   // Pop the current expression evaluation context off the stack.
12299   ExprEvalContexts.pop_back();
12300 
12301   if (!ExprEvalContexts.empty())
12302     ExprEvalContexts.back().NumTypos += NumTypos;
12303   else
12304     assert(NumTypos == 0 && "There are outstanding typos after popping the "
12305                             "last ExpressionEvaluationContextRecord");
12306 }
12307 
12308 void Sema::DiscardCleanupsInEvaluationContext() {
12309   ExprCleanupObjects.erase(
12310          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
12311          ExprCleanupObjects.end());
12312   ExprNeedsCleanups = false;
12313   MaybeODRUseExprs.clear();
12314 }
12315 
12316 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
12317   if (!E->getType()->isVariablyModifiedType())
12318     return E;
12319   return TransformToPotentiallyEvaluated(E);
12320 }
12321 
12322 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
12323   // Do not mark anything as "used" within a dependent context; wait for
12324   // an instantiation.
12325   if (SemaRef.CurContext->isDependentContext())
12326     return false;
12327 
12328   switch (SemaRef.ExprEvalContexts.back().Context) {
12329     case Sema::Unevaluated:
12330     case Sema::UnevaluatedAbstract:
12331       // We are in an expression that is not potentially evaluated; do nothing.
12332       // (Depending on how you read the standard, we actually do need to do
12333       // something here for null pointer constants, but the standard's
12334       // definition of a null pointer constant is completely crazy.)
12335       return false;
12336 
12337     case Sema::ConstantEvaluated:
12338     case Sema::PotentiallyEvaluated:
12339       // We are in a potentially evaluated expression (or a constant-expression
12340       // in C++03); we need to do implicit template instantiation, implicitly
12341       // define class members, and mark most declarations as used.
12342       return true;
12343 
12344     case Sema::PotentiallyEvaluatedIfUsed:
12345       // Referenced declarations will only be used if the construct in the
12346       // containing expression is used.
12347       return false;
12348   }
12349   llvm_unreachable("Invalid context");
12350 }
12351 
12352 /// \brief Mark a function referenced, and check whether it is odr-used
12353 /// (C++ [basic.def.odr]p2, C99 6.9p3)
12354 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func,
12355                                   bool OdrUse) {
12356   assert(Func && "No function?");
12357 
12358   Func->setReferenced();
12359 
12360   // C++11 [basic.def.odr]p3:
12361   //   A function whose name appears as a potentially-evaluated expression is
12362   //   odr-used if it is the unique lookup result or the selected member of a
12363   //   set of overloaded functions [...].
12364   //
12365   // We (incorrectly) mark overload resolution as an unevaluated context, so we
12366   // can just check that here. Skip the rest of this function if we've already
12367   // marked the function as used.
12368   if (Func->isUsed(/*CheckUsedAttr=*/false) ||
12369       !IsPotentiallyEvaluatedContext(*this)) {
12370     // C++11 [temp.inst]p3:
12371     //   Unless a function template specialization has been explicitly
12372     //   instantiated or explicitly specialized, the function template
12373     //   specialization is implicitly instantiated when the specialization is
12374     //   referenced in a context that requires a function definition to exist.
12375     //
12376     // We consider constexpr function templates to be referenced in a context
12377     // that requires a definition to exist whenever they are referenced.
12378     //
12379     // FIXME: This instantiates constexpr functions too frequently. If this is
12380     // really an unevaluated context (and we're not just in the definition of a
12381     // function template or overload resolution or other cases which we
12382     // incorrectly consider to be unevaluated contexts), and we're not in a
12383     // subexpression which we actually need to evaluate (for instance, a
12384     // template argument, array bound or an expression in a braced-init-list),
12385     // we are not permitted to instantiate this constexpr function definition.
12386     //
12387     // FIXME: This also implicitly defines special members too frequently. They
12388     // are only supposed to be implicitly defined if they are odr-used, but they
12389     // are not odr-used from constant expressions in unevaluated contexts.
12390     // However, they cannot be referenced if they are deleted, and they are
12391     // deleted whenever the implicit definition of the special member would
12392     // fail.
12393     if (!Func->isConstexpr() || Func->getBody())
12394       return;
12395     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
12396     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
12397       return;
12398   }
12399 
12400   // Note that this declaration has been used.
12401   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
12402     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
12403     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
12404       if (Constructor->isDefaultConstructor()) {
12405         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
12406           return;
12407         DefineImplicitDefaultConstructor(Loc, Constructor);
12408       } else if (Constructor->isCopyConstructor()) {
12409         DefineImplicitCopyConstructor(Loc, Constructor);
12410       } else if (Constructor->isMoveConstructor()) {
12411         DefineImplicitMoveConstructor(Loc, Constructor);
12412       }
12413     } else if (Constructor->getInheritedConstructor()) {
12414       DefineInheritingConstructor(Loc, Constructor);
12415     }
12416   } else if (CXXDestructorDecl *Destructor =
12417                  dyn_cast<CXXDestructorDecl>(Func)) {
12418     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
12419     if (Destructor->isDefaulted() && !Destructor->isDeleted()) {
12420       if (Destructor->isTrivial() && !Destructor->hasAttr<DLLExportAttr>())
12421         return;
12422       DefineImplicitDestructor(Loc, Destructor);
12423     }
12424     if (Destructor->isVirtual() && getLangOpts().AppleKext)
12425       MarkVTableUsed(Loc, Destructor->getParent());
12426   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
12427     if (MethodDecl->isOverloadedOperator() &&
12428         MethodDecl->getOverloadedOperator() == OO_Equal) {
12429       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
12430       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
12431         if (MethodDecl->isCopyAssignmentOperator())
12432           DefineImplicitCopyAssignment(Loc, MethodDecl);
12433         else
12434           DefineImplicitMoveAssignment(Loc, MethodDecl);
12435       }
12436     } else if (isa<CXXConversionDecl>(MethodDecl) &&
12437                MethodDecl->getParent()->isLambda()) {
12438       CXXConversionDecl *Conversion =
12439           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
12440       if (Conversion->isLambdaToBlockPointerConversion())
12441         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
12442       else
12443         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
12444     } else if (MethodDecl->isVirtual() && getLangOpts().AppleKext)
12445       MarkVTableUsed(Loc, MethodDecl->getParent());
12446   }
12447 
12448   // Recursive functions should be marked when used from another function.
12449   // FIXME: Is this really right?
12450   if (CurContext == Func) return;
12451 
12452   // Resolve the exception specification for any function which is
12453   // used: CodeGen will need it.
12454   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
12455   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
12456     ResolveExceptionSpec(Loc, FPT);
12457 
12458   if (!OdrUse) return;
12459 
12460   // Implicit instantiation of function templates and member functions of
12461   // class templates.
12462   if (Func->isImplicitlyInstantiable()) {
12463     bool AlreadyInstantiated = false;
12464     SourceLocation PointOfInstantiation = Loc;
12465     if (FunctionTemplateSpecializationInfo *SpecInfo
12466                               = Func->getTemplateSpecializationInfo()) {
12467       if (SpecInfo->getPointOfInstantiation().isInvalid())
12468         SpecInfo->setPointOfInstantiation(Loc);
12469       else if (SpecInfo->getTemplateSpecializationKind()
12470                  == TSK_ImplicitInstantiation) {
12471         AlreadyInstantiated = true;
12472         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
12473       }
12474     } else if (MemberSpecializationInfo *MSInfo
12475                                 = Func->getMemberSpecializationInfo()) {
12476       if (MSInfo->getPointOfInstantiation().isInvalid())
12477         MSInfo->setPointOfInstantiation(Loc);
12478       else if (MSInfo->getTemplateSpecializationKind()
12479                  == TSK_ImplicitInstantiation) {
12480         AlreadyInstantiated = true;
12481         PointOfInstantiation = MSInfo->getPointOfInstantiation();
12482       }
12483     }
12484 
12485     if (!AlreadyInstantiated || Func->isConstexpr()) {
12486       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
12487           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
12488           ActiveTemplateInstantiations.size())
12489         PendingLocalImplicitInstantiations.push_back(
12490             std::make_pair(Func, PointOfInstantiation));
12491       else if (Func->isConstexpr())
12492         // Do not defer instantiations of constexpr functions, to avoid the
12493         // expression evaluator needing to call back into Sema if it sees a
12494         // call to such a function.
12495         InstantiateFunctionDefinition(PointOfInstantiation, Func);
12496       else {
12497         PendingInstantiations.push_back(std::make_pair(Func,
12498                                                        PointOfInstantiation));
12499         // Notify the consumer that a function was implicitly instantiated.
12500         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
12501       }
12502     }
12503   } else {
12504     // Walk redefinitions, as some of them may be instantiable.
12505     for (auto i : Func->redecls()) {
12506       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
12507         MarkFunctionReferenced(Loc, i);
12508     }
12509   }
12510 
12511   // Keep track of used but undefined functions.
12512   if (!Func->isDefined()) {
12513     if (mightHaveNonExternalLinkage(Func))
12514       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12515     else if (Func->getMostRecentDecl()->isInlined() &&
12516              !LangOpts.GNUInline &&
12517              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
12518       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
12519   }
12520 
12521   // Normally the most current decl is marked used while processing the use and
12522   // any subsequent decls are marked used by decl merging. This fails with
12523   // template instantiation since marking can happen at the end of the file
12524   // and, because of the two phase lookup, this function is called with at
12525   // decl in the middle of a decl chain. We loop to maintain the invariant
12526   // that once a decl is used, all decls after it are also used.
12527   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
12528     F->markUsed(Context);
12529     if (F == Func)
12530       break;
12531   }
12532 }
12533 
12534 static void
12535 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
12536                                    VarDecl *var, DeclContext *DC) {
12537   DeclContext *VarDC = var->getDeclContext();
12538 
12539   //  If the parameter still belongs to the translation unit, then
12540   //  we're actually just using one parameter in the declaration of
12541   //  the next.
12542   if (isa<ParmVarDecl>(var) &&
12543       isa<TranslationUnitDecl>(VarDC))
12544     return;
12545 
12546   // For C code, don't diagnose about capture if we're not actually in code
12547   // right now; it's impossible to write a non-constant expression outside of
12548   // function context, so we'll get other (more useful) diagnostics later.
12549   //
12550   // For C++, things get a bit more nasty... it would be nice to suppress this
12551   // diagnostic for certain cases like using a local variable in an array bound
12552   // for a member of a local class, but the correct predicate is not obvious.
12553   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
12554     return;
12555 
12556   if (isa<CXXMethodDecl>(VarDC) &&
12557       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
12558     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
12559       << var->getIdentifier();
12560   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
12561     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
12562       << var->getIdentifier() << fn->getDeclName();
12563   } else if (isa<BlockDecl>(VarDC)) {
12564     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
12565       << var->getIdentifier();
12566   } else {
12567     // FIXME: Is there any other context where a local variable can be
12568     // declared?
12569     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
12570       << var->getIdentifier();
12571   }
12572 
12573   S.Diag(var->getLocation(), diag::note_entity_declared_at)
12574       << var->getIdentifier();
12575 
12576   // FIXME: Add additional diagnostic info about class etc. which prevents
12577   // capture.
12578 }
12579 
12580 
12581 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
12582                                       bool &SubCapturesAreNested,
12583                                       QualType &CaptureType,
12584                                       QualType &DeclRefType) {
12585    // Check whether we've already captured it.
12586   if (CSI->CaptureMap.count(Var)) {
12587     // If we found a capture, any subcaptures are nested.
12588     SubCapturesAreNested = true;
12589 
12590     // Retrieve the capture type for this variable.
12591     CaptureType = CSI->getCapture(Var).getCaptureType();
12592 
12593     // Compute the type of an expression that refers to this variable.
12594     DeclRefType = CaptureType.getNonReferenceType();
12595 
12596     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
12597     if (Cap.isCopyCapture() &&
12598         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
12599       DeclRefType.addConst();
12600     return true;
12601   }
12602   return false;
12603 }
12604 
12605 // Only block literals, captured statements, and lambda expressions can
12606 // capture; other scopes don't work.
12607 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
12608                                  SourceLocation Loc,
12609                                  const bool Diagnose, Sema &S) {
12610   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
12611     return getLambdaAwareParentOfDeclContext(DC);
12612   else if (Var->hasLocalStorage()) {
12613     if (Diagnose)
12614        diagnoseUncapturableValueReference(S, Loc, Var, DC);
12615   }
12616   return nullptr;
12617 }
12618 
12619 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12620 // certain types of variables (unnamed, variably modified types etc.)
12621 // so check for eligibility.
12622 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
12623                                  SourceLocation Loc,
12624                                  const bool Diagnose, Sema &S) {
12625 
12626   bool IsBlock = isa<BlockScopeInfo>(CSI);
12627   bool IsLambda = isa<LambdaScopeInfo>(CSI);
12628 
12629   // Lambdas are not allowed to capture unnamed variables
12630   // (e.g. anonymous unions).
12631   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
12632   // assuming that's the intent.
12633   if (IsLambda && !Var->getDeclName()) {
12634     if (Diagnose) {
12635       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
12636       S.Diag(Var->getLocation(), diag::note_declared_at);
12637     }
12638     return false;
12639   }
12640 
12641   // Prohibit variably-modified types in blocks; they're difficult to deal with.
12642   if (Var->getType()->isVariablyModifiedType() && IsBlock) {
12643     if (Diagnose) {
12644       S.Diag(Loc, diag::err_ref_vm_type);
12645       S.Diag(Var->getLocation(), diag::note_previous_decl)
12646         << Var->getDeclName();
12647     }
12648     return false;
12649   }
12650   // Prohibit structs with flexible array members too.
12651   // We cannot capture what is in the tail end of the struct.
12652   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
12653     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
12654       if (Diagnose) {
12655         if (IsBlock)
12656           S.Diag(Loc, diag::err_ref_flexarray_type);
12657         else
12658           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
12659             << Var->getDeclName();
12660         S.Diag(Var->getLocation(), diag::note_previous_decl)
12661           << Var->getDeclName();
12662       }
12663       return false;
12664     }
12665   }
12666   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12667   // Lambdas and captured statements are not allowed to capture __block
12668   // variables; they don't support the expected semantics.
12669   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
12670     if (Diagnose) {
12671       S.Diag(Loc, diag::err_capture_block_variable)
12672         << Var->getDeclName() << !IsLambda;
12673       S.Diag(Var->getLocation(), diag::note_previous_decl)
12674         << Var->getDeclName();
12675     }
12676     return false;
12677   }
12678 
12679   return true;
12680 }
12681 
12682 // Returns true if the capture by block was successful.
12683 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
12684                                  SourceLocation Loc,
12685                                  const bool BuildAndDiagnose,
12686                                  QualType &CaptureType,
12687                                  QualType &DeclRefType,
12688                                  const bool Nested,
12689                                  Sema &S) {
12690   Expr *CopyExpr = nullptr;
12691   bool ByRef = false;
12692 
12693   // Blocks are not allowed to capture arrays.
12694   if (CaptureType->isArrayType()) {
12695     if (BuildAndDiagnose) {
12696       S.Diag(Loc, diag::err_ref_array_type);
12697       S.Diag(Var->getLocation(), diag::note_previous_decl)
12698       << Var->getDeclName();
12699     }
12700     return false;
12701   }
12702 
12703   // Forbid the block-capture of autoreleasing variables.
12704   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12705     if (BuildAndDiagnose) {
12706       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
12707         << /*block*/ 0;
12708       S.Diag(Var->getLocation(), diag::note_previous_decl)
12709         << Var->getDeclName();
12710     }
12711     return false;
12712   }
12713   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
12714   if (HasBlocksAttr || CaptureType->isReferenceType()) {
12715     // Block capture by reference does not change the capture or
12716     // declaration reference types.
12717     ByRef = true;
12718   } else {
12719     // Block capture by copy introduces 'const'.
12720     CaptureType = CaptureType.getNonReferenceType().withConst();
12721     DeclRefType = CaptureType;
12722 
12723     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
12724       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
12725         // The capture logic needs the destructor, so make sure we mark it.
12726         // Usually this is unnecessary because most local variables have
12727         // their destructors marked at declaration time, but parameters are
12728         // an exception because it's technically only the call site that
12729         // actually requires the destructor.
12730         if (isa<ParmVarDecl>(Var))
12731           S.FinalizeVarWithDestructor(Var, Record);
12732 
12733         // Enter a new evaluation context to insulate the copy
12734         // full-expression.
12735         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
12736 
12737         // According to the blocks spec, the capture of a variable from
12738         // the stack requires a const copy constructor.  This is not true
12739         // of the copy/move done to move a __block variable to the heap.
12740         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
12741                                                   DeclRefType.withConst(),
12742                                                   VK_LValue, Loc);
12743 
12744         ExprResult Result
12745           = S.PerformCopyInitialization(
12746               InitializedEntity::InitializeBlock(Var->getLocation(),
12747                                                   CaptureType, false),
12748               Loc, DeclRef);
12749 
12750         // Build a full-expression copy expression if initialization
12751         // succeeded and used a non-trivial constructor.  Recover from
12752         // errors by pretending that the copy isn't necessary.
12753         if (!Result.isInvalid() &&
12754             !cast<CXXConstructExpr>(Result.get())->getConstructor()
12755                 ->isTrivial()) {
12756           Result = S.MaybeCreateExprWithCleanups(Result);
12757           CopyExpr = Result.get();
12758         }
12759       }
12760     }
12761   }
12762 
12763   // Actually capture the variable.
12764   if (BuildAndDiagnose)
12765     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
12766                     SourceLocation(), CaptureType, CopyExpr);
12767 
12768   return true;
12769 
12770 }
12771 
12772 
12773 /// \brief Capture the given variable in the captured region.
12774 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
12775                                     VarDecl *Var,
12776                                     SourceLocation Loc,
12777                                     const bool BuildAndDiagnose,
12778                                     QualType &CaptureType,
12779                                     QualType &DeclRefType,
12780                                     const bool RefersToCapturedVariable,
12781                                     Sema &S) {
12782 
12783   // By default, capture variables by reference.
12784   bool ByRef = true;
12785   // Using an LValue reference type is consistent with Lambdas (see below).
12786   if (S.getLangOpts().OpenMP && S.IsOpenMPCapturedVar(Var))
12787     DeclRefType = DeclRefType.getUnqualifiedType();
12788   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12789   Expr *CopyExpr = nullptr;
12790   if (BuildAndDiagnose) {
12791     // The current implementation assumes that all variables are captured
12792     // by references. Since there is no capture by copy, no expression
12793     // evaluation will be needed.
12794     RecordDecl *RD = RSI->TheRecordDecl;
12795 
12796     FieldDecl *Field
12797       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
12798                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
12799                           nullptr, false, ICIS_NoInit);
12800     Field->setImplicit(true);
12801     Field->setAccess(AS_private);
12802     RD->addDecl(Field);
12803 
12804     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToCapturedVariable,
12805                                             DeclRefType, VK_LValue, Loc);
12806     Var->setReferenced(true);
12807     Var->markUsed(S.Context);
12808   }
12809 
12810   // Actually capture the variable.
12811   if (BuildAndDiagnose)
12812     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToCapturedVariable, Loc,
12813                     SourceLocation(), CaptureType, CopyExpr);
12814 
12815 
12816   return true;
12817 }
12818 
12819 /// \brief Create a field within the lambda class for the variable
12820 /// being captured.
12821 static void addAsFieldToClosureType(Sema &S, LambdaScopeInfo *LSI, VarDecl *Var,
12822                                     QualType FieldType, QualType DeclRefType,
12823                                     SourceLocation Loc,
12824                                     bool RefersToCapturedVariable) {
12825   CXXRecordDecl *Lambda = LSI->Lambda;
12826 
12827   // Build the non-static data member.
12828   FieldDecl *Field
12829     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
12830                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
12831                         nullptr, false, ICIS_NoInit);
12832   Field->setImplicit(true);
12833   Field->setAccess(AS_private);
12834   Lambda->addDecl(Field);
12835 }
12836 
12837 /// \brief Capture the given variable in the lambda.
12838 static bool captureInLambda(LambdaScopeInfo *LSI,
12839                             VarDecl *Var,
12840                             SourceLocation Loc,
12841                             const bool BuildAndDiagnose,
12842                             QualType &CaptureType,
12843                             QualType &DeclRefType,
12844                             const bool RefersToCapturedVariable,
12845                             const Sema::TryCaptureKind Kind,
12846                             SourceLocation EllipsisLoc,
12847                             const bool IsTopScope,
12848                             Sema &S) {
12849 
12850   // Determine whether we are capturing by reference or by value.
12851   bool ByRef = false;
12852   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
12853     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
12854   } else {
12855     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
12856   }
12857 
12858   // Compute the type of the field that will capture this variable.
12859   if (ByRef) {
12860     // C++11 [expr.prim.lambda]p15:
12861     //   An entity is captured by reference if it is implicitly or
12862     //   explicitly captured but not captured by copy. It is
12863     //   unspecified whether additional unnamed non-static data
12864     //   members are declared in the closure type for entities
12865     //   captured by reference.
12866     //
12867     // FIXME: It is not clear whether we want to build an lvalue reference
12868     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
12869     // to do the former, while EDG does the latter. Core issue 1249 will
12870     // clarify, but for now we follow GCC because it's a more permissive and
12871     // easily defensible position.
12872     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
12873   } else {
12874     // C++11 [expr.prim.lambda]p14:
12875     //   For each entity captured by copy, an unnamed non-static
12876     //   data member is declared in the closure type. The
12877     //   declaration order of these members is unspecified. The type
12878     //   of such a data member is the type of the corresponding
12879     //   captured entity if the entity is not a reference to an
12880     //   object, or the referenced type otherwise. [Note: If the
12881     //   captured entity is a reference to a function, the
12882     //   corresponding data member is also a reference to a
12883     //   function. - end note ]
12884     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
12885       if (!RefType->getPointeeType()->isFunctionType())
12886         CaptureType = RefType->getPointeeType();
12887     }
12888 
12889     // Forbid the lambda copy-capture of autoreleasing variables.
12890     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
12891       if (BuildAndDiagnose) {
12892         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
12893         S.Diag(Var->getLocation(), diag::note_previous_decl)
12894           << Var->getDeclName();
12895       }
12896       return false;
12897     }
12898 
12899     // Make sure that by-copy captures are of a complete and non-abstract type.
12900     if (BuildAndDiagnose) {
12901       if (!CaptureType->isDependentType() &&
12902           S.RequireCompleteType(Loc, CaptureType,
12903                                 diag::err_capture_of_incomplete_type,
12904                                 Var->getDeclName()))
12905         return false;
12906 
12907       if (S.RequireNonAbstractType(Loc, CaptureType,
12908                                    diag::err_capture_of_abstract_type))
12909         return false;
12910     }
12911   }
12912 
12913   // Capture this variable in the lambda.
12914   if (BuildAndDiagnose)
12915     addAsFieldToClosureType(S, LSI, Var, CaptureType, DeclRefType, Loc,
12916                             RefersToCapturedVariable);
12917 
12918   // Compute the type of a reference to this captured variable.
12919   if (ByRef)
12920     DeclRefType = CaptureType.getNonReferenceType();
12921   else {
12922     // C++ [expr.prim.lambda]p5:
12923     //   The closure type for a lambda-expression has a public inline
12924     //   function call operator [...]. This function call operator is
12925     //   declared const (9.3.1) if and only if the lambda-expression’s
12926     //   parameter-declaration-clause is not followed by mutable.
12927     DeclRefType = CaptureType.getNonReferenceType();
12928     if (!LSI->Mutable && !CaptureType->isReferenceType())
12929       DeclRefType.addConst();
12930   }
12931 
12932   // Add the capture.
12933   if (BuildAndDiagnose)
12934     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToCapturedVariable,
12935                     Loc, EllipsisLoc, CaptureType, /*CopyExpr=*/nullptr);
12936 
12937   return true;
12938 }
12939 
12940 bool Sema::tryCaptureVariable(
12941     VarDecl *Var, SourceLocation ExprLoc, TryCaptureKind Kind,
12942     SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType,
12943     QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt) {
12944   // An init-capture is notionally from the context surrounding its
12945   // declaration, but its parent DC is the lambda class.
12946   DeclContext *VarDC = Var->getDeclContext();
12947   if (Var->isInitCapture())
12948     VarDC = VarDC->getParent();
12949 
12950   DeclContext *DC = CurContext;
12951   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
12952       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
12953   // We need to sync up the Declaration Context with the
12954   // FunctionScopeIndexToStopAt
12955   if (FunctionScopeIndexToStopAt) {
12956     unsigned FSIndex = FunctionScopes.size() - 1;
12957     while (FSIndex != MaxFunctionScopesIndex) {
12958       DC = getLambdaAwareParentOfDeclContext(DC);
12959       --FSIndex;
12960     }
12961   }
12962 
12963 
12964   // If the variable is declared in the current context, there is no need to
12965   // capture it.
12966   if (VarDC == DC) return true;
12967 
12968   // Capture global variables if it is required to use private copy of this
12969   // variable.
12970   bool IsGlobal = !Var->hasLocalStorage();
12971   if (IsGlobal && !(LangOpts.OpenMP && IsOpenMPCapturedVar(Var)))
12972     return true;
12973 
12974   // Walk up the stack to determine whether we can capture the variable,
12975   // performing the "simple" checks that don't depend on type. We stop when
12976   // we've either hit the declared scope of the variable or find an existing
12977   // capture of that variable.  We start from the innermost capturing-entity
12978   // (the DC) and ensure that all intervening capturing-entities
12979   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
12980   // declcontext can either capture the variable or have already captured
12981   // the variable.
12982   CaptureType = Var->getType();
12983   DeclRefType = CaptureType.getNonReferenceType();
12984   bool Nested = false;
12985   bool Explicit = (Kind != TryCapture_Implicit);
12986   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12987   unsigned OpenMPLevel = 0;
12988   do {
12989     // Only block literals, captured statements, and lambda expressions can
12990     // capture; other scopes don't work.
12991     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12992                                                               ExprLoc,
12993                                                               BuildAndDiagnose,
12994                                                               *this);
12995     // We need to check for the parent *first* because, if we *have*
12996     // private-captured a global variable, we need to recursively capture it in
12997     // intermediate blocks, lambdas, etc.
12998     if (!ParentDC) {
12999       if (IsGlobal) {
13000         FunctionScopesIndex = MaxFunctionScopesIndex - 1;
13001         break;
13002       }
13003       return true;
13004     }
13005 
13006     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
13007     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
13008 
13009 
13010     // Check whether we've already captured it.
13011     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
13012                                              DeclRefType))
13013       break;
13014     // If we are instantiating a generic lambda call operator body,
13015     // we do not want to capture new variables.  What was captured
13016     // during either a lambdas transformation or initial parsing
13017     // should be used.
13018     if (isGenericLambdaCallOperatorSpecialization(DC)) {
13019       if (BuildAndDiagnose) {
13020         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13021         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
13022           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13023           Diag(Var->getLocation(), diag::note_previous_decl)
13024              << Var->getDeclName();
13025           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
13026         } else
13027           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
13028       }
13029       return true;
13030     }
13031     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
13032     // certain types of variables (unnamed, variably modified types etc.)
13033     // so check for eligibility.
13034     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
13035        return true;
13036 
13037     // Try to capture variable-length arrays types.
13038     if (Var->getType()->isVariablyModifiedType()) {
13039       // We're going to walk down into the type and look for VLA
13040       // expressions.
13041       QualType QTy = Var->getType();
13042       if (ParmVarDecl *PVD = dyn_cast_or_null<ParmVarDecl>(Var))
13043         QTy = PVD->getOriginalType();
13044       do {
13045         const Type *Ty = QTy.getTypePtr();
13046         switch (Ty->getTypeClass()) {
13047 #define TYPE(Class, Base)
13048 #define ABSTRACT_TYPE(Class, Base)
13049 #define NON_CANONICAL_TYPE(Class, Base)
13050 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
13051 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base)
13052 #include "clang/AST/TypeNodes.def"
13053           QTy = QualType();
13054           break;
13055         // These types are never variably-modified.
13056         case Type::Builtin:
13057         case Type::Complex:
13058         case Type::Vector:
13059         case Type::ExtVector:
13060         case Type::Record:
13061         case Type::Enum:
13062         case Type::Elaborated:
13063         case Type::TemplateSpecialization:
13064         case Type::ObjCObject:
13065         case Type::ObjCInterface:
13066         case Type::ObjCObjectPointer:
13067           llvm_unreachable("type class is never variably-modified!");
13068         case Type::Adjusted:
13069           QTy = cast<AdjustedType>(Ty)->getOriginalType();
13070           break;
13071         case Type::Decayed:
13072           QTy = cast<DecayedType>(Ty)->getPointeeType();
13073           break;
13074         case Type::Pointer:
13075           QTy = cast<PointerType>(Ty)->getPointeeType();
13076           break;
13077         case Type::BlockPointer:
13078           QTy = cast<BlockPointerType>(Ty)->getPointeeType();
13079           break;
13080         case Type::LValueReference:
13081         case Type::RValueReference:
13082           QTy = cast<ReferenceType>(Ty)->getPointeeType();
13083           break;
13084         case Type::MemberPointer:
13085           QTy = cast<MemberPointerType>(Ty)->getPointeeType();
13086           break;
13087         case Type::ConstantArray:
13088         case Type::IncompleteArray:
13089           // Losing element qualification here is fine.
13090           QTy = cast<ArrayType>(Ty)->getElementType();
13091           break;
13092         case Type::VariableArray: {
13093           // Losing element qualification here is fine.
13094           const VariableArrayType *VAT = cast<VariableArrayType>(Ty);
13095 
13096           // Unknown size indication requires no size computation.
13097           // Otherwise, evaluate and record it.
13098           if (auto Size = VAT->getSizeExpr()) {
13099             if (!CSI->isVLATypeCaptured(VAT)) {
13100               RecordDecl *CapRecord = nullptr;
13101               if (auto LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
13102                 CapRecord = LSI->Lambda;
13103               } else if (auto CRSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13104                 CapRecord = CRSI->TheRecordDecl;
13105               }
13106               if (CapRecord) {
13107                 auto ExprLoc = Size->getExprLoc();
13108                 auto SizeType = Context.getSizeType();
13109                 // Build the non-static data member.
13110                 auto Field = FieldDecl::Create(
13111                     Context, CapRecord, ExprLoc, ExprLoc,
13112                     /*Id*/ nullptr, SizeType, /*TInfo*/ nullptr,
13113                     /*BW*/ nullptr, /*Mutable*/ false,
13114                     /*InitStyle*/ ICIS_NoInit);
13115                 Field->setImplicit(true);
13116                 Field->setAccess(AS_private);
13117                 Field->setCapturedVLAType(VAT);
13118                 CapRecord->addDecl(Field);
13119 
13120                 CSI->addVLATypeCapture(ExprLoc, SizeType);
13121               }
13122             }
13123           }
13124           QTy = VAT->getElementType();
13125           break;
13126         }
13127         case Type::FunctionProto:
13128         case Type::FunctionNoProto:
13129           QTy = cast<FunctionType>(Ty)->getReturnType();
13130           break;
13131         case Type::Paren:
13132         case Type::TypeOf:
13133         case Type::UnaryTransform:
13134         case Type::Attributed:
13135         case Type::SubstTemplateTypeParm:
13136         case Type::PackExpansion:
13137           // Keep walking after single level desugaring.
13138           QTy = QTy.getSingleStepDesugaredType(getASTContext());
13139           break;
13140         case Type::Typedef:
13141           QTy = cast<TypedefType>(Ty)->desugar();
13142           break;
13143         case Type::Decltype:
13144           QTy = cast<DecltypeType>(Ty)->desugar();
13145           break;
13146         case Type::Auto:
13147           QTy = cast<AutoType>(Ty)->getDeducedType();
13148           break;
13149         case Type::TypeOfExpr:
13150           QTy = cast<TypeOfExprType>(Ty)->getUnderlyingExpr()->getType();
13151           break;
13152         case Type::Atomic:
13153           QTy = cast<AtomicType>(Ty)->getValueType();
13154           break;
13155         }
13156       } while (!QTy.isNull() && QTy->isVariablyModifiedType());
13157     }
13158 
13159     if (getLangOpts().OpenMP) {
13160       if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13161         // OpenMP private variables should not be captured in outer scope, so
13162         // just break here. Similarly, global variables that are captured in a
13163         // target region should not be captured outside the scope of the region.
13164         if (RSI->CapRegionKind == CR_OpenMP) {
13165           auto isTargetCap = isOpenMPTargetCapturedVar(Var, OpenMPLevel);
13166           // When we detect target captures we are looking from inside the
13167           // target region, therefore we need to propagate the capture from the
13168           // enclosing region. Therefore, the capture is not initially nested.
13169           if (isTargetCap)
13170             FunctionScopesIndex--;
13171 
13172           if (isTargetCap || isOpenMPPrivateVar(Var, OpenMPLevel)) {
13173             Nested = !isTargetCap;
13174             DeclRefType = DeclRefType.getUnqualifiedType();
13175             CaptureType = Context.getLValueReferenceType(DeclRefType);
13176             break;
13177           }
13178           ++OpenMPLevel;
13179         }
13180       }
13181     }
13182     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
13183       // No capture-default, and this is not an explicit capture
13184       // so cannot capture this variable.
13185       if (BuildAndDiagnose) {
13186         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
13187         Diag(Var->getLocation(), diag::note_previous_decl)
13188           << Var->getDeclName();
13189         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
13190              diag::note_lambda_decl);
13191         // FIXME: If we error out because an outer lambda can not implicitly
13192         // capture a variable that an inner lambda explicitly captures, we
13193         // should have the inner lambda do the explicit capture - because
13194         // it makes for cleaner diagnostics later.  This would purely be done
13195         // so that the diagnostic does not misleadingly claim that a variable
13196         // can not be captured by a lambda implicitly even though it is captured
13197         // explicitly.  Suggestion:
13198         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
13199         //    at the function head
13200         //  - cache the StartingDeclContext - this must be a lambda
13201         //  - captureInLambda in the innermost lambda the variable.
13202       }
13203       return true;
13204     }
13205 
13206     FunctionScopesIndex--;
13207     DC = ParentDC;
13208     Explicit = false;
13209   } while (!VarDC->Equals(DC));
13210 
13211   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
13212   // computing the type of the capture at each step, checking type-specific
13213   // requirements, and adding captures if requested.
13214   // If the variable had already been captured previously, we start capturing
13215   // at the lambda nested within that one.
13216   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
13217        ++I) {
13218     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
13219 
13220     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
13221       if (!captureInBlock(BSI, Var, ExprLoc,
13222                           BuildAndDiagnose, CaptureType,
13223                           DeclRefType, Nested, *this))
13224         return true;
13225       Nested = true;
13226     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
13227       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
13228                                    BuildAndDiagnose, CaptureType,
13229                                    DeclRefType, Nested, *this))
13230         return true;
13231       Nested = true;
13232     } else {
13233       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
13234       if (!captureInLambda(LSI, Var, ExprLoc,
13235                            BuildAndDiagnose, CaptureType,
13236                            DeclRefType, Nested, Kind, EllipsisLoc,
13237                             /*IsTopScope*/I == N - 1, *this))
13238         return true;
13239       Nested = true;
13240     }
13241   }
13242   return false;
13243 }
13244 
13245 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
13246                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
13247   QualType CaptureType;
13248   QualType DeclRefType;
13249   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
13250                             /*BuildAndDiagnose=*/true, CaptureType,
13251                             DeclRefType, nullptr);
13252 }
13253 
13254 bool Sema::NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc) {
13255   QualType CaptureType;
13256   QualType DeclRefType;
13257   return !tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13258                              /*BuildAndDiagnose=*/false, CaptureType,
13259                              DeclRefType, nullptr);
13260 }
13261 
13262 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
13263   QualType CaptureType;
13264   QualType DeclRefType;
13265 
13266   // Determine whether we can capture this variable.
13267   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
13268                          /*BuildAndDiagnose=*/false, CaptureType,
13269                          DeclRefType, nullptr))
13270     return QualType();
13271 
13272   return DeclRefType;
13273 }
13274 
13275 
13276 
13277 // If either the type of the variable or the initializer is dependent,
13278 // return false. Otherwise, determine whether the variable is a constant
13279 // expression. Use this if you need to know if a variable that might or
13280 // might not be dependent is truly a constant expression.
13281 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
13282     ASTContext &Context) {
13283 
13284   if (Var->getType()->isDependentType())
13285     return false;
13286   const VarDecl *DefVD = nullptr;
13287   Var->getAnyInitializer(DefVD);
13288   if (!DefVD)
13289     return false;
13290   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
13291   Expr *Init = cast<Expr>(Eval->Value);
13292   if (Init->isValueDependent())
13293     return false;
13294   return IsVariableAConstantExpression(Var, Context);
13295 }
13296 
13297 
13298 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
13299   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
13300   // an object that satisfies the requirements for appearing in a
13301   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
13302   // is immediately applied."  This function handles the lvalue-to-rvalue
13303   // conversion part.
13304   MaybeODRUseExprs.erase(E->IgnoreParens());
13305 
13306   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
13307   // to a variable that is a constant expression, and if so, identify it as
13308   // a reference to a variable that does not involve an odr-use of that
13309   // variable.
13310   if (LambdaScopeInfo *LSI = getCurLambda()) {
13311     Expr *SansParensExpr = E->IgnoreParens();
13312     VarDecl *Var = nullptr;
13313     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
13314       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
13315     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
13316       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
13317 
13318     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
13319       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
13320   }
13321 }
13322 
13323 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
13324   Res = CorrectDelayedTyposInExpr(Res);
13325 
13326   if (!Res.isUsable())
13327     return Res;
13328 
13329   // If a constant-expression is a reference to a variable where we delay
13330   // deciding whether it is an odr-use, just assume we will apply the
13331   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
13332   // (a non-type template argument), we have special handling anyway.
13333   UpdateMarkingForLValueToRValue(Res.get());
13334   return Res;
13335 }
13336 
13337 void Sema::CleanupVarDeclMarking() {
13338   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
13339                                         e = MaybeODRUseExprs.end();
13340        i != e; ++i) {
13341     VarDecl *Var;
13342     SourceLocation Loc;
13343     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
13344       Var = cast<VarDecl>(DRE->getDecl());
13345       Loc = DRE->getLocation();
13346     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
13347       Var = cast<VarDecl>(ME->getMemberDecl());
13348       Loc = ME->getMemberLoc();
13349     } else {
13350       llvm_unreachable("Unexpected expression");
13351     }
13352 
13353     MarkVarDeclODRUsed(Var, Loc, *this,
13354                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
13355   }
13356 
13357   MaybeODRUseExprs.clear();
13358 }
13359 
13360 
13361 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
13362                                     VarDecl *Var, Expr *E) {
13363   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
13364          "Invalid Expr argument to DoMarkVarDeclReferenced");
13365   Var->setReferenced();
13366 
13367   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
13368   bool MarkODRUsed = true;
13369 
13370   // If the context is not potentially evaluated, this is not an odr-use and
13371   // does not trigger instantiation.
13372   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
13373     if (SemaRef.isUnevaluatedContext())
13374       return;
13375 
13376     // If we don't yet know whether this context is going to end up being an
13377     // evaluated context, and we're referencing a variable from an enclosing
13378     // scope, add a potential capture.
13379     //
13380     // FIXME: Is this necessary? These contexts are only used for default
13381     // arguments, where local variables can't be used.
13382     const bool RefersToEnclosingScope =
13383         (SemaRef.CurContext != Var->getDeclContext() &&
13384          Var->getDeclContext()->isFunctionOrMethod() && Var->hasLocalStorage());
13385     if (RefersToEnclosingScope) {
13386       if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
13387         // If a variable could potentially be odr-used, defer marking it so
13388         // until we finish analyzing the full expression for any
13389         // lvalue-to-rvalue
13390         // or discarded value conversions that would obviate odr-use.
13391         // Add it to the list of potential captures that will be analyzed
13392         // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
13393         // unless the variable is a reference that was initialized by a constant
13394         // expression (this will never need to be captured or odr-used).
13395         assert(E && "Capture variable should be used in an expression.");
13396         if (!Var->getType()->isReferenceType() ||
13397             !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
13398           LSI->addPotentialCapture(E->IgnoreParens());
13399       }
13400     }
13401 
13402     if (!isTemplateInstantiation(TSK))
13403     	return;
13404 
13405     // Instantiate, but do not mark as odr-used, variable templates.
13406     MarkODRUsed = false;
13407   }
13408 
13409   VarTemplateSpecializationDecl *VarSpec =
13410       dyn_cast<VarTemplateSpecializationDecl>(Var);
13411   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
13412          "Can't instantiate a partial template specialization.");
13413 
13414   // Perform implicit instantiation of static data members, static data member
13415   // templates of class templates, and variable template specializations. Delay
13416   // instantiations of variable templates, except for those that could be used
13417   // in a constant expression.
13418   if (isTemplateInstantiation(TSK)) {
13419     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
13420 
13421     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
13422       if (Var->getPointOfInstantiation().isInvalid()) {
13423         // This is a modification of an existing AST node. Notify listeners.
13424         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
13425           L->StaticDataMemberInstantiated(Var);
13426       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
13427         // Don't bother trying to instantiate it again, unless we might need
13428         // its initializer before we get to the end of the TU.
13429         TryInstantiating = false;
13430     }
13431 
13432     if (Var->getPointOfInstantiation().isInvalid())
13433       Var->setTemplateSpecializationKind(TSK, Loc);
13434 
13435     if (TryInstantiating) {
13436       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
13437       bool InstantiationDependent = false;
13438       bool IsNonDependent =
13439           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
13440                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
13441                   : true;
13442 
13443       // Do not instantiate specializations that are still type-dependent.
13444       if (IsNonDependent) {
13445         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
13446           // Do not defer instantiations of variables which could be used in a
13447           // constant expression.
13448           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
13449         } else {
13450           SemaRef.PendingInstantiations
13451               .push_back(std::make_pair(Var, PointOfInstantiation));
13452         }
13453       }
13454     }
13455   }
13456 
13457   if(!MarkODRUsed) return;
13458 
13459   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
13460   // the requirements for appearing in a constant expression (5.19) and, if
13461   // it is an object, the lvalue-to-rvalue conversion (4.1)
13462   // is immediately applied."  We check the first part here, and
13463   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
13464   // Note that we use the C++11 definition everywhere because nothing in
13465   // C++03 depends on whether we get the C++03 version correct. The second
13466   // part does not apply to references, since they are not objects.
13467   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
13468     // A reference initialized by a constant expression can never be
13469     // odr-used, so simply ignore it.
13470     if (!Var->getType()->isReferenceType())
13471       SemaRef.MaybeODRUseExprs.insert(E);
13472   } else
13473     MarkVarDeclODRUsed(Var, Loc, SemaRef,
13474                        /*MaxFunctionScopeIndex ptr*/ nullptr);
13475 }
13476 
13477 /// \brief Mark a variable referenced, and check whether it is odr-used
13478 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
13479 /// used directly for normal expressions referring to VarDecl.
13480 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
13481   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
13482 }
13483 
13484 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
13485                                Decl *D, Expr *E, bool OdrUse) {
13486   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
13487     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
13488     return;
13489   }
13490 
13491   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
13492 
13493   // If this is a call to a method via a cast, also mark the method in the
13494   // derived class used in case codegen can devirtualize the call.
13495   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
13496   if (!ME)
13497     return;
13498   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
13499   if (!MD)
13500     return;
13501   // Only attempt to devirtualize if this is truly a virtual call.
13502   bool IsVirtualCall = MD->isVirtual() &&
13503                           ME->performsVirtualDispatch(SemaRef.getLangOpts());
13504   if (!IsVirtualCall)
13505     return;
13506   const Expr *Base = ME->getBase();
13507   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
13508   if (!MostDerivedClassDecl)
13509     return;
13510   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
13511   if (!DM || DM->isPure())
13512     return;
13513   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
13514 }
13515 
13516 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
13517 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
13518   // TODO: update this with DR# once a defect report is filed.
13519   // C++11 defect. The address of a pure member should not be an ODR use, even
13520   // if it's a qualified reference.
13521   bool OdrUse = true;
13522   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
13523     if (Method->isVirtual())
13524       OdrUse = false;
13525   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
13526 }
13527 
13528 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
13529 void Sema::MarkMemberReferenced(MemberExpr *E) {
13530   // C++11 [basic.def.odr]p2:
13531   //   A non-overloaded function whose name appears as a potentially-evaluated
13532   //   expression or a member of a set of candidate functions, if selected by
13533   //   overload resolution when referred to from a potentially-evaluated
13534   //   expression, is odr-used, unless it is a pure virtual function and its
13535   //   name is not explicitly qualified.
13536   bool OdrUse = true;
13537   if (E->performsVirtualDispatch(getLangOpts())) {
13538     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
13539       if (Method->isPure())
13540         OdrUse = false;
13541   }
13542   SourceLocation Loc = E->getMemberLoc().isValid() ?
13543                             E->getMemberLoc() : E->getLocStart();
13544   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
13545 }
13546 
13547 /// \brief Perform marking for a reference to an arbitrary declaration.  It
13548 /// marks the declaration referenced, and performs odr-use checking for
13549 /// functions and variables. This method should not be used when building a
13550 /// normal expression which refers to a variable.
13551 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
13552   if (OdrUse) {
13553     if (auto *VD = dyn_cast<VarDecl>(D)) {
13554       MarkVariableReferenced(Loc, VD);
13555       return;
13556     }
13557   }
13558   if (auto *FD = dyn_cast<FunctionDecl>(D)) {
13559     MarkFunctionReferenced(Loc, FD, OdrUse);
13560     return;
13561   }
13562   D->setReferenced();
13563 }
13564 
13565 namespace {
13566   // Mark all of the declarations referenced
13567   // FIXME: Not fully implemented yet! We need to have a better understanding
13568   // of when we're entering
13569   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
13570     Sema &S;
13571     SourceLocation Loc;
13572 
13573   public:
13574     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
13575 
13576     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
13577 
13578     bool TraverseTemplateArgument(const TemplateArgument &Arg);
13579     bool TraverseRecordType(RecordType *T);
13580   };
13581 }
13582 
13583 bool MarkReferencedDecls::TraverseTemplateArgument(
13584     const TemplateArgument &Arg) {
13585   if (Arg.getKind() == TemplateArgument::Declaration) {
13586     if (Decl *D = Arg.getAsDecl())
13587       S.MarkAnyDeclReferenced(Loc, D, true);
13588   }
13589 
13590   return Inherited::TraverseTemplateArgument(Arg);
13591 }
13592 
13593 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
13594   if (ClassTemplateSpecializationDecl *Spec
13595                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
13596     const TemplateArgumentList &Args = Spec->getTemplateArgs();
13597     return TraverseTemplateArguments(Args.data(), Args.size());
13598   }
13599 
13600   return true;
13601 }
13602 
13603 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
13604   MarkReferencedDecls Marker(*this, Loc);
13605   Marker.TraverseType(Context.getCanonicalType(T));
13606 }
13607 
13608 namespace {
13609   /// \brief Helper class that marks all of the declarations referenced by
13610   /// potentially-evaluated subexpressions as "referenced".
13611   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
13612     Sema &S;
13613     bool SkipLocalVariables;
13614 
13615   public:
13616     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
13617 
13618     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
13619       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
13620 
13621     void VisitDeclRefExpr(DeclRefExpr *E) {
13622       // If we were asked not to visit local variables, don't.
13623       if (SkipLocalVariables) {
13624         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
13625           if (VD->hasLocalStorage())
13626             return;
13627       }
13628 
13629       S.MarkDeclRefReferenced(E);
13630     }
13631 
13632     void VisitMemberExpr(MemberExpr *E) {
13633       S.MarkMemberReferenced(E);
13634       Inherited::VisitMemberExpr(E);
13635     }
13636 
13637     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13638       S.MarkFunctionReferenced(E->getLocStart(),
13639             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
13640       Visit(E->getSubExpr());
13641     }
13642 
13643     void VisitCXXNewExpr(CXXNewExpr *E) {
13644       if (E->getOperatorNew())
13645         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
13646       if (E->getOperatorDelete())
13647         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13648       Inherited::VisitCXXNewExpr(E);
13649     }
13650 
13651     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
13652       if (E->getOperatorDelete())
13653         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
13654       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
13655       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
13656         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
13657         S.MarkFunctionReferenced(E->getLocStart(),
13658                                     S.LookupDestructor(Record));
13659       }
13660 
13661       Inherited::VisitCXXDeleteExpr(E);
13662     }
13663 
13664     void VisitCXXConstructExpr(CXXConstructExpr *E) {
13665       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
13666       Inherited::VisitCXXConstructExpr(E);
13667     }
13668 
13669     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
13670       Visit(E->getExpr());
13671     }
13672 
13673     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
13674       Inherited::VisitImplicitCastExpr(E);
13675 
13676       if (E->getCastKind() == CK_LValueToRValue)
13677         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
13678     }
13679   };
13680 }
13681 
13682 /// \brief Mark any declarations that appear within this expression or any
13683 /// potentially-evaluated subexpressions as "referenced".
13684 ///
13685 /// \param SkipLocalVariables If true, don't mark local variables as
13686 /// 'referenced'.
13687 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
13688                                             bool SkipLocalVariables) {
13689   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
13690 }
13691 
13692 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
13693 /// of the program being compiled.
13694 ///
13695 /// This routine emits the given diagnostic when the code currently being
13696 /// type-checked is "potentially evaluated", meaning that there is a
13697 /// possibility that the code will actually be executable. Code in sizeof()
13698 /// expressions, code used only during overload resolution, etc., are not
13699 /// potentially evaluated. This routine will suppress such diagnostics or,
13700 /// in the absolutely nutty case of potentially potentially evaluated
13701 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
13702 /// later.
13703 ///
13704 /// This routine should be used for all diagnostics that describe the run-time
13705 /// behavior of a program, such as passing a non-POD value through an ellipsis.
13706 /// Failure to do so will likely result in spurious diagnostics or failures
13707 /// during overload resolution or within sizeof/alignof/typeof/typeid.
13708 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
13709                                const PartialDiagnostic &PD) {
13710   switch (ExprEvalContexts.back().Context) {
13711   case Unevaluated:
13712   case UnevaluatedAbstract:
13713     // The argument will never be evaluated, so don't complain.
13714     break;
13715 
13716   case ConstantEvaluated:
13717     // Relevant diagnostics should be produced by constant evaluation.
13718     break;
13719 
13720   case PotentiallyEvaluated:
13721   case PotentiallyEvaluatedIfUsed:
13722     if (Statement && getCurFunctionOrMethodDecl()) {
13723       FunctionScopes.back()->PossiblyUnreachableDiags.
13724         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
13725     }
13726     else
13727       Diag(Loc, PD);
13728 
13729     return true;
13730   }
13731 
13732   return false;
13733 }
13734 
13735 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
13736                                CallExpr *CE, FunctionDecl *FD) {
13737   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
13738     return false;
13739 
13740   // If we're inside a decltype's expression, don't check for a valid return
13741   // type or construct temporaries until we know whether this is the last call.
13742   if (ExprEvalContexts.back().IsDecltype) {
13743     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
13744     return false;
13745   }
13746 
13747   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
13748     FunctionDecl *FD;
13749     CallExpr *CE;
13750 
13751   public:
13752     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
13753       : FD(FD), CE(CE) { }
13754 
13755     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
13756       if (!FD) {
13757         S.Diag(Loc, diag::err_call_incomplete_return)
13758           << T << CE->getSourceRange();
13759         return;
13760       }
13761 
13762       S.Diag(Loc, diag::err_call_function_incomplete_return)
13763         << CE->getSourceRange() << FD->getDeclName() << T;
13764       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
13765           << FD->getDeclName();
13766     }
13767   } Diagnoser(FD, CE);
13768 
13769   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
13770     return true;
13771 
13772   return false;
13773 }
13774 
13775 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
13776 // will prevent this condition from triggering, which is what we want.
13777 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
13778   SourceLocation Loc;
13779 
13780   unsigned diagnostic = diag::warn_condition_is_assignment;
13781   bool IsOrAssign = false;
13782 
13783   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
13784     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
13785       return;
13786 
13787     IsOrAssign = Op->getOpcode() == BO_OrAssign;
13788 
13789     // Greylist some idioms by putting them into a warning subcategory.
13790     if (ObjCMessageExpr *ME
13791           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
13792       Selector Sel = ME->getSelector();
13793 
13794       // self = [<foo> init...]
13795       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
13796         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13797 
13798       // <foo> = [<bar> nextObject]
13799       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
13800         diagnostic = diag::warn_condition_is_idiomatic_assignment;
13801     }
13802 
13803     Loc = Op->getOperatorLoc();
13804   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
13805     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
13806       return;
13807 
13808     IsOrAssign = Op->getOperator() == OO_PipeEqual;
13809     Loc = Op->getOperatorLoc();
13810   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
13811     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
13812   else {
13813     // Not an assignment.
13814     return;
13815   }
13816 
13817   Diag(Loc, diagnostic) << E->getSourceRange();
13818 
13819   SourceLocation Open = E->getLocStart();
13820   SourceLocation Close = getLocForEndOfToken(E->getSourceRange().getEnd());
13821   Diag(Loc, diag::note_condition_assign_silence)
13822         << FixItHint::CreateInsertion(Open, "(")
13823         << FixItHint::CreateInsertion(Close, ")");
13824 
13825   if (IsOrAssign)
13826     Diag(Loc, diag::note_condition_or_assign_to_comparison)
13827       << FixItHint::CreateReplacement(Loc, "!=");
13828   else
13829     Diag(Loc, diag::note_condition_assign_to_comparison)
13830       << FixItHint::CreateReplacement(Loc, "==");
13831 }
13832 
13833 /// \brief Redundant parentheses over an equality comparison can indicate
13834 /// that the user intended an assignment used as condition.
13835 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
13836   // Don't warn if the parens came from a macro.
13837   SourceLocation parenLoc = ParenE->getLocStart();
13838   if (parenLoc.isInvalid() || parenLoc.isMacroID())
13839     return;
13840   // Don't warn for dependent expressions.
13841   if (ParenE->isTypeDependent())
13842     return;
13843 
13844   Expr *E = ParenE->IgnoreParens();
13845 
13846   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
13847     if (opE->getOpcode() == BO_EQ &&
13848         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
13849                                                            == Expr::MLV_Valid) {
13850       SourceLocation Loc = opE->getOperatorLoc();
13851 
13852       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
13853       SourceRange ParenERange = ParenE->getSourceRange();
13854       Diag(Loc, diag::note_equality_comparison_silence)
13855         << FixItHint::CreateRemoval(ParenERange.getBegin())
13856         << FixItHint::CreateRemoval(ParenERange.getEnd());
13857       Diag(Loc, diag::note_equality_comparison_to_assign)
13858         << FixItHint::CreateReplacement(Loc, "=");
13859     }
13860 }
13861 
13862 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
13863   DiagnoseAssignmentAsCondition(E);
13864   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
13865     DiagnoseEqualityWithExtraParens(parenE);
13866 
13867   ExprResult result = CheckPlaceholderExpr(E);
13868   if (result.isInvalid()) return ExprError();
13869   E = result.get();
13870 
13871   if (!E->isTypeDependent()) {
13872     if (getLangOpts().CPlusPlus)
13873       return CheckCXXBooleanCondition(E); // C++ 6.4p4
13874 
13875     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
13876     if (ERes.isInvalid())
13877       return ExprError();
13878     E = ERes.get();
13879 
13880     QualType T = E->getType();
13881     if (!T->isScalarType()) { // C99 6.8.4.1p1
13882       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
13883         << T << E->getSourceRange();
13884       return ExprError();
13885     }
13886     CheckBoolLikeConversion(E, Loc);
13887   }
13888 
13889   return E;
13890 }
13891 
13892 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
13893                                        Expr *SubExpr) {
13894   if (!SubExpr)
13895     return ExprError();
13896 
13897   return CheckBooleanCondition(SubExpr, Loc);
13898 }
13899 
13900 namespace {
13901   /// A visitor for rebuilding a call to an __unknown_any expression
13902   /// to have an appropriate type.
13903   struct RebuildUnknownAnyFunction
13904     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
13905 
13906     Sema &S;
13907 
13908     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
13909 
13910     ExprResult VisitStmt(Stmt *S) {
13911       llvm_unreachable("unexpected statement!");
13912     }
13913 
13914     ExprResult VisitExpr(Expr *E) {
13915       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
13916         << E->getSourceRange();
13917       return ExprError();
13918     }
13919 
13920     /// Rebuild an expression which simply semantically wraps another
13921     /// expression which it shares the type and value kind of.
13922     template <class T> ExprResult rebuildSugarExpr(T *E) {
13923       ExprResult SubResult = Visit(E->getSubExpr());
13924       if (SubResult.isInvalid()) return ExprError();
13925 
13926       Expr *SubExpr = SubResult.get();
13927       E->setSubExpr(SubExpr);
13928       E->setType(SubExpr->getType());
13929       E->setValueKind(SubExpr->getValueKind());
13930       assert(E->getObjectKind() == OK_Ordinary);
13931       return E;
13932     }
13933 
13934     ExprResult VisitParenExpr(ParenExpr *E) {
13935       return rebuildSugarExpr(E);
13936     }
13937 
13938     ExprResult VisitUnaryExtension(UnaryOperator *E) {
13939       return rebuildSugarExpr(E);
13940     }
13941 
13942     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
13943       ExprResult SubResult = Visit(E->getSubExpr());
13944       if (SubResult.isInvalid()) return ExprError();
13945 
13946       Expr *SubExpr = SubResult.get();
13947       E->setSubExpr(SubExpr);
13948       E->setType(S.Context.getPointerType(SubExpr->getType()));
13949       assert(E->getValueKind() == VK_RValue);
13950       assert(E->getObjectKind() == OK_Ordinary);
13951       return E;
13952     }
13953 
13954     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
13955       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
13956 
13957       E->setType(VD->getType());
13958 
13959       assert(E->getValueKind() == VK_RValue);
13960       if (S.getLangOpts().CPlusPlus &&
13961           !(isa<CXXMethodDecl>(VD) &&
13962             cast<CXXMethodDecl>(VD)->isInstance()))
13963         E->setValueKind(VK_LValue);
13964 
13965       return E;
13966     }
13967 
13968     ExprResult VisitMemberExpr(MemberExpr *E) {
13969       return resolveDecl(E, E->getMemberDecl());
13970     }
13971 
13972     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
13973       return resolveDecl(E, E->getDecl());
13974     }
13975   };
13976 }
13977 
13978 /// Given a function expression of unknown-any type, try to rebuild it
13979 /// to have a function type.
13980 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
13981   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
13982   if (Result.isInvalid()) return ExprError();
13983   return S.DefaultFunctionArrayConversion(Result.get());
13984 }
13985 
13986 namespace {
13987   /// A visitor for rebuilding an expression of type __unknown_anytype
13988   /// into one which resolves the type directly on the referring
13989   /// expression.  Strict preservation of the original source
13990   /// structure is not a goal.
13991   struct RebuildUnknownAnyExpr
13992     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
13993 
13994     Sema &S;
13995 
13996     /// The current destination type.
13997     QualType DestType;
13998 
13999     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
14000       : S(S), DestType(CastType) {}
14001 
14002     ExprResult VisitStmt(Stmt *S) {
14003       llvm_unreachable("unexpected statement!");
14004     }
14005 
14006     ExprResult VisitExpr(Expr *E) {
14007       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14008         << E->getSourceRange();
14009       return ExprError();
14010     }
14011 
14012     ExprResult VisitCallExpr(CallExpr *E);
14013     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
14014 
14015     /// Rebuild an expression which simply semantically wraps another
14016     /// expression which it shares the type and value kind of.
14017     template <class T> ExprResult rebuildSugarExpr(T *E) {
14018       ExprResult SubResult = Visit(E->getSubExpr());
14019       if (SubResult.isInvalid()) return ExprError();
14020       Expr *SubExpr = SubResult.get();
14021       E->setSubExpr(SubExpr);
14022       E->setType(SubExpr->getType());
14023       E->setValueKind(SubExpr->getValueKind());
14024       assert(E->getObjectKind() == OK_Ordinary);
14025       return E;
14026     }
14027 
14028     ExprResult VisitParenExpr(ParenExpr *E) {
14029       return rebuildSugarExpr(E);
14030     }
14031 
14032     ExprResult VisitUnaryExtension(UnaryOperator *E) {
14033       return rebuildSugarExpr(E);
14034     }
14035 
14036     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
14037       const PointerType *Ptr = DestType->getAs<PointerType>();
14038       if (!Ptr) {
14039         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
14040           << E->getSourceRange();
14041         return ExprError();
14042       }
14043       assert(E->getValueKind() == VK_RValue);
14044       assert(E->getObjectKind() == OK_Ordinary);
14045       E->setType(DestType);
14046 
14047       // Build the sub-expression as if it were an object of the pointee type.
14048       DestType = Ptr->getPointeeType();
14049       ExprResult SubResult = Visit(E->getSubExpr());
14050       if (SubResult.isInvalid()) return ExprError();
14051       E->setSubExpr(SubResult.get());
14052       return E;
14053     }
14054 
14055     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
14056 
14057     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
14058 
14059     ExprResult VisitMemberExpr(MemberExpr *E) {
14060       return resolveDecl(E, E->getMemberDecl());
14061     }
14062 
14063     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
14064       return resolveDecl(E, E->getDecl());
14065     }
14066   };
14067 }
14068 
14069 /// Rebuilds a call expression which yielded __unknown_anytype.
14070 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
14071   Expr *CalleeExpr = E->getCallee();
14072 
14073   enum FnKind {
14074     FK_MemberFunction,
14075     FK_FunctionPointer,
14076     FK_BlockPointer
14077   };
14078 
14079   FnKind Kind;
14080   QualType CalleeType = CalleeExpr->getType();
14081   if (CalleeType == S.Context.BoundMemberTy) {
14082     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
14083     Kind = FK_MemberFunction;
14084     CalleeType = Expr::findBoundMemberType(CalleeExpr);
14085   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
14086     CalleeType = Ptr->getPointeeType();
14087     Kind = FK_FunctionPointer;
14088   } else {
14089     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
14090     Kind = FK_BlockPointer;
14091   }
14092   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
14093 
14094   // Verify that this is a legal result type of a function.
14095   if (DestType->isArrayType() || DestType->isFunctionType()) {
14096     unsigned diagID = diag::err_func_returning_array_function;
14097     if (Kind == FK_BlockPointer)
14098       diagID = diag::err_block_returning_array_function;
14099 
14100     S.Diag(E->getExprLoc(), diagID)
14101       << DestType->isFunctionType() << DestType;
14102     return ExprError();
14103   }
14104 
14105   // Otherwise, go ahead and set DestType as the call's result.
14106   E->setType(DestType.getNonLValueExprType(S.Context));
14107   E->setValueKind(Expr::getValueKindForType(DestType));
14108   assert(E->getObjectKind() == OK_Ordinary);
14109 
14110   // Rebuild the function type, replacing the result type with DestType.
14111   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
14112   if (Proto) {
14113     // __unknown_anytype(...) is a special case used by the debugger when
14114     // it has no idea what a function's signature is.
14115     //
14116     // We want to build this call essentially under the K&R
14117     // unprototyped rules, but making a FunctionNoProtoType in C++
14118     // would foul up all sorts of assumptions.  However, we cannot
14119     // simply pass all arguments as variadic arguments, nor can we
14120     // portably just call the function under a non-variadic type; see
14121     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
14122     // However, it turns out that in practice it is generally safe to
14123     // call a function declared as "A foo(B,C,D);" under the prototype
14124     // "A foo(B,C,D,...);".  The only known exception is with the
14125     // Windows ABI, where any variadic function is implicitly cdecl
14126     // regardless of its normal CC.  Therefore we change the parameter
14127     // types to match the types of the arguments.
14128     //
14129     // This is a hack, but it is far superior to moving the
14130     // corresponding target-specific code from IR-gen to Sema/AST.
14131 
14132     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
14133     SmallVector<QualType, 8> ArgTypes;
14134     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
14135       ArgTypes.reserve(E->getNumArgs());
14136       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
14137         Expr *Arg = E->getArg(i);
14138         QualType ArgType = Arg->getType();
14139         if (E->isLValue()) {
14140           ArgType = S.Context.getLValueReferenceType(ArgType);
14141         } else if (E->isXValue()) {
14142           ArgType = S.Context.getRValueReferenceType(ArgType);
14143         }
14144         ArgTypes.push_back(ArgType);
14145       }
14146       ParamTypes = ArgTypes;
14147     }
14148     DestType = S.Context.getFunctionType(DestType, ParamTypes,
14149                                          Proto->getExtProtoInfo());
14150   } else {
14151     DestType = S.Context.getFunctionNoProtoType(DestType,
14152                                                 FnType->getExtInfo());
14153   }
14154 
14155   // Rebuild the appropriate pointer-to-function type.
14156   switch (Kind) {
14157   case FK_MemberFunction:
14158     // Nothing to do.
14159     break;
14160 
14161   case FK_FunctionPointer:
14162     DestType = S.Context.getPointerType(DestType);
14163     break;
14164 
14165   case FK_BlockPointer:
14166     DestType = S.Context.getBlockPointerType(DestType);
14167     break;
14168   }
14169 
14170   // Finally, we can recurse.
14171   ExprResult CalleeResult = Visit(CalleeExpr);
14172   if (!CalleeResult.isUsable()) return ExprError();
14173   E->setCallee(CalleeResult.get());
14174 
14175   // Bind a temporary if necessary.
14176   return S.MaybeBindToTemporary(E);
14177 }
14178 
14179 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
14180   // Verify that this is a legal result type of a call.
14181   if (DestType->isArrayType() || DestType->isFunctionType()) {
14182     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
14183       << DestType->isFunctionType() << DestType;
14184     return ExprError();
14185   }
14186 
14187   // Rewrite the method result type if available.
14188   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
14189     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
14190     Method->setReturnType(DestType);
14191   }
14192 
14193   // Change the type of the message.
14194   E->setType(DestType.getNonReferenceType());
14195   E->setValueKind(Expr::getValueKindForType(DestType));
14196 
14197   return S.MaybeBindToTemporary(E);
14198 }
14199 
14200 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
14201   // The only case we should ever see here is a function-to-pointer decay.
14202   if (E->getCastKind() == CK_FunctionToPointerDecay) {
14203     assert(E->getValueKind() == VK_RValue);
14204     assert(E->getObjectKind() == OK_Ordinary);
14205 
14206     E->setType(DestType);
14207 
14208     // Rebuild the sub-expression as the pointee (function) type.
14209     DestType = DestType->castAs<PointerType>()->getPointeeType();
14210 
14211     ExprResult Result = Visit(E->getSubExpr());
14212     if (!Result.isUsable()) return ExprError();
14213 
14214     E->setSubExpr(Result.get());
14215     return E;
14216   } else if (E->getCastKind() == CK_LValueToRValue) {
14217     assert(E->getValueKind() == VK_RValue);
14218     assert(E->getObjectKind() == OK_Ordinary);
14219 
14220     assert(isa<BlockPointerType>(E->getType()));
14221 
14222     E->setType(DestType);
14223 
14224     // The sub-expression has to be a lvalue reference, so rebuild it as such.
14225     DestType = S.Context.getLValueReferenceType(DestType);
14226 
14227     ExprResult Result = Visit(E->getSubExpr());
14228     if (!Result.isUsable()) return ExprError();
14229 
14230     E->setSubExpr(Result.get());
14231     return E;
14232   } else {
14233     llvm_unreachable("Unhandled cast type!");
14234   }
14235 }
14236 
14237 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
14238   ExprValueKind ValueKind = VK_LValue;
14239   QualType Type = DestType;
14240 
14241   // We know how to make this work for certain kinds of decls:
14242 
14243   //  - functions
14244   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
14245     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
14246       DestType = Ptr->getPointeeType();
14247       ExprResult Result = resolveDecl(E, VD);
14248       if (Result.isInvalid()) return ExprError();
14249       return S.ImpCastExprToType(Result.get(), Type,
14250                                  CK_FunctionToPointerDecay, VK_RValue);
14251     }
14252 
14253     if (!Type->isFunctionType()) {
14254       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
14255         << VD << E->getSourceRange();
14256       return ExprError();
14257     }
14258     if (const FunctionProtoType *FT = Type->getAs<FunctionProtoType>()) {
14259       // We must match the FunctionDecl's type to the hack introduced in
14260       // RebuildUnknownAnyExpr::VisitCallExpr to vararg functions of unknown
14261       // type. See the lengthy commentary in that routine.
14262       QualType FDT = FD->getType();
14263       const FunctionType *FnType = FDT->castAs<FunctionType>();
14264       const FunctionProtoType *Proto = dyn_cast_or_null<FunctionProtoType>(FnType);
14265       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
14266       if (DRE && Proto && Proto->getParamTypes().empty() && Proto->isVariadic()) {
14267         SourceLocation Loc = FD->getLocation();
14268         FunctionDecl *NewFD = FunctionDecl::Create(FD->getASTContext(),
14269                                       FD->getDeclContext(),
14270                                       Loc, Loc, FD->getNameInfo().getName(),
14271                                       DestType, FD->getTypeSourceInfo(),
14272                                       SC_None, false/*isInlineSpecified*/,
14273                                       FD->hasPrototype(),
14274                                       false/*isConstexprSpecified*/);
14275 
14276         if (FD->getQualifier())
14277           NewFD->setQualifierInfo(FD->getQualifierLoc());
14278 
14279         SmallVector<ParmVarDecl*, 16> Params;
14280         for (const auto &AI : FT->param_types()) {
14281           ParmVarDecl *Param =
14282             S.BuildParmVarDeclForTypedef(FD, Loc, AI);
14283           Param->setScopeInfo(0, Params.size());
14284           Params.push_back(Param);
14285         }
14286         NewFD->setParams(Params);
14287         DRE->setDecl(NewFD);
14288         VD = DRE->getDecl();
14289       }
14290     }
14291 
14292     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
14293       if (MD->isInstance()) {
14294         ValueKind = VK_RValue;
14295         Type = S.Context.BoundMemberTy;
14296       }
14297 
14298     // Function references aren't l-values in C.
14299     if (!S.getLangOpts().CPlusPlus)
14300       ValueKind = VK_RValue;
14301 
14302   //  - variables
14303   } else if (isa<VarDecl>(VD)) {
14304     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
14305       Type = RefTy->getPointeeType();
14306     } else if (Type->isFunctionType()) {
14307       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
14308         << VD << E->getSourceRange();
14309       return ExprError();
14310     }
14311 
14312   //  - nothing else
14313   } else {
14314     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
14315       << VD << E->getSourceRange();
14316     return ExprError();
14317   }
14318 
14319   // Modifying the declaration like this is friendly to IR-gen but
14320   // also really dangerous.
14321   VD->setType(DestType);
14322   E->setType(Type);
14323   E->setValueKind(ValueKind);
14324   return E;
14325 }
14326 
14327 /// Check a cast of an unknown-any type.  We intentionally only
14328 /// trigger this for C-style casts.
14329 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
14330                                      Expr *CastExpr, CastKind &CastKind,
14331                                      ExprValueKind &VK, CXXCastPath &Path) {
14332   // Rewrite the casted expression from scratch.
14333   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
14334   if (!result.isUsable()) return ExprError();
14335 
14336   CastExpr = result.get();
14337   VK = CastExpr->getValueKind();
14338   CastKind = CK_NoOp;
14339 
14340   return CastExpr;
14341 }
14342 
14343 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
14344   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
14345 }
14346 
14347 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
14348                                     Expr *arg, QualType &paramType) {
14349   // If the syntactic form of the argument is not an explicit cast of
14350   // any sort, just do default argument promotion.
14351   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
14352   if (!castArg) {
14353     ExprResult result = DefaultArgumentPromotion(arg);
14354     if (result.isInvalid()) return ExprError();
14355     paramType = result.get()->getType();
14356     return result;
14357   }
14358 
14359   // Otherwise, use the type that was written in the explicit cast.
14360   assert(!arg->hasPlaceholderType());
14361   paramType = castArg->getTypeAsWritten();
14362 
14363   // Copy-initialize a parameter of that type.
14364   InitializedEntity entity =
14365     InitializedEntity::InitializeParameter(Context, paramType,
14366                                            /*consumed*/ false);
14367   return PerformCopyInitialization(entity, callLoc, arg);
14368 }
14369 
14370 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
14371   Expr *orig = E;
14372   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
14373   while (true) {
14374     E = E->IgnoreParenImpCasts();
14375     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
14376       E = call->getCallee();
14377       diagID = diag::err_uncasted_call_of_unknown_any;
14378     } else {
14379       break;
14380     }
14381   }
14382 
14383   SourceLocation loc;
14384   NamedDecl *d;
14385   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
14386     loc = ref->getLocation();
14387     d = ref->getDecl();
14388   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
14389     loc = mem->getMemberLoc();
14390     d = mem->getMemberDecl();
14391   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
14392     diagID = diag::err_uncasted_call_of_unknown_any;
14393     loc = msg->getSelectorStartLoc();
14394     d = msg->getMethodDecl();
14395     if (!d) {
14396       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
14397         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
14398         << orig->getSourceRange();
14399       return ExprError();
14400     }
14401   } else {
14402     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
14403       << E->getSourceRange();
14404     return ExprError();
14405   }
14406 
14407   S.Diag(loc, diagID) << d << orig->getSourceRange();
14408 
14409   // Never recoverable.
14410   return ExprError();
14411 }
14412 
14413 /// Check for operands with placeholder types and complain if found.
14414 /// Returns true if there was an error and no recovery was possible.
14415 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
14416   if (!getLangOpts().CPlusPlus) {
14417     // C cannot handle TypoExpr nodes on either side of a binop because it
14418     // doesn't handle dependent types properly, so make sure any TypoExprs have
14419     // been dealt with before checking the operands.
14420     ExprResult Result = CorrectDelayedTyposInExpr(E);
14421     if (!Result.isUsable()) return ExprError();
14422     E = Result.get();
14423   }
14424 
14425   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
14426   if (!placeholderType) return E;
14427 
14428   switch (placeholderType->getKind()) {
14429 
14430   // Overloaded expressions.
14431   case BuiltinType::Overload: {
14432     // Try to resolve a single function template specialization.
14433     // This is obligatory.
14434     ExprResult result = E;
14435     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
14436       return result;
14437 
14438     // If that failed, try to recover with a call.
14439     } else {
14440       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
14441                            /*complain*/ true);
14442       return result;
14443     }
14444   }
14445 
14446   // Bound member functions.
14447   case BuiltinType::BoundMember: {
14448     ExprResult result = E;
14449     const Expr *BME = E->IgnoreParens();
14450     PartialDiagnostic PD = PDiag(diag::err_bound_member_function);
14451     // Try to give a nicer diagnostic if it is a bound member that we recognize.
14452     if (isa<CXXPseudoDestructorExpr>(BME)) {
14453       PD = PDiag(diag::err_dtor_expr_without_call) << /*pseudo-destructor*/ 1;
14454     } else if (const auto *ME = dyn_cast<MemberExpr>(BME)) {
14455       if (ME->getMemberNameInfo().getName().getNameKind() ==
14456           DeclarationName::CXXDestructorName)
14457         PD = PDiag(diag::err_dtor_expr_without_call) << /*destructor*/ 0;
14458     }
14459     tryToRecoverWithCall(result, PD,
14460                          /*complain*/ true);
14461     return result;
14462   }
14463 
14464   // ARC unbridged casts.
14465   case BuiltinType::ARCUnbridgedCast: {
14466     Expr *realCast = stripARCUnbridgedCast(E);
14467     diagnoseARCUnbridgedCast(realCast);
14468     return realCast;
14469   }
14470 
14471   // Expressions of unknown type.
14472   case BuiltinType::UnknownAny:
14473     return diagnoseUnknownAnyExpr(*this, E);
14474 
14475   // Pseudo-objects.
14476   case BuiltinType::PseudoObject:
14477     return checkPseudoObjectRValue(E);
14478 
14479   case BuiltinType::BuiltinFn: {
14480     // Accept __noop without parens by implicitly converting it to a call expr.
14481     auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
14482     if (DRE) {
14483       auto *FD = cast<FunctionDecl>(DRE->getDecl());
14484       if (FD->getBuiltinID() == Builtin::BI__noop) {
14485         E = ImpCastExprToType(E, Context.getPointerType(FD->getType()),
14486                               CK_BuiltinFnToFnPtr).get();
14487         return new (Context) CallExpr(Context, E, None, Context.IntTy,
14488                                       VK_RValue, SourceLocation());
14489       }
14490     }
14491 
14492     Diag(E->getLocStart(), diag::err_builtin_fn_use);
14493     return ExprError();
14494   }
14495 
14496   // Expressions of unknown type.
14497   case BuiltinType::OMPArraySection:
14498     Diag(E->getLocStart(), diag::err_omp_array_section_use);
14499     return ExprError();
14500 
14501   // Everything else should be impossible.
14502 #define BUILTIN_TYPE(Id, SingletonId) \
14503   case BuiltinType::Id:
14504 #define PLACEHOLDER_TYPE(Id, SingletonId)
14505 #include "clang/AST/BuiltinTypes.def"
14506     break;
14507   }
14508 
14509   llvm_unreachable("invalid placeholder type!");
14510 }
14511 
14512 bool Sema::CheckCaseExpression(Expr *E) {
14513   if (E->isTypeDependent())
14514     return true;
14515   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
14516     return E->getType()->isIntegralOrEnumerationType();
14517   return false;
14518 }
14519 
14520 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
14521 ExprResult
14522 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
14523   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
14524          "Unknown Objective-C Boolean value!");
14525   QualType BoolT = Context.ObjCBuiltinBoolTy;
14526   if (!Context.getBOOLDecl()) {
14527     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
14528                         Sema::LookupOrdinaryName);
14529     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
14530       NamedDecl *ND = Result.getFoundDecl();
14531       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
14532         Context.setBOOLDecl(TD);
14533     }
14534   }
14535   if (Context.getBOOLDecl())
14536     BoolT = Context.getBOOLType();
14537   return new (Context)
14538       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
14539 }
14540