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/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/AnalysisBasedWarnings.h"
35 #include "clang/Sema/DeclSpec.h"
36 #include "clang/Sema/DelayedDiagnostic.h"
37 #include "clang/Sema/Designator.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaFixItUtils.h"
44 #include "clang/Sema/Template.h"
45 using namespace clang;
46 using namespace sema;
47 
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51   // See if this is an auto-typed variable whose initializer we are parsing.
52   if (ParsingInitForAutoVars.count(D))
53     return false;
54 
55   // See if this is a deleted function.
56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57     if (FD->isDeleted())
58       return false;
59 
60     // If the function has a deduced return type, and we can't deduce it,
61     // then we can't use it either.
62     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
63         DeduceReturnType(FD, SourceLocation(), /*Diagnose*/ false))
64       return false;
65   }
66 
67   // See if this function is unavailable.
68   if (D->getAvailability() == AR_Unavailable &&
69       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
70     return false;
71 
72   return true;
73 }
74 
75 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
76   // Warn if this is used but marked unused.
77   if (D->hasAttr<UnusedAttr>()) {
78     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
79     if (!DC->hasAttr<UnusedAttr>())
80       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
81   }
82 }
83 
84 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
85                               NamedDecl *D, SourceLocation Loc,
86                               const ObjCInterfaceDecl *UnknownObjCClass) {
87   // See if this declaration is unavailable or deprecated.
88   std::string Message;
89   AvailabilityResult Result = D->getAvailability(&Message);
90   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
91     if (Result == AR_Available) {
92       const DeclContext *DC = ECD->getDeclContext();
93       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
94         Result = TheEnumDecl->getAvailability(&Message);
95     }
96 
97   const ObjCPropertyDecl *ObjCPDecl = nullptr;
98   if (Result == AR_Deprecated || Result == AR_Unavailable) {
99     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
100       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
101         AvailabilityResult PDeclResult = PD->getAvailability(nullptr);
102         if (PDeclResult == Result)
103           ObjCPDecl = PD;
104       }
105     }
106   }
107 
108   switch (Result) {
109     case AR_Available:
110     case AR_NotYetIntroduced:
111       break;
112 
113     case AR_Deprecated:
114       if (S.getCurContextAvailability() != AR_Deprecated)
115         S.EmitAvailabilityWarning(Sema::AD_Deprecation,
116                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl);
117       break;
118 
119     case AR_Unavailable:
120       if (S.getCurContextAvailability() != AR_Unavailable)
121         S.EmitAvailabilityWarning(Sema::AD_Unavailable,
122                                   D, Message, Loc, UnknownObjCClass, ObjCPDecl);
123       break;
124 
125     }
126     return Result;
127 }
128 
129 /// \brief Emit a note explaining that this function is deleted.
130 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
131   assert(Decl->isDeleted());
132 
133   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
134 
135   if (Method && Method->isDeleted() && Method->isDefaulted()) {
136     // If the method was explicitly defaulted, point at that declaration.
137     if (!Method->isImplicit())
138       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
139 
140     // Try to diagnose why this special member function was implicitly
141     // deleted. This might fail, if that reason no longer applies.
142     CXXSpecialMember CSM = getSpecialMember(Method);
143     if (CSM != CXXInvalid)
144       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
145 
146     return;
147   }
148 
149   if (CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Decl)) {
150     if (CXXConstructorDecl *BaseCD =
151             const_cast<CXXConstructorDecl*>(CD->getInheritedConstructor())) {
152       Diag(Decl->getLocation(), diag::note_inherited_deleted_here);
153       if (BaseCD->isDeleted()) {
154         NoteDeletedFunction(BaseCD);
155       } else {
156         // FIXME: An explanation of why exactly it can't be inherited
157         // would be nice.
158         Diag(BaseCD->getLocation(), diag::note_cannot_inherit);
159       }
160       return;
161     }
162   }
163 
164   Diag(Decl->getLocation(), diag::note_availability_specified_here)
165     << Decl << true;
166 }
167 
168 /// \brief Determine whether a FunctionDecl was ever declared with an
169 /// explicit storage class.
170 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
171   for (auto I : D->redecls()) {
172     if (I->getStorageClass() != SC_None)
173       return true;
174   }
175   return false;
176 }
177 
178 /// \brief Check whether we're in an extern inline function and referring to a
179 /// variable or function with internal linkage (C11 6.7.4p3).
180 ///
181 /// This is only a warning because we used to silently accept this code, but
182 /// in many cases it will not behave correctly. This is not enabled in C++ mode
183 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
184 /// and so while there may still be user mistakes, most of the time we can't
185 /// prove that there are errors.
186 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
187                                                       const NamedDecl *D,
188                                                       SourceLocation Loc) {
189   // This is disabled under C++; there are too many ways for this to fire in
190   // contexts where the warning is a false positive, or where it is technically
191   // correct but benign.
192   if (S.getLangOpts().CPlusPlus)
193     return;
194 
195   // Check if this is an inlined function or method.
196   FunctionDecl *Current = S.getCurFunctionDecl();
197   if (!Current)
198     return;
199   if (!Current->isInlined())
200     return;
201   if (!Current->isExternallyVisible())
202     return;
203 
204   // Check if the decl has internal linkage.
205   if (D->getFormalLinkage() != InternalLinkage)
206     return;
207 
208   // Downgrade from ExtWarn to Extension if
209   //  (1) the supposedly external inline function is in the main file,
210   //      and probably won't be included anywhere else.
211   //  (2) the thing we're referencing is a pure function.
212   //  (3) the thing we're referencing is another inline function.
213   // This last can give us false negatives, but it's better than warning on
214   // wrappers for simple C library functions.
215   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
216   bool DowngradeWarning = S.getSourceManager().isInMainFile(Loc);
217   if (!DowngradeWarning && UsedFn)
218     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
219 
220   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
221                                : diag::warn_internal_in_extern_inline)
222     << /*IsVar=*/!UsedFn << D;
223 
224   S.MaybeSuggestAddingStaticToDecl(Current);
225 
226   S.Diag(D->getCanonicalDecl()->getLocation(), diag::note_entity_declared_at)
227       << D;
228 }
229 
230 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
231   const FunctionDecl *First = Cur->getFirstDecl();
232 
233   // Suggest "static" on the function, if possible.
234   if (!hasAnyExplicitStorageClass(First)) {
235     SourceLocation DeclBegin = First->getSourceRange().getBegin();
236     Diag(DeclBegin, diag::note_convert_inline_to_static)
237       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
238   }
239 }
240 
241 /// \brief Determine whether the use of this declaration is valid, and
242 /// emit any corresponding diagnostics.
243 ///
244 /// This routine diagnoses various problems with referencing
245 /// declarations that can occur when using a declaration. For example,
246 /// it might warn if a deprecated or unavailable declaration is being
247 /// used, or produce an error (and return true) if a C++0x deleted
248 /// function is being used.
249 ///
250 /// \returns true if there was an error (this declaration cannot be
251 /// referenced), false otherwise.
252 ///
253 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
254                              const ObjCInterfaceDecl *UnknownObjCClass) {
255   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
256     // If there were any diagnostics suppressed by template argument deduction,
257     // emit them now.
258     SuppressedDiagnosticsMap::iterator
259       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
260     if (Pos != SuppressedDiagnostics.end()) {
261       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
262       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
263         Diag(Suppressed[I].first, Suppressed[I].second);
264 
265       // Clear out the list of suppressed diagnostics, so that we don't emit
266       // them again for this specialization. However, we don't obsolete this
267       // entry from the table, because we want to avoid ever emitting these
268       // diagnostics again.
269       Suppressed.clear();
270     }
271 
272     // C++ [basic.start.main]p3:
273     //   The function 'main' shall not be used within a program.
274     if (cast<FunctionDecl>(D)->isMain())
275       Diag(Loc, diag::ext_main_used);
276   }
277 
278   // See if this is an auto-typed variable whose initializer we are parsing.
279   if (ParsingInitForAutoVars.count(D)) {
280     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
281       << D->getDeclName();
282     return true;
283   }
284 
285   // See if this is a deleted function.
286   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
287     if (FD->isDeleted()) {
288       Diag(Loc, diag::err_deleted_function_use);
289       NoteDeletedFunction(FD);
290       return true;
291     }
292 
293     // If the function has a deduced return type, and we can't deduce it,
294     // then we can't use it either.
295     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
296         DeduceReturnType(FD, Loc))
297       return true;
298   }
299   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
300 
301   DiagnoseUnusedOfDecl(*this, D, Loc);
302 
303   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
304 
305   return false;
306 }
307 
308 /// \brief Retrieve the message suffix that should be added to a
309 /// diagnostic complaining about the given function being deleted or
310 /// unavailable.
311 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
312   std::string Message;
313   if (FD->getAvailability(&Message))
314     return ": " + Message;
315 
316   return std::string();
317 }
318 
319 /// DiagnoseSentinelCalls - This routine checks whether a call or
320 /// message-send is to a declaration with the sentinel attribute, and
321 /// if so, it checks that the requirements of the sentinel are
322 /// satisfied.
323 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
324                                  ArrayRef<Expr *> Args) {
325   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
326   if (!attr)
327     return;
328 
329   // The number of formal parameters of the declaration.
330   unsigned numFormalParams;
331 
332   // The kind of declaration.  This is also an index into a %select in
333   // the diagnostic.
334   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
335 
336   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
337     numFormalParams = MD->param_size();
338     calleeType = CT_Method;
339   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
340     numFormalParams = FD->param_size();
341     calleeType = CT_Function;
342   } else if (isa<VarDecl>(D)) {
343     QualType type = cast<ValueDecl>(D)->getType();
344     const FunctionType *fn = nullptr;
345     if (const PointerType *ptr = type->getAs<PointerType>()) {
346       fn = ptr->getPointeeType()->getAs<FunctionType>();
347       if (!fn) return;
348       calleeType = CT_Function;
349     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
350       fn = ptr->getPointeeType()->castAs<FunctionType>();
351       calleeType = CT_Block;
352     } else {
353       return;
354     }
355 
356     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
357       numFormalParams = proto->getNumParams();
358     } else {
359       numFormalParams = 0;
360     }
361   } else {
362     return;
363   }
364 
365   // "nullPos" is the number of formal parameters at the end which
366   // effectively count as part of the variadic arguments.  This is
367   // useful if you would prefer to not have *any* formal parameters,
368   // but the language forces you to have at least one.
369   unsigned nullPos = attr->getNullPos();
370   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
371   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
372 
373   // The number of arguments which should follow the sentinel.
374   unsigned numArgsAfterSentinel = attr->getSentinel();
375 
376   // If there aren't enough arguments for all the formal parameters,
377   // the sentinel, and the args after the sentinel, complain.
378   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
379     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
380     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
381     return;
382   }
383 
384   // Otherwise, find the sentinel expression.
385   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
386   if (!sentinelExpr) return;
387   if (sentinelExpr->isValueDependent()) return;
388   if (Context.isSentinelNullExpr(sentinelExpr)) return;
389 
390   // Pick a reasonable string to insert.  Optimistically use 'nil' or
391   // 'NULL' if those are actually defined in the context.  Only use
392   // 'nil' for ObjC methods, where it's much more likely that the
393   // variadic arguments form a list of object pointers.
394   SourceLocation MissingNilLoc
395     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
396   std::string NullValue;
397   if (calleeType == CT_Method &&
398       PP.getIdentifierInfo("nil")->hasMacroDefinition())
399     NullValue = "nil";
400   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
401     NullValue = "NULL";
402   else
403     NullValue = "(void*) 0";
404 
405   if (MissingNilLoc.isInvalid())
406     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
407   else
408     Diag(MissingNilLoc, diag::warn_missing_sentinel)
409       << int(calleeType)
410       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
411   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
412 }
413 
414 SourceRange Sema::getExprRange(Expr *E) const {
415   return E ? E->getSourceRange() : SourceRange();
416 }
417 
418 //===----------------------------------------------------------------------===//
419 //  Standard Promotions and Conversions
420 //===----------------------------------------------------------------------===//
421 
422 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
423 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
424   // Handle any placeholder expressions which made it here.
425   if (E->getType()->isPlaceholderType()) {
426     ExprResult result = CheckPlaceholderExpr(E);
427     if (result.isInvalid()) return ExprError();
428     E = result.get();
429   }
430 
431   QualType Ty = E->getType();
432   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
433 
434   if (Ty->isFunctionType()) {
435     // If we are here, we are not calling a function but taking
436     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
437     if (getLangOpts().OpenCL) {
438       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
439       return ExprError();
440     }
441     E = ImpCastExprToType(E, Context.getPointerType(Ty),
442                           CK_FunctionToPointerDecay).get();
443   } else if (Ty->isArrayType()) {
444     // In C90 mode, arrays only promote to pointers if the array expression is
445     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
446     // type 'array of type' is converted to an expression that has type 'pointer
447     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
448     // that has type 'array of type' ...".  The relevant change is "an lvalue"
449     // (C90) to "an expression" (C99).
450     //
451     // C++ 4.2p1:
452     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
453     // T" can be converted to an rvalue of type "pointer to T".
454     //
455     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
456       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
457                             CK_ArrayToPointerDecay).get();
458   }
459   return E;
460 }
461 
462 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
463   // Check to see if we are dereferencing a null pointer.  If so,
464   // and if not volatile-qualified, this is undefined behavior that the
465   // optimizer will delete, so warn about it.  People sometimes try to use this
466   // to get a deterministic trap and are surprised by clang's behavior.  This
467   // only handles the pattern "*null", which is a very syntactic check.
468   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
469     if (UO->getOpcode() == UO_Deref &&
470         UO->getSubExpr()->IgnoreParenCasts()->
471           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
472         !UO->getType().isVolatileQualified()) {
473     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
474                           S.PDiag(diag::warn_indirection_through_null)
475                             << UO->getSubExpr()->getSourceRange());
476     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
477                         S.PDiag(diag::note_indirection_through_null));
478   }
479 }
480 
481 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
482                                     SourceLocation AssignLoc,
483                                     const Expr* RHS) {
484   const ObjCIvarDecl *IV = OIRE->getDecl();
485   if (!IV)
486     return;
487 
488   DeclarationName MemberName = IV->getDeclName();
489   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
490   if (!Member || !Member->isStr("isa"))
491     return;
492 
493   const Expr *Base = OIRE->getBase();
494   QualType BaseType = Base->getType();
495   if (OIRE->isArrow())
496     BaseType = BaseType->getPointeeType();
497   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
498     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
499       ObjCInterfaceDecl *ClassDeclared = nullptr;
500       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
501       if (!ClassDeclared->getSuperClass()
502           && (*ClassDeclared->ivar_begin()) == IV) {
503         if (RHS) {
504           NamedDecl *ObjectSetClass =
505             S.LookupSingleName(S.TUScope,
506                                &S.Context.Idents.get("object_setClass"),
507                                SourceLocation(), S.LookupOrdinaryName);
508           if (ObjectSetClass) {
509             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
510             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
511             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
512             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
513                                                      AssignLoc), ",") <<
514             FixItHint::CreateInsertion(RHSLocEnd, ")");
515           }
516           else
517             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
518         } else {
519           NamedDecl *ObjectGetClass =
520             S.LookupSingleName(S.TUScope,
521                                &S.Context.Idents.get("object_getClass"),
522                                SourceLocation(), S.LookupOrdinaryName);
523           if (ObjectGetClass)
524             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
525             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
526             FixItHint::CreateReplacement(
527                                          SourceRange(OIRE->getOpLoc(),
528                                                      OIRE->getLocEnd()), ")");
529           else
530             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
531         }
532         S.Diag(IV->getLocation(), diag::note_ivar_decl);
533       }
534     }
535 }
536 
537 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
538   // Handle any placeholder expressions which made it here.
539   if (E->getType()->isPlaceholderType()) {
540     ExprResult result = CheckPlaceholderExpr(E);
541     if (result.isInvalid()) return ExprError();
542     E = result.get();
543   }
544 
545   // C++ [conv.lval]p1:
546   //   A glvalue of a non-function, non-array type T can be
547   //   converted to a prvalue.
548   if (!E->isGLValue()) return E;
549 
550   QualType T = E->getType();
551   assert(!T.isNull() && "r-value conversion on typeless expression?");
552 
553   // We don't want to throw lvalue-to-rvalue casts on top of
554   // expressions of certain types in C++.
555   if (getLangOpts().CPlusPlus &&
556       (E->getType() == Context.OverloadTy ||
557        T->isDependentType() ||
558        T->isRecordType()))
559     return E;
560 
561   // The C standard is actually really unclear on this point, and
562   // DR106 tells us what the result should be but not why.  It's
563   // generally best to say that void types just doesn't undergo
564   // lvalue-to-rvalue at all.  Note that expressions of unqualified
565   // 'void' type are never l-values, but qualified void can be.
566   if (T->isVoidType())
567     return E;
568 
569   // OpenCL usually rejects direct accesses to values of 'half' type.
570   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
571       T->isHalfType()) {
572     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
573       << 0 << T;
574     return ExprError();
575   }
576 
577   CheckForNullPointerDereference(*this, E);
578   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
579     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
580                                      &Context.Idents.get("object_getClass"),
581                                      SourceLocation(), LookupOrdinaryName);
582     if (ObjectGetClass)
583       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
584         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
585         FixItHint::CreateReplacement(
586                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
587     else
588       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
589   }
590   else if (const ObjCIvarRefExpr *OIRE =
591             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
592     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/nullptr);
593 
594   // C++ [conv.lval]p1:
595   //   [...] If T is a non-class type, the type of the prvalue is the
596   //   cv-unqualified version of T. Otherwise, the type of the
597   //   rvalue is T.
598   //
599   // C99 6.3.2.1p2:
600   //   If the lvalue has qualified type, the value has the unqualified
601   //   version of the type of the lvalue; otherwise, the value has the
602   //   type of the lvalue.
603   if (T.hasQualifiers())
604     T = T.getUnqualifiedType();
605 
606   UpdateMarkingForLValueToRValue(E);
607 
608   // Loading a __weak object implicitly retains the value, so we need a cleanup to
609   // balance that.
610   if (getLangOpts().ObjCAutoRefCount &&
611       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
612     ExprNeedsCleanups = true;
613 
614   ExprResult Res = ImplicitCastExpr::Create(Context, T, CK_LValueToRValue, E,
615                                             nullptr, VK_RValue);
616 
617   // C11 6.3.2.1p2:
618   //   ... if the lvalue has atomic type, the value has the non-atomic version
619   //   of the type of the lvalue ...
620   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
621     T = Atomic->getValueType().getUnqualifiedType();
622     Res = ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic, Res.get(),
623                                    nullptr, VK_RValue);
624   }
625 
626   return Res;
627 }
628 
629 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
630   ExprResult Res = DefaultFunctionArrayConversion(E);
631   if (Res.isInvalid())
632     return ExprError();
633   Res = DefaultLvalueConversion(Res.get());
634   if (Res.isInvalid())
635     return ExprError();
636   return Res;
637 }
638 
639 /// CallExprUnaryConversions - a special case of an unary conversion
640 /// performed on a function designator of a call expression.
641 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
642   QualType Ty = E->getType();
643   ExprResult Res = E;
644   // Only do implicit cast for a function type, but not for a pointer
645   // to function type.
646   if (Ty->isFunctionType()) {
647     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
648                             CK_FunctionToPointerDecay).get();
649     if (Res.isInvalid())
650       return ExprError();
651   }
652   Res = DefaultLvalueConversion(Res.get());
653   if (Res.isInvalid())
654     return ExprError();
655   return Res.get();
656 }
657 
658 /// UsualUnaryConversions - Performs various conversions that are common to most
659 /// operators (C99 6.3). The conversions of array and function types are
660 /// sometimes suppressed. For example, the array->pointer conversion doesn't
661 /// apply if the array is an argument to the sizeof or address (&) operators.
662 /// In these instances, this routine should *not* be called.
663 ExprResult Sema::UsualUnaryConversions(Expr *E) {
664   // First, convert to an r-value.
665   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
666   if (Res.isInvalid())
667     return ExprError();
668   E = Res.get();
669 
670   QualType Ty = E->getType();
671   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
672 
673   // Half FP have to be promoted to float unless it is natively supported
674   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
675     return ImpCastExprToType(Res.get(), Context.FloatTy, CK_FloatingCast);
676 
677   // Try to perform integral promotions if the object has a theoretically
678   // promotable type.
679   if (Ty->isIntegralOrUnscopedEnumerationType()) {
680     // C99 6.3.1.1p2:
681     //
682     //   The following may be used in an expression wherever an int or
683     //   unsigned int may be used:
684     //     - an object or expression with an integer type whose integer
685     //       conversion rank is less than or equal to the rank of int
686     //       and unsigned int.
687     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
688     //
689     //   If an int can represent all values of the original type, the
690     //   value is converted to an int; otherwise, it is converted to an
691     //   unsigned int. These are called the integer promotions. All
692     //   other types are unchanged by the integer promotions.
693 
694     QualType PTy = Context.isPromotableBitField(E);
695     if (!PTy.isNull()) {
696       E = ImpCastExprToType(E, PTy, CK_IntegralCast).get();
697       return E;
698     }
699     if (Ty->isPromotableIntegerType()) {
700       QualType PT = Context.getPromotedIntegerType(Ty);
701       E = ImpCastExprToType(E, PT, CK_IntegralCast).get();
702       return E;
703     }
704   }
705   return E;
706 }
707 
708 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
709 /// do not have a prototype. Arguments that have type float or __fp16
710 /// are promoted to double. All other argument types are converted by
711 /// UsualUnaryConversions().
712 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
713   QualType Ty = E->getType();
714   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
715 
716   ExprResult Res = UsualUnaryConversions(E);
717   if (Res.isInvalid())
718     return ExprError();
719   E = Res.get();
720 
721   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
722   // double.
723   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
724   if (BTy && (BTy->getKind() == BuiltinType::Half ||
725               BTy->getKind() == BuiltinType::Float))
726     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).get();
727 
728   // C++ performs lvalue-to-rvalue conversion as a default argument
729   // promotion, even on class types, but note:
730   //   C++11 [conv.lval]p2:
731   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
732   //     operand or a subexpression thereof the value contained in the
733   //     referenced object is not accessed. Otherwise, if the glvalue
734   //     has a class type, the conversion copy-initializes a temporary
735   //     of type T from the glvalue and the result of the conversion
736   //     is a prvalue for the temporary.
737   // FIXME: add some way to gate this entire thing for correctness in
738   // potentially potentially evaluated contexts.
739   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
740     ExprResult Temp = PerformCopyInitialization(
741                        InitializedEntity::InitializeTemporary(E->getType()),
742                                                 E->getExprLoc(), E);
743     if (Temp.isInvalid())
744       return ExprError();
745     E = Temp.get();
746   }
747 
748   return E;
749 }
750 
751 /// Determine the degree of POD-ness for an expression.
752 /// Incomplete types are considered POD, since this check can be performed
753 /// when we're in an unevaluated context.
754 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
755   if (Ty->isIncompleteType()) {
756     // C++11 [expr.call]p7:
757     //   After these conversions, if the argument does not have arithmetic,
758     //   enumeration, pointer, pointer to member, or class type, the program
759     //   is ill-formed.
760     //
761     // Since we've already performed array-to-pointer and function-to-pointer
762     // decay, the only such type in C++ is cv void. This also handles
763     // initializer lists as variadic arguments.
764     if (Ty->isVoidType())
765       return VAK_Invalid;
766 
767     if (Ty->isObjCObjectType())
768       return VAK_Invalid;
769     return VAK_Valid;
770   }
771 
772   if (Ty.isCXX98PODType(Context))
773     return VAK_Valid;
774 
775   // C++11 [expr.call]p7:
776   //   Passing a potentially-evaluated argument of class type (Clause 9)
777   //   having a non-trivial copy constructor, a non-trivial move constructor,
778   //   or a non-trivial destructor, with no corresponding parameter,
779   //   is conditionally-supported with implementation-defined semantics.
780   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
781     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
782       if (!Record->hasNonTrivialCopyConstructor() &&
783           !Record->hasNonTrivialMoveConstructor() &&
784           !Record->hasNonTrivialDestructor())
785         return VAK_ValidInCXX11;
786 
787   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
788     return VAK_Valid;
789 
790   if (Ty->isObjCObjectType())
791     return VAK_Invalid;
792 
793   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
794   // permitted to reject them. We should consider doing so.
795   return VAK_Undefined;
796 }
797 
798 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
799   // Don't allow one to pass an Objective-C interface to a vararg.
800   const QualType &Ty = E->getType();
801   VarArgKind VAK = isValidVarArgType(Ty);
802 
803   // Complain about passing non-POD types through varargs.
804   switch (VAK) {
805   case VAK_ValidInCXX11:
806     DiagRuntimeBehavior(
807         E->getLocStart(), nullptr,
808         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
809           << Ty << CT);
810     // Fall through.
811   case VAK_Valid:
812     if (Ty->isRecordType()) {
813       // This is unlikely to be what the user intended. If the class has a
814       // 'c_str' member function, the user probably meant to call that.
815       DiagRuntimeBehavior(E->getLocStart(), nullptr,
816                           PDiag(diag::warn_pass_class_arg_to_vararg)
817                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
818     }
819     break;
820 
821   case VAK_Undefined:
822     DiagRuntimeBehavior(
823         E->getLocStart(), nullptr,
824         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
825           << getLangOpts().CPlusPlus11 << Ty << CT);
826     break;
827 
828   case VAK_Invalid:
829     if (Ty->isObjCObjectType())
830       DiagRuntimeBehavior(
831           E->getLocStart(), nullptr,
832           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
833             << Ty << CT);
834     else
835       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
836         << isa<InitListExpr>(E) << Ty << CT;
837     break;
838   }
839 }
840 
841 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
842 /// will create a trap if the resulting type is not a POD type.
843 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
844                                                   FunctionDecl *FDecl) {
845   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
846     // Strip the unbridged-cast placeholder expression off, if applicable.
847     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
848         (CT == VariadicMethod ||
849          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
850       E = stripARCUnbridgedCast(E);
851 
852     // Otherwise, do normal placeholder checking.
853     } else {
854       ExprResult ExprRes = CheckPlaceholderExpr(E);
855       if (ExprRes.isInvalid())
856         return ExprError();
857       E = ExprRes.get();
858     }
859   }
860 
861   ExprResult ExprRes = DefaultArgumentPromotion(E);
862   if (ExprRes.isInvalid())
863     return ExprError();
864   E = ExprRes.get();
865 
866   // Diagnostics regarding non-POD argument types are
867   // emitted along with format string checking in Sema::CheckFunctionCall().
868   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
869     // Turn this into a trap.
870     CXXScopeSpec SS;
871     SourceLocation TemplateKWLoc;
872     UnqualifiedId Name;
873     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
874                        E->getLocStart());
875     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
876                                           Name, true, false);
877     if (TrapFn.isInvalid())
878       return ExprError();
879 
880     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
881                                     E->getLocStart(), None,
882                                     E->getLocEnd());
883     if (Call.isInvalid())
884       return ExprError();
885 
886     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
887                                   Call.get(), E);
888     if (Comma.isInvalid())
889       return ExprError();
890     return Comma.get();
891   }
892 
893   if (!getLangOpts().CPlusPlus &&
894       RequireCompleteType(E->getExprLoc(), E->getType(),
895                           diag::err_call_incomplete_argument))
896     return ExprError();
897 
898   return E;
899 }
900 
901 /// \brief Converts an integer to complex float type.  Helper function of
902 /// UsualArithmeticConversions()
903 ///
904 /// \return false if the integer expression is an integer type and is
905 /// successfully converted to the complex type.
906 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
907                                                   ExprResult &ComplexExpr,
908                                                   QualType IntTy,
909                                                   QualType ComplexTy,
910                                                   bool SkipCast) {
911   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
912   if (SkipCast) return false;
913   if (IntTy->isIntegerType()) {
914     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
915     IntExpr = S.ImpCastExprToType(IntExpr.get(), fpTy, CK_IntegralToFloating);
916     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
917                                   CK_FloatingRealToComplex);
918   } else {
919     assert(IntTy->isComplexIntegerType());
920     IntExpr = S.ImpCastExprToType(IntExpr.get(), ComplexTy,
921                                   CK_IntegralComplexToFloatingComplex);
922   }
923   return false;
924 }
925 
926 /// \brief Takes two complex float types and converts them to the same type.
927 /// Helper function of UsualArithmeticConversions()
928 static QualType
929 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
930                                             ExprResult &RHS, QualType LHSType,
931                                             QualType RHSType,
932                                             bool IsCompAssign) {
933   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
934 
935   if (order < 0) {
936     // _Complex float -> _Complex double
937     if (!IsCompAssign)
938       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingComplexCast);
939     return RHSType;
940   }
941   if (order > 0)
942     // _Complex float -> _Complex double
943     RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingComplexCast);
944   return LHSType;
945 }
946 
947 /// \brief Converts otherExpr to complex float and promotes complexExpr if
948 /// necessary.  Helper function of UsualArithmeticConversions()
949 static QualType handleOtherComplexFloatConversion(Sema &S,
950                                                   ExprResult &ComplexExpr,
951                                                   ExprResult &OtherExpr,
952                                                   QualType ComplexTy,
953                                                   QualType OtherTy,
954                                                   bool ConvertComplexExpr,
955                                                   bool ConvertOtherExpr) {
956   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
957 
958   // If just the complexExpr is complex, the otherExpr needs to be converted,
959   // and the complexExpr might need to be promoted.
960   if (order > 0) { // complexExpr is wider
961     // float -> _Complex double
962     if (ConvertOtherExpr) {
963       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
964       OtherExpr = S.ImpCastExprToType(OtherExpr.get(), fp, CK_FloatingCast);
965       OtherExpr = S.ImpCastExprToType(OtherExpr.get(), ComplexTy,
966                                       CK_FloatingRealToComplex);
967     }
968     return ComplexTy;
969   }
970 
971   // otherTy is at least as wide.  Find its corresponding complex type.
972   QualType result = (order == 0 ? ComplexTy :
973                                   S.Context.getComplexType(OtherTy));
974 
975   // double -> _Complex double
976   if (ConvertOtherExpr)
977     OtherExpr = S.ImpCastExprToType(OtherExpr.get(), result,
978                                     CK_FloatingRealToComplex);
979 
980   // _Complex float -> _Complex double
981   if (ConvertComplexExpr && order < 0)
982     ComplexExpr = S.ImpCastExprToType(ComplexExpr.get(), result,
983                                       CK_FloatingComplexCast);
984 
985   return result;
986 }
987 
988 /// \brief Handle arithmetic conversion with complex types.  Helper function of
989 /// UsualArithmeticConversions()
990 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
991                                              ExprResult &RHS, QualType LHSType,
992                                              QualType RHSType,
993                                              bool IsCompAssign) {
994   // if we have an integer operand, the result is the complex type.
995   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
996                                              /*skipCast*/false))
997     return LHSType;
998   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
999                                              /*skipCast*/IsCompAssign))
1000     return RHSType;
1001 
1002   // This handles complex/complex, complex/float, or float/complex.
1003   // When both operands are complex, the shorter operand is converted to the
1004   // type of the longer, and that is the type of the result. This corresponds
1005   // to what is done when combining two real floating-point operands.
1006   // The fun begins when size promotion occur across type domains.
1007   // From H&S 6.3.4: When one operand is complex and the other is a real
1008   // floating-point type, the less precise type is converted, within it's
1009   // real or complex domain, to the precision of the other type. For example,
1010   // when combining a "long double" with a "double _Complex", the
1011   // "double _Complex" is promoted to "long double _Complex".
1012 
1013   bool LHSComplexFloat = LHSType->isComplexType();
1014   bool RHSComplexFloat = RHSType->isComplexType();
1015 
1016   // If both are complex, just cast to the more precise type.
1017   if (LHSComplexFloat && RHSComplexFloat)
1018     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1019                                                        LHSType, RHSType,
1020                                                        IsCompAssign);
1021 
1022   // If only one operand is complex, promote it if necessary and convert the
1023   // other operand to complex.
1024   if (LHSComplexFloat)
1025     return handleOtherComplexFloatConversion(
1026         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1027         /*convertOtherExpr*/ true);
1028 
1029   assert(RHSComplexFloat);
1030   return handleOtherComplexFloatConversion(
1031       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1032       /*convertOtherExpr*/ !IsCompAssign);
1033 }
1034 
1035 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1036 /// of UsualArithmeticConversions()
1037 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1038                                            ExprResult &IntExpr,
1039                                            QualType FloatTy, QualType IntTy,
1040                                            bool ConvertFloat, bool ConvertInt) {
1041   if (IntTy->isIntegerType()) {
1042     if (ConvertInt)
1043       // Convert intExpr to the lhs floating point type.
1044       IntExpr = S.ImpCastExprToType(IntExpr.get(), FloatTy,
1045                                     CK_IntegralToFloating);
1046     return FloatTy;
1047   }
1048 
1049   // Convert both sides to the appropriate complex float.
1050   assert(IntTy->isComplexIntegerType());
1051   QualType result = S.Context.getComplexType(FloatTy);
1052 
1053   // _Complex int -> _Complex float
1054   if (ConvertInt)
1055     IntExpr = S.ImpCastExprToType(IntExpr.get(), result,
1056                                   CK_IntegralComplexToFloatingComplex);
1057 
1058   // float -> _Complex float
1059   if (ConvertFloat)
1060     FloatExpr = S.ImpCastExprToType(FloatExpr.get(), result,
1061                                     CK_FloatingRealToComplex);
1062 
1063   return result;
1064 }
1065 
1066 /// \brief Handle arithmethic conversion with floating point types.  Helper
1067 /// function of UsualArithmeticConversions()
1068 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1069                                       ExprResult &RHS, QualType LHSType,
1070                                       QualType RHSType, bool IsCompAssign) {
1071   bool LHSFloat = LHSType->isRealFloatingType();
1072   bool RHSFloat = RHSType->isRealFloatingType();
1073 
1074   // If we have two real floating types, convert the smaller operand
1075   // to the bigger result.
1076   if (LHSFloat && RHSFloat) {
1077     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1078     if (order > 0) {
1079       RHS = S.ImpCastExprToType(RHS.get(), LHSType, CK_FloatingCast);
1080       return LHSType;
1081     }
1082 
1083     assert(order < 0 && "illegal float comparison");
1084     if (!IsCompAssign)
1085       LHS = S.ImpCastExprToType(LHS.get(), RHSType, CK_FloatingCast);
1086     return RHSType;
1087   }
1088 
1089   if (LHSFloat)
1090     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1091                                       /*convertFloat=*/!IsCompAssign,
1092                                       /*convertInt=*/ true);
1093   assert(RHSFloat);
1094   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1095                                     /*convertInt=*/ true,
1096                                     /*convertFloat=*/!IsCompAssign);
1097 }
1098 
1099 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1100 
1101 namespace {
1102 /// These helper callbacks are placed in an anonymous namespace to
1103 /// permit their use as function template parameters.
1104 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1105   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1106 }
1107 
1108 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1109   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1110                              CK_IntegralComplexCast);
1111 }
1112 }
1113 
1114 /// \brief Handle integer arithmetic conversions.  Helper function of
1115 /// UsualArithmeticConversions()
1116 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1117 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1118                                         ExprResult &RHS, QualType LHSType,
1119                                         QualType RHSType, bool IsCompAssign) {
1120   // The rules for this case are in C99 6.3.1.8
1121   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1122   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1123   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1124   if (LHSSigned == RHSSigned) {
1125     // Same signedness; use the higher-ranked type
1126     if (order >= 0) {
1127       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1128       return LHSType;
1129     } else if (!IsCompAssign)
1130       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1131     return RHSType;
1132   } else if (order != (LHSSigned ? 1 : -1)) {
1133     // The unsigned type has greater than or equal rank to the
1134     // signed type, so use the unsigned type
1135     if (RHSSigned) {
1136       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1137       return LHSType;
1138     } else if (!IsCompAssign)
1139       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1140     return RHSType;
1141   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1142     // The two types are different widths; if we are here, that
1143     // means the signed type is larger than the unsigned type, so
1144     // use the signed type.
1145     if (LHSSigned) {
1146       RHS = (*doRHSCast)(S, RHS.get(), LHSType);
1147       return LHSType;
1148     } else if (!IsCompAssign)
1149       LHS = (*doLHSCast)(S, LHS.get(), RHSType);
1150     return RHSType;
1151   } else {
1152     // The signed type is higher-ranked than the unsigned type,
1153     // but isn't actually any bigger (like unsigned int and long
1154     // on most 32-bit systems).  Use the unsigned type corresponding
1155     // to the signed type.
1156     QualType result =
1157       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1158     RHS = (*doRHSCast)(S, RHS.get(), result);
1159     if (!IsCompAssign)
1160       LHS = (*doLHSCast)(S, LHS.get(), result);
1161     return result;
1162   }
1163 }
1164 
1165 /// \brief Handle conversions with GCC complex int extension.  Helper function
1166 /// of UsualArithmeticConversions()
1167 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1168                                            ExprResult &RHS, QualType LHSType,
1169                                            QualType RHSType,
1170                                            bool IsCompAssign) {
1171   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1172   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1173 
1174   if (LHSComplexInt && RHSComplexInt) {
1175     QualType LHSEltType = LHSComplexInt->getElementType();
1176     QualType RHSEltType = RHSComplexInt->getElementType();
1177     QualType ScalarType =
1178       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1179         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1180 
1181     return S.Context.getComplexType(ScalarType);
1182   }
1183 
1184   if (LHSComplexInt) {
1185     QualType LHSEltType = LHSComplexInt->getElementType();
1186     QualType ScalarType =
1187       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1188         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1189     QualType ComplexType = S.Context.getComplexType(ScalarType);
1190     RHS = S.ImpCastExprToType(RHS.get(), ComplexType,
1191                               CK_IntegralRealToComplex);
1192 
1193     return ComplexType;
1194   }
1195 
1196   assert(RHSComplexInt);
1197 
1198   QualType RHSEltType = RHSComplexInt->getElementType();
1199   QualType ScalarType =
1200     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1201       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1202   QualType ComplexType = S.Context.getComplexType(ScalarType);
1203 
1204   if (!IsCompAssign)
1205     LHS = S.ImpCastExprToType(LHS.get(), ComplexType,
1206                               CK_IntegralRealToComplex);
1207   return ComplexType;
1208 }
1209 
1210 /// UsualArithmeticConversions - Performs various conversions that are common to
1211 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1212 /// routine returns the first non-arithmetic type found. The client is
1213 /// responsible for emitting appropriate error diagnostics.
1214 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1215                                           bool IsCompAssign) {
1216   if (!IsCompAssign) {
1217     LHS = UsualUnaryConversions(LHS.get());
1218     if (LHS.isInvalid())
1219       return QualType();
1220   }
1221 
1222   RHS = UsualUnaryConversions(RHS.get());
1223   if (RHS.isInvalid())
1224     return QualType();
1225 
1226   // For conversion purposes, we ignore any qualifiers.
1227   // For example, "const float" and "float" are equivalent.
1228   QualType LHSType =
1229     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1230   QualType RHSType =
1231     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1232 
1233   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1234   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1235     LHSType = AtomicLHS->getValueType();
1236 
1237   // If both types are identical, no conversion is needed.
1238   if (LHSType == RHSType)
1239     return LHSType;
1240 
1241   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1242   // The caller can deal with this (e.g. pointer + int).
1243   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1244     return QualType();
1245 
1246   // Apply unary and bitfield promotions to the LHS's type.
1247   QualType LHSUnpromotedType = LHSType;
1248   if (LHSType->isPromotableIntegerType())
1249     LHSType = Context.getPromotedIntegerType(LHSType);
1250   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1251   if (!LHSBitfieldPromoteTy.isNull())
1252     LHSType = LHSBitfieldPromoteTy;
1253   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1254     LHS = ImpCastExprToType(LHS.get(), LHSType, CK_IntegralCast);
1255 
1256   // If both types are identical, no conversion is needed.
1257   if (LHSType == RHSType)
1258     return LHSType;
1259 
1260   // At this point, we have two different arithmetic types.
1261 
1262   // Handle complex types first (C99 6.3.1.8p1).
1263   if (LHSType->isComplexType() || RHSType->isComplexType())
1264     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1265                                         IsCompAssign);
1266 
1267   // Now handle "real" floating types (i.e. float, double, long double).
1268   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1269     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1270                                  IsCompAssign);
1271 
1272   // Handle GCC complex int extension.
1273   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1274     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1275                                       IsCompAssign);
1276 
1277   // Finally, we have two differing integer types.
1278   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1279            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1280 }
1281 
1282 
1283 //===----------------------------------------------------------------------===//
1284 //  Semantic Analysis for various Expression Types
1285 //===----------------------------------------------------------------------===//
1286 
1287 
1288 ExprResult
1289 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1290                                 SourceLocation DefaultLoc,
1291                                 SourceLocation RParenLoc,
1292                                 Expr *ControllingExpr,
1293                                 ArrayRef<ParsedType> ArgTypes,
1294                                 ArrayRef<Expr *> ArgExprs) {
1295   unsigned NumAssocs = ArgTypes.size();
1296   assert(NumAssocs == ArgExprs.size());
1297 
1298   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1299   for (unsigned i = 0; i < NumAssocs; ++i) {
1300     if (ArgTypes[i])
1301       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1302     else
1303       Types[i] = nullptr;
1304   }
1305 
1306   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1307                                              ControllingExpr,
1308                                              llvm::makeArrayRef(Types, NumAssocs),
1309                                              ArgExprs);
1310   delete [] Types;
1311   return ER;
1312 }
1313 
1314 ExprResult
1315 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1316                                  SourceLocation DefaultLoc,
1317                                  SourceLocation RParenLoc,
1318                                  Expr *ControllingExpr,
1319                                  ArrayRef<TypeSourceInfo *> Types,
1320                                  ArrayRef<Expr *> Exprs) {
1321   unsigned NumAssocs = Types.size();
1322   assert(NumAssocs == Exprs.size());
1323   if (ControllingExpr->getType()->isPlaceholderType()) {
1324     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1325     if (result.isInvalid()) return ExprError();
1326     ControllingExpr = result.get();
1327   }
1328 
1329   bool TypeErrorFound = false,
1330        IsResultDependent = ControllingExpr->isTypeDependent(),
1331        ContainsUnexpandedParameterPack
1332          = ControllingExpr->containsUnexpandedParameterPack();
1333 
1334   for (unsigned i = 0; i < NumAssocs; ++i) {
1335     if (Exprs[i]->containsUnexpandedParameterPack())
1336       ContainsUnexpandedParameterPack = true;
1337 
1338     if (Types[i]) {
1339       if (Types[i]->getType()->containsUnexpandedParameterPack())
1340         ContainsUnexpandedParameterPack = true;
1341 
1342       if (Types[i]->getType()->isDependentType()) {
1343         IsResultDependent = true;
1344       } else {
1345         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1346         // complete object type other than a variably modified type."
1347         unsigned D = 0;
1348         if (Types[i]->getType()->isIncompleteType())
1349           D = diag::err_assoc_type_incomplete;
1350         else if (!Types[i]->getType()->isObjectType())
1351           D = diag::err_assoc_type_nonobject;
1352         else if (Types[i]->getType()->isVariablyModifiedType())
1353           D = diag::err_assoc_type_variably_modified;
1354 
1355         if (D != 0) {
1356           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1357             << Types[i]->getTypeLoc().getSourceRange()
1358             << Types[i]->getType();
1359           TypeErrorFound = true;
1360         }
1361 
1362         // C11 6.5.1.1p2 "No two generic associations in the same generic
1363         // selection shall specify compatible types."
1364         for (unsigned j = i+1; j < NumAssocs; ++j)
1365           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1366               Context.typesAreCompatible(Types[i]->getType(),
1367                                          Types[j]->getType())) {
1368             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1369                  diag::err_assoc_compatible_types)
1370               << Types[j]->getTypeLoc().getSourceRange()
1371               << Types[j]->getType()
1372               << Types[i]->getType();
1373             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1374                  diag::note_compat_assoc)
1375               << Types[i]->getTypeLoc().getSourceRange()
1376               << Types[i]->getType();
1377             TypeErrorFound = true;
1378           }
1379       }
1380     }
1381   }
1382   if (TypeErrorFound)
1383     return ExprError();
1384 
1385   // If we determined that the generic selection is result-dependent, don't
1386   // try to compute the result expression.
1387   if (IsResultDependent)
1388     return new (Context) GenericSelectionExpr(
1389         Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1390         ContainsUnexpandedParameterPack);
1391 
1392   SmallVector<unsigned, 1> CompatIndices;
1393   unsigned DefaultIndex = -1U;
1394   for (unsigned i = 0; i < NumAssocs; ++i) {
1395     if (!Types[i])
1396       DefaultIndex = i;
1397     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1398                                         Types[i]->getType()))
1399       CompatIndices.push_back(i);
1400   }
1401 
1402   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1403   // type compatible with at most one of the types named in its generic
1404   // association list."
1405   if (CompatIndices.size() > 1) {
1406     // We strip parens here because the controlling expression is typically
1407     // parenthesized in macro definitions.
1408     ControllingExpr = ControllingExpr->IgnoreParens();
1409     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1410       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1411       << (unsigned) CompatIndices.size();
1412     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1413          E = CompatIndices.end(); I != E; ++I) {
1414       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1415            diag::note_compat_assoc)
1416         << Types[*I]->getTypeLoc().getSourceRange()
1417         << Types[*I]->getType();
1418     }
1419     return ExprError();
1420   }
1421 
1422   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1423   // its controlling expression shall have type compatible with exactly one of
1424   // the types named in its generic association list."
1425   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1426     // We strip parens here because the controlling expression is typically
1427     // parenthesized in macro definitions.
1428     ControllingExpr = ControllingExpr->IgnoreParens();
1429     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1430       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1431     return ExprError();
1432   }
1433 
1434   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1435   // type name that is compatible with the type of the controlling expression,
1436   // then the result expression of the generic selection is the expression
1437   // in that generic association. Otherwise, the result expression of the
1438   // generic selection is the expression in the default generic association."
1439   unsigned ResultIndex =
1440     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1441 
1442   return new (Context) GenericSelectionExpr(
1443       Context, KeyLoc, ControllingExpr, Types, Exprs, DefaultLoc, RParenLoc,
1444       ContainsUnexpandedParameterPack, ResultIndex);
1445 }
1446 
1447 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1448 /// location of the token and the offset of the ud-suffix within it.
1449 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1450                                      unsigned Offset) {
1451   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1452                                         S.getLangOpts());
1453 }
1454 
1455 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1456 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1457 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1458                                                  IdentifierInfo *UDSuffix,
1459                                                  SourceLocation UDSuffixLoc,
1460                                                  ArrayRef<Expr*> Args,
1461                                                  SourceLocation LitEndLoc) {
1462   assert(Args.size() <= 2 && "too many arguments for literal operator");
1463 
1464   QualType ArgTy[2];
1465   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1466     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1467     if (ArgTy[ArgIdx]->isArrayType())
1468       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1469   }
1470 
1471   DeclarationName OpName =
1472     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1473   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1474   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1475 
1476   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1477   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1478                               /*AllowRaw*/false, /*AllowTemplate*/false,
1479                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1480     return ExprError();
1481 
1482   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1483 }
1484 
1485 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1486 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1487 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1488 /// multiple tokens.  However, the common case is that StringToks points to one
1489 /// string.
1490 ///
1491 ExprResult
1492 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1493                          Scope *UDLScope) {
1494   assert(NumStringToks && "Must have at least one string!");
1495 
1496   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1497   if (Literal.hadError)
1498     return ExprError();
1499 
1500   SmallVector<SourceLocation, 4> StringTokLocs;
1501   for (unsigned i = 0; i != NumStringToks; ++i)
1502     StringTokLocs.push_back(StringToks[i].getLocation());
1503 
1504   QualType CharTy = Context.CharTy;
1505   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1506   if (Literal.isWide()) {
1507     CharTy = Context.getWideCharType();
1508     Kind = StringLiteral::Wide;
1509   } else if (Literal.isUTF8()) {
1510     Kind = StringLiteral::UTF8;
1511   } else if (Literal.isUTF16()) {
1512     CharTy = Context.Char16Ty;
1513     Kind = StringLiteral::UTF16;
1514   } else if (Literal.isUTF32()) {
1515     CharTy = Context.Char32Ty;
1516     Kind = StringLiteral::UTF32;
1517   } else if (Literal.isPascal()) {
1518     CharTy = Context.UnsignedCharTy;
1519   }
1520 
1521   QualType CharTyConst = CharTy;
1522   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1523   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1524     CharTyConst.addConst();
1525 
1526   // Get an array type for the string, according to C99 6.4.5.  This includes
1527   // the nul terminator character as well as the string length for pascal
1528   // strings.
1529   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1530                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1531                                  ArrayType::Normal, 0);
1532 
1533   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1534   if (getLangOpts().OpenCL) {
1535     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1536   }
1537 
1538   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1539   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1540                                              Kind, Literal.Pascal, StrTy,
1541                                              &StringTokLocs[0],
1542                                              StringTokLocs.size());
1543   if (Literal.getUDSuffix().empty())
1544     return Lit;
1545 
1546   // We're building a user-defined literal.
1547   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1548   SourceLocation UDSuffixLoc =
1549     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1550                    Literal.getUDSuffixOffset());
1551 
1552   // Make sure we're allowed user-defined literals here.
1553   if (!UDLScope)
1554     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1555 
1556   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1557   //   operator "" X (str, len)
1558   QualType SizeType = Context.getSizeType();
1559 
1560   DeclarationName OpName =
1561     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1562   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1563   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1564 
1565   QualType ArgTy[] = {
1566     Context.getArrayDecayedType(StrTy), SizeType
1567   };
1568 
1569   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1570   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1571                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1572                                 /*AllowStringTemplate*/true)) {
1573 
1574   case LOLR_Cooked: {
1575     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1576     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1577                                                     StringTokLocs[0]);
1578     Expr *Args[] = { Lit, LenArg };
1579 
1580     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1581   }
1582 
1583   case LOLR_StringTemplate: {
1584     TemplateArgumentListInfo ExplicitArgs;
1585 
1586     unsigned CharBits = Context.getIntWidth(CharTy);
1587     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1588     llvm::APSInt Value(CharBits, CharIsUnsigned);
1589 
1590     TemplateArgument TypeArg(CharTy);
1591     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1592     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1593 
1594     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1595       Value = Lit->getCodeUnit(I);
1596       TemplateArgument Arg(Context, Value, CharTy);
1597       TemplateArgumentLocInfo ArgInfo;
1598       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1599     }
1600     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1601                                     &ExplicitArgs);
1602   }
1603   case LOLR_Raw:
1604   case LOLR_Template:
1605     llvm_unreachable("unexpected literal operator lookup result");
1606   case LOLR_Error:
1607     return ExprError();
1608   }
1609   llvm_unreachable("unexpected literal operator lookup result");
1610 }
1611 
1612 ExprResult
1613 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1614                        SourceLocation Loc,
1615                        const CXXScopeSpec *SS) {
1616   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1617   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1618 }
1619 
1620 /// BuildDeclRefExpr - Build an expression that references a
1621 /// declaration that does not require a closure capture.
1622 ExprResult
1623 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1624                        const DeclarationNameInfo &NameInfo,
1625                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1626                        const TemplateArgumentListInfo *TemplateArgs) {
1627   if (getLangOpts().CUDA)
1628     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1629       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1630         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1631                            CalleeTarget = IdentifyCUDATarget(Callee);
1632         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1633           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1634             << CalleeTarget << D->getIdentifier() << CallerTarget;
1635           Diag(D->getLocation(), diag::note_previous_decl)
1636             << D->getIdentifier();
1637           return ExprError();
1638         }
1639       }
1640 
1641   bool refersToEnclosingScope =
1642     (CurContext != D->getDeclContext() &&
1643      D->getDeclContext()->isFunctionOrMethod()) ||
1644     (isa<VarDecl>(D) &&
1645      cast<VarDecl>(D)->isInitCapture());
1646 
1647   DeclRefExpr *E;
1648   if (isa<VarTemplateSpecializationDecl>(D)) {
1649     VarTemplateSpecializationDecl *VarSpec =
1650         cast<VarTemplateSpecializationDecl>(D);
1651 
1652     E = DeclRefExpr::Create(
1653         Context,
1654         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1655         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1656         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1657   } else {
1658     assert(!TemplateArgs && "No template arguments for non-variable"
1659                             " template specialization references");
1660     E = DeclRefExpr::Create(
1661         Context,
1662         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1663         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1664   }
1665 
1666   MarkDeclRefReferenced(E);
1667 
1668   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1669       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1670     DiagnosticsEngine::Level Level =
1671       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1672                                E->getLocStart());
1673     if (Level != DiagnosticsEngine::Ignored)
1674       recordUseOfEvaluatedWeak(E);
1675   }
1676 
1677   // Just in case we're building an illegal pointer-to-member.
1678   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1679   if (FD && FD->isBitField())
1680     E->setObjectKind(OK_BitField);
1681 
1682   return E;
1683 }
1684 
1685 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1686 /// possibly a list of template arguments.
1687 ///
1688 /// If this produces template arguments, it is permitted to call
1689 /// DecomposeTemplateName.
1690 ///
1691 /// This actually loses a lot of source location information for
1692 /// non-standard name kinds; we should consider preserving that in
1693 /// some way.
1694 void
1695 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1696                              TemplateArgumentListInfo &Buffer,
1697                              DeclarationNameInfo &NameInfo,
1698                              const TemplateArgumentListInfo *&TemplateArgs) {
1699   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1700     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1701     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1702 
1703     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1704                                        Id.TemplateId->NumArgs);
1705     translateTemplateArguments(TemplateArgsPtr, Buffer);
1706 
1707     TemplateName TName = Id.TemplateId->Template.get();
1708     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1709     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1710     TemplateArgs = &Buffer;
1711   } else {
1712     NameInfo = GetNameFromUnqualifiedId(Id);
1713     TemplateArgs = nullptr;
1714   }
1715 }
1716 
1717 /// Diagnose an empty lookup.
1718 ///
1719 /// \return false if new lookup candidates were found
1720 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1721                                CorrectionCandidateCallback &CCC,
1722                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1723                                ArrayRef<Expr *> Args) {
1724   DeclarationName Name = R.getLookupName();
1725 
1726   unsigned diagnostic = diag::err_undeclared_var_use;
1727   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1728   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1729       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1730       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1731     diagnostic = diag::err_undeclared_use;
1732     diagnostic_suggest = diag::err_undeclared_use_suggest;
1733   }
1734 
1735   // If the original lookup was an unqualified lookup, fake an
1736   // unqualified lookup.  This is useful when (for example) the
1737   // original lookup would not have found something because it was a
1738   // dependent name.
1739   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1740     ? CurContext : nullptr;
1741   while (DC) {
1742     if (isa<CXXRecordDecl>(DC)) {
1743       LookupQualifiedName(R, DC);
1744 
1745       if (!R.empty()) {
1746         // Don't give errors about ambiguities in this lookup.
1747         R.suppressDiagnostics();
1748 
1749         // During a default argument instantiation the CurContext points
1750         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1751         // function parameter list, hence add an explicit check.
1752         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1753                               ActiveTemplateInstantiations.back().Kind ==
1754             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1755         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1756         bool isInstance = CurMethod &&
1757                           CurMethod->isInstance() &&
1758                           DC == CurMethod->getParent() && !isDefaultArgument;
1759 
1760 
1761         // Give a code modification hint to insert 'this->'.
1762         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1763         // Actually quite difficult!
1764         if (getLangOpts().MSVCCompat)
1765           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1766         if (isInstance) {
1767           Diag(R.getNameLoc(), diagnostic) << Name
1768             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1769           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1770               CallsUndergoingInstantiation.back()->getCallee());
1771 
1772           CXXMethodDecl *DepMethod;
1773           if (CurMethod->isDependentContext())
1774             DepMethod = CurMethod;
1775           else if (CurMethod->getTemplatedKind() ==
1776               FunctionDecl::TK_FunctionTemplateSpecialization)
1777             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1778                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1779           else
1780             DepMethod = cast<CXXMethodDecl>(
1781                 CurMethod->getInstantiatedFromMemberFunction());
1782           assert(DepMethod && "No template pattern found");
1783 
1784           QualType DepThisType = DepMethod->getThisType(Context);
1785           CheckCXXThisCapture(R.getNameLoc());
1786           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1787                                      R.getNameLoc(), DepThisType, false);
1788           TemplateArgumentListInfo TList;
1789           if (ULE->hasExplicitTemplateArgs())
1790             ULE->copyTemplateArgumentsInto(TList);
1791 
1792           CXXScopeSpec SS;
1793           SS.Adopt(ULE->getQualifierLoc());
1794           CXXDependentScopeMemberExpr *DepExpr =
1795               CXXDependentScopeMemberExpr::Create(
1796                   Context, DepThis, DepThisType, true, SourceLocation(),
1797                   SS.getWithLocInContext(Context),
1798                   ULE->getTemplateKeywordLoc(), nullptr,
1799                   R.getLookupNameInfo(),
1800                   ULE->hasExplicitTemplateArgs() ? &TList : nullptr);
1801           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1802         } else {
1803           Diag(R.getNameLoc(), diagnostic) << Name;
1804         }
1805 
1806         // Do we really want to note all of these?
1807         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1808           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1809 
1810         // Return true if we are inside a default argument instantiation
1811         // and the found name refers to an instance member function, otherwise
1812         // the function calling DiagnoseEmptyLookup will try to create an
1813         // implicit member call and this is wrong for default argument.
1814         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1815           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1816           return true;
1817         }
1818 
1819         // Tell the callee to try to recover.
1820         return false;
1821       }
1822 
1823       R.clear();
1824     }
1825 
1826     // In Microsoft mode, if we are performing lookup from within a friend
1827     // function definition declared at class scope then we must set
1828     // DC to the lexical parent to be able to search into the parent
1829     // class.
1830     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1831         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1832         DC->getLexicalParent()->isRecord())
1833       DC = DC->getLexicalParent();
1834     else
1835       DC = DC->getParent();
1836   }
1837 
1838   // We didn't find anything, so try to correct for a typo.
1839   TypoCorrection Corrected;
1840   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1841                                     S, &SS, CCC, CTK_ErrorRecovery))) {
1842     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1843     bool DroppedSpecifier =
1844         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1845     R.setLookupName(Corrected.getCorrection());
1846 
1847     bool AcceptableWithRecovery = false;
1848     bool AcceptableWithoutRecovery = false;
1849     NamedDecl *ND = Corrected.getCorrectionDecl();
1850     if (ND) {
1851       if (Corrected.isOverloaded()) {
1852         OverloadCandidateSet OCS(R.getNameLoc(),
1853                                  OverloadCandidateSet::CSK_Normal);
1854         OverloadCandidateSet::iterator Best;
1855         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1856                                         CDEnd = Corrected.end();
1857              CD != CDEnd; ++CD) {
1858           if (FunctionTemplateDecl *FTD =
1859                    dyn_cast<FunctionTemplateDecl>(*CD))
1860             AddTemplateOverloadCandidate(
1861                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1862                 Args, OCS);
1863           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1864             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1865               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1866                                    Args, OCS);
1867         }
1868         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1869         case OR_Success:
1870           ND = Best->Function;
1871           Corrected.setCorrectionDecl(ND);
1872           break;
1873         default:
1874           // FIXME: Arbitrarily pick the first declaration for the note.
1875           Corrected.setCorrectionDecl(ND);
1876           break;
1877         }
1878       }
1879       R.addDecl(ND);
1880 
1881       AcceptableWithRecovery =
1882           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1883       // FIXME: If we ended up with a typo for a type name or
1884       // Objective-C class name, we're in trouble because the parser
1885       // is in the wrong place to recover. Suggest the typo
1886       // correction, but don't make it a fix-it since we're not going
1887       // to recover well anyway.
1888       AcceptableWithoutRecovery =
1889           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1890     } else {
1891       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1892       // because we aren't able to recover.
1893       AcceptableWithoutRecovery = true;
1894     }
1895 
1896     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1897       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1898                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1899                             ? diag::note_implicit_param_decl
1900                             : diag::note_previous_decl;
1901       if (SS.isEmpty())
1902         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1903                      PDiag(NoteID), AcceptableWithRecovery);
1904       else
1905         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1906                                   << Name << computeDeclContext(SS, false)
1907                                   << DroppedSpecifier << SS.getRange(),
1908                      PDiag(NoteID), AcceptableWithRecovery);
1909 
1910       // Tell the callee whether to try to recover.
1911       return !AcceptableWithRecovery;
1912     }
1913   }
1914   R.clear();
1915 
1916   // Emit a special diagnostic for failed member lookups.
1917   // FIXME: computing the declaration context might fail here (?)
1918   if (!SS.isEmpty()) {
1919     Diag(R.getNameLoc(), diag::err_no_member)
1920       << Name << computeDeclContext(SS, false)
1921       << SS.getRange();
1922     return true;
1923   }
1924 
1925   // Give up, we can't recover.
1926   Diag(R.getNameLoc(), diagnostic) << Name;
1927   return true;
1928 }
1929 
1930 ExprResult Sema::ActOnIdExpression(Scope *S,
1931                                    CXXScopeSpec &SS,
1932                                    SourceLocation TemplateKWLoc,
1933                                    UnqualifiedId &Id,
1934                                    bool HasTrailingLParen,
1935                                    bool IsAddressOfOperand,
1936                                    CorrectionCandidateCallback *CCC,
1937                                    bool IsInlineAsmIdentifier) {
1938   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1939          "cannot be direct & operand and have a trailing lparen");
1940   if (SS.isInvalid())
1941     return ExprError();
1942 
1943   TemplateArgumentListInfo TemplateArgsBuffer;
1944 
1945   // Decompose the UnqualifiedId into the following data.
1946   DeclarationNameInfo NameInfo;
1947   const TemplateArgumentListInfo *TemplateArgs;
1948   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1949 
1950   DeclarationName Name = NameInfo.getName();
1951   IdentifierInfo *II = Name.getAsIdentifierInfo();
1952   SourceLocation NameLoc = NameInfo.getLoc();
1953 
1954   // C++ [temp.dep.expr]p3:
1955   //   An id-expression is type-dependent if it contains:
1956   //     -- an identifier that was declared with a dependent type,
1957   //        (note: handled after lookup)
1958   //     -- a template-id that is dependent,
1959   //        (note: handled in BuildTemplateIdExpr)
1960   //     -- a conversion-function-id that specifies a dependent type,
1961   //     -- a nested-name-specifier that contains a class-name that
1962   //        names a dependent type.
1963   // Determine whether this is a member of an unknown specialization;
1964   // we need to handle these differently.
1965   bool DependentID = false;
1966   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1967       Name.getCXXNameType()->isDependentType()) {
1968     DependentID = true;
1969   } else if (SS.isSet()) {
1970     if (DeclContext *DC = computeDeclContext(SS, false)) {
1971       if (RequireCompleteDeclContext(SS, DC))
1972         return ExprError();
1973     } else {
1974       DependentID = true;
1975     }
1976   }
1977 
1978   if (DependentID)
1979     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1980                                       IsAddressOfOperand, TemplateArgs);
1981 
1982   // Perform the required lookup.
1983   LookupResult R(*this, NameInfo,
1984                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1985                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1986   if (TemplateArgs) {
1987     // Lookup the template name again to correctly establish the context in
1988     // which it was found. This is really unfortunate as we already did the
1989     // lookup to determine that it was a template name in the first place. If
1990     // this becomes a performance hit, we can work harder to preserve those
1991     // results until we get here but it's likely not worth it.
1992     bool MemberOfUnknownSpecialization;
1993     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1994                        MemberOfUnknownSpecialization);
1995 
1996     if (MemberOfUnknownSpecialization ||
1997         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1998       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1999                                         IsAddressOfOperand, TemplateArgs);
2000   } else {
2001     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2002     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2003 
2004     // If the result might be in a dependent base class, this is a dependent
2005     // id-expression.
2006     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2007       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2008                                         IsAddressOfOperand, TemplateArgs);
2009 
2010     // If this reference is in an Objective-C method, then we need to do
2011     // some special Objective-C lookup, too.
2012     if (IvarLookupFollowUp) {
2013       ExprResult E(LookupInObjCMethod(R, S, II, true));
2014       if (E.isInvalid())
2015         return ExprError();
2016 
2017       if (Expr *Ex = E.getAs<Expr>())
2018         return Ex;
2019     }
2020   }
2021 
2022   if (R.isAmbiguous())
2023     return ExprError();
2024 
2025   // Determine whether this name might be a candidate for
2026   // argument-dependent lookup.
2027   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2028 
2029   if (R.empty() && !ADL) {
2030 
2031     // Otherwise, this could be an implicitly declared function reference (legal
2032     // in C90, extension in C99, forbidden in C++).
2033     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2034       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2035       if (D) R.addDecl(D);
2036     }
2037 
2038     // If this name wasn't predeclared and if this is not a function
2039     // call, diagnose the problem.
2040     if (R.empty()) {
2041       // In Microsoft mode, if we are inside a template class member function
2042       // whose parent class has dependent base classes, and we can't resolve
2043       // an unqualified identifier, then assume the identifier is a member of a
2044       // dependent base class.  The goal is to postpone name lookup to
2045       // instantiation time to be able to search into the type dependent base
2046       // classes.
2047       // FIXME: If we want 100% compatibility with MSVC, we will have delay all
2048       // unqualified name lookup.  Any name lookup during template parsing means
2049       // clang might find something that MSVC doesn't.  For now, we only handle
2050       // the common case of members of a dependent base class.
2051       if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2052         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2053         if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) {
2054           QualType ThisType = MD->getThisType(Context);
2055           // Since the 'this' expression is synthesized, we don't need to
2056           // perform the double-lookup check.
2057           NamedDecl *FirstQualifierInScope = nullptr;
2058           return CXXDependentScopeMemberExpr::Create(
2059               Context, /*This=*/nullptr, ThisType, /*IsArrow=*/true,
2060               /*Op=*/SourceLocation(), SS.getWithLocInContext(Context),
2061               TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs);
2062         }
2063       }
2064 
2065       // Don't diagnose an empty lookup for inline assmebly.
2066       if (IsInlineAsmIdentifier)
2067         return ExprError();
2068 
2069       CorrectionCandidateCallback DefaultValidator;
2070       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2071         return ExprError();
2072 
2073       assert(!R.empty() &&
2074              "DiagnoseEmptyLookup returned false but added no results");
2075 
2076       // If we found an Objective-C instance variable, let
2077       // LookupInObjCMethod build the appropriate expression to
2078       // reference the ivar.
2079       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2080         R.clear();
2081         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2082         // In a hopelessly buggy code, Objective-C instance variable
2083         // lookup fails and no expression will be built to reference it.
2084         if (!E.isInvalid() && !E.get())
2085           return ExprError();
2086         return E;
2087       }
2088     }
2089   }
2090 
2091   // This is guaranteed from this point on.
2092   assert(!R.empty() || ADL);
2093 
2094   // Check whether this might be a C++ implicit instance member access.
2095   // C++ [class.mfct.non-static]p3:
2096   //   When an id-expression that is not part of a class member access
2097   //   syntax and not used to form a pointer to member is used in the
2098   //   body of a non-static member function of class X, if name lookup
2099   //   resolves the name in the id-expression to a non-static non-type
2100   //   member of some class C, the id-expression is transformed into a
2101   //   class member access expression using (*this) as the
2102   //   postfix-expression to the left of the . operator.
2103   //
2104   // But we don't actually need to do this for '&' operands if R
2105   // resolved to a function or overloaded function set, because the
2106   // expression is ill-formed if it actually works out to be a
2107   // non-static member function:
2108   //
2109   // C++ [expr.ref]p4:
2110   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2111   //   [t]he expression can be used only as the left-hand operand of a
2112   //   member function call.
2113   //
2114   // There are other safeguards against such uses, but it's important
2115   // to get this right here so that we don't end up making a
2116   // spuriously dependent expression if we're inside a dependent
2117   // instance method.
2118   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2119     bool MightBeImplicitMember;
2120     if (!IsAddressOfOperand)
2121       MightBeImplicitMember = true;
2122     else if (!SS.isEmpty())
2123       MightBeImplicitMember = false;
2124     else if (R.isOverloadedResult())
2125       MightBeImplicitMember = false;
2126     else if (R.isUnresolvableResult())
2127       MightBeImplicitMember = true;
2128     else
2129       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2130                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2131                               isa<MSPropertyDecl>(R.getFoundDecl());
2132 
2133     if (MightBeImplicitMember)
2134       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2135                                              R, TemplateArgs);
2136   }
2137 
2138   if (TemplateArgs || TemplateKWLoc.isValid()) {
2139 
2140     // In C++1y, if this is a variable template id, then check it
2141     // in BuildTemplateIdExpr().
2142     // The single lookup result must be a variable template declaration.
2143     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2144         Id.TemplateId->Kind == TNK_Var_template) {
2145       assert(R.getAsSingle<VarTemplateDecl>() &&
2146              "There should only be one declaration found.");
2147     }
2148 
2149     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2150   }
2151 
2152   return BuildDeclarationNameExpr(SS, R, ADL);
2153 }
2154 
2155 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2156 /// declaration name, generally during template instantiation.
2157 /// There's a large number of things which don't need to be done along
2158 /// this path.
2159 ExprResult
2160 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2161                                         const DeclarationNameInfo &NameInfo,
2162                                         bool IsAddressOfOperand) {
2163   DeclContext *DC = computeDeclContext(SS, false);
2164   if (!DC)
2165     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2166                                      NameInfo, /*TemplateArgs=*/nullptr);
2167 
2168   if (RequireCompleteDeclContext(SS, DC))
2169     return ExprError();
2170 
2171   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2172   LookupQualifiedName(R, DC);
2173 
2174   if (R.isAmbiguous())
2175     return ExprError();
2176 
2177   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2178     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2179                                      NameInfo, /*TemplateArgs=*/nullptr);
2180 
2181   if (R.empty()) {
2182     Diag(NameInfo.getLoc(), diag::err_no_member)
2183       << NameInfo.getName() << DC << SS.getRange();
2184     return ExprError();
2185   }
2186 
2187   // Defend against this resolving to an implicit member access. We usually
2188   // won't get here if this might be a legitimate a class member (we end up in
2189   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2190   // a pointer-to-member or in an unevaluated context in C++11.
2191   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2192     return BuildPossibleImplicitMemberExpr(SS,
2193                                            /*TemplateKWLoc=*/SourceLocation(),
2194                                            R, /*TemplateArgs=*/nullptr);
2195 
2196   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2197 }
2198 
2199 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2200 /// detected that we're currently inside an ObjC method.  Perform some
2201 /// additional lookup.
2202 ///
2203 /// Ideally, most of this would be done by lookup, but there's
2204 /// actually quite a lot of extra work involved.
2205 ///
2206 /// Returns a null sentinel to indicate trivial success.
2207 ExprResult
2208 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2209                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2210   SourceLocation Loc = Lookup.getNameLoc();
2211   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2212 
2213   // Check for error condition which is already reported.
2214   if (!CurMethod)
2215     return ExprError();
2216 
2217   // There are two cases to handle here.  1) scoped lookup could have failed,
2218   // in which case we should look for an ivar.  2) scoped lookup could have
2219   // found a decl, but that decl is outside the current instance method (i.e.
2220   // a global variable).  In these two cases, we do a lookup for an ivar with
2221   // this name, if the lookup sucedes, we replace it our current decl.
2222 
2223   // If we're in a class method, we don't normally want to look for
2224   // ivars.  But if we don't find anything else, and there's an
2225   // ivar, that's an error.
2226   bool IsClassMethod = CurMethod->isClassMethod();
2227 
2228   bool LookForIvars;
2229   if (Lookup.empty())
2230     LookForIvars = true;
2231   else if (IsClassMethod)
2232     LookForIvars = false;
2233   else
2234     LookForIvars = (Lookup.isSingleResult() &&
2235                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2236   ObjCInterfaceDecl *IFace = nullptr;
2237   if (LookForIvars) {
2238     IFace = CurMethod->getClassInterface();
2239     ObjCInterfaceDecl *ClassDeclared;
2240     ObjCIvarDecl *IV = nullptr;
2241     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2242       // Diagnose using an ivar in a class method.
2243       if (IsClassMethod)
2244         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2245                          << IV->getDeclName());
2246 
2247       // If we're referencing an invalid decl, just return this as a silent
2248       // error node.  The error diagnostic was already emitted on the decl.
2249       if (IV->isInvalidDecl())
2250         return ExprError();
2251 
2252       // Check if referencing a field with __attribute__((deprecated)).
2253       if (DiagnoseUseOfDecl(IV, Loc))
2254         return ExprError();
2255 
2256       // Diagnose the use of an ivar outside of the declaring class.
2257       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2258           !declaresSameEntity(ClassDeclared, IFace) &&
2259           !getLangOpts().DebuggerSupport)
2260         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2261 
2262       // FIXME: This should use a new expr for a direct reference, don't
2263       // turn this into Self->ivar, just return a BareIVarExpr or something.
2264       IdentifierInfo &II = Context.Idents.get("self");
2265       UnqualifiedId SelfName;
2266       SelfName.setIdentifier(&II, SourceLocation());
2267       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2268       CXXScopeSpec SelfScopeSpec;
2269       SourceLocation TemplateKWLoc;
2270       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2271                                               SelfName, false, false);
2272       if (SelfExpr.isInvalid())
2273         return ExprError();
2274 
2275       SelfExpr = DefaultLvalueConversion(SelfExpr.get());
2276       if (SelfExpr.isInvalid())
2277         return ExprError();
2278 
2279       MarkAnyDeclReferenced(Loc, IV, true);
2280 
2281       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2282       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2283           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2284         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2285 
2286       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2287                                                               Loc, IV->getLocation(),
2288                                                               SelfExpr.get(),
2289                                                               true, true);
2290 
2291       if (getLangOpts().ObjCAutoRefCount) {
2292         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2293           DiagnosticsEngine::Level Level =
2294             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2295           if (Level != DiagnosticsEngine::Ignored)
2296             recordUseOfEvaluatedWeak(Result);
2297         }
2298         if (CurContext->isClosure())
2299           Diag(Loc, diag::warn_implicitly_retains_self)
2300             << FixItHint::CreateInsertion(Loc, "self->");
2301       }
2302 
2303       return Result;
2304     }
2305   } else if (CurMethod->isInstanceMethod()) {
2306     // We should warn if a local variable hides an ivar.
2307     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2308       ObjCInterfaceDecl *ClassDeclared;
2309       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2310         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2311             declaresSameEntity(IFace, ClassDeclared))
2312           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2313       }
2314     }
2315   } else if (Lookup.isSingleResult() &&
2316              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2317     // If accessing a stand-alone ivar in a class method, this is an error.
2318     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2319       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2320                        << IV->getDeclName());
2321   }
2322 
2323   if (Lookup.empty() && II && AllowBuiltinCreation) {
2324     // FIXME. Consolidate this with similar code in LookupName.
2325     if (unsigned BuiltinID = II->getBuiltinID()) {
2326       if (!(getLangOpts().CPlusPlus &&
2327             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2328         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2329                                            S, Lookup.isForRedeclaration(),
2330                                            Lookup.getNameLoc());
2331         if (D) Lookup.addDecl(D);
2332       }
2333     }
2334   }
2335   // Sentinel value saying that we didn't do anything special.
2336   return ExprResult((Expr *)nullptr);
2337 }
2338 
2339 /// \brief Cast a base object to a member's actual type.
2340 ///
2341 /// Logically this happens in three phases:
2342 ///
2343 /// * First we cast from the base type to the naming class.
2344 ///   The naming class is the class into which we were looking
2345 ///   when we found the member;  it's the qualifier type if a
2346 ///   qualifier was provided, and otherwise it's the base type.
2347 ///
2348 /// * Next we cast from the naming class to the declaring class.
2349 ///   If the member we found was brought into a class's scope by
2350 ///   a using declaration, this is that class;  otherwise it's
2351 ///   the class declaring the member.
2352 ///
2353 /// * Finally we cast from the declaring class to the "true"
2354 ///   declaring class of the member.  This conversion does not
2355 ///   obey access control.
2356 ExprResult
2357 Sema::PerformObjectMemberConversion(Expr *From,
2358                                     NestedNameSpecifier *Qualifier,
2359                                     NamedDecl *FoundDecl,
2360                                     NamedDecl *Member) {
2361   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2362   if (!RD)
2363     return From;
2364 
2365   QualType DestRecordType;
2366   QualType DestType;
2367   QualType FromRecordType;
2368   QualType FromType = From->getType();
2369   bool PointerConversions = false;
2370   if (isa<FieldDecl>(Member)) {
2371     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2372 
2373     if (FromType->getAs<PointerType>()) {
2374       DestType = Context.getPointerType(DestRecordType);
2375       FromRecordType = FromType->getPointeeType();
2376       PointerConversions = true;
2377     } else {
2378       DestType = DestRecordType;
2379       FromRecordType = FromType;
2380     }
2381   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2382     if (Method->isStatic())
2383       return From;
2384 
2385     DestType = Method->getThisType(Context);
2386     DestRecordType = DestType->getPointeeType();
2387 
2388     if (FromType->getAs<PointerType>()) {
2389       FromRecordType = FromType->getPointeeType();
2390       PointerConversions = true;
2391     } else {
2392       FromRecordType = FromType;
2393       DestType = DestRecordType;
2394     }
2395   } else {
2396     // No conversion necessary.
2397     return From;
2398   }
2399 
2400   if (DestType->isDependentType() || FromType->isDependentType())
2401     return From;
2402 
2403   // If the unqualified types are the same, no conversion is necessary.
2404   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2405     return From;
2406 
2407   SourceRange FromRange = From->getSourceRange();
2408   SourceLocation FromLoc = FromRange.getBegin();
2409 
2410   ExprValueKind VK = From->getValueKind();
2411 
2412   // C++ [class.member.lookup]p8:
2413   //   [...] Ambiguities can often be resolved by qualifying a name with its
2414   //   class name.
2415   //
2416   // If the member was a qualified name and the qualified referred to a
2417   // specific base subobject type, we'll cast to that intermediate type
2418   // first and then to the object in which the member is declared. That allows
2419   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2420   //
2421   //   class Base { public: int x; };
2422   //   class Derived1 : public Base { };
2423   //   class Derived2 : public Base { };
2424   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2425   //
2426   //   void VeryDerived::f() {
2427   //     x = 17; // error: ambiguous base subobjects
2428   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2429   //   }
2430   if (Qualifier && Qualifier->getAsType()) {
2431     QualType QType = QualType(Qualifier->getAsType(), 0);
2432     assert(QType->isRecordType() && "lookup done with non-record type");
2433 
2434     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2435 
2436     // In C++98, the qualifier type doesn't actually have to be a base
2437     // type of the object type, in which case we just ignore it.
2438     // Otherwise build the appropriate casts.
2439     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2440       CXXCastPath BasePath;
2441       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2442                                        FromLoc, FromRange, &BasePath))
2443         return ExprError();
2444 
2445       if (PointerConversions)
2446         QType = Context.getPointerType(QType);
2447       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2448                                VK, &BasePath).get();
2449 
2450       FromType = QType;
2451       FromRecordType = QRecordType;
2452 
2453       // If the qualifier type was the same as the destination type,
2454       // we're done.
2455       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2456         return From;
2457     }
2458   }
2459 
2460   bool IgnoreAccess = false;
2461 
2462   // If we actually found the member through a using declaration, cast
2463   // down to the using declaration's type.
2464   //
2465   // Pointer equality is fine here because only one declaration of a
2466   // class ever has member declarations.
2467   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2468     assert(isa<UsingShadowDecl>(FoundDecl));
2469     QualType URecordType = Context.getTypeDeclType(
2470                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2471 
2472     // We only need to do this if the naming-class to declaring-class
2473     // conversion is non-trivial.
2474     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2475       assert(IsDerivedFrom(FromRecordType, URecordType));
2476       CXXCastPath BasePath;
2477       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2478                                        FromLoc, FromRange, &BasePath))
2479         return ExprError();
2480 
2481       QualType UType = URecordType;
2482       if (PointerConversions)
2483         UType = Context.getPointerType(UType);
2484       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2485                                VK, &BasePath).get();
2486       FromType = UType;
2487       FromRecordType = URecordType;
2488     }
2489 
2490     // We don't do access control for the conversion from the
2491     // declaring class to the true declaring class.
2492     IgnoreAccess = true;
2493   }
2494 
2495   CXXCastPath BasePath;
2496   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2497                                    FromLoc, FromRange, &BasePath,
2498                                    IgnoreAccess))
2499     return ExprError();
2500 
2501   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2502                            VK, &BasePath);
2503 }
2504 
2505 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2506                                       const LookupResult &R,
2507                                       bool HasTrailingLParen) {
2508   // Only when used directly as the postfix-expression of a call.
2509   if (!HasTrailingLParen)
2510     return false;
2511 
2512   // Never if a scope specifier was provided.
2513   if (SS.isSet())
2514     return false;
2515 
2516   // Only in C++ or ObjC++.
2517   if (!getLangOpts().CPlusPlus)
2518     return false;
2519 
2520   // Turn off ADL when we find certain kinds of declarations during
2521   // normal lookup:
2522   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2523     NamedDecl *D = *I;
2524 
2525     // C++0x [basic.lookup.argdep]p3:
2526     //     -- a declaration of a class member
2527     // Since using decls preserve this property, we check this on the
2528     // original decl.
2529     if (D->isCXXClassMember())
2530       return false;
2531 
2532     // C++0x [basic.lookup.argdep]p3:
2533     //     -- a block-scope function declaration that is not a
2534     //        using-declaration
2535     // NOTE: we also trigger this for function templates (in fact, we
2536     // don't check the decl type at all, since all other decl types
2537     // turn off ADL anyway).
2538     if (isa<UsingShadowDecl>(D))
2539       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2540     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2541       return false;
2542 
2543     // C++0x [basic.lookup.argdep]p3:
2544     //     -- a declaration that is neither a function or a function
2545     //        template
2546     // And also for builtin functions.
2547     if (isa<FunctionDecl>(D)) {
2548       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2549 
2550       // But also builtin functions.
2551       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2552         return false;
2553     } else if (!isa<FunctionTemplateDecl>(D))
2554       return false;
2555   }
2556 
2557   return true;
2558 }
2559 
2560 
2561 /// Diagnoses obvious problems with the use of the given declaration
2562 /// as an expression.  This is only actually called for lookups that
2563 /// were not overloaded, and it doesn't promise that the declaration
2564 /// will in fact be used.
2565 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2566   if (isa<TypedefNameDecl>(D)) {
2567     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2568     return true;
2569   }
2570 
2571   if (isa<ObjCInterfaceDecl>(D)) {
2572     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2573     return true;
2574   }
2575 
2576   if (isa<NamespaceDecl>(D)) {
2577     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2578     return true;
2579   }
2580 
2581   return false;
2582 }
2583 
2584 ExprResult
2585 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2586                                LookupResult &R,
2587                                bool NeedsADL) {
2588   // If this is a single, fully-resolved result and we don't need ADL,
2589   // just build an ordinary singleton decl ref.
2590   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2591     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2592                                     R.getRepresentativeDecl());
2593 
2594   // We only need to check the declaration if there's exactly one
2595   // result, because in the overloaded case the results can only be
2596   // functions and function templates.
2597   if (R.isSingleResult() &&
2598       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2599     return ExprError();
2600 
2601   // Otherwise, just build an unresolved lookup expression.  Suppress
2602   // any lookup-related diagnostics; we'll hash these out later, when
2603   // we've picked a target.
2604   R.suppressDiagnostics();
2605 
2606   UnresolvedLookupExpr *ULE
2607     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2608                                    SS.getWithLocInContext(Context),
2609                                    R.getLookupNameInfo(),
2610                                    NeedsADL, R.isOverloadedResult(),
2611                                    R.begin(), R.end());
2612 
2613   return ULE;
2614 }
2615 
2616 /// \brief Complete semantic analysis for a reference to the given declaration.
2617 ExprResult Sema::BuildDeclarationNameExpr(
2618     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2619     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2620   assert(D && "Cannot refer to a NULL declaration");
2621   assert(!isa<FunctionTemplateDecl>(D) &&
2622          "Cannot refer unambiguously to a function template");
2623 
2624   SourceLocation Loc = NameInfo.getLoc();
2625   if (CheckDeclInExpr(*this, Loc, D))
2626     return ExprError();
2627 
2628   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2629     // Specifically diagnose references to class templates that are missing
2630     // a template argument list.
2631     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2632                                            << Template << SS.getRange();
2633     Diag(Template->getLocation(), diag::note_template_decl_here);
2634     return ExprError();
2635   }
2636 
2637   // Make sure that we're referring to a value.
2638   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2639   if (!VD) {
2640     Diag(Loc, diag::err_ref_non_value)
2641       << D << SS.getRange();
2642     Diag(D->getLocation(), diag::note_declared_at);
2643     return ExprError();
2644   }
2645 
2646   // Check whether this declaration can be used. Note that we suppress
2647   // this check when we're going to perform argument-dependent lookup
2648   // on this function name, because this might not be the function
2649   // that overload resolution actually selects.
2650   if (DiagnoseUseOfDecl(VD, Loc))
2651     return ExprError();
2652 
2653   // Only create DeclRefExpr's for valid Decl's.
2654   if (VD->isInvalidDecl())
2655     return ExprError();
2656 
2657   // Handle members of anonymous structs and unions.  If we got here,
2658   // and the reference is to a class member indirect field, then this
2659   // must be the subject of a pointer-to-member expression.
2660   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2661     if (!indirectField->isCXXClassMember())
2662       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2663                                                       indirectField);
2664 
2665   {
2666     QualType type = VD->getType();
2667     ExprValueKind valueKind = VK_RValue;
2668 
2669     switch (D->getKind()) {
2670     // Ignore all the non-ValueDecl kinds.
2671 #define ABSTRACT_DECL(kind)
2672 #define VALUE(type, base)
2673 #define DECL(type, base) \
2674     case Decl::type:
2675 #include "clang/AST/DeclNodes.inc"
2676       llvm_unreachable("invalid value decl kind");
2677 
2678     // These shouldn't make it here.
2679     case Decl::ObjCAtDefsField:
2680     case Decl::ObjCIvar:
2681       llvm_unreachable("forming non-member reference to ivar?");
2682 
2683     // Enum constants are always r-values and never references.
2684     // Unresolved using declarations are dependent.
2685     case Decl::EnumConstant:
2686     case Decl::UnresolvedUsingValue:
2687       valueKind = VK_RValue;
2688       break;
2689 
2690     // Fields and indirect fields that got here must be for
2691     // pointer-to-member expressions; we just call them l-values for
2692     // internal consistency, because this subexpression doesn't really
2693     // exist in the high-level semantics.
2694     case Decl::Field:
2695     case Decl::IndirectField:
2696       assert(getLangOpts().CPlusPlus &&
2697              "building reference to field in C?");
2698 
2699       // These can't have reference type in well-formed programs, but
2700       // for internal consistency we do this anyway.
2701       type = type.getNonReferenceType();
2702       valueKind = VK_LValue;
2703       break;
2704 
2705     // Non-type template parameters are either l-values or r-values
2706     // depending on the type.
2707     case Decl::NonTypeTemplateParm: {
2708       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2709         type = reftype->getPointeeType();
2710         valueKind = VK_LValue; // even if the parameter is an r-value reference
2711         break;
2712       }
2713 
2714       // For non-references, we need to strip qualifiers just in case
2715       // the template parameter was declared as 'const int' or whatever.
2716       valueKind = VK_RValue;
2717       type = type.getUnqualifiedType();
2718       break;
2719     }
2720 
2721     case Decl::Var:
2722     case Decl::VarTemplateSpecialization:
2723     case Decl::VarTemplatePartialSpecialization:
2724       // In C, "extern void blah;" is valid and is an r-value.
2725       if (!getLangOpts().CPlusPlus &&
2726           !type.hasQualifiers() &&
2727           type->isVoidType()) {
2728         valueKind = VK_RValue;
2729         break;
2730       }
2731       // fallthrough
2732 
2733     case Decl::ImplicitParam:
2734     case Decl::ParmVar: {
2735       // These are always l-values.
2736       valueKind = VK_LValue;
2737       type = type.getNonReferenceType();
2738 
2739       // FIXME: Does the addition of const really only apply in
2740       // potentially-evaluated contexts? Since the variable isn't actually
2741       // captured in an unevaluated context, it seems that the answer is no.
2742       if (!isUnevaluatedContext()) {
2743         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2744         if (!CapturedType.isNull())
2745           type = CapturedType;
2746       }
2747 
2748       break;
2749     }
2750 
2751     case Decl::Function: {
2752       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2753         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2754           type = Context.BuiltinFnTy;
2755           valueKind = VK_RValue;
2756           break;
2757         }
2758       }
2759 
2760       const FunctionType *fty = type->castAs<FunctionType>();
2761 
2762       // If we're referring to a function with an __unknown_anytype
2763       // result type, make the entire expression __unknown_anytype.
2764       if (fty->getReturnType() == Context.UnknownAnyTy) {
2765         type = Context.UnknownAnyTy;
2766         valueKind = VK_RValue;
2767         break;
2768       }
2769 
2770       // Functions are l-values in C++.
2771       if (getLangOpts().CPlusPlus) {
2772         valueKind = VK_LValue;
2773         break;
2774       }
2775 
2776       // C99 DR 316 says that, if a function type comes from a
2777       // function definition (without a prototype), that type is only
2778       // used for checking compatibility. Therefore, when referencing
2779       // the function, we pretend that we don't have the full function
2780       // type.
2781       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2782           isa<FunctionProtoType>(fty))
2783         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2784                                               fty->getExtInfo());
2785 
2786       // Functions are r-values in C.
2787       valueKind = VK_RValue;
2788       break;
2789     }
2790 
2791     case Decl::MSProperty:
2792       valueKind = VK_LValue;
2793       break;
2794 
2795     case Decl::CXXMethod:
2796       // If we're referring to a method with an __unknown_anytype
2797       // result type, make the entire expression __unknown_anytype.
2798       // This should only be possible with a type written directly.
2799       if (const FunctionProtoType *proto
2800             = dyn_cast<FunctionProtoType>(VD->getType()))
2801         if (proto->getReturnType() == Context.UnknownAnyTy) {
2802           type = Context.UnknownAnyTy;
2803           valueKind = VK_RValue;
2804           break;
2805         }
2806 
2807       // C++ methods are l-values if static, r-values if non-static.
2808       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2809         valueKind = VK_LValue;
2810         break;
2811       }
2812       // fallthrough
2813 
2814     case Decl::CXXConversion:
2815     case Decl::CXXDestructor:
2816     case Decl::CXXConstructor:
2817       valueKind = VK_RValue;
2818       break;
2819     }
2820 
2821     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2822                             TemplateArgs);
2823   }
2824 }
2825 
2826 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2827                                      PredefinedExpr::IdentType IT) {
2828   // Pick the current block, lambda, captured statement or function.
2829   Decl *currentDecl = nullptr;
2830   if (const BlockScopeInfo *BSI = getCurBlock())
2831     currentDecl = BSI->TheDecl;
2832   else if (const LambdaScopeInfo *LSI = getCurLambda())
2833     currentDecl = LSI->CallOperator;
2834   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2835     currentDecl = CSI->TheCapturedDecl;
2836   else
2837     currentDecl = getCurFunctionOrMethodDecl();
2838 
2839   if (!currentDecl) {
2840     Diag(Loc, diag::ext_predef_outside_function);
2841     currentDecl = Context.getTranslationUnitDecl();
2842   }
2843 
2844   QualType ResTy;
2845   if (cast<DeclContext>(currentDecl)->isDependentContext())
2846     ResTy = Context.DependentTy;
2847   else {
2848     // Pre-defined identifiers are of type char[x], where x is the length of
2849     // the string.
2850     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2851 
2852     llvm::APInt LengthI(32, Length + 1);
2853     if (IT == PredefinedExpr::LFunction)
2854       ResTy = Context.WideCharTy.withConst();
2855     else
2856       ResTy = Context.CharTy.withConst();
2857     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2858   }
2859 
2860   return new (Context) PredefinedExpr(Loc, ResTy, IT);
2861 }
2862 
2863 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2864   PredefinedExpr::IdentType IT;
2865 
2866   switch (Kind) {
2867   default: llvm_unreachable("Unknown simple primary expr!");
2868   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2869   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2870   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2871   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
2872   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2873   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2874   }
2875 
2876   return BuildPredefinedExpr(Loc, IT);
2877 }
2878 
2879 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2880   SmallString<16> CharBuffer;
2881   bool Invalid = false;
2882   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2883   if (Invalid)
2884     return ExprError();
2885 
2886   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2887                             PP, Tok.getKind());
2888   if (Literal.hadError())
2889     return ExprError();
2890 
2891   QualType Ty;
2892   if (Literal.isWide())
2893     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2894   else if (Literal.isUTF16())
2895     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2896   else if (Literal.isUTF32())
2897     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2898   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2899     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2900   else
2901     Ty = Context.CharTy;  // 'x' -> char in C++
2902 
2903   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2904   if (Literal.isWide())
2905     Kind = CharacterLiteral::Wide;
2906   else if (Literal.isUTF16())
2907     Kind = CharacterLiteral::UTF16;
2908   else if (Literal.isUTF32())
2909     Kind = CharacterLiteral::UTF32;
2910 
2911   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2912                                              Tok.getLocation());
2913 
2914   if (Literal.getUDSuffix().empty())
2915     return Lit;
2916 
2917   // We're building a user-defined literal.
2918   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2919   SourceLocation UDSuffixLoc =
2920     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2921 
2922   // Make sure we're allowed user-defined literals here.
2923   if (!UDLScope)
2924     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2925 
2926   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2927   //   operator "" X (ch)
2928   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2929                                         Lit, Tok.getLocation());
2930 }
2931 
2932 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2933   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2934   return IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2935                                 Context.IntTy, Loc);
2936 }
2937 
2938 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2939                                   QualType Ty, SourceLocation Loc) {
2940   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2941 
2942   using llvm::APFloat;
2943   APFloat Val(Format);
2944 
2945   APFloat::opStatus result = Literal.GetFloatValue(Val);
2946 
2947   // Overflow is always an error, but underflow is only an error if
2948   // we underflowed to zero (APFloat reports denormals as underflow).
2949   if ((result & APFloat::opOverflow) ||
2950       ((result & APFloat::opUnderflow) && Val.isZero())) {
2951     unsigned diagnostic;
2952     SmallString<20> buffer;
2953     if (result & APFloat::opOverflow) {
2954       diagnostic = diag::warn_float_overflow;
2955       APFloat::getLargest(Format).toString(buffer);
2956     } else {
2957       diagnostic = diag::warn_float_underflow;
2958       APFloat::getSmallest(Format).toString(buffer);
2959     }
2960 
2961     S.Diag(Loc, diagnostic)
2962       << Ty
2963       << StringRef(buffer.data(), buffer.size());
2964   }
2965 
2966   bool isExact = (result == APFloat::opOK);
2967   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2968 }
2969 
2970 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2971   // Fast path for a single digit (which is quite common).  A single digit
2972   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2973   if (Tok.getLength() == 1) {
2974     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2975     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2976   }
2977 
2978   SmallString<128> SpellingBuffer;
2979   // NumericLiteralParser wants to overread by one character.  Add padding to
2980   // the buffer in case the token is copied to the buffer.  If getSpelling()
2981   // returns a StringRef to the memory buffer, it should have a null char at
2982   // the EOF, so it is also safe.
2983   SpellingBuffer.resize(Tok.getLength() + 1);
2984 
2985   // Get the spelling of the token, which eliminates trigraphs, etc.
2986   bool Invalid = false;
2987   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2988   if (Invalid)
2989     return ExprError();
2990 
2991   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2992   if (Literal.hadError)
2993     return ExprError();
2994 
2995   if (Literal.hasUDSuffix()) {
2996     // We're building a user-defined literal.
2997     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2998     SourceLocation UDSuffixLoc =
2999       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3000 
3001     // Make sure we're allowed user-defined literals here.
3002     if (!UDLScope)
3003       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3004 
3005     QualType CookedTy;
3006     if (Literal.isFloatingLiteral()) {
3007       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3008       // long double, the literal is treated as a call of the form
3009       //   operator "" X (f L)
3010       CookedTy = Context.LongDoubleTy;
3011     } else {
3012       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3013       // unsigned long long, the literal is treated as a call of the form
3014       //   operator "" X (n ULL)
3015       CookedTy = Context.UnsignedLongLongTy;
3016     }
3017 
3018     DeclarationName OpName =
3019       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3020     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3021     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3022 
3023     SourceLocation TokLoc = Tok.getLocation();
3024 
3025     // Perform literal operator lookup to determine if we're building a raw
3026     // literal or a cooked one.
3027     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3028     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3029                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3030                                   /*AllowStringTemplate*/false)) {
3031     case LOLR_Error:
3032       return ExprError();
3033 
3034     case LOLR_Cooked: {
3035       Expr *Lit;
3036       if (Literal.isFloatingLiteral()) {
3037         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3038       } else {
3039         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3040         if (Literal.GetIntegerValue(ResultVal))
3041           Diag(Tok.getLocation(), diag::err_integer_too_large);
3042         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3043                                      Tok.getLocation());
3044       }
3045       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3046     }
3047 
3048     case LOLR_Raw: {
3049       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3050       // literal is treated as a call of the form
3051       //   operator "" X ("n")
3052       unsigned Length = Literal.getUDSuffixOffset();
3053       QualType StrTy = Context.getConstantArrayType(
3054           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3055           ArrayType::Normal, 0);
3056       Expr *Lit = StringLiteral::Create(
3057           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3058           /*Pascal*/false, StrTy, &TokLoc, 1);
3059       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3060     }
3061 
3062     case LOLR_Template: {
3063       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3064       // template), L is treated as a call fo the form
3065       //   operator "" X <'c1', 'c2', ... 'ck'>()
3066       // where n is the source character sequence c1 c2 ... ck.
3067       TemplateArgumentListInfo ExplicitArgs;
3068       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3069       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3070       llvm::APSInt Value(CharBits, CharIsUnsigned);
3071       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3072         Value = TokSpelling[I];
3073         TemplateArgument Arg(Context, Value, Context.CharTy);
3074         TemplateArgumentLocInfo ArgInfo;
3075         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3076       }
3077       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3078                                       &ExplicitArgs);
3079     }
3080     case LOLR_StringTemplate:
3081       llvm_unreachable("unexpected literal operator lookup result");
3082     }
3083   }
3084 
3085   Expr *Res;
3086 
3087   if (Literal.isFloatingLiteral()) {
3088     QualType Ty;
3089     if (Literal.isFloat)
3090       Ty = Context.FloatTy;
3091     else if (!Literal.isLong)
3092       Ty = Context.DoubleTy;
3093     else
3094       Ty = Context.LongDoubleTy;
3095 
3096     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3097 
3098     if (Ty == Context.DoubleTy) {
3099       if (getLangOpts().SinglePrecisionConstants) {
3100         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3101       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3102         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3103         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).get();
3104       }
3105     }
3106   } else if (!Literal.isIntegerLiteral()) {
3107     return ExprError();
3108   } else {
3109     QualType Ty;
3110 
3111     // 'long long' is a C99 or C++11 feature.
3112     if (!getLangOpts().C99 && Literal.isLongLong) {
3113       if (getLangOpts().CPlusPlus)
3114         Diag(Tok.getLocation(),
3115              getLangOpts().CPlusPlus11 ?
3116              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3117       else
3118         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3119     }
3120 
3121     // Get the value in the widest-possible width.
3122     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3123     // The microsoft literal suffix extensions support 128-bit literals, which
3124     // may be wider than [u]intmax_t.
3125     // FIXME: Actually, they don't. We seem to have accidentally invented the
3126     //        i128 suffix.
3127     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3128         Context.getTargetInfo().hasInt128Type())
3129       MaxWidth = 128;
3130     llvm::APInt ResultVal(MaxWidth, 0);
3131 
3132     if (Literal.GetIntegerValue(ResultVal)) {
3133       // If this value didn't fit into uintmax_t, error and force to ull.
3134       Diag(Tok.getLocation(), diag::err_integer_too_large);
3135       Ty = Context.UnsignedLongLongTy;
3136       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3137              "long long is not intmax_t?");
3138     } else {
3139       // If this value fits into a ULL, try to figure out what else it fits into
3140       // according to the rules of C99 6.4.4.1p5.
3141 
3142       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3143       // be an unsigned int.
3144       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3145 
3146       // Check from smallest to largest, picking the smallest type we can.
3147       unsigned Width = 0;
3148       if (!Literal.isLong && !Literal.isLongLong) {
3149         // Are int/unsigned possibilities?
3150         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3151 
3152         // Does it fit in a unsigned int?
3153         if (ResultVal.isIntN(IntSize)) {
3154           // Does it fit in a signed int?
3155           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3156             Ty = Context.IntTy;
3157           else if (AllowUnsigned)
3158             Ty = Context.UnsignedIntTy;
3159           Width = IntSize;
3160         }
3161       }
3162 
3163       // Are long/unsigned long possibilities?
3164       if (Ty.isNull() && !Literal.isLongLong) {
3165         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3166 
3167         // Does it fit in a unsigned long?
3168         if (ResultVal.isIntN(LongSize)) {
3169           // Does it fit in a signed long?
3170           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3171             Ty = Context.LongTy;
3172           else if (AllowUnsigned)
3173             Ty = Context.UnsignedLongTy;
3174           Width = LongSize;
3175         }
3176       }
3177 
3178       // Check long long if needed.
3179       if (Ty.isNull()) {
3180         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3181 
3182         // Does it fit in a unsigned long long?
3183         if (ResultVal.isIntN(LongLongSize)) {
3184           // Does it fit in a signed long long?
3185           // To be compatible with MSVC, hex integer literals ending with the
3186           // LL or i64 suffix are always signed in Microsoft mode.
3187           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3188               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3189             Ty = Context.LongLongTy;
3190           else if (AllowUnsigned)
3191             Ty = Context.UnsignedLongLongTy;
3192           Width = LongLongSize;
3193         }
3194       }
3195 
3196       // If it doesn't fit in unsigned long long, and we're using Microsoft
3197       // extensions, then its a 128-bit integer literal.
3198       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3199           Context.getTargetInfo().hasInt128Type()) {
3200         if (Literal.isUnsigned)
3201           Ty = Context.UnsignedInt128Ty;
3202         else
3203           Ty = Context.Int128Ty;
3204         Width = 128;
3205       }
3206 
3207       // If we still couldn't decide a type, we probably have something that
3208       // does not fit in a signed long long, but has no U suffix.
3209       if (Ty.isNull()) {
3210         Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed);
3211         Ty = Context.UnsignedLongLongTy;
3212         Width = Context.getTargetInfo().getLongLongWidth();
3213       }
3214 
3215       if (ResultVal.getBitWidth() != Width)
3216         ResultVal = ResultVal.trunc(Width);
3217     }
3218     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3219   }
3220 
3221   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3222   if (Literal.isImaginary)
3223     Res = new (Context) ImaginaryLiteral(Res,
3224                                         Context.getComplexType(Res->getType()));
3225 
3226   return Res;
3227 }
3228 
3229 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3230   assert(E && "ActOnParenExpr() missing expr");
3231   return new (Context) ParenExpr(L, R, E);
3232 }
3233 
3234 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3235                                          SourceLocation Loc,
3236                                          SourceRange ArgRange) {
3237   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3238   // scalar or vector data type argument..."
3239   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3240   // type (C99 6.2.5p18) or void.
3241   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3242     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3243       << T << ArgRange;
3244     return true;
3245   }
3246 
3247   assert((T->isVoidType() || !T->isIncompleteType()) &&
3248          "Scalar types should always be complete");
3249   return false;
3250 }
3251 
3252 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3253                                            SourceLocation Loc,
3254                                            SourceRange ArgRange,
3255                                            UnaryExprOrTypeTrait TraitKind) {
3256   // Invalid types must be hard errors for SFINAE in C++.
3257   if (S.LangOpts.CPlusPlus)
3258     return true;
3259 
3260   // C99 6.5.3.4p1:
3261   if (T->isFunctionType() &&
3262       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3263     // sizeof(function)/alignof(function) is allowed as an extension.
3264     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3265       << TraitKind << ArgRange;
3266     return false;
3267   }
3268 
3269   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3270   // this is an error (OpenCL v1.1 s6.3.k)
3271   if (T->isVoidType()) {
3272     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3273                                         : diag::ext_sizeof_alignof_void_type;
3274     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3275     return false;
3276   }
3277 
3278   return true;
3279 }
3280 
3281 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3282                                              SourceLocation Loc,
3283                                              SourceRange ArgRange,
3284                                              UnaryExprOrTypeTrait TraitKind) {
3285   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3286   // runtime doesn't allow it.
3287   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3288     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3289       << T << (TraitKind == UETT_SizeOf)
3290       << ArgRange;
3291     return true;
3292   }
3293 
3294   return false;
3295 }
3296 
3297 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3298 /// pointer type is equal to T) and emit a warning if it is.
3299 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3300                                      Expr *E) {
3301   // Don't warn if the operation changed the type.
3302   if (T != E->getType())
3303     return;
3304 
3305   // Now look for array decays.
3306   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3307   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3308     return;
3309 
3310   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3311                                              << ICE->getType()
3312                                              << ICE->getSubExpr()->getType();
3313 }
3314 
3315 /// \brief Check the constraints on expression operands to unary type expression
3316 /// and type traits.
3317 ///
3318 /// Completes any types necessary and validates the constraints on the operand
3319 /// expression. The logic mostly mirrors the type-based overload, but may modify
3320 /// the expression as it completes the type for that expression through template
3321 /// instantiation, etc.
3322 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3323                                             UnaryExprOrTypeTrait ExprKind) {
3324   QualType ExprTy = E->getType();
3325   assert(!ExprTy->isReferenceType());
3326 
3327   if (ExprKind == UETT_VecStep)
3328     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3329                                         E->getSourceRange());
3330 
3331   // Whitelist some types as extensions
3332   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3333                                       E->getSourceRange(), ExprKind))
3334     return false;
3335 
3336   if (RequireCompleteExprType(E,
3337                               diag::err_sizeof_alignof_incomplete_type,
3338                               ExprKind, E->getSourceRange()))
3339     return true;
3340 
3341   // Completing the expression's type may have changed it.
3342   ExprTy = E->getType();
3343   assert(!ExprTy->isReferenceType());
3344 
3345   if (ExprTy->isFunctionType()) {
3346     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3347       << ExprKind << E->getSourceRange();
3348     return true;
3349   }
3350 
3351   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3352                                        E->getSourceRange(), ExprKind))
3353     return true;
3354 
3355   if (ExprKind == UETT_SizeOf) {
3356     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3357       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3358         QualType OType = PVD->getOriginalType();
3359         QualType Type = PVD->getType();
3360         if (Type->isPointerType() && OType->isArrayType()) {
3361           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3362             << Type << OType;
3363           Diag(PVD->getLocation(), diag::note_declared_at);
3364         }
3365       }
3366     }
3367 
3368     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3369     // decays into a pointer and returns an unintended result. This is most
3370     // likely a typo for "sizeof(array) op x".
3371     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3372       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3373                                BO->getLHS());
3374       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3375                                BO->getRHS());
3376     }
3377   }
3378 
3379   return false;
3380 }
3381 
3382 /// \brief Check the constraints on operands to unary expression and type
3383 /// traits.
3384 ///
3385 /// This will complete any types necessary, and validate the various constraints
3386 /// on those operands.
3387 ///
3388 /// The UsualUnaryConversions() function is *not* called by this routine.
3389 /// C99 6.3.2.1p[2-4] all state:
3390 ///   Except when it is the operand of the sizeof operator ...
3391 ///
3392 /// C++ [expr.sizeof]p4
3393 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3394 ///   standard conversions are not applied to the operand of sizeof.
3395 ///
3396 /// This policy is followed for all of the unary trait expressions.
3397 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3398                                             SourceLocation OpLoc,
3399                                             SourceRange ExprRange,
3400                                             UnaryExprOrTypeTrait ExprKind) {
3401   if (ExprType->isDependentType())
3402     return false;
3403 
3404   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3405   //   the result is the size of the referenced type."
3406   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3407   //   result shall be the alignment of the referenced type."
3408   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3409     ExprType = Ref->getPointeeType();
3410 
3411   if (ExprKind == UETT_VecStep)
3412     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3413 
3414   // Whitelist some types as extensions
3415   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3416                                       ExprKind))
3417     return false;
3418 
3419   if (RequireCompleteType(OpLoc, ExprType,
3420                           diag::err_sizeof_alignof_incomplete_type,
3421                           ExprKind, ExprRange))
3422     return true;
3423 
3424   if (ExprType->isFunctionType()) {
3425     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3426       << ExprKind << ExprRange;
3427     return true;
3428   }
3429 
3430   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3431                                        ExprKind))
3432     return true;
3433 
3434   return false;
3435 }
3436 
3437 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3438   E = E->IgnoreParens();
3439 
3440   // Cannot know anything else if the expression is dependent.
3441   if (E->isTypeDependent())
3442     return false;
3443 
3444   if (E->getObjectKind() == OK_BitField) {
3445     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3446        << 1 << E->getSourceRange();
3447     return true;
3448   }
3449 
3450   ValueDecl *D = nullptr;
3451   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3452     D = DRE->getDecl();
3453   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3454     D = ME->getMemberDecl();
3455   }
3456 
3457   // If it's a field, require the containing struct to have a
3458   // complete definition so that we can compute the layout.
3459   //
3460   // This requires a very particular set of circumstances.  For a
3461   // field to be contained within an incomplete type, we must in the
3462   // process of parsing that type.  To have an expression refer to a
3463   // field, it must be an id-expression or a member-expression, but
3464   // the latter are always ill-formed when the base type is
3465   // incomplete, including only being partially complete.  An
3466   // id-expression can never refer to a field in C because fields
3467   // are not in the ordinary namespace.  In C++, an id-expression
3468   // can implicitly be a member access, but only if there's an
3469   // implicit 'this' value, and all such contexts are subject to
3470   // delayed parsing --- except for trailing return types in C++11.
3471   // And if an id-expression referring to a field occurs in a
3472   // context that lacks a 'this' value, it's ill-formed --- except,
3473   // again, in C++11, where such references are allowed in an
3474   // unevaluated context.  So C++11 introduces some new complexity.
3475   //
3476   // For the record, since __alignof__ on expressions is a GCC
3477   // extension, GCC seems to permit this but always gives the
3478   // nonsensical answer 0.
3479   //
3480   // We don't really need the layout here --- we could instead just
3481   // directly check for all the appropriate alignment-lowing
3482   // attributes --- but that would require duplicating a lot of
3483   // logic that just isn't worth duplicating for such a marginal
3484   // use-case.
3485   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3486     // Fast path this check, since we at least know the record has a
3487     // definition if we can find a member of it.
3488     if (!FD->getParent()->isCompleteDefinition()) {
3489       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3490         << E->getSourceRange();
3491       return true;
3492     }
3493 
3494     // Otherwise, if it's a field, and the field doesn't have
3495     // reference type, then it must have a complete type (or be a
3496     // flexible array member, which we explicitly want to
3497     // white-list anyway), which makes the following checks trivial.
3498     if (!FD->getType()->isReferenceType())
3499       return false;
3500   }
3501 
3502   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3503 }
3504 
3505 bool Sema::CheckVecStepExpr(Expr *E) {
3506   E = E->IgnoreParens();
3507 
3508   // Cannot know anything else if the expression is dependent.
3509   if (E->isTypeDependent())
3510     return false;
3511 
3512   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3513 }
3514 
3515 /// \brief Build a sizeof or alignof expression given a type operand.
3516 ExprResult
3517 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3518                                      SourceLocation OpLoc,
3519                                      UnaryExprOrTypeTrait ExprKind,
3520                                      SourceRange R) {
3521   if (!TInfo)
3522     return ExprError();
3523 
3524   QualType T = TInfo->getType();
3525 
3526   if (!T->isDependentType() &&
3527       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3528     return ExprError();
3529 
3530   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3531   return new (Context) UnaryExprOrTypeTraitExpr(
3532       ExprKind, TInfo, Context.getSizeType(), OpLoc, R.getEnd());
3533 }
3534 
3535 /// \brief Build a sizeof or alignof expression given an expression
3536 /// operand.
3537 ExprResult
3538 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3539                                      UnaryExprOrTypeTrait ExprKind) {
3540   ExprResult PE = CheckPlaceholderExpr(E);
3541   if (PE.isInvalid())
3542     return ExprError();
3543 
3544   E = PE.get();
3545 
3546   // Verify that the operand is valid.
3547   bool isInvalid = false;
3548   if (E->isTypeDependent()) {
3549     // Delay type-checking for type-dependent expressions.
3550   } else if (ExprKind == UETT_AlignOf) {
3551     isInvalid = CheckAlignOfExpr(*this, E);
3552   } else if (ExprKind == UETT_VecStep) {
3553     isInvalid = CheckVecStepExpr(E);
3554   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3555     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3556     isInvalid = true;
3557   } else {
3558     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3559   }
3560 
3561   if (isInvalid)
3562     return ExprError();
3563 
3564   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3565     PE = TransformToPotentiallyEvaluated(E);
3566     if (PE.isInvalid()) return ExprError();
3567     E = PE.get();
3568   }
3569 
3570   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3571   return new (Context) UnaryExprOrTypeTraitExpr(
3572       ExprKind, E, Context.getSizeType(), OpLoc, E->getSourceRange().getEnd());
3573 }
3574 
3575 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3576 /// expr and the same for @c alignof and @c __alignof
3577 /// Note that the ArgRange is invalid if isType is false.
3578 ExprResult
3579 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3580                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3581                                     void *TyOrEx, const SourceRange &ArgRange) {
3582   // If error parsing type, ignore.
3583   if (!TyOrEx) return ExprError();
3584 
3585   if (IsType) {
3586     TypeSourceInfo *TInfo;
3587     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3588     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3589   }
3590 
3591   Expr *ArgEx = (Expr *)TyOrEx;
3592   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3593   return Result;
3594 }
3595 
3596 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3597                                      bool IsReal) {
3598   if (V.get()->isTypeDependent())
3599     return S.Context.DependentTy;
3600 
3601   // _Real and _Imag are only l-values for normal l-values.
3602   if (V.get()->getObjectKind() != OK_Ordinary) {
3603     V = S.DefaultLvalueConversion(V.get());
3604     if (V.isInvalid())
3605       return QualType();
3606   }
3607 
3608   // These operators return the element type of a complex type.
3609   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3610     return CT->getElementType();
3611 
3612   // Otherwise they pass through real integer and floating point types here.
3613   if (V.get()->getType()->isArithmeticType())
3614     return V.get()->getType();
3615 
3616   // Test for placeholders.
3617   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3618   if (PR.isInvalid()) return QualType();
3619   if (PR.get() != V.get()) {
3620     V = PR;
3621     return CheckRealImagOperand(S, V, Loc, IsReal);
3622   }
3623 
3624   // Reject anything else.
3625   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3626     << (IsReal ? "__real" : "__imag");
3627   return QualType();
3628 }
3629 
3630 
3631 
3632 ExprResult
3633 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3634                           tok::TokenKind Kind, Expr *Input) {
3635   UnaryOperatorKind Opc;
3636   switch (Kind) {
3637   default: llvm_unreachable("Unknown unary op!");
3638   case tok::plusplus:   Opc = UO_PostInc; break;
3639   case tok::minusminus: Opc = UO_PostDec; break;
3640   }
3641 
3642   // Since this might is a postfix expression, get rid of ParenListExprs.
3643   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3644   if (Result.isInvalid()) return ExprError();
3645   Input = Result.get();
3646 
3647   return BuildUnaryOp(S, OpLoc, Opc, Input);
3648 }
3649 
3650 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3651 ///
3652 /// \return true on error
3653 static bool checkArithmeticOnObjCPointer(Sema &S,
3654                                          SourceLocation opLoc,
3655                                          Expr *op) {
3656   assert(op->getType()->isObjCObjectPointerType());
3657   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3658       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3659     return false;
3660 
3661   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3662     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3663     << op->getSourceRange();
3664   return true;
3665 }
3666 
3667 ExprResult
3668 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3669                               Expr *idx, SourceLocation rbLoc) {
3670   // Since this might be a postfix expression, get rid of ParenListExprs.
3671   if (isa<ParenListExpr>(base)) {
3672     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3673     if (result.isInvalid()) return ExprError();
3674     base = result.get();
3675   }
3676 
3677   // Handle any non-overload placeholder types in the base and index
3678   // expressions.  We can't handle overloads here because the other
3679   // operand might be an overloadable type, in which case the overload
3680   // resolution for the operator overload should get the first crack
3681   // at the overload.
3682   if (base->getType()->isNonOverloadPlaceholderType()) {
3683     ExprResult result = CheckPlaceholderExpr(base);
3684     if (result.isInvalid()) return ExprError();
3685     base = result.get();
3686   }
3687   if (idx->getType()->isNonOverloadPlaceholderType()) {
3688     ExprResult result = CheckPlaceholderExpr(idx);
3689     if (result.isInvalid()) return ExprError();
3690     idx = result.get();
3691   }
3692 
3693   // Build an unanalyzed expression if either operand is type-dependent.
3694   if (getLangOpts().CPlusPlus &&
3695       (base->isTypeDependent() || idx->isTypeDependent())) {
3696     return new (Context) ArraySubscriptExpr(base, idx, Context.DependentTy,
3697                                             VK_LValue, OK_Ordinary, rbLoc);
3698   }
3699 
3700   // Use C++ overloaded-operator rules if either operand has record
3701   // type.  The spec says to do this if either type is *overloadable*,
3702   // but enum types can't declare subscript operators or conversion
3703   // operators, so there's nothing interesting for overload resolution
3704   // to do if there aren't any record types involved.
3705   //
3706   // ObjC pointers have their own subscripting logic that is not tied
3707   // to overload resolution and so should not take this path.
3708   if (getLangOpts().CPlusPlus &&
3709       (base->getType()->isRecordType() ||
3710        (!base->getType()->isObjCObjectPointerType() &&
3711         idx->getType()->isRecordType()))) {
3712     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3713   }
3714 
3715   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3716 }
3717 
3718 ExprResult
3719 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3720                                       Expr *Idx, SourceLocation RLoc) {
3721   Expr *LHSExp = Base;
3722   Expr *RHSExp = Idx;
3723 
3724   // Perform default conversions.
3725   if (!LHSExp->getType()->getAs<VectorType>()) {
3726     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3727     if (Result.isInvalid())
3728       return ExprError();
3729     LHSExp = Result.get();
3730   }
3731   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3732   if (Result.isInvalid())
3733     return ExprError();
3734   RHSExp = Result.get();
3735 
3736   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3737   ExprValueKind VK = VK_LValue;
3738   ExprObjectKind OK = OK_Ordinary;
3739 
3740   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3741   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3742   // in the subscript position. As a result, we need to derive the array base
3743   // and index from the expression types.
3744   Expr *BaseExpr, *IndexExpr;
3745   QualType ResultType;
3746   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3747     BaseExpr = LHSExp;
3748     IndexExpr = RHSExp;
3749     ResultType = Context.DependentTy;
3750   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3751     BaseExpr = LHSExp;
3752     IndexExpr = RHSExp;
3753     ResultType = PTy->getPointeeType();
3754   } else if (const ObjCObjectPointerType *PTy =
3755                LHSTy->getAs<ObjCObjectPointerType>()) {
3756     BaseExpr = LHSExp;
3757     IndexExpr = RHSExp;
3758 
3759     // Use custom logic if this should be the pseudo-object subscript
3760     // expression.
3761     if (!LangOpts.isSubscriptPointerArithmetic())
3762       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, nullptr,
3763                                           nullptr);
3764 
3765     ResultType = PTy->getPointeeType();
3766   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3767      // Handle the uncommon case of "123[Ptr]".
3768     BaseExpr = RHSExp;
3769     IndexExpr = LHSExp;
3770     ResultType = PTy->getPointeeType();
3771   } else if (const ObjCObjectPointerType *PTy =
3772                RHSTy->getAs<ObjCObjectPointerType>()) {
3773      // Handle the uncommon case of "123[Ptr]".
3774     BaseExpr = RHSExp;
3775     IndexExpr = LHSExp;
3776     ResultType = PTy->getPointeeType();
3777     if (!LangOpts.isSubscriptPointerArithmetic()) {
3778       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3779         << ResultType << BaseExpr->getSourceRange();
3780       return ExprError();
3781     }
3782   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3783     BaseExpr = LHSExp;    // vectors: V[123]
3784     IndexExpr = RHSExp;
3785     VK = LHSExp->getValueKind();
3786     if (VK != VK_RValue)
3787       OK = OK_VectorComponent;
3788 
3789     // FIXME: need to deal with const...
3790     ResultType = VTy->getElementType();
3791   } else if (LHSTy->isArrayType()) {
3792     // If we see an array that wasn't promoted by
3793     // DefaultFunctionArrayLvalueConversion, it must be an array that
3794     // wasn't promoted because of the C90 rule that doesn't
3795     // allow promoting non-lvalue arrays.  Warn, then
3796     // force the promotion here.
3797     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3798         LHSExp->getSourceRange();
3799     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3800                                CK_ArrayToPointerDecay).get();
3801     LHSTy = LHSExp->getType();
3802 
3803     BaseExpr = LHSExp;
3804     IndexExpr = RHSExp;
3805     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3806   } else if (RHSTy->isArrayType()) {
3807     // Same as previous, except for 123[f().a] case
3808     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3809         RHSExp->getSourceRange();
3810     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3811                                CK_ArrayToPointerDecay).get();
3812     RHSTy = RHSExp->getType();
3813 
3814     BaseExpr = RHSExp;
3815     IndexExpr = LHSExp;
3816     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3817   } else {
3818     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3819        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3820   }
3821   // C99 6.5.2.1p1
3822   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3823     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3824                      << IndexExpr->getSourceRange());
3825 
3826   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3827        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3828          && !IndexExpr->isTypeDependent())
3829     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3830 
3831   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3832   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3833   // type. Note that Functions are not objects, and that (in C99 parlance)
3834   // incomplete types are not object types.
3835   if (ResultType->isFunctionType()) {
3836     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3837       << ResultType << BaseExpr->getSourceRange();
3838     return ExprError();
3839   }
3840 
3841   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3842     // GNU extension: subscripting on pointer to void
3843     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3844       << BaseExpr->getSourceRange();
3845 
3846     // C forbids expressions of unqualified void type from being l-values.
3847     // See IsCForbiddenLValueType.
3848     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3849   } else if (!ResultType->isDependentType() &&
3850       RequireCompleteType(LLoc, ResultType,
3851                           diag::err_subscript_incomplete_type, BaseExpr))
3852     return ExprError();
3853 
3854   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3855          !ResultType.isCForbiddenLValueType());
3856 
3857   return new (Context)
3858       ArraySubscriptExpr(LHSExp, RHSExp, ResultType, VK, OK, RLoc);
3859 }
3860 
3861 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3862                                         FunctionDecl *FD,
3863                                         ParmVarDecl *Param) {
3864   if (Param->hasUnparsedDefaultArg()) {
3865     Diag(CallLoc,
3866          diag::err_use_of_default_argument_to_function_declared_later) <<
3867       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3868     Diag(UnparsedDefaultArgLocs[Param],
3869          diag::note_default_argument_declared_here);
3870     return ExprError();
3871   }
3872 
3873   if (Param->hasUninstantiatedDefaultArg()) {
3874     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3875 
3876     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3877                                                  Param);
3878 
3879     // Instantiate the expression.
3880     MultiLevelTemplateArgumentList MutiLevelArgList
3881       = getTemplateInstantiationArgs(FD, nullptr, /*RelativeToPrimary=*/true);
3882 
3883     InstantiatingTemplate Inst(*this, CallLoc, Param,
3884                                MutiLevelArgList.getInnermost());
3885     if (Inst.isInvalid())
3886       return ExprError();
3887 
3888     ExprResult Result;
3889     {
3890       // C++ [dcl.fct.default]p5:
3891       //   The names in the [default argument] expression are bound, and
3892       //   the semantic constraints are checked, at the point where the
3893       //   default argument expression appears.
3894       ContextRAII SavedContext(*this, FD);
3895       LocalInstantiationScope Local(*this);
3896       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3897     }
3898     if (Result.isInvalid())
3899       return ExprError();
3900 
3901     // Check the expression as an initializer for the parameter.
3902     InitializedEntity Entity
3903       = InitializedEntity::InitializeParameter(Context, Param);
3904     InitializationKind Kind
3905       = InitializationKind::CreateCopy(Param->getLocation(),
3906              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3907     Expr *ResultE = Result.getAs<Expr>();
3908 
3909     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3910     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3911     if (Result.isInvalid())
3912       return ExprError();
3913 
3914     Expr *Arg = Result.getAs<Expr>();
3915     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3916     // Build the default argument expression.
3917     return CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg);
3918   }
3919 
3920   // If the default expression creates temporaries, we need to
3921   // push them to the current stack of expression temporaries so they'll
3922   // be properly destroyed.
3923   // FIXME: We should really be rebuilding the default argument with new
3924   // bound temporaries; see the comment in PR5810.
3925   // We don't need to do that with block decls, though, because
3926   // blocks in default argument expression can never capture anything.
3927   if (isa<ExprWithCleanups>(Param->getInit())) {
3928     // Set the "needs cleanups" bit regardless of whether there are
3929     // any explicit objects.
3930     ExprNeedsCleanups = true;
3931 
3932     // Append all the objects to the cleanup list.  Right now, this
3933     // should always be a no-op, because blocks in default argument
3934     // expressions should never be able to capture anything.
3935     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3936            "default argument expression has capturing blocks?");
3937   }
3938 
3939   // We already type-checked the argument, so we know it works.
3940   // Just mark all of the declarations in this potentially-evaluated expression
3941   // as being "referenced".
3942   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3943                                    /*SkipLocalVariables=*/true);
3944   return CXXDefaultArgExpr::Create(Context, CallLoc, Param);
3945 }
3946 
3947 
3948 Sema::VariadicCallType
3949 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3950                           Expr *Fn) {
3951   if (Proto && Proto->isVariadic()) {
3952     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3953       return VariadicConstructor;
3954     else if (Fn && Fn->getType()->isBlockPointerType())
3955       return VariadicBlock;
3956     else if (FDecl) {
3957       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3958         if (Method->isInstance())
3959           return VariadicMethod;
3960     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3961       return VariadicMethod;
3962     return VariadicFunction;
3963   }
3964   return VariadicDoesNotApply;
3965 }
3966 
3967 namespace {
3968 class FunctionCallCCC : public FunctionCallFilterCCC {
3969 public:
3970   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3971                   unsigned NumArgs, MemberExpr *ME)
3972       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
3973         FunctionName(FuncName) {}
3974 
3975   bool ValidateCandidate(const TypoCorrection &candidate) override {
3976     if (!candidate.getCorrectionSpecifier() ||
3977         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3978       return false;
3979     }
3980 
3981     return FunctionCallFilterCCC::ValidateCandidate(candidate);
3982   }
3983 
3984 private:
3985   const IdentifierInfo *const FunctionName;
3986 };
3987 }
3988 
3989 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
3990                                                FunctionDecl *FDecl,
3991                                                ArrayRef<Expr *> Args) {
3992   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
3993   DeclarationName FuncName = FDecl->getDeclName();
3994   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
3995   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
3996 
3997   if (TypoCorrection Corrected = S.CorrectTypo(
3998           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
3999           S.getScopeForContext(S.CurContext), nullptr, CCC,
4000           Sema::CTK_ErrorRecovery)) {
4001     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4002       if (Corrected.isOverloaded()) {
4003         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4004         OverloadCandidateSet::iterator Best;
4005         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4006                                            CDEnd = Corrected.end();
4007              CD != CDEnd; ++CD) {
4008           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4009             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4010                                    OCS);
4011         }
4012         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4013         case OR_Success:
4014           ND = Best->Function;
4015           Corrected.setCorrectionDecl(ND);
4016           break;
4017         default:
4018           break;
4019         }
4020       }
4021       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4022         return Corrected;
4023       }
4024     }
4025   }
4026   return TypoCorrection();
4027 }
4028 
4029 /// ConvertArgumentsForCall - Converts the arguments specified in
4030 /// Args/NumArgs to the parameter types of the function FDecl with
4031 /// function prototype Proto. Call is the call expression itself, and
4032 /// Fn is the function expression. For a C++ member function, this
4033 /// routine does not attempt to convert the object argument. Returns
4034 /// true if the call is ill-formed.
4035 bool
4036 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4037                               FunctionDecl *FDecl,
4038                               const FunctionProtoType *Proto,
4039                               ArrayRef<Expr *> Args,
4040                               SourceLocation RParenLoc,
4041                               bool IsExecConfig) {
4042   // Bail out early if calling a builtin with custom typechecking.
4043   // We don't need to do this in the
4044   if (FDecl)
4045     if (unsigned ID = FDecl->getBuiltinID())
4046       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4047         return false;
4048 
4049   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4050   // assignment, to the types of the corresponding parameter, ...
4051   unsigned NumParams = Proto->getNumParams();
4052   bool Invalid = false;
4053   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4054   unsigned FnKind = Fn->getType()->isBlockPointerType()
4055                        ? 1 /* block */
4056                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4057                                        : 0 /* function */);
4058 
4059   // If too few arguments are available (and we don't have default
4060   // arguments for the remaining parameters), don't make the call.
4061   if (Args.size() < NumParams) {
4062     if (Args.size() < MinArgs) {
4063       TypoCorrection TC;
4064       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4065         unsigned diag_id =
4066             MinArgs == NumParams && !Proto->isVariadic()
4067                 ? diag::err_typecheck_call_too_few_args_suggest
4068                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4069         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4070                                         << static_cast<unsigned>(Args.size())
4071                                         << TC.getCorrectionRange());
4072       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4073         Diag(RParenLoc,
4074              MinArgs == NumParams && !Proto->isVariadic()
4075                  ? diag::err_typecheck_call_too_few_args_one
4076                  : diag::err_typecheck_call_too_few_args_at_least_one)
4077             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4078       else
4079         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4080                             ? diag::err_typecheck_call_too_few_args
4081                             : diag::err_typecheck_call_too_few_args_at_least)
4082             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4083             << Fn->getSourceRange();
4084 
4085       // Emit the location of the prototype.
4086       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4087         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4088           << FDecl;
4089 
4090       return true;
4091     }
4092     Call->setNumArgs(Context, NumParams);
4093   }
4094 
4095   // If too many are passed and not variadic, error on the extras and drop
4096   // them.
4097   if (Args.size() > NumParams) {
4098     if (!Proto->isVariadic()) {
4099       TypoCorrection TC;
4100       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4101         unsigned diag_id =
4102             MinArgs == NumParams && !Proto->isVariadic()
4103                 ? diag::err_typecheck_call_too_many_args_suggest
4104                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4105         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4106                                         << static_cast<unsigned>(Args.size())
4107                                         << TC.getCorrectionRange());
4108       } else if (NumParams == 1 && FDecl &&
4109                  FDecl->getParamDecl(0)->getDeclName())
4110         Diag(Args[NumParams]->getLocStart(),
4111              MinArgs == NumParams
4112                  ? diag::err_typecheck_call_too_many_args_one
4113                  : diag::err_typecheck_call_too_many_args_at_most_one)
4114             << FnKind << FDecl->getParamDecl(0)
4115             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4116             << SourceRange(Args[NumParams]->getLocStart(),
4117                            Args.back()->getLocEnd());
4118       else
4119         Diag(Args[NumParams]->getLocStart(),
4120              MinArgs == NumParams
4121                  ? diag::err_typecheck_call_too_many_args
4122                  : diag::err_typecheck_call_too_many_args_at_most)
4123             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4124             << Fn->getSourceRange()
4125             << SourceRange(Args[NumParams]->getLocStart(),
4126                            Args.back()->getLocEnd());
4127 
4128       // Emit the location of the prototype.
4129       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4130         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4131           << FDecl;
4132 
4133       // This deletes the extra arguments.
4134       Call->setNumArgs(Context, NumParams);
4135       return true;
4136     }
4137   }
4138   SmallVector<Expr *, 8> AllArgs;
4139   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4140 
4141   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4142                                    Proto, 0, Args, AllArgs, CallType);
4143   if (Invalid)
4144     return true;
4145   unsigned TotalNumArgs = AllArgs.size();
4146   for (unsigned i = 0; i < TotalNumArgs; ++i)
4147     Call->setArg(i, AllArgs[i]);
4148 
4149   return false;
4150 }
4151 
4152 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4153                                   const FunctionProtoType *Proto,
4154                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4155                                   SmallVectorImpl<Expr *> &AllArgs,
4156                                   VariadicCallType CallType, bool AllowExplicit,
4157                                   bool IsListInitialization) {
4158   unsigned NumParams = Proto->getNumParams();
4159   bool Invalid = false;
4160   unsigned ArgIx = 0;
4161   // Continue to check argument types (even if we have too few/many args).
4162   for (unsigned i = FirstParam; i < NumParams; i++) {
4163     QualType ProtoArgType = Proto->getParamType(i);
4164 
4165     Expr *Arg;
4166     ParmVarDecl *Param = FDecl ? FDecl->getParamDecl(i) : nullptr;
4167     if (ArgIx < Args.size()) {
4168       Arg = Args[ArgIx++];
4169 
4170       if (RequireCompleteType(Arg->getLocStart(),
4171                               ProtoArgType,
4172                               diag::err_call_incomplete_argument, Arg))
4173         return true;
4174 
4175       // Strip the unbridged-cast placeholder expression off, if applicable.
4176       bool CFAudited = false;
4177       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4178           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4179           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4180         Arg = stripARCUnbridgedCast(Arg);
4181       else if (getLangOpts().ObjCAutoRefCount &&
4182                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4183                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4184         CFAudited = true;
4185 
4186       InitializedEntity Entity =
4187           Param ? InitializedEntity::InitializeParameter(Context, Param,
4188                                                          ProtoArgType)
4189                 : InitializedEntity::InitializeParameter(
4190                       Context, ProtoArgType, Proto->isParamConsumed(i));
4191 
4192       // Remember that parameter belongs to a CF audited API.
4193       if (CFAudited)
4194         Entity.setParameterCFAudited();
4195 
4196       ExprResult ArgE = PerformCopyInitialization(
4197           Entity, SourceLocation(), Arg, IsListInitialization, AllowExplicit);
4198       if (ArgE.isInvalid())
4199         return true;
4200 
4201       Arg = ArgE.getAs<Expr>();
4202     } else {
4203       assert(Param && "can't use default arguments without a known callee");
4204 
4205       ExprResult ArgExpr =
4206         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4207       if (ArgExpr.isInvalid())
4208         return true;
4209 
4210       Arg = ArgExpr.getAs<Expr>();
4211     }
4212 
4213     // Check for array bounds violations for each argument to the call. This
4214     // check only triggers warnings when the argument isn't a more complex Expr
4215     // with its own checking, such as a BinaryOperator.
4216     CheckArrayAccess(Arg);
4217 
4218     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4219     CheckStaticArrayArgument(CallLoc, Param, Arg);
4220 
4221     AllArgs.push_back(Arg);
4222   }
4223 
4224   // If this is a variadic call, handle args passed through "...".
4225   if (CallType != VariadicDoesNotApply) {
4226     // Assume that extern "C" functions with variadic arguments that
4227     // return __unknown_anytype aren't *really* variadic.
4228     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4229         FDecl->isExternC()) {
4230       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4231         QualType paramType; // ignored
4232         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4233         Invalid |= arg.isInvalid();
4234         AllArgs.push_back(arg.get());
4235       }
4236 
4237     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4238     } else {
4239       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4240         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4241                                                           FDecl);
4242         Invalid |= Arg.isInvalid();
4243         AllArgs.push_back(Arg.get());
4244       }
4245     }
4246 
4247     // Check for array bounds violations.
4248     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4249       CheckArrayAccess(Args[i]);
4250   }
4251   return Invalid;
4252 }
4253 
4254 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4255   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4256   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4257     TL = DTL.getOriginalLoc();
4258   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4259     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4260       << ATL.getLocalSourceRange();
4261 }
4262 
4263 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4264 /// array parameter, check that it is non-null, and that if it is formed by
4265 /// array-to-pointer decay, the underlying array is sufficiently large.
4266 ///
4267 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4268 /// array type derivation, then for each call to the function, the value of the
4269 /// corresponding actual argument shall provide access to the first element of
4270 /// an array with at least as many elements as specified by the size expression.
4271 void
4272 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4273                                ParmVarDecl *Param,
4274                                const Expr *ArgExpr) {
4275   // Static array parameters are not supported in C++.
4276   if (!Param || getLangOpts().CPlusPlus)
4277     return;
4278 
4279   QualType OrigTy = Param->getOriginalType();
4280 
4281   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4282   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4283     return;
4284 
4285   if (ArgExpr->isNullPointerConstant(Context,
4286                                      Expr::NPC_NeverValueDependent)) {
4287     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4288     DiagnoseCalleeStaticArrayParam(*this, Param);
4289     return;
4290   }
4291 
4292   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4293   if (!CAT)
4294     return;
4295 
4296   const ConstantArrayType *ArgCAT =
4297     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4298   if (!ArgCAT)
4299     return;
4300 
4301   if (ArgCAT->getSize().ult(CAT->getSize())) {
4302     Diag(CallLoc, diag::warn_static_array_too_small)
4303       << ArgExpr->getSourceRange()
4304       << (unsigned) ArgCAT->getSize().getZExtValue()
4305       << (unsigned) CAT->getSize().getZExtValue();
4306     DiagnoseCalleeStaticArrayParam(*this, Param);
4307   }
4308 }
4309 
4310 /// Given a function expression of unknown-any type, try to rebuild it
4311 /// to have a function type.
4312 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4313 
4314 /// Is the given type a placeholder that we need to lower out
4315 /// immediately during argument processing?
4316 static bool isPlaceholderToRemoveAsArg(QualType type) {
4317   // Placeholders are never sugared.
4318   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4319   if (!placeholder) return false;
4320 
4321   switch (placeholder->getKind()) {
4322   // Ignore all the non-placeholder types.
4323 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4324 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4325 #include "clang/AST/BuiltinTypes.def"
4326     return false;
4327 
4328   // We cannot lower out overload sets; they might validly be resolved
4329   // by the call machinery.
4330   case BuiltinType::Overload:
4331     return false;
4332 
4333   // Unbridged casts in ARC can be handled in some call positions and
4334   // should be left in place.
4335   case BuiltinType::ARCUnbridgedCast:
4336     return false;
4337 
4338   // Pseudo-objects should be converted as soon as possible.
4339   case BuiltinType::PseudoObject:
4340     return true;
4341 
4342   // The debugger mode could theoretically but currently does not try
4343   // to resolve unknown-typed arguments based on known parameter types.
4344   case BuiltinType::UnknownAny:
4345     return true;
4346 
4347   // These are always invalid as call arguments and should be reported.
4348   case BuiltinType::BoundMember:
4349   case BuiltinType::BuiltinFn:
4350     return true;
4351   }
4352   llvm_unreachable("bad builtin type kind");
4353 }
4354 
4355 /// Check an argument list for placeholders that we won't try to
4356 /// handle later.
4357 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4358   // Apply this processing to all the arguments at once instead of
4359   // dying at the first failure.
4360   bool hasInvalid = false;
4361   for (size_t i = 0, e = args.size(); i != e; i++) {
4362     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4363       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4364       if (result.isInvalid()) hasInvalid = true;
4365       else args[i] = result.get();
4366     }
4367   }
4368   return hasInvalid;
4369 }
4370 
4371 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4372 /// This provides the location of the left/right parens and a list of comma
4373 /// locations.
4374 ExprResult
4375 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4376                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4377                     Expr *ExecConfig, bool IsExecConfig) {
4378   // Since this might be a postfix expression, get rid of ParenListExprs.
4379   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4380   if (Result.isInvalid()) return ExprError();
4381   Fn = Result.get();
4382 
4383   if (checkArgsForPlaceholders(*this, ArgExprs))
4384     return ExprError();
4385 
4386   if (getLangOpts().CPlusPlus) {
4387     // If this is a pseudo-destructor expression, build the call immediately.
4388     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4389       if (!ArgExprs.empty()) {
4390         // Pseudo-destructor calls should not have any arguments.
4391         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4392           << FixItHint::CreateRemoval(
4393                                     SourceRange(ArgExprs[0]->getLocStart(),
4394                                                 ArgExprs.back()->getLocEnd()));
4395       }
4396 
4397       return new (Context)
4398           CallExpr(Context, Fn, None, Context.VoidTy, VK_RValue, RParenLoc);
4399     }
4400     if (Fn->getType() == Context.PseudoObjectTy) {
4401       ExprResult result = CheckPlaceholderExpr(Fn);
4402       if (result.isInvalid()) return ExprError();
4403       Fn = result.get();
4404     }
4405 
4406     // Determine whether this is a dependent call inside a C++ template,
4407     // in which case we won't do any semantic analysis now.
4408     // FIXME: Will need to cache the results of name lookup (including ADL) in
4409     // Fn.
4410     bool Dependent = false;
4411     if (Fn->isTypeDependent())
4412       Dependent = true;
4413     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4414       Dependent = true;
4415 
4416     if (Dependent) {
4417       if (ExecConfig) {
4418         return new (Context) CUDAKernelCallExpr(
4419             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4420             Context.DependentTy, VK_RValue, RParenLoc);
4421       } else {
4422         return new (Context) CallExpr(
4423             Context, Fn, ArgExprs, Context.DependentTy, VK_RValue, RParenLoc);
4424       }
4425     }
4426 
4427     // Determine whether this is a call to an object (C++ [over.call.object]).
4428     if (Fn->getType()->isRecordType())
4429       return BuildCallToObjectOfClassType(S, Fn, LParenLoc, ArgExprs,
4430                                           RParenLoc);
4431 
4432     if (Fn->getType() == Context.UnknownAnyTy) {
4433       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4434       if (result.isInvalid()) return ExprError();
4435       Fn = result.get();
4436     }
4437 
4438     if (Fn->getType() == Context.BoundMemberTy) {
4439       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4440     }
4441   }
4442 
4443   // Check for overloaded calls.  This can happen even in C due to extensions.
4444   if (Fn->getType() == Context.OverloadTy) {
4445     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4446 
4447     // We aren't supposed to apply this logic for if there's an '&' involved.
4448     if (!find.HasFormOfMemberPointer) {
4449       OverloadExpr *ovl = find.Expression;
4450       if (isa<UnresolvedLookupExpr>(ovl)) {
4451         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4452         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4453                                        RParenLoc, ExecConfig);
4454       } else {
4455         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4456                                          RParenLoc);
4457       }
4458     }
4459   }
4460 
4461   // If we're directly calling a function, get the appropriate declaration.
4462   if (Fn->getType() == Context.UnknownAnyTy) {
4463     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4464     if (result.isInvalid()) return ExprError();
4465     Fn = result.get();
4466   }
4467 
4468   Expr *NakedFn = Fn->IgnoreParens();
4469 
4470   NamedDecl *NDecl = nullptr;
4471   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4472     if (UnOp->getOpcode() == UO_AddrOf)
4473       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4474 
4475   if (isa<DeclRefExpr>(NakedFn))
4476     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4477   else if (isa<MemberExpr>(NakedFn))
4478     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4479 
4480   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4481     if (FD->hasAttr<EnableIfAttr>()) {
4482       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4483         Diag(Fn->getLocStart(),
4484              isa<CXXMethodDecl>(FD) ?
4485                  diag::err_ovl_no_viable_member_function_in_call :
4486                  diag::err_ovl_no_viable_function_in_call)
4487           << FD << FD->getSourceRange();
4488         Diag(FD->getLocation(),
4489              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4490             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4491       }
4492     }
4493   }
4494 
4495   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4496                                ExecConfig, IsExecConfig);
4497 }
4498 
4499 ExprResult
4500 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4501                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4502   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4503   if (!ConfigDecl)
4504     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4505                           << "cudaConfigureCall");
4506   QualType ConfigQTy = ConfigDecl->getType();
4507 
4508   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4509       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4510   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4511 
4512   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, nullptr,
4513                        /*IsExecConfig=*/true);
4514 }
4515 
4516 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4517 ///
4518 /// __builtin_astype( value, dst type )
4519 ///
4520 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4521                                  SourceLocation BuiltinLoc,
4522                                  SourceLocation RParenLoc) {
4523   ExprValueKind VK = VK_RValue;
4524   ExprObjectKind OK = OK_Ordinary;
4525   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4526   QualType SrcTy = E->getType();
4527   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4528     return ExprError(Diag(BuiltinLoc,
4529                           diag::err_invalid_astype_of_different_size)
4530                      << DstTy
4531                      << SrcTy
4532                      << E->getSourceRange());
4533   return new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc, RParenLoc);
4534 }
4535 
4536 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4537 /// provided arguments.
4538 ///
4539 /// __builtin_convertvector( value, dst type )
4540 ///
4541 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4542                                         SourceLocation BuiltinLoc,
4543                                         SourceLocation RParenLoc) {
4544   TypeSourceInfo *TInfo;
4545   GetTypeFromParser(ParsedDestTy, &TInfo);
4546   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4547 }
4548 
4549 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4550 /// i.e. an expression not of \p OverloadTy.  The expression should
4551 /// unary-convert to an expression of function-pointer or
4552 /// block-pointer type.
4553 ///
4554 /// \param NDecl the declaration being called, if available
4555 ExprResult
4556 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4557                             SourceLocation LParenLoc,
4558                             ArrayRef<Expr *> Args,
4559                             SourceLocation RParenLoc,
4560                             Expr *Config, bool IsExecConfig) {
4561   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4562   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4563 
4564   // Promote the function operand.
4565   // We special-case function promotion here because we only allow promoting
4566   // builtin functions to function pointers in the callee of a call.
4567   ExprResult Result;
4568   if (BuiltinID &&
4569       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4570     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4571                                CK_BuiltinFnToFnPtr).get();
4572   } else {
4573     Result = CallExprUnaryConversions(Fn);
4574   }
4575   if (Result.isInvalid())
4576     return ExprError();
4577   Fn = Result.get();
4578 
4579   // Make the call expr early, before semantic checks.  This guarantees cleanup
4580   // of arguments and function on error.
4581   CallExpr *TheCall;
4582   if (Config)
4583     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4584                                                cast<CallExpr>(Config), Args,
4585                                                Context.BoolTy, VK_RValue,
4586                                                RParenLoc);
4587   else
4588     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4589                                      VK_RValue, RParenLoc);
4590 
4591   // Bail out early if calling a builtin with custom typechecking.
4592   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4593     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4594 
4595  retry:
4596   const FunctionType *FuncT;
4597   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4598     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4599     // have type pointer to function".
4600     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4601     if (!FuncT)
4602       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4603                          << Fn->getType() << Fn->getSourceRange());
4604   } else if (const BlockPointerType *BPT =
4605                Fn->getType()->getAs<BlockPointerType>()) {
4606     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4607   } else {
4608     // Handle calls to expressions of unknown-any type.
4609     if (Fn->getType() == Context.UnknownAnyTy) {
4610       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4611       if (rewrite.isInvalid()) return ExprError();
4612       Fn = rewrite.get();
4613       TheCall->setCallee(Fn);
4614       goto retry;
4615     }
4616 
4617     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4618       << Fn->getType() << Fn->getSourceRange());
4619   }
4620 
4621   if (getLangOpts().CUDA) {
4622     if (Config) {
4623       // CUDA: Kernel calls must be to global functions
4624       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4625         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4626             << FDecl->getName() << Fn->getSourceRange());
4627 
4628       // CUDA: Kernel function must have 'void' return type
4629       if (!FuncT->getReturnType()->isVoidType())
4630         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4631             << Fn->getType() << Fn->getSourceRange());
4632     } else {
4633       // CUDA: Calls to global functions must be configured
4634       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4635         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4636             << FDecl->getName() << Fn->getSourceRange());
4637     }
4638   }
4639 
4640   // Check for a valid return type
4641   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4642                           FDecl))
4643     return ExprError();
4644 
4645   // We know the result type of the call, set it.
4646   TheCall->setType(FuncT->getCallResultType(Context));
4647   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4648 
4649   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4650   if (Proto) {
4651     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4652                                 IsExecConfig))
4653       return ExprError();
4654   } else {
4655     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4656 
4657     if (FDecl) {
4658       // Check if we have too few/too many template arguments, based
4659       // on our knowledge of the function definition.
4660       const FunctionDecl *Def = nullptr;
4661       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4662         Proto = Def->getType()->getAs<FunctionProtoType>();
4663        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4664           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4665           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4666       }
4667 
4668       // If the function we're calling isn't a function prototype, but we have
4669       // a function prototype from a prior declaratiom, use that prototype.
4670       if (!FDecl->hasPrototype())
4671         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4672     }
4673 
4674     // Promote the arguments (C99 6.5.2.2p6).
4675     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4676       Expr *Arg = Args[i];
4677 
4678       if (Proto && i < Proto->getNumParams()) {
4679         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4680             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4681         ExprResult ArgE =
4682             PerformCopyInitialization(Entity, SourceLocation(), Arg);
4683         if (ArgE.isInvalid())
4684           return true;
4685 
4686         Arg = ArgE.getAs<Expr>();
4687 
4688       } else {
4689         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4690 
4691         if (ArgE.isInvalid())
4692           return true;
4693 
4694         Arg = ArgE.getAs<Expr>();
4695       }
4696 
4697       if (RequireCompleteType(Arg->getLocStart(),
4698                               Arg->getType(),
4699                               diag::err_call_incomplete_argument, Arg))
4700         return ExprError();
4701 
4702       TheCall->setArg(i, Arg);
4703     }
4704   }
4705 
4706   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4707     if (!Method->isStatic())
4708       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4709         << Fn->getSourceRange());
4710 
4711   // Check for sentinels
4712   if (NDecl)
4713     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4714 
4715   // Do special checking on direct calls to functions.
4716   if (FDecl) {
4717     if (CheckFunctionCall(FDecl, TheCall, Proto))
4718       return ExprError();
4719 
4720     if (BuiltinID)
4721       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4722   } else if (NDecl) {
4723     if (CheckPointerCall(NDecl, TheCall, Proto))
4724       return ExprError();
4725   } else {
4726     if (CheckOtherCall(TheCall, Proto))
4727       return ExprError();
4728   }
4729 
4730   return MaybeBindToTemporary(TheCall);
4731 }
4732 
4733 ExprResult
4734 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4735                            SourceLocation RParenLoc, Expr *InitExpr) {
4736   assert(Ty && "ActOnCompoundLiteral(): missing type");
4737   // FIXME: put back this assert when initializers are worked out.
4738   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4739 
4740   TypeSourceInfo *TInfo;
4741   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4742   if (!TInfo)
4743     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4744 
4745   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4746 }
4747 
4748 ExprResult
4749 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4750                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4751   QualType literalType = TInfo->getType();
4752 
4753   if (literalType->isArrayType()) {
4754     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4755           diag::err_illegal_decl_array_incomplete_type,
4756           SourceRange(LParenLoc,
4757                       LiteralExpr->getSourceRange().getEnd())))
4758       return ExprError();
4759     if (literalType->isVariableArrayType())
4760       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4761         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4762   } else if (!literalType->isDependentType() &&
4763              RequireCompleteType(LParenLoc, literalType,
4764                diag::err_typecheck_decl_incomplete_type,
4765                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4766     return ExprError();
4767 
4768   InitializedEntity Entity
4769     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4770   InitializationKind Kind
4771     = InitializationKind::CreateCStyleCast(LParenLoc,
4772                                            SourceRange(LParenLoc, RParenLoc),
4773                                            /*InitList=*/true);
4774   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4775   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4776                                       &literalType);
4777   if (Result.isInvalid())
4778     return ExprError();
4779   LiteralExpr = Result.get();
4780 
4781   bool isFileScope = getCurFunctionOrMethodDecl() == nullptr;
4782   if (isFileScope &&
4783       !LiteralExpr->isTypeDependent() &&
4784       !LiteralExpr->isValueDependent() &&
4785       !literalType->isDependentType()) { // 6.5.2.5p3
4786     if (CheckForConstantInitializer(LiteralExpr, literalType))
4787       return ExprError();
4788   }
4789 
4790   // In C, compound literals are l-values for some reason.
4791   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4792 
4793   return MaybeBindToTemporary(
4794            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4795                                              VK, LiteralExpr, isFileScope));
4796 }
4797 
4798 ExprResult
4799 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4800                     SourceLocation RBraceLoc) {
4801   // Immediately handle non-overload placeholders.  Overloads can be
4802   // resolved contextually, but everything else here can't.
4803   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4804     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4805       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4806 
4807       // Ignore failures; dropping the entire initializer list because
4808       // of one failure would be terrible for indexing/etc.
4809       if (result.isInvalid()) continue;
4810 
4811       InitArgList[I] = result.get();
4812     }
4813   }
4814 
4815   // Semantic analysis for initializers is done by ActOnDeclarator() and
4816   // CheckInitializer() - it requires knowledge of the object being intialized.
4817 
4818   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4819                                                RBraceLoc);
4820   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4821   return E;
4822 }
4823 
4824 /// Do an explicit extend of the given block pointer if we're in ARC.
4825 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4826   assert(E.get()->getType()->isBlockPointerType());
4827   assert(E.get()->isRValue());
4828 
4829   // Only do this in an r-value context.
4830   if (!S.getLangOpts().ObjCAutoRefCount) return;
4831 
4832   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4833                                CK_ARCExtendBlockObject, E.get(),
4834                                /*base path*/ nullptr, VK_RValue);
4835   S.ExprNeedsCleanups = true;
4836 }
4837 
4838 /// Prepare a conversion of the given expression to an ObjC object
4839 /// pointer type.
4840 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4841   QualType type = E.get()->getType();
4842   if (type->isObjCObjectPointerType()) {
4843     return CK_BitCast;
4844   } else if (type->isBlockPointerType()) {
4845     maybeExtendBlockObject(*this, E);
4846     return CK_BlockPointerToObjCPointerCast;
4847   } else {
4848     assert(type->isPointerType());
4849     return CK_CPointerToObjCPointerCast;
4850   }
4851 }
4852 
4853 /// Prepares for a scalar cast, performing all the necessary stages
4854 /// except the final cast and returning the kind required.
4855 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4856   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4857   // Also, callers should have filtered out the invalid cases with
4858   // pointers.  Everything else should be possible.
4859 
4860   QualType SrcTy = Src.get()->getType();
4861   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4862     return CK_NoOp;
4863 
4864   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4865   case Type::STK_MemberPointer:
4866     llvm_unreachable("member pointer type in C");
4867 
4868   case Type::STK_CPointer:
4869   case Type::STK_BlockPointer:
4870   case Type::STK_ObjCObjectPointer:
4871     switch (DestTy->getScalarTypeKind()) {
4872     case Type::STK_CPointer: {
4873       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4874       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4875       if (SrcAS != DestAS)
4876         return CK_AddressSpaceConversion;
4877       return CK_BitCast;
4878     }
4879     case Type::STK_BlockPointer:
4880       return (SrcKind == Type::STK_BlockPointer
4881                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4882     case Type::STK_ObjCObjectPointer:
4883       if (SrcKind == Type::STK_ObjCObjectPointer)
4884         return CK_BitCast;
4885       if (SrcKind == Type::STK_CPointer)
4886         return CK_CPointerToObjCPointerCast;
4887       maybeExtendBlockObject(*this, Src);
4888       return CK_BlockPointerToObjCPointerCast;
4889     case Type::STK_Bool:
4890       return CK_PointerToBoolean;
4891     case Type::STK_Integral:
4892       return CK_PointerToIntegral;
4893     case Type::STK_Floating:
4894     case Type::STK_FloatingComplex:
4895     case Type::STK_IntegralComplex:
4896     case Type::STK_MemberPointer:
4897       llvm_unreachable("illegal cast from pointer");
4898     }
4899     llvm_unreachable("Should have returned before this");
4900 
4901   case Type::STK_Bool: // casting from bool is like casting from an integer
4902   case Type::STK_Integral:
4903     switch (DestTy->getScalarTypeKind()) {
4904     case Type::STK_CPointer:
4905     case Type::STK_ObjCObjectPointer:
4906     case Type::STK_BlockPointer:
4907       if (Src.get()->isNullPointerConstant(Context,
4908                                            Expr::NPC_ValueDependentIsNull))
4909         return CK_NullToPointer;
4910       return CK_IntegralToPointer;
4911     case Type::STK_Bool:
4912       return CK_IntegralToBoolean;
4913     case Type::STK_Integral:
4914       return CK_IntegralCast;
4915     case Type::STK_Floating:
4916       return CK_IntegralToFloating;
4917     case Type::STK_IntegralComplex:
4918       Src = ImpCastExprToType(Src.get(),
4919                               DestTy->castAs<ComplexType>()->getElementType(),
4920                               CK_IntegralCast);
4921       return CK_IntegralRealToComplex;
4922     case Type::STK_FloatingComplex:
4923       Src = ImpCastExprToType(Src.get(),
4924                               DestTy->castAs<ComplexType>()->getElementType(),
4925                               CK_IntegralToFloating);
4926       return CK_FloatingRealToComplex;
4927     case Type::STK_MemberPointer:
4928       llvm_unreachable("member pointer type in C");
4929     }
4930     llvm_unreachable("Should have returned before this");
4931 
4932   case Type::STK_Floating:
4933     switch (DestTy->getScalarTypeKind()) {
4934     case Type::STK_Floating:
4935       return CK_FloatingCast;
4936     case Type::STK_Bool:
4937       return CK_FloatingToBoolean;
4938     case Type::STK_Integral:
4939       return CK_FloatingToIntegral;
4940     case Type::STK_FloatingComplex:
4941       Src = ImpCastExprToType(Src.get(),
4942                               DestTy->castAs<ComplexType>()->getElementType(),
4943                               CK_FloatingCast);
4944       return CK_FloatingRealToComplex;
4945     case Type::STK_IntegralComplex:
4946       Src = ImpCastExprToType(Src.get(),
4947                               DestTy->castAs<ComplexType>()->getElementType(),
4948                               CK_FloatingToIntegral);
4949       return CK_IntegralRealToComplex;
4950     case Type::STK_CPointer:
4951     case Type::STK_ObjCObjectPointer:
4952     case Type::STK_BlockPointer:
4953       llvm_unreachable("valid float->pointer cast?");
4954     case Type::STK_MemberPointer:
4955       llvm_unreachable("member pointer type in C");
4956     }
4957     llvm_unreachable("Should have returned before this");
4958 
4959   case Type::STK_FloatingComplex:
4960     switch (DestTy->getScalarTypeKind()) {
4961     case Type::STK_FloatingComplex:
4962       return CK_FloatingComplexCast;
4963     case Type::STK_IntegralComplex:
4964       return CK_FloatingComplexToIntegralComplex;
4965     case Type::STK_Floating: {
4966       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4967       if (Context.hasSameType(ET, DestTy))
4968         return CK_FloatingComplexToReal;
4969       Src = ImpCastExprToType(Src.get(), ET, CK_FloatingComplexToReal);
4970       return CK_FloatingCast;
4971     }
4972     case Type::STK_Bool:
4973       return CK_FloatingComplexToBoolean;
4974     case Type::STK_Integral:
4975       Src = ImpCastExprToType(Src.get(),
4976                               SrcTy->castAs<ComplexType>()->getElementType(),
4977                               CK_FloatingComplexToReal);
4978       return CK_FloatingToIntegral;
4979     case Type::STK_CPointer:
4980     case Type::STK_ObjCObjectPointer:
4981     case Type::STK_BlockPointer:
4982       llvm_unreachable("valid complex float->pointer cast?");
4983     case Type::STK_MemberPointer:
4984       llvm_unreachable("member pointer type in C");
4985     }
4986     llvm_unreachable("Should have returned before this");
4987 
4988   case Type::STK_IntegralComplex:
4989     switch (DestTy->getScalarTypeKind()) {
4990     case Type::STK_FloatingComplex:
4991       return CK_IntegralComplexToFloatingComplex;
4992     case Type::STK_IntegralComplex:
4993       return CK_IntegralComplexCast;
4994     case Type::STK_Integral: {
4995       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4996       if (Context.hasSameType(ET, DestTy))
4997         return CK_IntegralComplexToReal;
4998       Src = ImpCastExprToType(Src.get(), ET, CK_IntegralComplexToReal);
4999       return CK_IntegralCast;
5000     }
5001     case Type::STK_Bool:
5002       return CK_IntegralComplexToBoolean;
5003     case Type::STK_Floating:
5004       Src = ImpCastExprToType(Src.get(),
5005                               SrcTy->castAs<ComplexType>()->getElementType(),
5006                               CK_IntegralComplexToReal);
5007       return CK_IntegralToFloating;
5008     case Type::STK_CPointer:
5009     case Type::STK_ObjCObjectPointer:
5010     case Type::STK_BlockPointer:
5011       llvm_unreachable("valid complex int->pointer cast?");
5012     case Type::STK_MemberPointer:
5013       llvm_unreachable("member pointer type in C");
5014     }
5015     llvm_unreachable("Should have returned before this");
5016   }
5017 
5018   llvm_unreachable("Unhandled scalar cast");
5019 }
5020 
5021 static bool breakDownVectorType(QualType type, uint64_t &len,
5022                                 QualType &eltType) {
5023   // Vectors are simple.
5024   if (const VectorType *vecType = type->getAs<VectorType>()) {
5025     len = vecType->getNumElements();
5026     eltType = vecType->getElementType();
5027     assert(eltType->isScalarType());
5028     return true;
5029   }
5030 
5031   // We allow lax conversion to and from non-vector types, but only if
5032   // they're real types (i.e. non-complex, non-pointer scalar types).
5033   if (!type->isRealType()) return false;
5034 
5035   len = 1;
5036   eltType = type;
5037   return true;
5038 }
5039 
5040 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5041   uint64_t srcLen, destLen;
5042   QualType srcElt, destElt;
5043   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5044   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5045 
5046   // ASTContext::getTypeSize will return the size rounded up to a
5047   // power of 2, so instead of using that, we need to use the raw
5048   // element size multiplied by the element count.
5049   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5050   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5051 
5052   return (srcLen * srcEltSize == destLen * destEltSize);
5053 }
5054 
5055 /// Is this a legal conversion between two known vector types?
5056 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5057   assert(destTy->isVectorType() || srcTy->isVectorType());
5058 
5059   if (!Context.getLangOpts().LaxVectorConversions)
5060     return false;
5061   return VectorTypesMatch(*this, srcTy, destTy);
5062 }
5063 
5064 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5065                            CastKind &Kind) {
5066   assert(VectorTy->isVectorType() && "Not a vector type!");
5067 
5068   if (Ty->isVectorType() || Ty->isIntegerType()) {
5069     if (!VectorTypesMatch(*this, Ty, VectorTy))
5070       return Diag(R.getBegin(),
5071                   Ty->isVectorType() ?
5072                   diag::err_invalid_conversion_between_vectors :
5073                   diag::err_invalid_conversion_between_vector_and_integer)
5074         << VectorTy << Ty << R;
5075   } else
5076     return Diag(R.getBegin(),
5077                 diag::err_invalid_conversion_between_vector_and_scalar)
5078       << VectorTy << Ty << R;
5079 
5080   Kind = CK_BitCast;
5081   return false;
5082 }
5083 
5084 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5085                                     Expr *CastExpr, CastKind &Kind) {
5086   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5087 
5088   QualType SrcTy = CastExpr->getType();
5089 
5090   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5091   // an ExtVectorType.
5092   // In OpenCL, casts between vectors of different types are not allowed.
5093   // (See OpenCL 6.2).
5094   if (SrcTy->isVectorType()) {
5095     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5096         || (getLangOpts().OpenCL &&
5097             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5098       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5099         << DestTy << SrcTy << R;
5100       return ExprError();
5101     }
5102     Kind = CK_BitCast;
5103     return CastExpr;
5104   }
5105 
5106   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5107   // conversion will take place first from scalar to elt type, and then
5108   // splat from elt type to vector.
5109   if (SrcTy->isPointerType())
5110     return Diag(R.getBegin(),
5111                 diag::err_invalid_conversion_between_vector_and_scalar)
5112       << DestTy << SrcTy << R;
5113 
5114   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5115   ExprResult CastExprRes = CastExpr;
5116   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5117   if (CastExprRes.isInvalid())
5118     return ExprError();
5119   CastExpr = ImpCastExprToType(CastExprRes.get(), DestElemTy, CK).get();
5120 
5121   Kind = CK_VectorSplat;
5122   return CastExpr;
5123 }
5124 
5125 ExprResult
5126 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5127                     Declarator &D, ParsedType &Ty,
5128                     SourceLocation RParenLoc, Expr *CastExpr) {
5129   assert(!D.isInvalidType() && (CastExpr != nullptr) &&
5130          "ActOnCastExpr(): missing type or expr");
5131 
5132   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5133   if (D.isInvalidType())
5134     return ExprError();
5135 
5136   if (getLangOpts().CPlusPlus) {
5137     // Check that there are no default arguments (C++ only).
5138     CheckExtraCXXDefaultArguments(D);
5139   }
5140 
5141   checkUnusedDeclAttributes(D);
5142 
5143   QualType castType = castTInfo->getType();
5144   Ty = CreateParsedType(castType, castTInfo);
5145 
5146   bool isVectorLiteral = false;
5147 
5148   // Check for an altivec or OpenCL literal,
5149   // i.e. all the elements are integer constants.
5150   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5151   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5152   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5153        && castType->isVectorType() && (PE || PLE)) {
5154     if (PLE && PLE->getNumExprs() == 0) {
5155       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5156       return ExprError();
5157     }
5158     if (PE || PLE->getNumExprs() == 1) {
5159       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5160       if (!E->getType()->isVectorType())
5161         isVectorLiteral = true;
5162     }
5163     else
5164       isVectorLiteral = true;
5165   }
5166 
5167   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5168   // then handle it as such.
5169   if (isVectorLiteral)
5170     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5171 
5172   // If the Expr being casted is a ParenListExpr, handle it specially.
5173   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5174   // sequence of BinOp comma operators.
5175   if (isa<ParenListExpr>(CastExpr)) {
5176     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5177     if (Result.isInvalid()) return ExprError();
5178     CastExpr = Result.get();
5179   }
5180 
5181   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5182       !getSourceManager().isInSystemMacro(LParenLoc))
5183     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5184 
5185   CheckTollFreeBridgeCast(castType, CastExpr);
5186 
5187   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5188 }
5189 
5190 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5191                                     SourceLocation RParenLoc, Expr *E,
5192                                     TypeSourceInfo *TInfo) {
5193   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5194          "Expected paren or paren list expression");
5195 
5196   Expr **exprs;
5197   unsigned numExprs;
5198   Expr *subExpr;
5199   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5200   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5201     LiteralLParenLoc = PE->getLParenLoc();
5202     LiteralRParenLoc = PE->getRParenLoc();
5203     exprs = PE->getExprs();
5204     numExprs = PE->getNumExprs();
5205   } else { // isa<ParenExpr> by assertion at function entrance
5206     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5207     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5208     subExpr = cast<ParenExpr>(E)->getSubExpr();
5209     exprs = &subExpr;
5210     numExprs = 1;
5211   }
5212 
5213   QualType Ty = TInfo->getType();
5214   assert(Ty->isVectorType() && "Expected vector type");
5215 
5216   SmallVector<Expr *, 8> initExprs;
5217   const VectorType *VTy = Ty->getAs<VectorType>();
5218   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5219 
5220   // '(...)' form of vector initialization in AltiVec: the number of
5221   // initializers must be one or must match the size of the vector.
5222   // If a single value is specified in the initializer then it will be
5223   // replicated to all the components of the vector
5224   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5225     // The number of initializers must be one or must match the size of the
5226     // vector. If a single value is specified in the initializer then it will
5227     // be replicated to all the components of the vector
5228     if (numExprs == 1) {
5229       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5230       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5231       if (Literal.isInvalid())
5232         return ExprError();
5233       Literal = ImpCastExprToType(Literal.get(), ElemTy,
5234                                   PrepareScalarCast(Literal, ElemTy));
5235       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5236     }
5237     else if (numExprs < numElems) {
5238       Diag(E->getExprLoc(),
5239            diag::err_incorrect_number_of_vector_initializers);
5240       return ExprError();
5241     }
5242     else
5243       initExprs.append(exprs, exprs + numExprs);
5244   }
5245   else {
5246     // For OpenCL, when the number of initializers is a single value,
5247     // it will be replicated to all components of the vector.
5248     if (getLangOpts().OpenCL &&
5249         VTy->getVectorKind() == VectorType::GenericVector &&
5250         numExprs == 1) {
5251         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5252         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5253         if (Literal.isInvalid())
5254           return ExprError();
5255         Literal = ImpCastExprToType(Literal.get(), ElemTy,
5256                                     PrepareScalarCast(Literal, ElemTy));
5257         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.get());
5258     }
5259 
5260     initExprs.append(exprs, exprs + numExprs);
5261   }
5262   // FIXME: This means that pretty-printing the final AST will produce curly
5263   // braces instead of the original commas.
5264   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5265                                                    initExprs, LiteralRParenLoc);
5266   initE->setType(Ty);
5267   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5268 }
5269 
5270 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5271 /// the ParenListExpr into a sequence of comma binary operators.
5272 ExprResult
5273 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5274   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5275   if (!E)
5276     return OrigExpr;
5277 
5278   ExprResult Result(E->getExpr(0));
5279 
5280   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5281     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5282                         E->getExpr(i));
5283 
5284   if (Result.isInvalid()) return ExprError();
5285 
5286   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5287 }
5288 
5289 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5290                                     SourceLocation R,
5291                                     MultiExprArg Val) {
5292   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5293   return expr;
5294 }
5295 
5296 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5297 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5298 /// emitted.
5299 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5300                                       SourceLocation QuestionLoc) {
5301   Expr *NullExpr = LHSExpr;
5302   Expr *NonPointerExpr = RHSExpr;
5303   Expr::NullPointerConstantKind NullKind =
5304       NullExpr->isNullPointerConstant(Context,
5305                                       Expr::NPC_ValueDependentIsNotNull);
5306 
5307   if (NullKind == Expr::NPCK_NotNull) {
5308     NullExpr = RHSExpr;
5309     NonPointerExpr = LHSExpr;
5310     NullKind =
5311         NullExpr->isNullPointerConstant(Context,
5312                                         Expr::NPC_ValueDependentIsNotNull);
5313   }
5314 
5315   if (NullKind == Expr::NPCK_NotNull)
5316     return false;
5317 
5318   if (NullKind == Expr::NPCK_ZeroExpression)
5319     return false;
5320 
5321   if (NullKind == Expr::NPCK_ZeroLiteral) {
5322     // In this case, check to make sure that we got here from a "NULL"
5323     // string in the source code.
5324     NullExpr = NullExpr->IgnoreParenImpCasts();
5325     SourceLocation loc = NullExpr->getExprLoc();
5326     if (!findMacroSpelling(loc, "NULL"))
5327       return false;
5328   }
5329 
5330   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5331   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5332       << NonPointerExpr->getType() << DiagType
5333       << NonPointerExpr->getSourceRange();
5334   return true;
5335 }
5336 
5337 /// \brief Return false if the condition expression is valid, true otherwise.
5338 static bool checkCondition(Sema &S, Expr *Cond) {
5339   QualType CondTy = Cond->getType();
5340 
5341   // C99 6.5.15p2
5342   if (CondTy->isScalarType()) return false;
5343 
5344   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5345   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5346     return false;
5347 
5348   // Emit the proper error message.
5349   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5350                               diag::err_typecheck_cond_expect_scalar :
5351                               diag::err_typecheck_cond_expect_scalar_or_vector)
5352     << CondTy;
5353   return true;
5354 }
5355 
5356 /// \brief Return false if the two expressions can be converted to a vector,
5357 /// true otherwise
5358 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5359                                                     ExprResult &RHS,
5360                                                     QualType CondTy) {
5361   // Both operands should be of scalar type.
5362   if (!LHS.get()->getType()->isScalarType()) {
5363     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5364       << CondTy;
5365     return true;
5366   }
5367   if (!RHS.get()->getType()->isScalarType()) {
5368     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5369       << CondTy;
5370     return true;
5371   }
5372 
5373   // Implicity convert these scalars to the type of the condition.
5374   LHS = S.ImpCastExprToType(LHS.get(), CondTy, CK_IntegralCast);
5375   RHS = S.ImpCastExprToType(RHS.get(), CondTy, CK_IntegralCast);
5376   return false;
5377 }
5378 
5379 /// \brief Handle when one or both operands are void type.
5380 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5381                                          ExprResult &RHS) {
5382     Expr *LHSExpr = LHS.get();
5383     Expr *RHSExpr = RHS.get();
5384 
5385     if (!LHSExpr->getType()->isVoidType())
5386       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5387         << RHSExpr->getSourceRange();
5388     if (!RHSExpr->getType()->isVoidType())
5389       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5390         << LHSExpr->getSourceRange();
5391     LHS = S.ImpCastExprToType(LHS.get(), S.Context.VoidTy, CK_ToVoid);
5392     RHS = S.ImpCastExprToType(RHS.get(), S.Context.VoidTy, CK_ToVoid);
5393     return S.Context.VoidTy;
5394 }
5395 
5396 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5397 /// true otherwise.
5398 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5399                                         QualType PointerTy) {
5400   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5401       !NullExpr.get()->isNullPointerConstant(S.Context,
5402                                             Expr::NPC_ValueDependentIsNull))
5403     return true;
5404 
5405   NullExpr = S.ImpCastExprToType(NullExpr.get(), PointerTy, CK_NullToPointer);
5406   return false;
5407 }
5408 
5409 /// \brief Checks compatibility between two pointers and return the resulting
5410 /// type.
5411 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5412                                                      ExprResult &RHS,
5413                                                      SourceLocation Loc) {
5414   QualType LHSTy = LHS.get()->getType();
5415   QualType RHSTy = RHS.get()->getType();
5416 
5417   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5418     // Two identical pointers types are always compatible.
5419     return LHSTy;
5420   }
5421 
5422   QualType lhptee, rhptee;
5423 
5424   // Get the pointee types.
5425   bool IsBlockPointer = false;
5426   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5427     lhptee = LHSBTy->getPointeeType();
5428     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5429     IsBlockPointer = true;
5430   } else {
5431     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5432     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5433   }
5434 
5435   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5436   // differently qualified versions of compatible types, the result type is
5437   // a pointer to an appropriately qualified version of the composite
5438   // type.
5439 
5440   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5441   // clause doesn't make sense for our extensions. E.g. address space 2 should
5442   // be incompatible with address space 3: they may live on different devices or
5443   // anything.
5444   Qualifiers lhQual = lhptee.getQualifiers();
5445   Qualifiers rhQual = rhptee.getQualifiers();
5446 
5447   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5448   lhQual.removeCVRQualifiers();
5449   rhQual.removeCVRQualifiers();
5450 
5451   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5452   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5453 
5454   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5455 
5456   if (CompositeTy.isNull()) {
5457     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5458       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5459       << RHS.get()->getSourceRange();
5460     // In this situation, we assume void* type. No especially good
5461     // reason, but this is what gcc does, and we do have to pick
5462     // to get a consistent AST.
5463     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5464     LHS = S.ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5465     RHS = S.ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5466     return incompatTy;
5467   }
5468 
5469   // The pointer types are compatible.
5470   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5471   if (IsBlockPointer)
5472     ResultTy = S.Context.getBlockPointerType(ResultTy);
5473   else
5474     ResultTy = S.Context.getPointerType(ResultTy);
5475 
5476   LHS = S.ImpCastExprToType(LHS.get(), ResultTy, CK_BitCast);
5477   RHS = S.ImpCastExprToType(RHS.get(), ResultTy, CK_BitCast);
5478   return ResultTy;
5479 }
5480 
5481 /// \brief Returns true if QT is quelified-id and implements 'NSObject' and/or
5482 /// 'NSCopying' protocols (and nothing else); or QT is an NSObject and optionally
5483 /// implements 'NSObject' and/or NSCopying' protocols (and nothing else).
5484 static bool isObjCPtrBlockCompatible(Sema &S, ASTContext &C, QualType QT) {
5485   if (QT->isObjCIdType())
5486     return true;
5487 
5488   const ObjCObjectPointerType *OPT = QT->getAs<ObjCObjectPointerType>();
5489   if (!OPT)
5490     return false;
5491 
5492   if (ObjCInterfaceDecl *ID = OPT->getInterfaceDecl())
5493     if (ID->getIdentifier() != &C.Idents.get("NSObject"))
5494       return false;
5495 
5496   ObjCProtocolDecl* PNSCopying =
5497     S.LookupProtocol(&C.Idents.get("NSCopying"), SourceLocation());
5498   ObjCProtocolDecl* PNSObject =
5499     S.LookupProtocol(&C.Idents.get("NSObject"), SourceLocation());
5500 
5501   for (auto *Proto : OPT->quals()) {
5502     if ((PNSCopying && declaresSameEntity(Proto, PNSCopying)) ||
5503         (PNSObject && declaresSameEntity(Proto, PNSObject)))
5504       ;
5505     else
5506       return false;
5507   }
5508   return true;
5509 }
5510 
5511 /// \brief Return the resulting type when the operands are both block pointers.
5512 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5513                                                           ExprResult &LHS,
5514                                                           ExprResult &RHS,
5515                                                           SourceLocation Loc) {
5516   QualType LHSTy = LHS.get()->getType();
5517   QualType RHSTy = RHS.get()->getType();
5518 
5519   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5520     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5521       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5522       LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5523       RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5524       return destType;
5525     }
5526     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5527       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5528       << RHS.get()->getSourceRange();
5529     return QualType();
5530   }
5531 
5532   // We have 2 block pointer types.
5533   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5534 }
5535 
5536 /// \brief Return the resulting type when the operands are both pointers.
5537 static QualType
5538 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5539                                             ExprResult &RHS,
5540                                             SourceLocation Loc) {
5541   // get the pointer types
5542   QualType LHSTy = LHS.get()->getType();
5543   QualType RHSTy = RHS.get()->getType();
5544 
5545   // get the "pointed to" types
5546   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5547   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5548 
5549   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5550   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5551     // Figure out necessary qualifiers (C99 6.5.15p6)
5552     QualType destPointee
5553       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5554     QualType destType = S.Context.getPointerType(destPointee);
5555     // Add qualifiers if necessary.
5556     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5557     // Promote to void*.
5558     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5559     return destType;
5560   }
5561   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5562     QualType destPointee
5563       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5564     QualType destType = S.Context.getPointerType(destPointee);
5565     // Add qualifiers if necessary.
5566     RHS = S.ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5567     // Promote to void*.
5568     LHS = S.ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5569     return destType;
5570   }
5571 
5572   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5573 }
5574 
5575 /// \brief Return false if the first expression is not an integer and the second
5576 /// expression is not a pointer, true otherwise.
5577 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5578                                         Expr* PointerExpr, SourceLocation Loc,
5579                                         bool IsIntFirstExpr) {
5580   if (!PointerExpr->getType()->isPointerType() ||
5581       !Int.get()->getType()->isIntegerType())
5582     return false;
5583 
5584   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5585   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5586 
5587   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5588     << Expr1->getType() << Expr2->getType()
5589     << Expr1->getSourceRange() << Expr2->getSourceRange();
5590   Int = S.ImpCastExprToType(Int.get(), PointerExpr->getType(),
5591                             CK_IntegralToPointer);
5592   return true;
5593 }
5594 
5595 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5596 /// In that case, LHS = cond.
5597 /// C99 6.5.15
5598 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5599                                         ExprResult &RHS, ExprValueKind &VK,
5600                                         ExprObjectKind &OK,
5601                                         SourceLocation QuestionLoc) {
5602 
5603   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5604   if (!LHSResult.isUsable()) return QualType();
5605   LHS = LHSResult;
5606 
5607   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5608   if (!RHSResult.isUsable()) return QualType();
5609   RHS = RHSResult;
5610 
5611   // C++ is sufficiently different to merit its own checker.
5612   if (getLangOpts().CPlusPlus)
5613     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5614 
5615   VK = VK_RValue;
5616   OK = OK_Ordinary;
5617 
5618   // First, check the condition.
5619   Cond = UsualUnaryConversions(Cond.get());
5620   if (Cond.isInvalid())
5621     return QualType();
5622   if (checkCondition(*this, Cond.get()))
5623     return QualType();
5624 
5625   // Now check the two expressions.
5626   if (LHS.get()->getType()->isVectorType() ||
5627       RHS.get()->getType()->isVectorType())
5628     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5629 
5630   UsualArithmeticConversions(LHS, RHS);
5631   if (LHS.isInvalid() || RHS.isInvalid())
5632     return QualType();
5633 
5634   QualType CondTy = Cond.get()->getType();
5635   QualType LHSTy = LHS.get()->getType();
5636   QualType RHSTy = RHS.get()->getType();
5637 
5638   // If the condition is a vector, and both operands are scalar,
5639   // attempt to implicity convert them to the vector type to act like the
5640   // built in select. (OpenCL v1.1 s6.3.i)
5641   if (getLangOpts().OpenCL && CondTy->isVectorType())
5642     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5643       return QualType();
5644 
5645   // If both operands have arithmetic type, do the usual arithmetic conversions
5646   // to find a common type: C99 6.5.15p3,5.
5647   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5648     return LHS.get()->getType();
5649 
5650   // If both operands are the same structure or union type, the result is that
5651   // type.
5652   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5653     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5654       if (LHSRT->getDecl() == RHSRT->getDecl())
5655         // "If both the operands have structure or union type, the result has
5656         // that type."  This implies that CV qualifiers are dropped.
5657         return LHSTy.getUnqualifiedType();
5658     // FIXME: Type of conditional expression must be complete in C mode.
5659   }
5660 
5661   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5662   // The following || allows only one side to be void (a GCC-ism).
5663   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5664     return checkConditionalVoidType(*this, LHS, RHS);
5665   }
5666 
5667   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5668   // the type of the other operand."
5669   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5670   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5671 
5672   // All objective-c pointer type analysis is done here.
5673   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5674                                                         QuestionLoc);
5675   if (LHS.isInvalid() || RHS.isInvalid())
5676     return QualType();
5677   if (!compositeType.isNull())
5678     return compositeType;
5679 
5680 
5681   // Handle block pointer types.
5682   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5683     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5684                                                      QuestionLoc);
5685 
5686   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5687   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5688     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5689                                                        QuestionLoc);
5690 
5691   // GCC compatibility: soften pointer/integer mismatch.  Note that
5692   // null pointers have been filtered out by this point.
5693   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5694       /*isIntFirstExpr=*/true))
5695     return RHSTy;
5696   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5697       /*isIntFirstExpr=*/false))
5698     return LHSTy;
5699 
5700   // Emit a better diagnostic if one of the expressions is a null pointer
5701   // constant and the other is not a pointer type. In this case, the user most
5702   // likely forgot to take the address of the other expression.
5703   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5704     return QualType();
5705 
5706   // Otherwise, the operands are not compatible.
5707   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5708     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5709     << RHS.get()->getSourceRange();
5710   return QualType();
5711 }
5712 
5713 /// FindCompositeObjCPointerType - Helper method to find composite type of
5714 /// two objective-c pointer types of the two input expressions.
5715 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5716                                             SourceLocation QuestionLoc) {
5717   QualType LHSTy = LHS.get()->getType();
5718   QualType RHSTy = RHS.get()->getType();
5719 
5720   // Handle things like Class and struct objc_class*.  Here we case the result
5721   // to the pseudo-builtin, because that will be implicitly cast back to the
5722   // redefinition type if an attempt is made to access its fields.
5723   if (LHSTy->isObjCClassType() &&
5724       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5725     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5726     return LHSTy;
5727   }
5728   if (RHSTy->isObjCClassType() &&
5729       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5730     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5731     return RHSTy;
5732   }
5733   // And the same for struct objc_object* / id
5734   if (LHSTy->isObjCIdType() &&
5735       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5736     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_CPointerToObjCPointerCast);
5737     return LHSTy;
5738   }
5739   if (RHSTy->isObjCIdType() &&
5740       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5741     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_CPointerToObjCPointerCast);
5742     return RHSTy;
5743   }
5744   // And the same for struct objc_selector* / SEL
5745   if (Context.isObjCSelType(LHSTy) &&
5746       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5747     RHS = ImpCastExprToType(RHS.get(), LHSTy, CK_BitCast);
5748     return LHSTy;
5749   }
5750   if (Context.isObjCSelType(RHSTy) &&
5751       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5752     LHS = ImpCastExprToType(LHS.get(), RHSTy, CK_BitCast);
5753     return RHSTy;
5754   }
5755   // Check constraints for Objective-C object pointers types.
5756   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5757 
5758     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5759       // Two identical object pointer types are always compatible.
5760       return LHSTy;
5761     }
5762     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5763     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5764     QualType compositeType = LHSTy;
5765 
5766     // If both operands are interfaces and either operand can be
5767     // assigned to the other, use that type as the composite
5768     // type. This allows
5769     //   xxx ? (A*) a : (B*) b
5770     // where B is a subclass of A.
5771     //
5772     // Additionally, as for assignment, if either type is 'id'
5773     // allow silent coercion. Finally, if the types are
5774     // incompatible then make sure to use 'id' as the composite
5775     // type so the result is acceptable for sending messages to.
5776 
5777     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5778     // It could return the composite type.
5779     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5780       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5781     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5782       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5783     } else if ((LHSTy->isObjCQualifiedIdType() ||
5784                 RHSTy->isObjCQualifiedIdType()) &&
5785                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5786       // Need to handle "id<xx>" explicitly.
5787       // GCC allows qualified id and any Objective-C type to devolve to
5788       // id. Currently localizing to here until clear this should be
5789       // part of ObjCQualifiedIdTypesAreCompatible.
5790       compositeType = Context.getObjCIdType();
5791     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5792       compositeType = Context.getObjCIdType();
5793     } else if (!(compositeType =
5794                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5795       ;
5796     else {
5797       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5798       << LHSTy << RHSTy
5799       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5800       QualType incompatTy = Context.getObjCIdType();
5801       LHS = ImpCastExprToType(LHS.get(), incompatTy, CK_BitCast);
5802       RHS = ImpCastExprToType(RHS.get(), incompatTy, CK_BitCast);
5803       return incompatTy;
5804     }
5805     // The object pointer types are compatible.
5806     LHS = ImpCastExprToType(LHS.get(), compositeType, CK_BitCast);
5807     RHS = ImpCastExprToType(RHS.get(), compositeType, CK_BitCast);
5808     return compositeType;
5809   }
5810   // Check Objective-C object pointer types and 'void *'
5811   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5812     if (getLangOpts().ObjCAutoRefCount) {
5813       // ARC forbids the implicit conversion of object pointers to 'void *',
5814       // so these types are not compatible.
5815       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5816           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5817       LHS = RHS = true;
5818       return QualType();
5819     }
5820     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5821     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5822     QualType destPointee
5823     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5824     QualType destType = Context.getPointerType(destPointee);
5825     // Add qualifiers if necessary.
5826     LHS = ImpCastExprToType(LHS.get(), destType, CK_NoOp);
5827     // Promote to void*.
5828     RHS = ImpCastExprToType(RHS.get(), destType, CK_BitCast);
5829     return destType;
5830   }
5831   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5832     if (getLangOpts().ObjCAutoRefCount) {
5833       // ARC forbids the implicit conversion of object pointers to 'void *',
5834       // so these types are not compatible.
5835       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5836           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5837       LHS = RHS = true;
5838       return QualType();
5839     }
5840     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5841     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5842     QualType destPointee
5843     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5844     QualType destType = Context.getPointerType(destPointee);
5845     // Add qualifiers if necessary.
5846     RHS = ImpCastExprToType(RHS.get(), destType, CK_NoOp);
5847     // Promote to void*.
5848     LHS = ImpCastExprToType(LHS.get(), destType, CK_BitCast);
5849     return destType;
5850   }
5851   return QualType();
5852 }
5853 
5854 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5855 /// ParenRange in parentheses.
5856 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5857                                const PartialDiagnostic &Note,
5858                                SourceRange ParenRange) {
5859   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5860   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5861       EndLoc.isValid()) {
5862     Self.Diag(Loc, Note)
5863       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5864       << FixItHint::CreateInsertion(EndLoc, ")");
5865   } else {
5866     // We can't display the parentheses, so just show the bare note.
5867     Self.Diag(Loc, Note) << ParenRange;
5868   }
5869 }
5870 
5871 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5872   return Opc >= BO_Mul && Opc <= BO_Shr;
5873 }
5874 
5875 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5876 /// expression, either using a built-in or overloaded operator,
5877 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5878 /// expression.
5879 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5880                                    Expr **RHSExprs) {
5881   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5882   E = E->IgnoreImpCasts();
5883   E = E->IgnoreConversionOperator();
5884   E = E->IgnoreImpCasts();
5885 
5886   // Built-in binary operator.
5887   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5888     if (IsArithmeticOp(OP->getOpcode())) {
5889       *Opcode = OP->getOpcode();
5890       *RHSExprs = OP->getRHS();
5891       return true;
5892     }
5893   }
5894 
5895   // Overloaded operator.
5896   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5897     if (Call->getNumArgs() != 2)
5898       return false;
5899 
5900     // Make sure this is really a binary operator that is safe to pass into
5901     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5902     OverloadedOperatorKind OO = Call->getOperator();
5903     if (OO < OO_Plus || OO > OO_Arrow ||
5904         OO == OO_PlusPlus || OO == OO_MinusMinus)
5905       return false;
5906 
5907     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5908     if (IsArithmeticOp(OpKind)) {
5909       *Opcode = OpKind;
5910       *RHSExprs = Call->getArg(1);
5911       return true;
5912     }
5913   }
5914 
5915   return false;
5916 }
5917 
5918 static bool IsLogicOp(BinaryOperatorKind Opc) {
5919   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5920 }
5921 
5922 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5923 /// or is a logical expression such as (x==y) which has int type, but is
5924 /// commonly interpreted as boolean.
5925 static bool ExprLooksBoolean(Expr *E) {
5926   E = E->IgnoreParenImpCasts();
5927 
5928   if (E->getType()->isBooleanType())
5929     return true;
5930   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5931     return IsLogicOp(OP->getOpcode());
5932   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5933     return OP->getOpcode() == UO_LNot;
5934 
5935   return false;
5936 }
5937 
5938 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5939 /// and binary operator are mixed in a way that suggests the programmer assumed
5940 /// the conditional operator has higher precedence, for example:
5941 /// "int x = a + someBinaryCondition ? 1 : 2".
5942 static void DiagnoseConditionalPrecedence(Sema &Self,
5943                                           SourceLocation OpLoc,
5944                                           Expr *Condition,
5945                                           Expr *LHSExpr,
5946                                           Expr *RHSExpr) {
5947   BinaryOperatorKind CondOpcode;
5948   Expr *CondRHS;
5949 
5950   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5951     return;
5952   if (!ExprLooksBoolean(CondRHS))
5953     return;
5954 
5955   // The condition is an arithmetic binary expression, with a right-
5956   // hand side that looks boolean, so warn.
5957 
5958   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5959       << Condition->getSourceRange()
5960       << BinaryOperator::getOpcodeStr(CondOpcode);
5961 
5962   SuggestParentheses(Self, OpLoc,
5963     Self.PDiag(diag::note_precedence_silence)
5964       << BinaryOperator::getOpcodeStr(CondOpcode),
5965     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5966 
5967   SuggestParentheses(Self, OpLoc,
5968     Self.PDiag(diag::note_precedence_conditional_first),
5969     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5970 }
5971 
5972 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5973 /// in the case of a the GNU conditional expr extension.
5974 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5975                                     SourceLocation ColonLoc,
5976                                     Expr *CondExpr, Expr *LHSExpr,
5977                                     Expr *RHSExpr) {
5978   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5979   // was the condition.
5980   OpaqueValueExpr *opaqueValue = nullptr;
5981   Expr *commonExpr = nullptr;
5982   if (!LHSExpr) {
5983     commonExpr = CondExpr;
5984     // Lower out placeholder types first.  This is important so that we don't
5985     // try to capture a placeholder. This happens in few cases in C++; such
5986     // as Objective-C++'s dictionary subscripting syntax.
5987     if (commonExpr->hasPlaceholderType()) {
5988       ExprResult result = CheckPlaceholderExpr(commonExpr);
5989       if (!result.isUsable()) return ExprError();
5990       commonExpr = result.get();
5991     }
5992     // We usually want to apply unary conversions *before* saving, except
5993     // in the special case of a C++ l-value conditional.
5994     if (!(getLangOpts().CPlusPlus
5995           && !commonExpr->isTypeDependent()
5996           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5997           && commonExpr->isGLValue()
5998           && commonExpr->isOrdinaryOrBitFieldObject()
5999           && RHSExpr->isOrdinaryOrBitFieldObject()
6000           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
6001       ExprResult commonRes = UsualUnaryConversions(commonExpr);
6002       if (commonRes.isInvalid())
6003         return ExprError();
6004       commonExpr = commonRes.get();
6005     }
6006 
6007     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6008                                                 commonExpr->getType(),
6009                                                 commonExpr->getValueKind(),
6010                                                 commonExpr->getObjectKind(),
6011                                                 commonExpr);
6012     LHSExpr = CondExpr = opaqueValue;
6013   }
6014 
6015   ExprValueKind VK = VK_RValue;
6016   ExprObjectKind OK = OK_Ordinary;
6017   ExprResult Cond = CondExpr, LHS = LHSExpr, RHS = RHSExpr;
6018   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6019                                              VK, OK, QuestionLoc);
6020   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6021       RHS.isInvalid())
6022     return ExprError();
6023 
6024   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6025                                 RHS.get());
6026 
6027   if (!commonExpr)
6028     return new (Context)
6029         ConditionalOperator(Cond.get(), QuestionLoc, LHS.get(), ColonLoc,
6030                             RHS.get(), result, VK, OK);
6031 
6032   return new (Context) BinaryConditionalOperator(
6033       commonExpr, opaqueValue, Cond.get(), LHS.get(), RHS.get(), QuestionLoc,
6034       ColonLoc, result, VK, OK);
6035 }
6036 
6037 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6038 // being closely modeled after the C99 spec:-). The odd characteristic of this
6039 // routine is it effectively iqnores the qualifiers on the top level pointee.
6040 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6041 // FIXME: add a couple examples in this comment.
6042 static Sema::AssignConvertType
6043 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6044   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6045   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6046 
6047   // get the "pointed to" type (ignoring qualifiers at the top level)
6048   const Type *lhptee, *rhptee;
6049   Qualifiers lhq, rhq;
6050   std::tie(lhptee, lhq) =
6051       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6052   std::tie(rhptee, rhq) =
6053       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6054 
6055   Sema::AssignConvertType ConvTy = Sema::Compatible;
6056 
6057   // C99 6.5.16.1p1: This following citation is common to constraints
6058   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6059   // qualifiers of the type *pointed to* by the right;
6060 
6061   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6062   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6063       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6064     // Ignore lifetime for further calculation.
6065     lhq.removeObjCLifetime();
6066     rhq.removeObjCLifetime();
6067   }
6068 
6069   if (!lhq.compatiblyIncludes(rhq)) {
6070     // Treat address-space mismatches as fatal.  TODO: address subspaces
6071     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6072       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6073 
6074     // It's okay to add or remove GC or lifetime qualifiers when converting to
6075     // and from void*.
6076     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6077                         .compatiblyIncludes(
6078                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6079              && (lhptee->isVoidType() || rhptee->isVoidType()))
6080       ; // keep old
6081 
6082     // Treat lifetime mismatches as fatal.
6083     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6084       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6085 
6086     // For GCC compatibility, other qualifier mismatches are treated
6087     // as still compatible in C.
6088     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6089   }
6090 
6091   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6092   // incomplete type and the other is a pointer to a qualified or unqualified
6093   // version of void...
6094   if (lhptee->isVoidType()) {
6095     if (rhptee->isIncompleteOrObjectType())
6096       return ConvTy;
6097 
6098     // As an extension, we allow cast to/from void* to function pointer.
6099     assert(rhptee->isFunctionType());
6100     return Sema::FunctionVoidPointer;
6101   }
6102 
6103   if (rhptee->isVoidType()) {
6104     if (lhptee->isIncompleteOrObjectType())
6105       return ConvTy;
6106 
6107     // As an extension, we allow cast to/from void* to function pointer.
6108     assert(lhptee->isFunctionType());
6109     return Sema::FunctionVoidPointer;
6110   }
6111 
6112   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6113   // unqualified versions of compatible types, ...
6114   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6115   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6116     // Check if the pointee types are compatible ignoring the sign.
6117     // We explicitly check for char so that we catch "char" vs
6118     // "unsigned char" on systems where "char" is unsigned.
6119     if (lhptee->isCharType())
6120       ltrans = S.Context.UnsignedCharTy;
6121     else if (lhptee->hasSignedIntegerRepresentation())
6122       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6123 
6124     if (rhptee->isCharType())
6125       rtrans = S.Context.UnsignedCharTy;
6126     else if (rhptee->hasSignedIntegerRepresentation())
6127       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6128 
6129     if (ltrans == rtrans) {
6130       // Types are compatible ignoring the sign. Qualifier incompatibility
6131       // takes priority over sign incompatibility because the sign
6132       // warning can be disabled.
6133       if (ConvTy != Sema::Compatible)
6134         return ConvTy;
6135 
6136       return Sema::IncompatiblePointerSign;
6137     }
6138 
6139     // If we are a multi-level pointer, it's possible that our issue is simply
6140     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6141     // the eventual target type is the same and the pointers have the same
6142     // level of indirection, this must be the issue.
6143     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6144       do {
6145         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6146         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6147       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6148 
6149       if (lhptee == rhptee)
6150         return Sema::IncompatibleNestedPointerQualifiers;
6151     }
6152 
6153     // General pointer incompatibility takes priority over qualifiers.
6154     return Sema::IncompatiblePointer;
6155   }
6156   if (!S.getLangOpts().CPlusPlus &&
6157       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6158     return Sema::IncompatiblePointer;
6159   return ConvTy;
6160 }
6161 
6162 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6163 /// block pointer types are compatible or whether a block and normal pointer
6164 /// are compatible. It is more restrict than comparing two function pointer
6165 // types.
6166 static Sema::AssignConvertType
6167 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6168                                     QualType RHSType) {
6169   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6170   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6171 
6172   QualType lhptee, rhptee;
6173 
6174   // get the "pointed to" type (ignoring qualifiers at the top level)
6175   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6176   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6177 
6178   // In C++, the types have to match exactly.
6179   if (S.getLangOpts().CPlusPlus)
6180     return Sema::IncompatibleBlockPointer;
6181 
6182   Sema::AssignConvertType ConvTy = Sema::Compatible;
6183 
6184   // For blocks we enforce that qualifiers are identical.
6185   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6186     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6187 
6188   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6189     return Sema::IncompatibleBlockPointer;
6190 
6191   return ConvTy;
6192 }
6193 
6194 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6195 /// for assignment compatibility.
6196 static Sema::AssignConvertType
6197 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6198                                    QualType RHSType) {
6199   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6200   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6201 
6202   if (LHSType->isObjCBuiltinType()) {
6203     // Class is not compatible with ObjC object pointers.
6204     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6205         !RHSType->isObjCQualifiedClassType())
6206       return Sema::IncompatiblePointer;
6207     return Sema::Compatible;
6208   }
6209   if (RHSType->isObjCBuiltinType()) {
6210     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6211         !LHSType->isObjCQualifiedClassType())
6212       return Sema::IncompatiblePointer;
6213     return Sema::Compatible;
6214   }
6215   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6216   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6217 
6218   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6219       // make an exception for id<P>
6220       !LHSType->isObjCQualifiedIdType())
6221     return Sema::CompatiblePointerDiscardsQualifiers;
6222 
6223   if (S.Context.typesAreCompatible(LHSType, RHSType))
6224     return Sema::Compatible;
6225   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6226     return Sema::IncompatibleObjCQualifiedId;
6227   return Sema::IncompatiblePointer;
6228 }
6229 
6230 Sema::AssignConvertType
6231 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6232                                  QualType LHSType, QualType RHSType) {
6233   // Fake up an opaque expression.  We don't actually care about what
6234   // cast operations are required, so if CheckAssignmentConstraints
6235   // adds casts to this they'll be wasted, but fortunately that doesn't
6236   // usually happen on valid code.
6237   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6238   ExprResult RHSPtr = &RHSExpr;
6239   CastKind K = CK_Invalid;
6240 
6241   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6242 }
6243 
6244 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6245 /// has code to accommodate several GCC extensions when type checking
6246 /// pointers. Here are some objectionable examples that GCC considers warnings:
6247 ///
6248 ///  int a, *pint;
6249 ///  short *pshort;
6250 ///  struct foo *pfoo;
6251 ///
6252 ///  pint = pshort; // warning: assignment from incompatible pointer type
6253 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6254 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6255 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6256 ///
6257 /// As a result, the code for dealing with pointers is more complex than the
6258 /// C99 spec dictates.
6259 ///
6260 /// Sets 'Kind' for any result kind except Incompatible.
6261 Sema::AssignConvertType
6262 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6263                                  CastKind &Kind) {
6264   QualType RHSType = RHS.get()->getType();
6265   QualType OrigLHSType = LHSType;
6266 
6267   // Get canonical types.  We're not formatting these types, just comparing
6268   // them.
6269   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6270   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6271 
6272   // Common case: no conversion required.
6273   if (LHSType == RHSType) {
6274     Kind = CK_NoOp;
6275     return Compatible;
6276   }
6277 
6278   // If we have an atomic type, try a non-atomic assignment, then just add an
6279   // atomic qualification step.
6280   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6281     Sema::AssignConvertType result =
6282       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6283     if (result != Compatible)
6284       return result;
6285     if (Kind != CK_NoOp)
6286       RHS = ImpCastExprToType(RHS.get(), AtomicTy->getValueType(), Kind);
6287     Kind = CK_NonAtomicToAtomic;
6288     return Compatible;
6289   }
6290 
6291   // If the left-hand side is a reference type, then we are in a
6292   // (rare!) case where we've allowed the use of references in C,
6293   // e.g., as a parameter type in a built-in function. In this case,
6294   // just make sure that the type referenced is compatible with the
6295   // right-hand side type. The caller is responsible for adjusting
6296   // LHSType so that the resulting expression does not have reference
6297   // type.
6298   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6299     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6300       Kind = CK_LValueBitCast;
6301       return Compatible;
6302     }
6303     return Incompatible;
6304   }
6305 
6306   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6307   // to the same ExtVector type.
6308   if (LHSType->isExtVectorType()) {
6309     if (RHSType->isExtVectorType())
6310       return Incompatible;
6311     if (RHSType->isArithmeticType()) {
6312       // CK_VectorSplat does T -> vector T, so first cast to the
6313       // element type.
6314       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6315       if (elType != RHSType) {
6316         Kind = PrepareScalarCast(RHS, elType);
6317         RHS = ImpCastExprToType(RHS.get(), elType, Kind);
6318       }
6319       Kind = CK_VectorSplat;
6320       return Compatible;
6321     }
6322   }
6323 
6324   // Conversions to or from vector type.
6325   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6326     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6327       // Allow assignments of an AltiVec vector type to an equivalent GCC
6328       // vector type and vice versa
6329       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6330         Kind = CK_BitCast;
6331         return Compatible;
6332       }
6333 
6334       // If we are allowing lax vector conversions, and LHS and RHS are both
6335       // vectors, the total size only needs to be the same. This is a bitcast;
6336       // no bits are changed but the result type is different.
6337       if (isLaxVectorConversion(RHSType, LHSType)) {
6338         Kind = CK_BitCast;
6339         return IncompatibleVectors;
6340       }
6341     }
6342     return Incompatible;
6343   }
6344 
6345   // Arithmetic conversions.
6346   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6347       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6348     Kind = PrepareScalarCast(RHS, LHSType);
6349     return Compatible;
6350   }
6351 
6352   // Conversions to normal pointers.
6353   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6354     // U* -> T*
6355     if (isa<PointerType>(RHSType)) {
6356       Kind = CK_BitCast;
6357       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6358     }
6359 
6360     // int -> T*
6361     if (RHSType->isIntegerType()) {
6362       Kind = CK_IntegralToPointer; // FIXME: null?
6363       return IntToPointer;
6364     }
6365 
6366     // C pointers are not compatible with ObjC object pointers,
6367     // with two exceptions:
6368     if (isa<ObjCObjectPointerType>(RHSType)) {
6369       //  - conversions to void*
6370       if (LHSPointer->getPointeeType()->isVoidType()) {
6371         Kind = CK_BitCast;
6372         return Compatible;
6373       }
6374 
6375       //  - conversions from 'Class' to the redefinition type
6376       if (RHSType->isObjCClassType() &&
6377           Context.hasSameType(LHSType,
6378                               Context.getObjCClassRedefinitionType())) {
6379         Kind = CK_BitCast;
6380         return Compatible;
6381       }
6382 
6383       Kind = CK_BitCast;
6384       return IncompatiblePointer;
6385     }
6386 
6387     // U^ -> void*
6388     if (RHSType->getAs<BlockPointerType>()) {
6389       if (LHSPointer->getPointeeType()->isVoidType()) {
6390         Kind = CK_BitCast;
6391         return Compatible;
6392       }
6393     }
6394 
6395     return Incompatible;
6396   }
6397 
6398   // Conversions to block pointers.
6399   if (isa<BlockPointerType>(LHSType)) {
6400     // U^ -> T^
6401     if (RHSType->isBlockPointerType()) {
6402       Kind = CK_BitCast;
6403       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6404     }
6405 
6406     // int or null -> T^
6407     if (RHSType->isIntegerType()) {
6408       Kind = CK_IntegralToPointer; // FIXME: null
6409       return IntToBlockPointer;
6410     }
6411 
6412     // id -> T^
6413     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6414       Kind = CK_AnyPointerToBlockPointerCast;
6415       return Compatible;
6416     }
6417 
6418     // void* -> T^
6419     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6420       if (RHSPT->getPointeeType()->isVoidType()) {
6421         Kind = CK_AnyPointerToBlockPointerCast;
6422         return Compatible;
6423       }
6424 
6425     return Incompatible;
6426   }
6427 
6428   // Conversions to Objective-C pointers.
6429   if (isa<ObjCObjectPointerType>(LHSType)) {
6430     // A* -> B*
6431     if (RHSType->isObjCObjectPointerType()) {
6432       Kind = CK_BitCast;
6433       Sema::AssignConvertType result =
6434         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6435       if (getLangOpts().ObjCAutoRefCount &&
6436           result == Compatible &&
6437           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6438         result = IncompatibleObjCWeakRef;
6439       return result;
6440     }
6441 
6442     // int or null -> A*
6443     if (RHSType->isIntegerType()) {
6444       Kind = CK_IntegralToPointer; // FIXME: null
6445       return IntToPointer;
6446     }
6447 
6448     // In general, C pointers are not compatible with ObjC object pointers,
6449     // with two exceptions:
6450     if (isa<PointerType>(RHSType)) {
6451       Kind = CK_CPointerToObjCPointerCast;
6452 
6453       //  - conversions from 'void*'
6454       if (RHSType->isVoidPointerType()) {
6455         return Compatible;
6456       }
6457 
6458       //  - conversions to 'Class' from its redefinition type
6459       if (LHSType->isObjCClassType() &&
6460           Context.hasSameType(RHSType,
6461                               Context.getObjCClassRedefinitionType())) {
6462         return Compatible;
6463       }
6464 
6465       return IncompatiblePointer;
6466     }
6467 
6468     // Only under strict condition T^ is compatible with an Objective-C pointer.
6469     if (RHSType->isBlockPointerType() &&
6470         isObjCPtrBlockCompatible(*this, Context, LHSType)) {
6471       maybeExtendBlockObject(*this, RHS);
6472       Kind = CK_BlockPointerToObjCPointerCast;
6473       return Compatible;
6474     }
6475 
6476     return Incompatible;
6477   }
6478 
6479   // Conversions from pointers that are not covered by the above.
6480   if (isa<PointerType>(RHSType)) {
6481     // T* -> _Bool
6482     if (LHSType == Context.BoolTy) {
6483       Kind = CK_PointerToBoolean;
6484       return Compatible;
6485     }
6486 
6487     // T* -> int
6488     if (LHSType->isIntegerType()) {
6489       Kind = CK_PointerToIntegral;
6490       return PointerToInt;
6491     }
6492 
6493     return Incompatible;
6494   }
6495 
6496   // Conversions from Objective-C pointers that are not covered by the above.
6497   if (isa<ObjCObjectPointerType>(RHSType)) {
6498     // T* -> _Bool
6499     if (LHSType == Context.BoolTy) {
6500       Kind = CK_PointerToBoolean;
6501       return Compatible;
6502     }
6503 
6504     // T* -> int
6505     if (LHSType->isIntegerType()) {
6506       Kind = CK_PointerToIntegral;
6507       return PointerToInt;
6508     }
6509 
6510     return Incompatible;
6511   }
6512 
6513   // struct A -> struct B
6514   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6515     if (Context.typesAreCompatible(LHSType, RHSType)) {
6516       Kind = CK_NoOp;
6517       return Compatible;
6518     }
6519   }
6520 
6521   return Incompatible;
6522 }
6523 
6524 /// \brief Constructs a transparent union from an expression that is
6525 /// used to initialize the transparent union.
6526 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6527                                       ExprResult &EResult, QualType UnionType,
6528                                       FieldDecl *Field) {
6529   // Build an initializer list that designates the appropriate member
6530   // of the transparent union.
6531   Expr *E = EResult.get();
6532   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6533                                                    E, SourceLocation());
6534   Initializer->setType(UnionType);
6535   Initializer->setInitializedFieldInUnion(Field);
6536 
6537   // Build a compound literal constructing a value of the transparent
6538   // union type from this initializer list.
6539   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6540   EResult = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6541                                         VK_RValue, Initializer, false);
6542 }
6543 
6544 Sema::AssignConvertType
6545 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6546                                                ExprResult &RHS) {
6547   QualType RHSType = RHS.get()->getType();
6548 
6549   // If the ArgType is a Union type, we want to handle a potential
6550   // transparent_union GCC extension.
6551   const RecordType *UT = ArgType->getAsUnionType();
6552   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6553     return Incompatible;
6554 
6555   // The field to initialize within the transparent union.
6556   RecordDecl *UD = UT->getDecl();
6557   FieldDecl *InitField = nullptr;
6558   // It's compatible if the expression matches any of the fields.
6559   for (auto *it : UD->fields()) {
6560     if (it->getType()->isPointerType()) {
6561       // If the transparent union contains a pointer type, we allow:
6562       // 1) void pointer
6563       // 2) null pointer constant
6564       if (RHSType->isPointerType())
6565         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6566           RHS = ImpCastExprToType(RHS.get(), it->getType(), CK_BitCast);
6567           InitField = it;
6568           break;
6569         }
6570 
6571       if (RHS.get()->isNullPointerConstant(Context,
6572                                            Expr::NPC_ValueDependentIsNull)) {
6573         RHS = ImpCastExprToType(RHS.get(), it->getType(),
6574                                 CK_NullToPointer);
6575         InitField = it;
6576         break;
6577       }
6578     }
6579 
6580     CastKind Kind = CK_Invalid;
6581     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6582           == Compatible) {
6583       RHS = ImpCastExprToType(RHS.get(), it->getType(), Kind);
6584       InitField = it;
6585       break;
6586     }
6587   }
6588 
6589   if (!InitField)
6590     return Incompatible;
6591 
6592   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6593   return Compatible;
6594 }
6595 
6596 Sema::AssignConvertType
6597 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6598                                        bool Diagnose,
6599                                        bool DiagnoseCFAudited) {
6600   if (getLangOpts().CPlusPlus) {
6601     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6602       // C++ 5.17p3: If the left operand is not of class type, the
6603       // expression is implicitly converted (C++ 4) to the
6604       // cv-unqualified type of the left operand.
6605       ExprResult Res;
6606       if (Diagnose) {
6607         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6608                                         AA_Assigning);
6609       } else {
6610         ImplicitConversionSequence ICS =
6611             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6612                                   /*SuppressUserConversions=*/false,
6613                                   /*AllowExplicit=*/false,
6614                                   /*InOverloadResolution=*/false,
6615                                   /*CStyle=*/false,
6616                                   /*AllowObjCWritebackConversion=*/false);
6617         if (ICS.isFailure())
6618           return Incompatible;
6619         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6620                                         ICS, AA_Assigning);
6621       }
6622       if (Res.isInvalid())
6623         return Incompatible;
6624       Sema::AssignConvertType result = Compatible;
6625       if (getLangOpts().ObjCAutoRefCount &&
6626           !CheckObjCARCUnavailableWeakConversion(LHSType,
6627                                                  RHS.get()->getType()))
6628         result = IncompatibleObjCWeakRef;
6629       RHS = Res;
6630       return result;
6631     }
6632 
6633     // FIXME: Currently, we fall through and treat C++ classes like C
6634     // structures.
6635     // FIXME: We also fall through for atomics; not sure what should
6636     // happen there, though.
6637   }
6638 
6639   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6640   // a null pointer constant.
6641   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6642        LHSType->isBlockPointerType()) &&
6643       RHS.get()->isNullPointerConstant(Context,
6644                                        Expr::NPC_ValueDependentIsNull)) {
6645     CastKind Kind;
6646     CXXCastPath Path;
6647     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6648     RHS = ImpCastExprToType(RHS.get(), LHSType, Kind, VK_RValue, &Path);
6649     return Compatible;
6650   }
6651 
6652   // This check seems unnatural, however it is necessary to ensure the proper
6653   // conversion of functions/arrays. If the conversion were done for all
6654   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6655   // expressions that suppress this implicit conversion (&, sizeof).
6656   //
6657   // Suppress this for references: C++ 8.5.3p5.
6658   if (!LHSType->isReferenceType()) {
6659     RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6660     if (RHS.isInvalid())
6661       return Incompatible;
6662   }
6663 
6664   CastKind Kind = CK_Invalid;
6665   Sema::AssignConvertType result =
6666     CheckAssignmentConstraints(LHSType, RHS, Kind);
6667 
6668   // C99 6.5.16.1p2: The value of the right operand is converted to the
6669   // type of the assignment expression.
6670   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6671   // so that we can use references in built-in functions even in C.
6672   // The getNonReferenceType() call makes sure that the resulting expression
6673   // does not have reference type.
6674   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6675     QualType Ty = LHSType.getNonLValueExprType(Context);
6676     Expr *E = RHS.get();
6677     if (getLangOpts().ObjCAutoRefCount)
6678       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6679                              DiagnoseCFAudited);
6680     if (getLangOpts().ObjC1 &&
6681         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6682                                           LHSType, E->getType(), E) ||
6683          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6684       RHS = E;
6685       return Compatible;
6686     }
6687 
6688     RHS = ImpCastExprToType(E, Ty, Kind);
6689   }
6690   return result;
6691 }
6692 
6693 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6694                                ExprResult &RHS) {
6695   Diag(Loc, diag::err_typecheck_invalid_operands)
6696     << LHS.get()->getType() << RHS.get()->getType()
6697     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6698   return QualType();
6699 }
6700 
6701 /// Try to convert a value of non-vector type to a vector type by converting
6702 /// the type to the element type of the vector and then performing a splat.
6703 /// If the language is OpenCL, we only use conversions that promote scalar
6704 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6705 /// for float->int.
6706 ///
6707 /// \param scalar - if non-null, actually perform the conversions
6708 /// \return true if the operation fails (but without diagnosing the failure)
6709 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6710                                      QualType scalarTy,
6711                                      QualType vectorEltTy,
6712                                      QualType vectorTy) {
6713   // The conversion to apply to the scalar before splatting it,
6714   // if necessary.
6715   CastKind scalarCast = CK_Invalid;
6716 
6717   if (vectorEltTy->isIntegralType(S.Context)) {
6718     if (!scalarTy->isIntegralType(S.Context))
6719       return true;
6720     if (S.getLangOpts().OpenCL &&
6721         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6722       return true;
6723     scalarCast = CK_IntegralCast;
6724   } else if (vectorEltTy->isRealFloatingType()) {
6725     if (scalarTy->isRealFloatingType()) {
6726       if (S.getLangOpts().OpenCL &&
6727           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6728         return true;
6729       scalarCast = CK_FloatingCast;
6730     }
6731     else if (scalarTy->isIntegralType(S.Context))
6732       scalarCast = CK_IntegralToFloating;
6733     else
6734       return true;
6735   } else {
6736     return true;
6737   }
6738 
6739   // Adjust scalar if desired.
6740   if (scalar) {
6741     if (scalarCast != CK_Invalid)
6742       *scalar = S.ImpCastExprToType(scalar->get(), vectorEltTy, scalarCast);
6743     *scalar = S.ImpCastExprToType(scalar->get(), vectorTy, CK_VectorSplat);
6744   }
6745   return false;
6746 }
6747 
6748 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6749                                    SourceLocation Loc, bool IsCompAssign) {
6750   if (!IsCompAssign) {
6751     LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
6752     if (LHS.isInvalid())
6753       return QualType();
6754   }
6755   RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
6756   if (RHS.isInvalid())
6757     return QualType();
6758 
6759   // For conversion purposes, we ignore any qualifiers.
6760   // For example, "const float" and "float" are equivalent.
6761   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6762   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6763 
6764   // If the vector types are identical, return.
6765   if (Context.hasSameType(LHSType, RHSType))
6766     return LHSType;
6767 
6768   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6769   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6770   assert(LHSVecType || RHSVecType);
6771 
6772   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6773   if (LHSVecType && RHSVecType &&
6774       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6775     if (isa<ExtVectorType>(LHSVecType)) {
6776       RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
6777       return LHSType;
6778     }
6779 
6780     if (!IsCompAssign)
6781       LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
6782     return RHSType;
6783   }
6784 
6785   // If there's an ext-vector type and a scalar, try to convert the scalar to
6786   // the vector element type and splat.
6787   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6788     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6789                                   LHSVecType->getElementType(), LHSType))
6790       return LHSType;
6791   }
6792   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6793     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? nullptr : &LHS),
6794                                   LHSType, RHSVecType->getElementType(),
6795                                   RHSType))
6796       return RHSType;
6797   }
6798 
6799   // If we're allowing lax vector conversions, only the total (data) size
6800   // needs to be the same.
6801   // FIXME: Should we really be allowing this?
6802   // FIXME: We really just pick the LHS type arbitrarily?
6803   if (isLaxVectorConversion(RHSType, LHSType)) {
6804     QualType resultType = LHSType;
6805     RHS = ImpCastExprToType(RHS.get(), resultType, CK_BitCast);
6806     return resultType;
6807   }
6808 
6809   // Okay, the expression is invalid.
6810 
6811   // If there's a non-vector, non-real operand, diagnose that.
6812   if ((!RHSVecType && !RHSType->isRealType()) ||
6813       (!LHSVecType && !LHSType->isRealType())) {
6814     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6815       << LHSType << RHSType
6816       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6817     return QualType();
6818   }
6819 
6820   // Otherwise, use the generic diagnostic.
6821   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6822     << LHSType << RHSType
6823     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6824   return QualType();
6825 }
6826 
6827 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6828 // expression.  These are mainly cases where the null pointer is used as an
6829 // integer instead of a pointer.
6830 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6831                                 SourceLocation Loc, bool IsCompare) {
6832   // The canonical way to check for a GNU null is with isNullPointerConstant,
6833   // but we use a bit of a hack here for speed; this is a relatively
6834   // hot path, and isNullPointerConstant is slow.
6835   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6836   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6837 
6838   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6839 
6840   // Avoid analyzing cases where the result will either be invalid (and
6841   // diagnosed as such) or entirely valid and not something to warn about.
6842   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6843       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6844     return;
6845 
6846   // Comparison operations would not make sense with a null pointer no matter
6847   // what the other expression is.
6848   if (!IsCompare) {
6849     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6850         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6851         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6852     return;
6853   }
6854 
6855   // The rest of the operations only make sense with a null pointer
6856   // if the other expression is a pointer.
6857   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6858       NonNullType->canDecayToPointerType())
6859     return;
6860 
6861   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6862       << LHSNull /* LHS is NULL */ << NonNullType
6863       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6864 }
6865 
6866 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6867                                            SourceLocation Loc,
6868                                            bool IsCompAssign, bool IsDiv) {
6869   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6870 
6871   if (LHS.get()->getType()->isVectorType() ||
6872       RHS.get()->getType()->isVectorType())
6873     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6874 
6875   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6876   if (LHS.isInvalid() || RHS.isInvalid())
6877     return QualType();
6878 
6879 
6880   if (compType.isNull() || !compType->isArithmeticType())
6881     return InvalidOperands(Loc, LHS, RHS);
6882 
6883   // Check for division by zero.
6884   llvm::APSInt RHSValue;
6885   if (IsDiv && !RHS.get()->isValueDependent() &&
6886       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6887     DiagRuntimeBehavior(Loc, RHS.get(),
6888                         PDiag(diag::warn_division_by_zero)
6889                           << RHS.get()->getSourceRange());
6890 
6891   return compType;
6892 }
6893 
6894 QualType Sema::CheckRemainderOperands(
6895   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6896   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6897 
6898   if (LHS.get()->getType()->isVectorType() ||
6899       RHS.get()->getType()->isVectorType()) {
6900     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6901         RHS.get()->getType()->hasIntegerRepresentation())
6902       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6903     return InvalidOperands(Loc, LHS, RHS);
6904   }
6905 
6906   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6907   if (LHS.isInvalid() || RHS.isInvalid())
6908     return QualType();
6909 
6910   if (compType.isNull() || !compType->isIntegerType())
6911     return InvalidOperands(Loc, LHS, RHS);
6912 
6913   // Check for remainder by zero.
6914   llvm::APSInt RHSValue;
6915   if (!RHS.get()->isValueDependent() &&
6916       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6917     DiagRuntimeBehavior(Loc, RHS.get(),
6918                         PDiag(diag::warn_remainder_by_zero)
6919                           << RHS.get()->getSourceRange());
6920 
6921   return compType;
6922 }
6923 
6924 /// \brief Diagnose invalid arithmetic on two void pointers.
6925 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6926                                                 Expr *LHSExpr, Expr *RHSExpr) {
6927   S.Diag(Loc, S.getLangOpts().CPlusPlus
6928                 ? diag::err_typecheck_pointer_arith_void_type
6929                 : diag::ext_gnu_void_ptr)
6930     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6931                             << RHSExpr->getSourceRange();
6932 }
6933 
6934 /// \brief Diagnose invalid arithmetic on a void pointer.
6935 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6936                                             Expr *Pointer) {
6937   S.Diag(Loc, S.getLangOpts().CPlusPlus
6938                 ? diag::err_typecheck_pointer_arith_void_type
6939                 : diag::ext_gnu_void_ptr)
6940     << 0 /* one pointer */ << Pointer->getSourceRange();
6941 }
6942 
6943 /// \brief Diagnose invalid arithmetic on two function pointers.
6944 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6945                                                     Expr *LHS, Expr *RHS) {
6946   assert(LHS->getType()->isAnyPointerType());
6947   assert(RHS->getType()->isAnyPointerType());
6948   S.Diag(Loc, S.getLangOpts().CPlusPlus
6949                 ? diag::err_typecheck_pointer_arith_function_type
6950                 : diag::ext_gnu_ptr_func_arith)
6951     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6952     // We only show the second type if it differs from the first.
6953     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6954                                                    RHS->getType())
6955     << RHS->getType()->getPointeeType()
6956     << LHS->getSourceRange() << RHS->getSourceRange();
6957 }
6958 
6959 /// \brief Diagnose invalid arithmetic on a function pointer.
6960 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6961                                                 Expr *Pointer) {
6962   assert(Pointer->getType()->isAnyPointerType());
6963   S.Diag(Loc, S.getLangOpts().CPlusPlus
6964                 ? diag::err_typecheck_pointer_arith_function_type
6965                 : diag::ext_gnu_ptr_func_arith)
6966     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6967     << 0 /* one pointer, so only one type */
6968     << Pointer->getSourceRange();
6969 }
6970 
6971 /// \brief Emit error if Operand is incomplete pointer type
6972 ///
6973 /// \returns True if pointer has incomplete type
6974 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6975                                                  Expr *Operand) {
6976   assert(Operand->getType()->isAnyPointerType() &&
6977          !Operand->getType()->isDependentType());
6978   QualType PointeeTy = Operand->getType()->getPointeeType();
6979   return S.RequireCompleteType(Loc, PointeeTy,
6980                                diag::err_typecheck_arithmetic_incomplete_type,
6981                                PointeeTy, Operand->getSourceRange());
6982 }
6983 
6984 /// \brief Check the validity of an arithmetic pointer operand.
6985 ///
6986 /// If the operand has pointer type, this code will check for pointer types
6987 /// which are invalid in arithmetic operations. These will be diagnosed
6988 /// appropriately, including whether or not the use is supported as an
6989 /// extension.
6990 ///
6991 /// \returns True when the operand is valid to use (even if as an extension).
6992 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6993                                             Expr *Operand) {
6994   if (!Operand->getType()->isAnyPointerType()) return true;
6995 
6996   QualType PointeeTy = Operand->getType()->getPointeeType();
6997   if (PointeeTy->isVoidType()) {
6998     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6999     return !S.getLangOpts().CPlusPlus;
7000   }
7001   if (PointeeTy->isFunctionType()) {
7002     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
7003     return !S.getLangOpts().CPlusPlus;
7004   }
7005 
7006   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7007 
7008   return true;
7009 }
7010 
7011 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7012 /// operands.
7013 ///
7014 /// This routine will diagnose any invalid arithmetic on pointer operands much
7015 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7016 /// for emitting a single diagnostic even for operations where both LHS and RHS
7017 /// are (potentially problematic) pointers.
7018 ///
7019 /// \returns True when the operand is valid to use (even if as an extension).
7020 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7021                                                 Expr *LHSExpr, Expr *RHSExpr) {
7022   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7023   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7024   if (!isLHSPointer && !isRHSPointer) return true;
7025 
7026   QualType LHSPointeeTy, RHSPointeeTy;
7027   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7028   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7029 
7030   // Check for arithmetic on pointers to incomplete types.
7031   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7032   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7033   if (isLHSVoidPtr || isRHSVoidPtr) {
7034     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7035     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7036     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7037 
7038     return !S.getLangOpts().CPlusPlus;
7039   }
7040 
7041   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7042   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7043   if (isLHSFuncPtr || isRHSFuncPtr) {
7044     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7045     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7046                                                                 RHSExpr);
7047     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7048 
7049     return !S.getLangOpts().CPlusPlus;
7050   }
7051 
7052   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7053     return false;
7054   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7055     return false;
7056 
7057   return true;
7058 }
7059 
7060 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7061 /// literal.
7062 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7063                                   Expr *LHSExpr, Expr *RHSExpr) {
7064   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7065   Expr* IndexExpr = RHSExpr;
7066   if (!StrExpr) {
7067     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7068     IndexExpr = LHSExpr;
7069   }
7070 
7071   bool IsStringPlusInt = StrExpr &&
7072       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7073   if (!IsStringPlusInt)
7074     return;
7075 
7076   llvm::APSInt index;
7077   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7078     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7079     if (index.isNonNegative() &&
7080         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7081                               index.isUnsigned()))
7082       return;
7083   }
7084 
7085   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7086   Self.Diag(OpLoc, diag::warn_string_plus_int)
7087       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7088 
7089   // Only print a fixit for "str" + int, not for int + "str".
7090   if (IndexExpr == RHSExpr) {
7091     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7092     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7093         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7094         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7095         << FixItHint::CreateInsertion(EndLoc, "]");
7096   } else
7097     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7098 }
7099 
7100 /// \brief Emit a warning when adding a char literal to a string.
7101 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7102                                    Expr *LHSExpr, Expr *RHSExpr) {
7103   const DeclRefExpr *StringRefExpr =
7104       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7105   const CharacterLiteral *CharExpr =
7106       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7107   if (!StringRefExpr) {
7108     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7109     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7110   }
7111 
7112   if (!CharExpr || !StringRefExpr)
7113     return;
7114 
7115   const QualType StringType = StringRefExpr->getType();
7116 
7117   // Return if not a PointerType.
7118   if (!StringType->isAnyPointerType())
7119     return;
7120 
7121   // Return if not a CharacterType.
7122   if (!StringType->getPointeeType()->isAnyCharacterType())
7123     return;
7124 
7125   ASTContext &Ctx = Self.getASTContext();
7126   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7127 
7128   const QualType CharType = CharExpr->getType();
7129   if (!CharType->isAnyCharacterType() &&
7130       CharType->isIntegerType() &&
7131       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7132     Self.Diag(OpLoc, diag::warn_string_plus_char)
7133         << DiagRange << Ctx.CharTy;
7134   } else {
7135     Self.Diag(OpLoc, diag::warn_string_plus_char)
7136         << DiagRange << CharExpr->getType();
7137   }
7138 
7139   // Only print a fixit for str + char, not for char + str.
7140   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7141     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7142     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7143         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7144         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7145         << FixItHint::CreateInsertion(EndLoc, "]");
7146   } else {
7147     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7148   }
7149 }
7150 
7151 /// \brief Emit error when two pointers are incompatible.
7152 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7153                                            Expr *LHSExpr, Expr *RHSExpr) {
7154   assert(LHSExpr->getType()->isAnyPointerType());
7155   assert(RHSExpr->getType()->isAnyPointerType());
7156   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7157     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7158     << RHSExpr->getSourceRange();
7159 }
7160 
7161 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7162     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7163     QualType* CompLHSTy) {
7164   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7165 
7166   if (LHS.get()->getType()->isVectorType() ||
7167       RHS.get()->getType()->isVectorType()) {
7168     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7169     if (CompLHSTy) *CompLHSTy = compType;
7170     return compType;
7171   }
7172 
7173   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7174   if (LHS.isInvalid() || RHS.isInvalid())
7175     return QualType();
7176 
7177   // Diagnose "string literal" '+' int and string '+' "char literal".
7178   if (Opc == BO_Add) {
7179     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7180     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7181   }
7182 
7183   // handle the common case first (both operands are arithmetic).
7184   if (!compType.isNull() && compType->isArithmeticType()) {
7185     if (CompLHSTy) *CompLHSTy = compType;
7186     return compType;
7187   }
7188 
7189   // Type-checking.  Ultimately the pointer's going to be in PExp;
7190   // note that we bias towards the LHS being the pointer.
7191   Expr *PExp = LHS.get(), *IExp = RHS.get();
7192 
7193   bool isObjCPointer;
7194   if (PExp->getType()->isPointerType()) {
7195     isObjCPointer = false;
7196   } else if (PExp->getType()->isObjCObjectPointerType()) {
7197     isObjCPointer = true;
7198   } else {
7199     std::swap(PExp, IExp);
7200     if (PExp->getType()->isPointerType()) {
7201       isObjCPointer = false;
7202     } else if (PExp->getType()->isObjCObjectPointerType()) {
7203       isObjCPointer = true;
7204     } else {
7205       return InvalidOperands(Loc, LHS, RHS);
7206     }
7207   }
7208   assert(PExp->getType()->isAnyPointerType());
7209 
7210   if (!IExp->getType()->isIntegerType())
7211     return InvalidOperands(Loc, LHS, RHS);
7212 
7213   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7214     return QualType();
7215 
7216   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7217     return QualType();
7218 
7219   // Check array bounds for pointer arithemtic
7220   CheckArrayAccess(PExp, IExp);
7221 
7222   if (CompLHSTy) {
7223     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7224     if (LHSTy.isNull()) {
7225       LHSTy = LHS.get()->getType();
7226       if (LHSTy->isPromotableIntegerType())
7227         LHSTy = Context.getPromotedIntegerType(LHSTy);
7228     }
7229     *CompLHSTy = LHSTy;
7230   }
7231 
7232   return PExp->getType();
7233 }
7234 
7235 // C99 6.5.6
7236 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7237                                         SourceLocation Loc,
7238                                         QualType* CompLHSTy) {
7239   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7240 
7241   if (LHS.get()->getType()->isVectorType() ||
7242       RHS.get()->getType()->isVectorType()) {
7243     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7244     if (CompLHSTy) *CompLHSTy = compType;
7245     return compType;
7246   }
7247 
7248   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7249   if (LHS.isInvalid() || RHS.isInvalid())
7250     return QualType();
7251 
7252   // Enforce type constraints: C99 6.5.6p3.
7253 
7254   // Handle the common case first (both operands are arithmetic).
7255   if (!compType.isNull() && compType->isArithmeticType()) {
7256     if (CompLHSTy) *CompLHSTy = compType;
7257     return compType;
7258   }
7259 
7260   // Either ptr - int   or   ptr - ptr.
7261   if (LHS.get()->getType()->isAnyPointerType()) {
7262     QualType lpointee = LHS.get()->getType()->getPointeeType();
7263 
7264     // Diagnose bad cases where we step over interface counts.
7265     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7266         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7267       return QualType();
7268 
7269     // The result type of a pointer-int computation is the pointer type.
7270     if (RHS.get()->getType()->isIntegerType()) {
7271       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7272         return QualType();
7273 
7274       // Check array bounds for pointer arithemtic
7275       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/nullptr,
7276                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7277 
7278       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7279       return LHS.get()->getType();
7280     }
7281 
7282     // Handle pointer-pointer subtractions.
7283     if (const PointerType *RHSPTy
7284           = RHS.get()->getType()->getAs<PointerType>()) {
7285       QualType rpointee = RHSPTy->getPointeeType();
7286 
7287       if (getLangOpts().CPlusPlus) {
7288         // Pointee types must be the same: C++ [expr.add]
7289         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7290           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7291         }
7292       } else {
7293         // Pointee types must be compatible C99 6.5.6p3
7294         if (!Context.typesAreCompatible(
7295                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7296                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7297           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7298           return QualType();
7299         }
7300       }
7301 
7302       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7303                                                LHS.get(), RHS.get()))
7304         return QualType();
7305 
7306       // The pointee type may have zero size.  As an extension, a structure or
7307       // union may have zero size or an array may have zero length.  In this
7308       // case subtraction does not make sense.
7309       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7310         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7311         if (ElementSize.isZero()) {
7312           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7313             << rpointee.getUnqualifiedType()
7314             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7315         }
7316       }
7317 
7318       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7319       return Context.getPointerDiffType();
7320     }
7321   }
7322 
7323   return InvalidOperands(Loc, LHS, RHS);
7324 }
7325 
7326 static bool isScopedEnumerationType(QualType T) {
7327   if (const EnumType *ET = dyn_cast<EnumType>(T))
7328     return ET->getDecl()->isScoped();
7329   return false;
7330 }
7331 
7332 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7333                                    SourceLocation Loc, unsigned Opc,
7334                                    QualType LHSType) {
7335   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7336   // so skip remaining warnings as we don't want to modify values within Sema.
7337   if (S.getLangOpts().OpenCL)
7338     return;
7339 
7340   llvm::APSInt Right;
7341   // Check right/shifter operand
7342   if (RHS.get()->isValueDependent() ||
7343       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7344     return;
7345 
7346   if (Right.isNegative()) {
7347     S.DiagRuntimeBehavior(Loc, RHS.get(),
7348                           S.PDiag(diag::warn_shift_negative)
7349                             << RHS.get()->getSourceRange());
7350     return;
7351   }
7352   llvm::APInt LeftBits(Right.getBitWidth(),
7353                        S.Context.getTypeSize(LHS.get()->getType()));
7354   if (Right.uge(LeftBits)) {
7355     S.DiagRuntimeBehavior(Loc, RHS.get(),
7356                           S.PDiag(diag::warn_shift_gt_typewidth)
7357                             << RHS.get()->getSourceRange());
7358     return;
7359   }
7360   if (Opc != BO_Shl)
7361     return;
7362 
7363   // When left shifting an ICE which is signed, we can check for overflow which
7364   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7365   // integers have defined behavior modulo one more than the maximum value
7366   // representable in the result type, so never warn for those.
7367   llvm::APSInt Left;
7368   if (LHS.get()->isValueDependent() ||
7369       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7370       LHSType->hasUnsignedIntegerRepresentation())
7371     return;
7372   llvm::APInt ResultBits =
7373       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7374   if (LeftBits.uge(ResultBits))
7375     return;
7376   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7377   Result = Result.shl(Right);
7378 
7379   // Print the bit representation of the signed integer as an unsigned
7380   // hexadecimal number.
7381   SmallString<40> HexResult;
7382   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7383 
7384   // If we are only missing a sign bit, this is less likely to result in actual
7385   // bugs -- if the result is cast back to an unsigned type, it will have the
7386   // expected value. Thus we place this behind a different warning that can be
7387   // turned off separately if needed.
7388   if (LeftBits == ResultBits - 1) {
7389     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7390         << HexResult.str() << LHSType
7391         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7392     return;
7393   }
7394 
7395   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7396     << HexResult.str() << Result.getMinSignedBits() << LHSType
7397     << Left.getBitWidth() << LHS.get()->getSourceRange()
7398     << RHS.get()->getSourceRange();
7399 }
7400 
7401 // C99 6.5.7
7402 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7403                                   SourceLocation Loc, unsigned Opc,
7404                                   bool IsCompAssign) {
7405   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7406 
7407   // Vector shifts promote their scalar inputs to vector type.
7408   if (LHS.get()->getType()->isVectorType() ||
7409       RHS.get()->getType()->isVectorType())
7410     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7411 
7412   // Shifts don't perform usual arithmetic conversions, they just do integer
7413   // promotions on each operand. C99 6.5.7p3
7414 
7415   // For the LHS, do usual unary conversions, but then reset them away
7416   // if this is a compound assignment.
7417   ExprResult OldLHS = LHS;
7418   LHS = UsualUnaryConversions(LHS.get());
7419   if (LHS.isInvalid())
7420     return QualType();
7421   QualType LHSType = LHS.get()->getType();
7422   if (IsCompAssign) LHS = OldLHS;
7423 
7424   // The RHS is simpler.
7425   RHS = UsualUnaryConversions(RHS.get());
7426   if (RHS.isInvalid())
7427     return QualType();
7428   QualType RHSType = RHS.get()->getType();
7429 
7430   // C99 6.5.7p2: Each of the operands shall have integer type.
7431   if (!LHSType->hasIntegerRepresentation() ||
7432       !RHSType->hasIntegerRepresentation())
7433     return InvalidOperands(Loc, LHS, RHS);
7434 
7435   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7436   // hasIntegerRepresentation() above instead of this.
7437   if (isScopedEnumerationType(LHSType) ||
7438       isScopedEnumerationType(RHSType)) {
7439     return InvalidOperands(Loc, LHS, RHS);
7440   }
7441   // Sanity-check shift operands
7442   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7443 
7444   // "The type of the result is that of the promoted left operand."
7445   return LHSType;
7446 }
7447 
7448 static bool IsWithinTemplateSpecialization(Decl *D) {
7449   if (DeclContext *DC = D->getDeclContext()) {
7450     if (isa<ClassTemplateSpecializationDecl>(DC))
7451       return true;
7452     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7453       return FD->isFunctionTemplateSpecialization();
7454   }
7455   return false;
7456 }
7457 
7458 /// If two different enums are compared, raise a warning.
7459 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7460                                 Expr *RHS) {
7461   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7462   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7463 
7464   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7465   if (!LHSEnumType)
7466     return;
7467   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7468   if (!RHSEnumType)
7469     return;
7470 
7471   // Ignore anonymous enums.
7472   if (!LHSEnumType->getDecl()->getIdentifier())
7473     return;
7474   if (!RHSEnumType->getDecl()->getIdentifier())
7475     return;
7476 
7477   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7478     return;
7479 
7480   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7481       << LHSStrippedType << RHSStrippedType
7482       << LHS->getSourceRange() << RHS->getSourceRange();
7483 }
7484 
7485 /// \brief Diagnose bad pointer comparisons.
7486 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7487                                               ExprResult &LHS, ExprResult &RHS,
7488                                               bool IsError) {
7489   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7490                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7491     << LHS.get()->getType() << RHS.get()->getType()
7492     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7493 }
7494 
7495 /// \brief Returns false if the pointers are converted to a composite type,
7496 /// true otherwise.
7497 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7498                                            ExprResult &LHS, ExprResult &RHS) {
7499   // C++ [expr.rel]p2:
7500   //   [...] Pointer conversions (4.10) and qualification
7501   //   conversions (4.4) are performed on pointer operands (or on
7502   //   a pointer operand and a null pointer constant) to bring
7503   //   them to their composite pointer type. [...]
7504   //
7505   // C++ [expr.eq]p1 uses the same notion for (in)equality
7506   // comparisons of pointers.
7507 
7508   // C++ [expr.eq]p2:
7509   //   In addition, pointers to members can be compared, or a pointer to
7510   //   member and a null pointer constant. Pointer to member conversions
7511   //   (4.11) and qualification conversions (4.4) are performed to bring
7512   //   them to a common type. If one operand is a null pointer constant,
7513   //   the common type is the type of the other operand. Otherwise, the
7514   //   common type is a pointer to member type similar (4.4) to the type
7515   //   of one of the operands, with a cv-qualification signature (4.4)
7516   //   that is the union of the cv-qualification signatures of the operand
7517   //   types.
7518 
7519   QualType LHSType = LHS.get()->getType();
7520   QualType RHSType = RHS.get()->getType();
7521   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7522          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7523 
7524   bool NonStandardCompositeType = false;
7525   bool *BoolPtr = S.isSFINAEContext() ? nullptr : &NonStandardCompositeType;
7526   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7527   if (T.isNull()) {
7528     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7529     return true;
7530   }
7531 
7532   if (NonStandardCompositeType)
7533     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7534       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7535       << RHS.get()->getSourceRange();
7536 
7537   LHS = S.ImpCastExprToType(LHS.get(), T, CK_BitCast);
7538   RHS = S.ImpCastExprToType(RHS.get(), T, CK_BitCast);
7539   return false;
7540 }
7541 
7542 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7543                                                     ExprResult &LHS,
7544                                                     ExprResult &RHS,
7545                                                     bool IsError) {
7546   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7547                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7548     << LHS.get()->getType() << RHS.get()->getType()
7549     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7550 }
7551 
7552 static bool isObjCObjectLiteral(ExprResult &E) {
7553   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7554   case Stmt::ObjCArrayLiteralClass:
7555   case Stmt::ObjCDictionaryLiteralClass:
7556   case Stmt::ObjCStringLiteralClass:
7557   case Stmt::ObjCBoxedExprClass:
7558     return true;
7559   default:
7560     // Note that ObjCBoolLiteral is NOT an object literal!
7561     return false;
7562   }
7563 }
7564 
7565 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7566   const ObjCObjectPointerType *Type =
7567     LHS->getType()->getAs<ObjCObjectPointerType>();
7568 
7569   // If this is not actually an Objective-C object, bail out.
7570   if (!Type)
7571     return false;
7572 
7573   // Get the LHS object's interface type.
7574   QualType InterfaceType = Type->getPointeeType();
7575   if (const ObjCObjectType *iQFaceTy =
7576       InterfaceType->getAsObjCQualifiedInterfaceType())
7577     InterfaceType = iQFaceTy->getBaseType();
7578 
7579   // If the RHS isn't an Objective-C object, bail out.
7580   if (!RHS->getType()->isObjCObjectPointerType())
7581     return false;
7582 
7583   // Try to find the -isEqual: method.
7584   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7585   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7586                                                       InterfaceType,
7587                                                       /*instance=*/true);
7588   if (!Method) {
7589     if (Type->isObjCIdType()) {
7590       // For 'id', just check the global pool.
7591       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7592                                                   /*receiverId=*/true,
7593                                                   /*warn=*/false);
7594     } else {
7595       // Check protocols.
7596       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7597                                              /*instance=*/true);
7598     }
7599   }
7600 
7601   if (!Method)
7602     return false;
7603 
7604   QualType T = Method->param_begin()[0]->getType();
7605   if (!T->isObjCObjectPointerType())
7606     return false;
7607 
7608   QualType R = Method->getReturnType();
7609   if (!R->isScalarType())
7610     return false;
7611 
7612   return true;
7613 }
7614 
7615 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7616   FromE = FromE->IgnoreParenImpCasts();
7617   switch (FromE->getStmtClass()) {
7618     default:
7619       break;
7620     case Stmt::ObjCStringLiteralClass:
7621       // "string literal"
7622       return LK_String;
7623     case Stmt::ObjCArrayLiteralClass:
7624       // "array literal"
7625       return LK_Array;
7626     case Stmt::ObjCDictionaryLiteralClass:
7627       // "dictionary literal"
7628       return LK_Dictionary;
7629     case Stmt::BlockExprClass:
7630       return LK_Block;
7631     case Stmt::ObjCBoxedExprClass: {
7632       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7633       switch (Inner->getStmtClass()) {
7634         case Stmt::IntegerLiteralClass:
7635         case Stmt::FloatingLiteralClass:
7636         case Stmt::CharacterLiteralClass:
7637         case Stmt::ObjCBoolLiteralExprClass:
7638         case Stmt::CXXBoolLiteralExprClass:
7639           // "numeric literal"
7640           return LK_Numeric;
7641         case Stmt::ImplicitCastExprClass: {
7642           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7643           // Boolean literals can be represented by implicit casts.
7644           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7645             return LK_Numeric;
7646           break;
7647         }
7648         default:
7649           break;
7650       }
7651       return LK_Boxed;
7652     }
7653   }
7654   return LK_None;
7655 }
7656 
7657 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7658                                           ExprResult &LHS, ExprResult &RHS,
7659                                           BinaryOperator::Opcode Opc){
7660   Expr *Literal;
7661   Expr *Other;
7662   if (isObjCObjectLiteral(LHS)) {
7663     Literal = LHS.get();
7664     Other = RHS.get();
7665   } else {
7666     Literal = RHS.get();
7667     Other = LHS.get();
7668   }
7669 
7670   // Don't warn on comparisons against nil.
7671   Other = Other->IgnoreParenCasts();
7672   if (Other->isNullPointerConstant(S.getASTContext(),
7673                                    Expr::NPC_ValueDependentIsNotNull))
7674     return;
7675 
7676   // This should be kept in sync with warn_objc_literal_comparison.
7677   // LK_String should always be after the other literals, since it has its own
7678   // warning flag.
7679   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7680   assert(LiteralKind != Sema::LK_Block);
7681   if (LiteralKind == Sema::LK_None) {
7682     llvm_unreachable("Unknown Objective-C object literal kind");
7683   }
7684 
7685   if (LiteralKind == Sema::LK_String)
7686     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7687       << Literal->getSourceRange();
7688   else
7689     S.Diag(Loc, diag::warn_objc_literal_comparison)
7690       << LiteralKind << Literal->getSourceRange();
7691 
7692   if (BinaryOperator::isEqualityOp(Opc) &&
7693       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7694     SourceLocation Start = LHS.get()->getLocStart();
7695     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7696     CharSourceRange OpRange =
7697       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7698 
7699     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7700       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7701       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7702       << FixItHint::CreateInsertion(End, "]");
7703   }
7704 }
7705 
7706 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7707                                                 ExprResult &RHS,
7708                                                 SourceLocation Loc,
7709                                                 unsigned OpaqueOpc) {
7710   // This checking requires bools.
7711   if (!S.getLangOpts().Bool) return;
7712 
7713   // Check that left hand side is !something.
7714   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7715   if (!UO || UO->getOpcode() != UO_LNot) return;
7716 
7717   // Only check if the right hand side is non-bool arithmetic type.
7718   if (RHS.get()->getType()->isBooleanType()) return;
7719 
7720   // Make sure that the something in !something is not bool.
7721   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7722   if (SubExpr->getType()->isBooleanType()) return;
7723 
7724   // Emit warning.
7725   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7726       << Loc;
7727 
7728   // First note suggest !(x < y)
7729   SourceLocation FirstOpen = SubExpr->getLocStart();
7730   SourceLocation FirstClose = RHS.get()->getLocEnd();
7731   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7732   if (FirstClose.isInvalid())
7733     FirstOpen = SourceLocation();
7734   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7735       << FixItHint::CreateInsertion(FirstOpen, "(")
7736       << FixItHint::CreateInsertion(FirstClose, ")");
7737 
7738   // Second note suggests (!x) < y
7739   SourceLocation SecondOpen = LHS.get()->getLocStart();
7740   SourceLocation SecondClose = LHS.get()->getLocEnd();
7741   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7742   if (SecondClose.isInvalid())
7743     SecondOpen = SourceLocation();
7744   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7745       << FixItHint::CreateInsertion(SecondOpen, "(")
7746       << FixItHint::CreateInsertion(SecondClose, ")");
7747 }
7748 
7749 // Get the decl for a simple expression: a reference to a variable,
7750 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7751 static ValueDecl *getCompareDecl(Expr *E) {
7752   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7753     return DR->getDecl();
7754   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7755     if (Ivar->isFreeIvar())
7756       return Ivar->getDecl();
7757   }
7758   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7759     if (Mem->isImplicitAccess())
7760       return Mem->getMemberDecl();
7761   }
7762   return nullptr;
7763 }
7764 
7765 // C99 6.5.8, C++ [expr.rel]
7766 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7767                                     SourceLocation Loc, unsigned OpaqueOpc,
7768                                     bool IsRelational) {
7769   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7770 
7771   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7772 
7773   // Handle vector comparisons separately.
7774   if (LHS.get()->getType()->isVectorType() ||
7775       RHS.get()->getType()->isVectorType())
7776     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7777 
7778   QualType LHSType = LHS.get()->getType();
7779   QualType RHSType = RHS.get()->getType();
7780 
7781   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7782   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7783 
7784   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7785   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7786 
7787   if (!LHSType->hasFloatingRepresentation() &&
7788       !(LHSType->isBlockPointerType() && IsRelational) &&
7789       !LHS.get()->getLocStart().isMacroID() &&
7790       !RHS.get()->getLocStart().isMacroID() &&
7791       ActiveTemplateInstantiations.empty()) {
7792     // For non-floating point types, check for self-comparisons of the form
7793     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7794     // often indicate logic errors in the program.
7795     //
7796     // NOTE: Don't warn about comparison expressions resulting from macro
7797     // expansion. Also don't warn about comparisons which are only self
7798     // comparisons within a template specialization. The warnings should catch
7799     // obvious cases in the definition of the template anyways. The idea is to
7800     // warn when the typed comparison operator will always evaluate to the same
7801     // result.
7802     ValueDecl *DL = getCompareDecl(LHSStripped);
7803     ValueDecl *DR = getCompareDecl(RHSStripped);
7804     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7805       DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7806                           << 0 // self-
7807                           << (Opc == BO_EQ
7808                               || Opc == BO_LE
7809                               || Opc == BO_GE));
7810     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7811                !DL->getType()->isReferenceType() &&
7812                !DR->getType()->isReferenceType()) {
7813         // what is it always going to eval to?
7814         char always_evals_to;
7815         switch(Opc) {
7816         case BO_EQ: // e.g. array1 == array2
7817           always_evals_to = 0; // false
7818           break;
7819         case BO_NE: // e.g. array1 != array2
7820           always_evals_to = 1; // true
7821           break;
7822         default:
7823           // best we can say is 'a constant'
7824           always_evals_to = 2; // e.g. array1 <= array2
7825           break;
7826         }
7827         DiagRuntimeBehavior(Loc, nullptr, PDiag(diag::warn_comparison_always)
7828                             << 1 // array
7829                             << always_evals_to);
7830     }
7831 
7832     if (isa<CastExpr>(LHSStripped))
7833       LHSStripped = LHSStripped->IgnoreParenCasts();
7834     if (isa<CastExpr>(RHSStripped))
7835       RHSStripped = RHSStripped->IgnoreParenCasts();
7836 
7837     // Warn about comparisons against a string constant (unless the other
7838     // operand is null), the user probably wants strcmp.
7839     Expr *literalString = nullptr;
7840     Expr *literalStringStripped = nullptr;
7841     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7842         !RHSStripped->isNullPointerConstant(Context,
7843                                             Expr::NPC_ValueDependentIsNull)) {
7844       literalString = LHS.get();
7845       literalStringStripped = LHSStripped;
7846     } else if ((isa<StringLiteral>(RHSStripped) ||
7847                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7848                !LHSStripped->isNullPointerConstant(Context,
7849                                             Expr::NPC_ValueDependentIsNull)) {
7850       literalString = RHS.get();
7851       literalStringStripped = RHSStripped;
7852     }
7853 
7854     if (literalString) {
7855       DiagRuntimeBehavior(Loc, nullptr,
7856         PDiag(diag::warn_stringcompare)
7857           << isa<ObjCEncodeExpr>(literalStringStripped)
7858           << literalString->getSourceRange());
7859     }
7860   }
7861 
7862   // C99 6.5.8p3 / C99 6.5.9p4
7863   UsualArithmeticConversions(LHS, RHS);
7864   if (LHS.isInvalid() || RHS.isInvalid())
7865     return QualType();
7866 
7867   LHSType = LHS.get()->getType();
7868   RHSType = RHS.get()->getType();
7869 
7870   // The result of comparisons is 'bool' in C++, 'int' in C.
7871   QualType ResultTy = Context.getLogicalOperationType();
7872 
7873   if (IsRelational) {
7874     if (LHSType->isRealType() && RHSType->isRealType())
7875       return ResultTy;
7876   } else {
7877     // Check for comparisons of floating point operands using != and ==.
7878     if (LHSType->hasFloatingRepresentation())
7879       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7880 
7881     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7882       return ResultTy;
7883   }
7884 
7885   const Expr::NullPointerConstantKind LHSNullKind =
7886       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7887   const Expr::NullPointerConstantKind RHSNullKind =
7888       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7889   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
7890   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
7891 
7892   if (!IsRelational && LHSIsNull != RHSIsNull) {
7893     bool IsEquality = Opc == BO_EQ;
7894     if (RHSIsNull)
7895       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
7896                                    RHS.get()->getSourceRange());
7897     else
7898       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
7899                                    LHS.get()->getSourceRange());
7900   }
7901 
7902   // All of the following pointer-related warnings are GCC extensions, except
7903   // when handling null pointer constants.
7904   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7905     QualType LCanPointeeTy =
7906       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7907     QualType RCanPointeeTy =
7908       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7909 
7910     if (getLangOpts().CPlusPlus) {
7911       if (LCanPointeeTy == RCanPointeeTy)
7912         return ResultTy;
7913       if (!IsRelational &&
7914           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7915         // Valid unless comparison between non-null pointer and function pointer
7916         // This is a gcc extension compatibility comparison.
7917         // In a SFINAE context, we treat this as a hard error to maintain
7918         // conformance with the C++ standard.
7919         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7920             && !LHSIsNull && !RHSIsNull) {
7921           diagnoseFunctionPointerToVoidComparison(
7922               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7923 
7924           if (isSFINAEContext())
7925             return QualType();
7926 
7927           RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
7928           return ResultTy;
7929         }
7930       }
7931 
7932       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7933         return QualType();
7934       else
7935         return ResultTy;
7936     }
7937     // C99 6.5.9p2 and C99 6.5.8p2
7938     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7939                                    RCanPointeeTy.getUnqualifiedType())) {
7940       // Valid unless a relational comparison of function pointers
7941       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7942         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7943           << LHSType << RHSType << LHS.get()->getSourceRange()
7944           << RHS.get()->getSourceRange();
7945       }
7946     } else if (!IsRelational &&
7947                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7948       // Valid unless comparison between non-null pointer and function pointer
7949       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7950           && !LHSIsNull && !RHSIsNull)
7951         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7952                                                 /*isError*/false);
7953     } else {
7954       // Invalid
7955       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7956     }
7957     if (LCanPointeeTy != RCanPointeeTy) {
7958       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
7959       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
7960       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
7961                                                : CK_BitCast;
7962       if (LHSIsNull && !RHSIsNull)
7963         LHS = ImpCastExprToType(LHS.get(), RHSType, Kind);
7964       else
7965         RHS = ImpCastExprToType(RHS.get(), LHSType, Kind);
7966     }
7967     return ResultTy;
7968   }
7969 
7970   if (getLangOpts().CPlusPlus) {
7971     // Comparison of nullptr_t with itself.
7972     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7973       return ResultTy;
7974 
7975     // Comparison of pointers with null pointer constants and equality
7976     // comparisons of member pointers to null pointer constants.
7977     if (RHSIsNull &&
7978         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7979          (!IsRelational &&
7980           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7981       RHS = ImpCastExprToType(RHS.get(), LHSType,
7982                         LHSType->isMemberPointerType()
7983                           ? CK_NullToMemberPointer
7984                           : CK_NullToPointer);
7985       return ResultTy;
7986     }
7987     if (LHSIsNull &&
7988         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7989          (!IsRelational &&
7990           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7991       LHS = ImpCastExprToType(LHS.get(), RHSType,
7992                         RHSType->isMemberPointerType()
7993                           ? CK_NullToMemberPointer
7994                           : CK_NullToPointer);
7995       return ResultTy;
7996     }
7997 
7998     // Comparison of member pointers.
7999     if (!IsRelational &&
8000         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
8001       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
8002         return QualType();
8003       else
8004         return ResultTy;
8005     }
8006 
8007     // Handle scoped enumeration types specifically, since they don't promote
8008     // to integers.
8009     if (LHS.get()->getType()->isEnumeralType() &&
8010         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8011                                        RHS.get()->getType()))
8012       return ResultTy;
8013   }
8014 
8015   // Handle block pointer types.
8016   if (!IsRelational && LHSType->isBlockPointerType() &&
8017       RHSType->isBlockPointerType()) {
8018     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8019     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8020 
8021     if (!LHSIsNull && !RHSIsNull &&
8022         !Context.typesAreCompatible(lpointee, rpointee)) {
8023       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8024         << LHSType << RHSType << LHS.get()->getSourceRange()
8025         << RHS.get()->getSourceRange();
8026     }
8027     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8028     return ResultTy;
8029   }
8030 
8031   // Allow block pointers to be compared with null pointer constants.
8032   if (!IsRelational
8033       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8034           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8035     if (!LHSIsNull && !RHSIsNull) {
8036       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8037              ->getPointeeType()->isVoidType())
8038             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8039                 ->getPointeeType()->isVoidType())))
8040         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8041           << LHSType << RHSType << LHS.get()->getSourceRange()
8042           << RHS.get()->getSourceRange();
8043     }
8044     if (LHSIsNull && !RHSIsNull)
8045       LHS = ImpCastExprToType(LHS.get(), RHSType,
8046                               RHSType->isPointerType() ? CK_BitCast
8047                                 : CK_AnyPointerToBlockPointerCast);
8048     else
8049       RHS = ImpCastExprToType(RHS.get(), LHSType,
8050                               LHSType->isPointerType() ? CK_BitCast
8051                                 : CK_AnyPointerToBlockPointerCast);
8052     return ResultTy;
8053   }
8054 
8055   if (LHSType->isObjCObjectPointerType() ||
8056       RHSType->isObjCObjectPointerType()) {
8057     const PointerType *LPT = LHSType->getAs<PointerType>();
8058     const PointerType *RPT = RHSType->getAs<PointerType>();
8059     if (LPT || RPT) {
8060       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8061       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8062 
8063       if (!LPtrToVoid && !RPtrToVoid &&
8064           !Context.typesAreCompatible(LHSType, RHSType)) {
8065         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8066                                           /*isError*/false);
8067       }
8068       if (LHSIsNull && !RHSIsNull) {
8069         Expr *E = LHS.get();
8070         if (getLangOpts().ObjCAutoRefCount)
8071           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8072         LHS = ImpCastExprToType(E, RHSType,
8073                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8074       }
8075       else {
8076         Expr *E = RHS.get();
8077         if (getLangOpts().ObjCAutoRefCount)
8078           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
8079         RHS = ImpCastExprToType(E, LHSType,
8080                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8081       }
8082       return ResultTy;
8083     }
8084     if (LHSType->isObjCObjectPointerType() &&
8085         RHSType->isObjCObjectPointerType()) {
8086       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8087         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8088                                           /*isError*/false);
8089       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8090         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8091 
8092       if (LHSIsNull && !RHSIsNull)
8093         LHS = ImpCastExprToType(LHS.get(), RHSType, CK_BitCast);
8094       else
8095         RHS = ImpCastExprToType(RHS.get(), LHSType, CK_BitCast);
8096       return ResultTy;
8097     }
8098   }
8099   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8100       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8101     unsigned DiagID = 0;
8102     bool isError = false;
8103     if (LangOpts.DebuggerSupport) {
8104       // Under a debugger, allow the comparison of pointers to integers,
8105       // since users tend to want to compare addresses.
8106     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8107         (RHSIsNull && RHSType->isIntegerType())) {
8108       if (IsRelational && !getLangOpts().CPlusPlus)
8109         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8110     } else if (IsRelational && !getLangOpts().CPlusPlus)
8111       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8112     else if (getLangOpts().CPlusPlus) {
8113       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8114       isError = true;
8115     } else
8116       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8117 
8118     if (DiagID) {
8119       Diag(Loc, DiagID)
8120         << LHSType << RHSType << LHS.get()->getSourceRange()
8121         << RHS.get()->getSourceRange();
8122       if (isError)
8123         return QualType();
8124     }
8125 
8126     if (LHSType->isIntegerType())
8127       LHS = ImpCastExprToType(LHS.get(), RHSType,
8128                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8129     else
8130       RHS = ImpCastExprToType(RHS.get(), LHSType,
8131                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8132     return ResultTy;
8133   }
8134 
8135   // Handle block pointers.
8136   if (!IsRelational && RHSIsNull
8137       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8138     RHS = ImpCastExprToType(RHS.get(), LHSType, CK_NullToPointer);
8139     return ResultTy;
8140   }
8141   if (!IsRelational && LHSIsNull
8142       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8143     LHS = ImpCastExprToType(LHS.get(), RHSType, CK_NullToPointer);
8144     return ResultTy;
8145   }
8146 
8147   return InvalidOperands(Loc, LHS, RHS);
8148 }
8149 
8150 
8151 // Return a signed type that is of identical size and number of elements.
8152 // For floating point vectors, return an integer type of identical size
8153 // and number of elements.
8154 QualType Sema::GetSignedVectorType(QualType V) {
8155   const VectorType *VTy = V->getAs<VectorType>();
8156   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8157   if (TypeSize == Context.getTypeSize(Context.CharTy))
8158     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8159   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8160     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8161   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8162     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8163   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8164     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8165   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8166          "Unhandled vector element size in vector compare");
8167   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8168 }
8169 
8170 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8171 /// operates on extended vector types.  Instead of producing an IntTy result,
8172 /// like a scalar comparison, a vector comparison produces a vector of integer
8173 /// types.
8174 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8175                                           SourceLocation Loc,
8176                                           bool IsRelational) {
8177   // Check to make sure we're operating on vectors of the same type and width,
8178   // Allowing one side to be a scalar of element type.
8179   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8180   if (vType.isNull())
8181     return vType;
8182 
8183   QualType LHSType = LHS.get()->getType();
8184 
8185   // If AltiVec, the comparison results in a numeric type, i.e.
8186   // bool for C++, int for C
8187   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8188     return Context.getLogicalOperationType();
8189 
8190   // For non-floating point types, check for self-comparisons of the form
8191   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8192   // often indicate logic errors in the program.
8193   if (!LHSType->hasFloatingRepresentation() &&
8194       ActiveTemplateInstantiations.empty()) {
8195     if (DeclRefExpr* DRL
8196           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8197       if (DeclRefExpr* DRR
8198             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8199         if (DRL->getDecl() == DRR->getDecl())
8200           DiagRuntimeBehavior(Loc, nullptr,
8201                               PDiag(diag::warn_comparison_always)
8202                                 << 0 // self-
8203                                 << 2 // "a constant"
8204                               );
8205   }
8206 
8207   // Check for comparisons of floating point operands using != and ==.
8208   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8209     assert (RHS.get()->getType()->hasFloatingRepresentation());
8210     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8211   }
8212 
8213   // Return a signed type for the vector.
8214   return GetSignedVectorType(LHSType);
8215 }
8216 
8217 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8218                                           SourceLocation Loc) {
8219   // Ensure that either both operands are of the same vector type, or
8220   // one operand is of a vector type and the other is of its element type.
8221   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8222   if (vType.isNull())
8223     return InvalidOperands(Loc, LHS, RHS);
8224   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8225       vType->hasFloatingRepresentation())
8226     return InvalidOperands(Loc, LHS, RHS);
8227 
8228   return GetSignedVectorType(LHS.get()->getType());
8229 }
8230 
8231 inline QualType Sema::CheckBitwiseOperands(
8232   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8233   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8234 
8235   if (LHS.get()->getType()->isVectorType() ||
8236       RHS.get()->getType()->isVectorType()) {
8237     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8238         RHS.get()->getType()->hasIntegerRepresentation())
8239       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8240 
8241     return InvalidOperands(Loc, LHS, RHS);
8242   }
8243 
8244   ExprResult LHSResult = LHS, RHSResult = RHS;
8245   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8246                                                  IsCompAssign);
8247   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8248     return QualType();
8249   LHS = LHSResult.get();
8250   RHS = RHSResult.get();
8251 
8252   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8253     return compType;
8254   return InvalidOperands(Loc, LHS, RHS);
8255 }
8256 
8257 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8258   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8259 
8260   // Check vector operands differently.
8261   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8262     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8263 
8264   // Diagnose cases where the user write a logical and/or but probably meant a
8265   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8266   // is a constant.
8267   if (LHS.get()->getType()->isIntegerType() &&
8268       !LHS.get()->getType()->isBooleanType() &&
8269       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8270       // Don't warn in macros or template instantiations.
8271       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8272     // If the RHS can be constant folded, and if it constant folds to something
8273     // that isn't 0 or 1 (which indicate a potential logical operation that
8274     // happened to fold to true/false) then warn.
8275     // Parens on the RHS are ignored.
8276     llvm::APSInt Result;
8277     if (RHS.get()->EvaluateAsInt(Result, Context))
8278       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType() &&
8279            !RHS.get()->getExprLoc().isMacroID()) ||
8280           (Result != 0 && Result != 1)) {
8281         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8282           << RHS.get()->getSourceRange()
8283           << (Opc == BO_LAnd ? "&&" : "||");
8284         // Suggest replacing the logical operator with the bitwise version
8285         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8286             << (Opc == BO_LAnd ? "&" : "|")
8287             << FixItHint::CreateReplacement(SourceRange(
8288                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8289                                                 getLangOpts())),
8290                                             Opc == BO_LAnd ? "&" : "|");
8291         if (Opc == BO_LAnd)
8292           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8293           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8294               << FixItHint::CreateRemoval(
8295                   SourceRange(
8296                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8297                                                  0, getSourceManager(),
8298                                                  getLangOpts()),
8299                       RHS.get()->getLocEnd()));
8300       }
8301   }
8302 
8303   if (!Context.getLangOpts().CPlusPlus) {
8304     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8305     // not operate on the built-in scalar and vector float types.
8306     if (Context.getLangOpts().OpenCL &&
8307         Context.getLangOpts().OpenCLVersion < 120) {
8308       if (LHS.get()->getType()->isFloatingType() ||
8309           RHS.get()->getType()->isFloatingType())
8310         return InvalidOperands(Loc, LHS, RHS);
8311     }
8312 
8313     LHS = UsualUnaryConversions(LHS.get());
8314     if (LHS.isInvalid())
8315       return QualType();
8316 
8317     RHS = UsualUnaryConversions(RHS.get());
8318     if (RHS.isInvalid())
8319       return QualType();
8320 
8321     if (!LHS.get()->getType()->isScalarType() ||
8322         !RHS.get()->getType()->isScalarType())
8323       return InvalidOperands(Loc, LHS, RHS);
8324 
8325     return Context.IntTy;
8326   }
8327 
8328   // The following is safe because we only use this method for
8329   // non-overloadable operands.
8330 
8331   // C++ [expr.log.and]p1
8332   // C++ [expr.log.or]p1
8333   // The operands are both contextually converted to type bool.
8334   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8335   if (LHSRes.isInvalid())
8336     return InvalidOperands(Loc, LHS, RHS);
8337   LHS = LHSRes;
8338 
8339   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8340   if (RHSRes.isInvalid())
8341     return InvalidOperands(Loc, LHS, RHS);
8342   RHS = RHSRes;
8343 
8344   // C++ [expr.log.and]p2
8345   // C++ [expr.log.or]p2
8346   // The result is a bool.
8347   return Context.BoolTy;
8348 }
8349 
8350 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8351   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8352   if (!ME) return false;
8353   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8354   ObjCMessageExpr *Base =
8355     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8356   if (!Base) return false;
8357   return Base->getMethodDecl() != nullptr;
8358 }
8359 
8360 /// Is the given expression (which must be 'const') a reference to a
8361 /// variable which was originally non-const, but which has become
8362 /// 'const' due to being captured within a block?
8363 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8364 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8365   assert(E->isLValue() && E->getType().isConstQualified());
8366   E = E->IgnoreParens();
8367 
8368   // Must be a reference to a declaration from an enclosing scope.
8369   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8370   if (!DRE) return NCCK_None;
8371   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8372 
8373   // The declaration must be a variable which is not declared 'const'.
8374   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8375   if (!var) return NCCK_None;
8376   if (var->getType().isConstQualified()) return NCCK_None;
8377   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8378 
8379   // Decide whether the first capture was for a block or a lambda.
8380   DeclContext *DC = S.CurContext, *Prev = nullptr;
8381   while (DC != var->getDeclContext()) {
8382     Prev = DC;
8383     DC = DC->getParent();
8384   }
8385   // Unless we have an init-capture, we've gone one step too far.
8386   if (!var->isInitCapture())
8387     DC = Prev;
8388   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8389 }
8390 
8391 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8392 /// emit an error and return true.  If so, return false.
8393 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8394   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8395   SourceLocation OrigLoc = Loc;
8396   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8397                                                               &Loc);
8398   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8399     IsLV = Expr::MLV_InvalidMessageExpression;
8400   if (IsLV == Expr::MLV_Valid)
8401     return false;
8402 
8403   unsigned Diag = 0;
8404   bool NeedType = false;
8405   switch (IsLV) { // C99 6.5.16p2
8406   case Expr::MLV_ConstQualified:
8407     Diag = diag::err_typecheck_assign_const;
8408 
8409     // Use a specialized diagnostic when we're assigning to an object
8410     // from an enclosing function or block.
8411     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8412       if (NCCK == NCCK_Block)
8413         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8414       else
8415         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8416       break;
8417     }
8418 
8419     // In ARC, use some specialized diagnostics for occasions where we
8420     // infer 'const'.  These are always pseudo-strong variables.
8421     if (S.getLangOpts().ObjCAutoRefCount) {
8422       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8423       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8424         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8425 
8426         // Use the normal diagnostic if it's pseudo-__strong but the
8427         // user actually wrote 'const'.
8428         if (var->isARCPseudoStrong() &&
8429             (!var->getTypeSourceInfo() ||
8430              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8431           // There are two pseudo-strong cases:
8432           //  - self
8433           ObjCMethodDecl *method = S.getCurMethodDecl();
8434           if (method && var == method->getSelfDecl())
8435             Diag = method->isClassMethod()
8436               ? diag::err_typecheck_arc_assign_self_class_method
8437               : diag::err_typecheck_arc_assign_self;
8438 
8439           //  - fast enumeration variables
8440           else
8441             Diag = diag::err_typecheck_arr_assign_enumeration;
8442 
8443           SourceRange Assign;
8444           if (Loc != OrigLoc)
8445             Assign = SourceRange(OrigLoc, OrigLoc);
8446           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8447           // We need to preserve the AST regardless, so migration tool
8448           // can do its job.
8449           return false;
8450         }
8451       }
8452     }
8453 
8454     break;
8455   case Expr::MLV_ArrayType:
8456   case Expr::MLV_ArrayTemporary:
8457     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8458     NeedType = true;
8459     break;
8460   case Expr::MLV_NotObjectType:
8461     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8462     NeedType = true;
8463     break;
8464   case Expr::MLV_LValueCast:
8465     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8466     break;
8467   case Expr::MLV_Valid:
8468     llvm_unreachable("did not take early return for MLV_Valid");
8469   case Expr::MLV_InvalidExpression:
8470   case Expr::MLV_MemberFunction:
8471   case Expr::MLV_ClassTemporary:
8472     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8473     break;
8474   case Expr::MLV_IncompleteType:
8475   case Expr::MLV_IncompleteVoidType:
8476     return S.RequireCompleteType(Loc, E->getType(),
8477              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8478   case Expr::MLV_DuplicateVectorComponents:
8479     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8480     break;
8481   case Expr::MLV_NoSetterProperty:
8482     llvm_unreachable("readonly properties should be processed differently");
8483   case Expr::MLV_InvalidMessageExpression:
8484     Diag = diag::error_readonly_message_assignment;
8485     break;
8486   case Expr::MLV_SubObjCPropertySetting:
8487     Diag = diag::error_no_subobject_property_setting;
8488     break;
8489   }
8490 
8491   SourceRange Assign;
8492   if (Loc != OrigLoc)
8493     Assign = SourceRange(OrigLoc, OrigLoc);
8494   if (NeedType)
8495     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8496   else
8497     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8498   return true;
8499 }
8500 
8501 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8502                                          SourceLocation Loc,
8503                                          Sema &Sema) {
8504   // C / C++ fields
8505   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8506   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8507   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8508     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8509       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8510   }
8511 
8512   // Objective-C instance variables
8513   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8514   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8515   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8516     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8517     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8518     if (RL && RR && RL->getDecl() == RR->getDecl())
8519       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8520   }
8521 }
8522 
8523 // C99 6.5.16.1
8524 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8525                                        SourceLocation Loc,
8526                                        QualType CompoundType) {
8527   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8528 
8529   // Verify that LHS is a modifiable lvalue, and emit error if not.
8530   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8531     return QualType();
8532 
8533   QualType LHSType = LHSExpr->getType();
8534   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8535                                              CompoundType;
8536   AssignConvertType ConvTy;
8537   if (CompoundType.isNull()) {
8538     Expr *RHSCheck = RHS.get();
8539 
8540     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8541 
8542     QualType LHSTy(LHSType);
8543     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8544     if (RHS.isInvalid())
8545       return QualType();
8546     // Special case of NSObject attributes on c-style pointer types.
8547     if (ConvTy == IncompatiblePointer &&
8548         ((Context.isObjCNSObjectType(LHSType) &&
8549           RHSType->isObjCObjectPointerType()) ||
8550          (Context.isObjCNSObjectType(RHSType) &&
8551           LHSType->isObjCObjectPointerType())))
8552       ConvTy = Compatible;
8553 
8554     if (ConvTy == Compatible &&
8555         LHSType->isObjCObjectType())
8556         Diag(Loc, diag::err_objc_object_assignment)
8557           << LHSType;
8558 
8559     // If the RHS is a unary plus or minus, check to see if they = and + are
8560     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8561     // instead of "x += 4".
8562     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8563       RHSCheck = ICE->getSubExpr();
8564     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8565       if ((UO->getOpcode() == UO_Plus ||
8566            UO->getOpcode() == UO_Minus) &&
8567           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8568           // Only if the two operators are exactly adjacent.
8569           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8570           // And there is a space or other character before the subexpr of the
8571           // unary +/-.  We don't want to warn on "x=-1".
8572           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8573           UO->getSubExpr()->getLocStart().isFileID()) {
8574         Diag(Loc, diag::warn_not_compound_assign)
8575           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8576           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8577       }
8578     }
8579 
8580     if (ConvTy == Compatible) {
8581       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8582         // Warn about retain cycles where a block captures the LHS, but
8583         // not if the LHS is a simple variable into which the block is
8584         // being stored...unless that variable can be captured by reference!
8585         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8586         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8587         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8588           checkRetainCycles(LHSExpr, RHS.get());
8589 
8590         // It is safe to assign a weak reference into a strong variable.
8591         // Although this code can still have problems:
8592         //   id x = self.weakProp;
8593         //   id y = self.weakProp;
8594         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8595         // paths through the function. This should be revisited if
8596         // -Wrepeated-use-of-weak is made flow-sensitive.
8597         DiagnosticsEngine::Level Level =
8598           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8599                                    RHS.get()->getLocStart());
8600         if (Level != DiagnosticsEngine::Ignored)
8601           getCurFunction()->markSafeWeakUse(RHS.get());
8602 
8603       } else if (getLangOpts().ObjCAutoRefCount) {
8604         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8605       }
8606     }
8607   } else {
8608     // Compound assignment "x += y"
8609     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8610   }
8611 
8612   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8613                                RHS.get(), AA_Assigning))
8614     return QualType();
8615 
8616   CheckForNullPointerDereference(*this, LHSExpr);
8617 
8618   // C99 6.5.16p3: The type of an assignment expression is the type of the
8619   // left operand unless the left operand has qualified type, in which case
8620   // it is the unqualified version of the type of the left operand.
8621   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8622   // is converted to the type of the assignment expression (above).
8623   // C++ 5.17p1: the type of the assignment expression is that of its left
8624   // operand.
8625   return (getLangOpts().CPlusPlus
8626           ? LHSType : LHSType.getUnqualifiedType());
8627 }
8628 
8629 // C99 6.5.17
8630 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8631                                    SourceLocation Loc) {
8632   LHS = S.CheckPlaceholderExpr(LHS.get());
8633   RHS = S.CheckPlaceholderExpr(RHS.get());
8634   if (LHS.isInvalid() || RHS.isInvalid())
8635     return QualType();
8636 
8637   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8638   // operands, but not unary promotions.
8639   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8640 
8641   // So we treat the LHS as a ignored value, and in C++ we allow the
8642   // containing site to determine what should be done with the RHS.
8643   LHS = S.IgnoredValueConversions(LHS.get());
8644   if (LHS.isInvalid())
8645     return QualType();
8646 
8647   S.DiagnoseUnusedExprResult(LHS.get());
8648 
8649   if (!S.getLangOpts().CPlusPlus) {
8650     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.get());
8651     if (RHS.isInvalid())
8652       return QualType();
8653     if (!RHS.get()->getType()->isVoidType())
8654       S.RequireCompleteType(Loc, RHS.get()->getType(),
8655                             diag::err_incomplete_type);
8656   }
8657 
8658   return RHS.get()->getType();
8659 }
8660 
8661 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8662 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8663 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8664                                                ExprValueKind &VK,
8665                                                SourceLocation OpLoc,
8666                                                bool IsInc, bool IsPrefix) {
8667   if (Op->isTypeDependent())
8668     return S.Context.DependentTy;
8669 
8670   QualType ResType = Op->getType();
8671   // Atomic types can be used for increment / decrement where the non-atomic
8672   // versions can, so ignore the _Atomic() specifier for the purpose of
8673   // checking.
8674   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8675     ResType = ResAtomicType->getValueType();
8676 
8677   assert(!ResType.isNull() && "no type for increment/decrement expression");
8678 
8679   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8680     // Decrement of bool is not allowed.
8681     if (!IsInc) {
8682       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8683       return QualType();
8684     }
8685     // Increment of bool sets it to true, but is deprecated.
8686     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8687   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8688     // Error on enum increments and decrements in C++ mode
8689     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8690     return QualType();
8691   } else if (ResType->isRealType()) {
8692     // OK!
8693   } else if (ResType->isPointerType()) {
8694     // C99 6.5.2.4p2, 6.5.6p2
8695     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8696       return QualType();
8697   } else if (ResType->isObjCObjectPointerType()) {
8698     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8699     // Otherwise, we just need a complete type.
8700     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8701         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8702       return QualType();
8703   } else if (ResType->isAnyComplexType()) {
8704     // C99 does not support ++/-- on complex types, we allow as an extension.
8705     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8706       << ResType << Op->getSourceRange();
8707   } else if (ResType->isPlaceholderType()) {
8708     ExprResult PR = S.CheckPlaceholderExpr(Op);
8709     if (PR.isInvalid()) return QualType();
8710     return CheckIncrementDecrementOperand(S, PR.get(), VK, OpLoc,
8711                                           IsInc, IsPrefix);
8712   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8713     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8714   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8715             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8716     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8717   } else {
8718     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8719       << ResType << int(IsInc) << Op->getSourceRange();
8720     return QualType();
8721   }
8722   // At this point, we know we have a real, complex or pointer type.
8723   // Now make sure the operand is a modifiable lvalue.
8724   if (CheckForModifiableLvalue(Op, OpLoc, S))
8725     return QualType();
8726   // In C++, a prefix increment is the same type as the operand. Otherwise
8727   // (in C or with postfix), the increment is the unqualified type of the
8728   // operand.
8729   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8730     VK = VK_LValue;
8731     return ResType;
8732   } else {
8733     VK = VK_RValue;
8734     return ResType.getUnqualifiedType();
8735   }
8736 }
8737 
8738 
8739 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8740 /// This routine allows us to typecheck complex/recursive expressions
8741 /// where the declaration is needed for type checking. We only need to
8742 /// handle cases when the expression references a function designator
8743 /// or is an lvalue. Here are some examples:
8744 ///  - &(x) => x
8745 ///  - &*****f => f for f a function designator.
8746 ///  - &s.xx => s
8747 ///  - &s.zz[1].yy -> s, if zz is an array
8748 ///  - *(x + 1) -> x, if x is an array
8749 ///  - &"123"[2] -> 0
8750 ///  - & __real__ x -> x
8751 static ValueDecl *getPrimaryDecl(Expr *E) {
8752   switch (E->getStmtClass()) {
8753   case Stmt::DeclRefExprClass:
8754     return cast<DeclRefExpr>(E)->getDecl();
8755   case Stmt::MemberExprClass:
8756     // If this is an arrow operator, the address is an offset from
8757     // the base's value, so the object the base refers to is
8758     // irrelevant.
8759     if (cast<MemberExpr>(E)->isArrow())
8760       return nullptr;
8761     // Otherwise, the expression refers to a part of the base
8762     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8763   case Stmt::ArraySubscriptExprClass: {
8764     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8765     // promotion of register arrays earlier.
8766     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8767     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8768       if (ICE->getSubExpr()->getType()->isArrayType())
8769         return getPrimaryDecl(ICE->getSubExpr());
8770     }
8771     return nullptr;
8772   }
8773   case Stmt::UnaryOperatorClass: {
8774     UnaryOperator *UO = cast<UnaryOperator>(E);
8775 
8776     switch(UO->getOpcode()) {
8777     case UO_Real:
8778     case UO_Imag:
8779     case UO_Extension:
8780       return getPrimaryDecl(UO->getSubExpr());
8781     default:
8782       return nullptr;
8783     }
8784   }
8785   case Stmt::ParenExprClass:
8786     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8787   case Stmt::ImplicitCastExprClass:
8788     // If the result of an implicit cast is an l-value, we care about
8789     // the sub-expression; otherwise, the result here doesn't matter.
8790     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8791   default:
8792     return nullptr;
8793   }
8794 }
8795 
8796 namespace {
8797   enum {
8798     AO_Bit_Field = 0,
8799     AO_Vector_Element = 1,
8800     AO_Property_Expansion = 2,
8801     AO_Register_Variable = 3,
8802     AO_No_Error = 4
8803   };
8804 }
8805 /// \brief Diagnose invalid operand for address of operations.
8806 ///
8807 /// \param Type The type of operand which cannot have its address taken.
8808 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8809                                          Expr *E, unsigned Type) {
8810   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8811 }
8812 
8813 /// CheckAddressOfOperand - The operand of & must be either a function
8814 /// designator or an lvalue designating an object. If it is an lvalue, the
8815 /// object cannot be declared with storage class register or be a bit field.
8816 /// Note: The usual conversions are *not* applied to the operand of the &
8817 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8818 /// In C++, the operand might be an overloaded function name, in which case
8819 /// we allow the '&' but retain the overloaded-function type.
8820 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8821   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8822     if (PTy->getKind() == BuiltinType::Overload) {
8823       Expr *E = OrigOp.get()->IgnoreParens();
8824       if (!isa<OverloadExpr>(E)) {
8825         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8826         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8827           << OrigOp.get()->getSourceRange();
8828         return QualType();
8829       }
8830 
8831       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8832       if (isa<UnresolvedMemberExpr>(Ovl))
8833         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8834           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8835             << OrigOp.get()->getSourceRange();
8836           return QualType();
8837         }
8838 
8839       return Context.OverloadTy;
8840     }
8841 
8842     if (PTy->getKind() == BuiltinType::UnknownAny)
8843       return Context.UnknownAnyTy;
8844 
8845     if (PTy->getKind() == BuiltinType::BoundMember) {
8846       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8847         << OrigOp.get()->getSourceRange();
8848       return QualType();
8849     }
8850 
8851     OrigOp = CheckPlaceholderExpr(OrigOp.get());
8852     if (OrigOp.isInvalid()) return QualType();
8853   }
8854 
8855   if (OrigOp.get()->isTypeDependent())
8856     return Context.DependentTy;
8857 
8858   assert(!OrigOp.get()->getType()->isPlaceholderType());
8859 
8860   // Make sure to ignore parentheses in subsequent checks
8861   Expr *op = OrigOp.get()->IgnoreParens();
8862 
8863   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8864   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8865     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8866     return QualType();
8867   }
8868 
8869   if (getLangOpts().C99) {
8870     // Implement C99-only parts of addressof rules.
8871     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8872       if (uOp->getOpcode() == UO_Deref)
8873         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8874         // (assuming the deref expression is valid).
8875         return uOp->getSubExpr()->getType();
8876     }
8877     // Technically, there should be a check for array subscript
8878     // expressions here, but the result of one is always an lvalue anyway.
8879   }
8880   ValueDecl *dcl = getPrimaryDecl(op);
8881   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8882   unsigned AddressOfError = AO_No_Error;
8883 
8884   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8885     bool sfinae = (bool)isSFINAEContext();
8886     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8887                                   : diag::ext_typecheck_addrof_temporary)
8888       << op->getType() << op->getSourceRange();
8889     if (sfinae)
8890       return QualType();
8891     // Materialize the temporary as an lvalue so that we can take its address.
8892     OrigOp = op = new (Context)
8893         MaterializeTemporaryExpr(op->getType(), OrigOp.get(), true);
8894   } else if (isa<ObjCSelectorExpr>(op)) {
8895     return Context.getPointerType(op->getType());
8896   } else if (lval == Expr::LV_MemberFunction) {
8897     // If it's an instance method, make a member pointer.
8898     // The expression must have exactly the form &A::foo.
8899 
8900     // If the underlying expression isn't a decl ref, give up.
8901     if (!isa<DeclRefExpr>(op)) {
8902       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8903         << OrigOp.get()->getSourceRange();
8904       return QualType();
8905     }
8906     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8907     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8908 
8909     // The id-expression was parenthesized.
8910     if (OrigOp.get() != DRE) {
8911       Diag(OpLoc, diag::err_parens_pointer_member_function)
8912         << OrigOp.get()->getSourceRange();
8913 
8914     // The method was named without a qualifier.
8915     } else if (!DRE->getQualifier()) {
8916       if (MD->getParent()->getName().empty())
8917         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8918           << op->getSourceRange();
8919       else {
8920         SmallString<32> Str;
8921         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8922         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8923           << op->getSourceRange()
8924           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8925       }
8926     }
8927 
8928     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
8929     if (isa<CXXDestructorDecl>(MD))
8930       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
8931 
8932     QualType MPTy = Context.getMemberPointerType(
8933         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
8934     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
8935       RequireCompleteType(OpLoc, MPTy, 0);
8936     return MPTy;
8937   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8938     // C99 6.5.3.2p1
8939     // The operand must be either an l-value or a function designator
8940     if (!op->getType()->isFunctionType()) {
8941       // Use a special diagnostic for loads from property references.
8942       if (isa<PseudoObjectExpr>(op)) {
8943         AddressOfError = AO_Property_Expansion;
8944       } else {
8945         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8946           << op->getType() << op->getSourceRange();
8947         return QualType();
8948       }
8949     }
8950   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8951     // The operand cannot be a bit-field
8952     AddressOfError = AO_Bit_Field;
8953   } else if (op->getObjectKind() == OK_VectorComponent) {
8954     // The operand cannot be an element of a vector
8955     AddressOfError = AO_Vector_Element;
8956   } else if (dcl) { // C99 6.5.3.2p1
8957     // We have an lvalue with a decl. Make sure the decl is not declared
8958     // with the register storage-class specifier.
8959     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8960       // in C++ it is not error to take address of a register
8961       // variable (c++03 7.1.1P3)
8962       if (vd->getStorageClass() == SC_Register &&
8963           !getLangOpts().CPlusPlus) {
8964         AddressOfError = AO_Register_Variable;
8965       }
8966     } else if (isa<FunctionTemplateDecl>(dcl)) {
8967       return Context.OverloadTy;
8968     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8969       // Okay: we can take the address of a field.
8970       // Could be a pointer to member, though, if there is an explicit
8971       // scope qualifier for the class.
8972       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8973         DeclContext *Ctx = dcl->getDeclContext();
8974         if (Ctx && Ctx->isRecord()) {
8975           if (dcl->getType()->isReferenceType()) {
8976             Diag(OpLoc,
8977                  diag::err_cannot_form_pointer_to_member_of_reference_type)
8978               << dcl->getDeclName() << dcl->getType();
8979             return QualType();
8980           }
8981 
8982           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8983             Ctx = Ctx->getParent();
8984 
8985           QualType MPTy = Context.getMemberPointerType(
8986               op->getType(),
8987               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8988           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
8989             RequireCompleteType(OpLoc, MPTy, 0);
8990           return MPTy;
8991         }
8992       }
8993     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8994       llvm_unreachable("Unknown/unexpected decl type");
8995   }
8996 
8997   if (AddressOfError != AO_No_Error) {
8998     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8999     return QualType();
9000   }
9001 
9002   if (lval == Expr::LV_IncompleteVoidType) {
9003     // Taking the address of a void variable is technically illegal, but we
9004     // allow it in cases which are otherwise valid.
9005     // Example: "extern void x; void* y = &x;".
9006     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
9007   }
9008 
9009   // If the operand has type "type", the result has type "pointer to type".
9010   if (op->getType()->isObjCObjectType())
9011     return Context.getObjCObjectPointerType(op->getType());
9012   return Context.getPointerType(op->getType());
9013 }
9014 
9015 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9016 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9017                                         SourceLocation OpLoc) {
9018   if (Op->isTypeDependent())
9019     return S.Context.DependentTy;
9020 
9021   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9022   if (ConvResult.isInvalid())
9023     return QualType();
9024   Op = ConvResult.get();
9025   QualType OpTy = Op->getType();
9026   QualType Result;
9027 
9028   if (isa<CXXReinterpretCastExpr>(Op)) {
9029     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9030     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9031                                      Op->getSourceRange());
9032   }
9033 
9034   if (const PointerType *PT = OpTy->getAs<PointerType>())
9035     Result = PT->getPointeeType();
9036   else if (const ObjCObjectPointerType *OPT =
9037              OpTy->getAs<ObjCObjectPointerType>())
9038     Result = OPT->getPointeeType();
9039   else {
9040     ExprResult PR = S.CheckPlaceholderExpr(Op);
9041     if (PR.isInvalid()) return QualType();
9042     if (PR.get() != Op)
9043       return CheckIndirectionOperand(S, PR.get(), VK, OpLoc);
9044   }
9045 
9046   if (Result.isNull()) {
9047     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9048       << OpTy << Op->getSourceRange();
9049     return QualType();
9050   }
9051 
9052   // Note that per both C89 and C99, indirection is always legal, even if Result
9053   // is an incomplete type or void.  It would be possible to warn about
9054   // dereferencing a void pointer, but it's completely well-defined, and such a
9055   // warning is unlikely to catch any mistakes. In C++, indirection is not valid
9056   // for pointers to 'void' but is fine for any other pointer type:
9057   //
9058   // C++ [expr.unary.op]p1:
9059   //   [...] the expression to which [the unary * operator] is applied shall
9060   //   be a pointer to an object type, or a pointer to a function type
9061   if (S.getLangOpts().CPlusPlus && Result->isVoidType())
9062     S.Diag(OpLoc, diag::ext_typecheck_indirection_through_void_pointer)
9063       << OpTy << Op->getSourceRange();
9064 
9065   // Dereferences are usually l-values...
9066   VK = VK_LValue;
9067 
9068   // ...except that certain expressions are never l-values in C.
9069   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9070     VK = VK_RValue;
9071 
9072   return Result;
9073 }
9074 
9075 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9076   tok::TokenKind Kind) {
9077   BinaryOperatorKind Opc;
9078   switch (Kind) {
9079   default: llvm_unreachable("Unknown binop!");
9080   case tok::periodstar:           Opc = BO_PtrMemD; break;
9081   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9082   case tok::star:                 Opc = BO_Mul; break;
9083   case tok::slash:                Opc = BO_Div; break;
9084   case tok::percent:              Opc = BO_Rem; break;
9085   case tok::plus:                 Opc = BO_Add; break;
9086   case tok::minus:                Opc = BO_Sub; break;
9087   case tok::lessless:             Opc = BO_Shl; break;
9088   case tok::greatergreater:       Opc = BO_Shr; break;
9089   case tok::lessequal:            Opc = BO_LE; break;
9090   case tok::less:                 Opc = BO_LT; break;
9091   case tok::greaterequal:         Opc = BO_GE; break;
9092   case tok::greater:              Opc = BO_GT; break;
9093   case tok::exclaimequal:         Opc = BO_NE; break;
9094   case tok::equalequal:           Opc = BO_EQ; break;
9095   case tok::amp:                  Opc = BO_And; break;
9096   case tok::caret:                Opc = BO_Xor; break;
9097   case tok::pipe:                 Opc = BO_Or; break;
9098   case tok::ampamp:               Opc = BO_LAnd; break;
9099   case tok::pipepipe:             Opc = BO_LOr; break;
9100   case tok::equal:                Opc = BO_Assign; break;
9101   case tok::starequal:            Opc = BO_MulAssign; break;
9102   case tok::slashequal:           Opc = BO_DivAssign; break;
9103   case tok::percentequal:         Opc = BO_RemAssign; break;
9104   case tok::plusequal:            Opc = BO_AddAssign; break;
9105   case tok::minusequal:           Opc = BO_SubAssign; break;
9106   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9107   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9108   case tok::ampequal:             Opc = BO_AndAssign; break;
9109   case tok::caretequal:           Opc = BO_XorAssign; break;
9110   case tok::pipeequal:            Opc = BO_OrAssign; break;
9111   case tok::comma:                Opc = BO_Comma; break;
9112   }
9113   return Opc;
9114 }
9115 
9116 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9117   tok::TokenKind Kind) {
9118   UnaryOperatorKind Opc;
9119   switch (Kind) {
9120   default: llvm_unreachable("Unknown unary op!");
9121   case tok::plusplus:     Opc = UO_PreInc; break;
9122   case tok::minusminus:   Opc = UO_PreDec; break;
9123   case tok::amp:          Opc = UO_AddrOf; break;
9124   case tok::star:         Opc = UO_Deref; break;
9125   case tok::plus:         Opc = UO_Plus; break;
9126   case tok::minus:        Opc = UO_Minus; break;
9127   case tok::tilde:        Opc = UO_Not; break;
9128   case tok::exclaim:      Opc = UO_LNot; break;
9129   case tok::kw___real:    Opc = UO_Real; break;
9130   case tok::kw___imag:    Opc = UO_Imag; break;
9131   case tok::kw___extension__: Opc = UO_Extension; break;
9132   }
9133   return Opc;
9134 }
9135 
9136 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9137 /// This warning is only emitted for builtin assignment operations. It is also
9138 /// suppressed in the event of macro expansions.
9139 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9140                                    SourceLocation OpLoc) {
9141   if (!S.ActiveTemplateInstantiations.empty())
9142     return;
9143   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9144     return;
9145   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9146   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9147   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9148   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9149   if (!LHSDeclRef || !RHSDeclRef ||
9150       LHSDeclRef->getLocation().isMacroID() ||
9151       RHSDeclRef->getLocation().isMacroID())
9152     return;
9153   const ValueDecl *LHSDecl =
9154     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9155   const ValueDecl *RHSDecl =
9156     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9157   if (LHSDecl != RHSDecl)
9158     return;
9159   if (LHSDecl->getType().isVolatileQualified())
9160     return;
9161   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9162     if (RefTy->getPointeeType().isVolatileQualified())
9163       return;
9164 
9165   S.Diag(OpLoc, diag::warn_self_assignment)
9166       << LHSDeclRef->getType()
9167       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9168 }
9169 
9170 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9171 /// is usually indicative of introspection within the Objective-C pointer.
9172 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9173                                           SourceLocation OpLoc) {
9174   if (!S.getLangOpts().ObjC1)
9175     return;
9176 
9177   const Expr *ObjCPointerExpr = nullptr, *OtherExpr = nullptr;
9178   const Expr *LHS = L.get();
9179   const Expr *RHS = R.get();
9180 
9181   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9182     ObjCPointerExpr = LHS;
9183     OtherExpr = RHS;
9184   }
9185   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9186     ObjCPointerExpr = RHS;
9187     OtherExpr = LHS;
9188   }
9189 
9190   // This warning is deliberately made very specific to reduce false
9191   // positives with logic that uses '&' for hashing.  This logic mainly
9192   // looks for code trying to introspect into tagged pointers, which
9193   // code should generally never do.
9194   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9195     unsigned Diag = diag::warn_objc_pointer_masking;
9196     // Determine if we are introspecting the result of performSelectorXXX.
9197     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9198     // Special case messages to -performSelector and friends, which
9199     // can return non-pointer values boxed in a pointer value.
9200     // Some clients may wish to silence warnings in this subcase.
9201     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9202       Selector S = ME->getSelector();
9203       StringRef SelArg0 = S.getNameForSlot(0);
9204       if (SelArg0.startswith("performSelector"))
9205         Diag = diag::warn_objc_pointer_masking_performSelector;
9206     }
9207 
9208     S.Diag(OpLoc, Diag)
9209       << ObjCPointerExpr->getSourceRange();
9210   }
9211 }
9212 
9213 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9214 /// operator @p Opc at location @c TokLoc. This routine only supports
9215 /// built-in operations; ActOnBinOp handles overloaded operators.
9216 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9217                                     BinaryOperatorKind Opc,
9218                                     Expr *LHSExpr, Expr *RHSExpr) {
9219   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9220     // The syntax only allows initializer lists on the RHS of assignment,
9221     // so we don't need to worry about accepting invalid code for
9222     // non-assignment operators.
9223     // C++11 5.17p9:
9224     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9225     //   of x = {} is x = T().
9226     InitializationKind Kind =
9227         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9228     InitializedEntity Entity =
9229         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9230     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9231     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9232     if (Init.isInvalid())
9233       return Init;
9234     RHSExpr = Init.get();
9235   }
9236 
9237   ExprResult LHS = LHSExpr, RHS = RHSExpr;
9238   QualType ResultTy;     // Result type of the binary operator.
9239   // The following two variables are used for compound assignment operators
9240   QualType CompLHSTy;    // Type of LHS after promotions for computation
9241   QualType CompResultTy; // Type of computation result
9242   ExprValueKind VK = VK_RValue;
9243   ExprObjectKind OK = OK_Ordinary;
9244 
9245   switch (Opc) {
9246   case BO_Assign:
9247     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9248     if (getLangOpts().CPlusPlus &&
9249         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9250       VK = LHS.get()->getValueKind();
9251       OK = LHS.get()->getObjectKind();
9252     }
9253     if (!ResultTy.isNull())
9254       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9255     break;
9256   case BO_PtrMemD:
9257   case BO_PtrMemI:
9258     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9259                                             Opc == BO_PtrMemI);
9260     break;
9261   case BO_Mul:
9262   case BO_Div:
9263     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9264                                            Opc == BO_Div);
9265     break;
9266   case BO_Rem:
9267     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9268     break;
9269   case BO_Add:
9270     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9271     break;
9272   case BO_Sub:
9273     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9274     break;
9275   case BO_Shl:
9276   case BO_Shr:
9277     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9278     break;
9279   case BO_LE:
9280   case BO_LT:
9281   case BO_GE:
9282   case BO_GT:
9283     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9284     break;
9285   case BO_EQ:
9286   case BO_NE:
9287     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9288     break;
9289   case BO_And:
9290     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9291   case BO_Xor:
9292   case BO_Or:
9293     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9294     break;
9295   case BO_LAnd:
9296   case BO_LOr:
9297     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9298     break;
9299   case BO_MulAssign:
9300   case BO_DivAssign:
9301     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9302                                                Opc == BO_DivAssign);
9303     CompLHSTy = CompResultTy;
9304     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9305       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9306     break;
9307   case BO_RemAssign:
9308     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9309     CompLHSTy = CompResultTy;
9310     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9311       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9312     break;
9313   case BO_AddAssign:
9314     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9315     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9316       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9317     break;
9318   case BO_SubAssign:
9319     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9320     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9321       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9322     break;
9323   case BO_ShlAssign:
9324   case BO_ShrAssign:
9325     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
9326     CompLHSTy = CompResultTy;
9327     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9328       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9329     break;
9330   case BO_AndAssign:
9331   case BO_OrAssign: // fallthrough
9332 	  DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9333   case BO_XorAssign:
9334     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9335     CompLHSTy = CompResultTy;
9336     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9337       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9338     break;
9339   case BO_Comma:
9340     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9341     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9342       VK = RHS.get()->getValueKind();
9343       OK = RHS.get()->getObjectKind();
9344     }
9345     break;
9346   }
9347   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9348     return ExprError();
9349 
9350   // Check for array bounds violations for both sides of the BinaryOperator
9351   CheckArrayAccess(LHS.get());
9352   CheckArrayAccess(RHS.get());
9353 
9354   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9355     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9356                                                  &Context.Idents.get("object_setClass"),
9357                                                  SourceLocation(), LookupOrdinaryName);
9358     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9359       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9360       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9361       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9362       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9363       FixItHint::CreateInsertion(RHSLocEnd, ")");
9364     }
9365     else
9366       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9367   }
9368   else if (const ObjCIvarRefExpr *OIRE =
9369            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9370     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9371 
9372   if (CompResultTy.isNull())
9373     return new (Context) BinaryOperator(LHS.get(), RHS.get(), Opc, ResultTy, VK,
9374                                         OK, OpLoc, FPFeatures.fp_contract);
9375   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9376       OK_ObjCProperty) {
9377     VK = VK_LValue;
9378     OK = LHS.get()->getObjectKind();
9379   }
9380   return new (Context) CompoundAssignOperator(
9381       LHS.get(), RHS.get(), Opc, ResultTy, VK, OK, CompLHSTy, CompResultTy,
9382       OpLoc, FPFeatures.fp_contract);
9383 }
9384 
9385 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9386 /// operators are mixed in a way that suggests that the programmer forgot that
9387 /// comparison operators have higher precedence. The most typical example of
9388 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9389 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9390                                       SourceLocation OpLoc, Expr *LHSExpr,
9391                                       Expr *RHSExpr) {
9392   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9393   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9394 
9395   // Check that one of the sides is a comparison operator.
9396   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9397   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9398   if (!isLeftComp && !isRightComp)
9399     return;
9400 
9401   // Bitwise operations are sometimes used as eager logical ops.
9402   // Don't diagnose this.
9403   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9404   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9405   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9406     return;
9407 
9408   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9409                                                    OpLoc)
9410                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9411   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9412   SourceRange ParensRange = isLeftComp ?
9413       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9414     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9415 
9416   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9417     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9418   SuggestParentheses(Self, OpLoc,
9419     Self.PDiag(diag::note_precedence_silence) << OpStr,
9420     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9421   SuggestParentheses(Self, OpLoc,
9422     Self.PDiag(diag::note_precedence_bitwise_first)
9423       << BinaryOperator::getOpcodeStr(Opc),
9424     ParensRange);
9425 }
9426 
9427 /// \brief It accepts a '&' expr that is inside a '|' one.
9428 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9429 /// in parentheses.
9430 static void
9431 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9432                                        BinaryOperator *Bop) {
9433   assert(Bop->getOpcode() == BO_And);
9434   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9435       << Bop->getSourceRange() << OpLoc;
9436   SuggestParentheses(Self, Bop->getOperatorLoc(),
9437     Self.PDiag(diag::note_precedence_silence)
9438       << Bop->getOpcodeStr(),
9439     Bop->getSourceRange());
9440 }
9441 
9442 /// \brief It accepts a '&&' expr that is inside a '||' one.
9443 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9444 /// in parentheses.
9445 static void
9446 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9447                                        BinaryOperator *Bop) {
9448   assert(Bop->getOpcode() == BO_LAnd);
9449   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9450       << Bop->getSourceRange() << OpLoc;
9451   SuggestParentheses(Self, Bop->getOperatorLoc(),
9452     Self.PDiag(diag::note_precedence_silence)
9453       << Bop->getOpcodeStr(),
9454     Bop->getSourceRange());
9455 }
9456 
9457 /// \brief Returns true if the given expression can be evaluated as a constant
9458 /// 'true'.
9459 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9460   bool Res;
9461   return !E->isValueDependent() &&
9462          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9463 }
9464 
9465 /// \brief Returns true if the given expression can be evaluated as a constant
9466 /// 'false'.
9467 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9468   bool Res;
9469   return !E->isValueDependent() &&
9470          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9471 }
9472 
9473 /// \brief Look for '&&' in the left hand of a '||' expr.
9474 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9475                                              Expr *LHSExpr, Expr *RHSExpr) {
9476   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9477     if (Bop->getOpcode() == BO_LAnd) {
9478       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9479       if (EvaluatesAsFalse(S, RHSExpr))
9480         return;
9481       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9482       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9483         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9484     } else if (Bop->getOpcode() == BO_LOr) {
9485       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9486         // If it's "a || b && 1 || c" we didn't warn earlier for
9487         // "a || b && 1", but warn now.
9488         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9489           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9490       }
9491     }
9492   }
9493 }
9494 
9495 /// \brief Look for '&&' in the right hand of a '||' expr.
9496 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9497                                              Expr *LHSExpr, Expr *RHSExpr) {
9498   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9499     if (Bop->getOpcode() == BO_LAnd) {
9500       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9501       if (EvaluatesAsFalse(S, LHSExpr))
9502         return;
9503       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9504       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9505         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9506     }
9507   }
9508 }
9509 
9510 /// \brief Look for '&' in the left or right hand of a '|' expr.
9511 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9512                                              Expr *OrArg) {
9513   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9514     if (Bop->getOpcode() == BO_And)
9515       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9516   }
9517 }
9518 
9519 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9520                                     Expr *SubExpr, StringRef Shift) {
9521   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9522     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9523       StringRef Op = Bop->getOpcodeStr();
9524       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9525           << Bop->getSourceRange() << OpLoc << Shift << Op;
9526       SuggestParentheses(S, Bop->getOperatorLoc(),
9527           S.PDiag(diag::note_precedence_silence) << Op,
9528           Bop->getSourceRange());
9529     }
9530   }
9531 }
9532 
9533 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9534                                  Expr *LHSExpr, Expr *RHSExpr) {
9535   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9536   if (!OCE)
9537     return;
9538 
9539   FunctionDecl *FD = OCE->getDirectCallee();
9540   if (!FD || !FD->isOverloadedOperator())
9541     return;
9542 
9543   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9544   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9545     return;
9546 
9547   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9548       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9549       << (Kind == OO_LessLess);
9550   SuggestParentheses(S, OCE->getOperatorLoc(),
9551                      S.PDiag(diag::note_precedence_silence)
9552                          << (Kind == OO_LessLess ? "<<" : ">>"),
9553                      OCE->getSourceRange());
9554   SuggestParentheses(S, OpLoc,
9555                      S.PDiag(diag::note_evaluate_comparison_first),
9556                      SourceRange(OCE->getArg(1)->getLocStart(),
9557                                  RHSExpr->getLocEnd()));
9558 }
9559 
9560 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9561 /// precedence.
9562 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9563                                     SourceLocation OpLoc, Expr *LHSExpr,
9564                                     Expr *RHSExpr){
9565   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9566   if (BinaryOperator::isBitwiseOp(Opc))
9567     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9568 
9569   // Diagnose "arg1 & arg2 | arg3"
9570   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9571     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9572     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9573   }
9574 
9575   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9576   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9577   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9578     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9579     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9580   }
9581 
9582   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9583       || Opc == BO_Shr) {
9584     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9585     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9586     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9587   }
9588 
9589   // Warn on overloaded shift operators and comparisons, such as:
9590   // cout << 5 == 4;
9591   if (BinaryOperator::isComparisonOp(Opc))
9592     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9593 }
9594 
9595 // Binary Operators.  'Tok' is the token for the operator.
9596 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9597                             tok::TokenKind Kind,
9598                             Expr *LHSExpr, Expr *RHSExpr) {
9599   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9600   assert(LHSExpr && "ActOnBinOp(): missing left expression");
9601   assert(RHSExpr && "ActOnBinOp(): missing right expression");
9602 
9603   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9604   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9605 
9606   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9607 }
9608 
9609 /// Build an overloaded binary operator expression in the given scope.
9610 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9611                                        BinaryOperatorKind Opc,
9612                                        Expr *LHS, Expr *RHS) {
9613   // Find all of the overloaded operators visible from this
9614   // point. We perform both an operator-name lookup from the local
9615   // scope and an argument-dependent lookup based on the types of
9616   // the arguments.
9617   UnresolvedSet<16> Functions;
9618   OverloadedOperatorKind OverOp
9619     = BinaryOperator::getOverloadedOperator(Opc);
9620   if (Sc && OverOp != OO_None)
9621     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9622                                    RHS->getType(), Functions);
9623 
9624   // Build the (potentially-overloaded, potentially-dependent)
9625   // binary operation.
9626   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9627 }
9628 
9629 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9630                             BinaryOperatorKind Opc,
9631                             Expr *LHSExpr, Expr *RHSExpr) {
9632   // We want to end up calling one of checkPseudoObjectAssignment
9633   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9634   // both expressions are overloadable or either is type-dependent),
9635   // or CreateBuiltinBinOp (in any other case).  We also want to get
9636   // any placeholder types out of the way.
9637 
9638   // Handle pseudo-objects in the LHS.
9639   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9640     // Assignments with a pseudo-object l-value need special analysis.
9641     if (pty->getKind() == BuiltinType::PseudoObject &&
9642         BinaryOperator::isAssignmentOp(Opc))
9643       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9644 
9645     // Don't resolve overloads if the other type is overloadable.
9646     if (pty->getKind() == BuiltinType::Overload) {
9647       // We can't actually test that if we still have a placeholder,
9648       // though.  Fortunately, none of the exceptions we see in that
9649       // code below are valid when the LHS is an overload set.  Note
9650       // that an overload set can be dependently-typed, but it never
9651       // instantiates to having an overloadable type.
9652       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9653       if (resolvedRHS.isInvalid()) return ExprError();
9654       RHSExpr = resolvedRHS.get();
9655 
9656       if (RHSExpr->isTypeDependent() ||
9657           RHSExpr->getType()->isOverloadableType())
9658         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9659     }
9660 
9661     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9662     if (LHS.isInvalid()) return ExprError();
9663     LHSExpr = LHS.get();
9664   }
9665 
9666   // Handle pseudo-objects in the RHS.
9667   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9668     // An overload in the RHS can potentially be resolved by the type
9669     // being assigned to.
9670     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9671       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9672         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9673 
9674       if (LHSExpr->getType()->isOverloadableType())
9675         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9676 
9677       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9678     }
9679 
9680     // Don't resolve overloads if the other type is overloadable.
9681     if (pty->getKind() == BuiltinType::Overload &&
9682         LHSExpr->getType()->isOverloadableType())
9683       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9684 
9685     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9686     if (!resolvedRHS.isUsable()) return ExprError();
9687     RHSExpr = resolvedRHS.get();
9688   }
9689 
9690   if (getLangOpts().CPlusPlus) {
9691     // If either expression is type-dependent, always build an
9692     // overloaded op.
9693     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9694       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9695 
9696     // Otherwise, build an overloaded op if either expression has an
9697     // overloadable type.
9698     if (LHSExpr->getType()->isOverloadableType() ||
9699         RHSExpr->getType()->isOverloadableType())
9700       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9701   }
9702 
9703   // Build a built-in binary operation.
9704   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9705 }
9706 
9707 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9708                                       UnaryOperatorKind Opc,
9709                                       Expr *InputExpr) {
9710   ExprResult Input = InputExpr;
9711   ExprValueKind VK = VK_RValue;
9712   ExprObjectKind OK = OK_Ordinary;
9713   QualType resultType;
9714   switch (Opc) {
9715   case UO_PreInc:
9716   case UO_PreDec:
9717   case UO_PostInc:
9718   case UO_PostDec:
9719     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9720                                                 Opc == UO_PreInc ||
9721                                                 Opc == UO_PostInc,
9722                                                 Opc == UO_PreInc ||
9723                                                 Opc == UO_PreDec);
9724     break;
9725   case UO_AddrOf:
9726     resultType = CheckAddressOfOperand(Input, OpLoc);
9727     break;
9728   case UO_Deref: {
9729     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9730     if (Input.isInvalid()) return ExprError();
9731     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9732     break;
9733   }
9734   case UO_Plus:
9735   case UO_Minus:
9736     Input = UsualUnaryConversions(Input.get());
9737     if (Input.isInvalid()) return ExprError();
9738     resultType = Input.get()->getType();
9739     if (resultType->isDependentType())
9740       break;
9741     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9742         resultType->isVectorType())
9743       break;
9744     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9745              Opc == UO_Plus &&
9746              resultType->isPointerType())
9747       break;
9748 
9749     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9750       << resultType << Input.get()->getSourceRange());
9751 
9752   case UO_Not: // bitwise complement
9753     Input = UsualUnaryConversions(Input.get());
9754     if (Input.isInvalid())
9755       return ExprError();
9756     resultType = Input.get()->getType();
9757     if (resultType->isDependentType())
9758       break;
9759     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9760     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9761       // C99 does not support '~' for complex conjugation.
9762       Diag(OpLoc, diag::ext_integer_complement_complex)
9763           << resultType << Input.get()->getSourceRange();
9764     else if (resultType->hasIntegerRepresentation())
9765       break;
9766     else if (resultType->isExtVectorType()) {
9767       if (Context.getLangOpts().OpenCL) {
9768         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9769         // on vector float types.
9770         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9771         if (!T->isIntegerType())
9772           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9773                            << resultType << Input.get()->getSourceRange());
9774       }
9775       break;
9776     } else {
9777       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9778                        << resultType << Input.get()->getSourceRange());
9779     }
9780     break;
9781 
9782   case UO_LNot: // logical negation
9783     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9784     Input = DefaultFunctionArrayLvalueConversion(Input.get());
9785     if (Input.isInvalid()) return ExprError();
9786     resultType = Input.get()->getType();
9787 
9788     // Though we still have to promote half FP to float...
9789     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9790       Input = ImpCastExprToType(Input.get(), Context.FloatTy, CK_FloatingCast).get();
9791       resultType = Context.FloatTy;
9792     }
9793 
9794     if (resultType->isDependentType())
9795       break;
9796     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9797       // C99 6.5.3.3p1: ok, fallthrough;
9798       if (Context.getLangOpts().CPlusPlus) {
9799         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9800         // operand contextually converted to bool.
9801         Input = ImpCastExprToType(Input.get(), Context.BoolTy,
9802                                   ScalarTypeToBooleanCastKind(resultType));
9803       } else if (Context.getLangOpts().OpenCL &&
9804                  Context.getLangOpts().OpenCLVersion < 120) {
9805         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9806         // operate on scalar float types.
9807         if (!resultType->isIntegerType())
9808           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9809                            << resultType << Input.get()->getSourceRange());
9810       }
9811     } else if (resultType->isExtVectorType()) {
9812       if (Context.getLangOpts().OpenCL &&
9813           Context.getLangOpts().OpenCLVersion < 120) {
9814         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9815         // operate on vector float types.
9816         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9817         if (!T->isIntegerType())
9818           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9819                            << resultType << Input.get()->getSourceRange());
9820       }
9821       // Vector logical not returns the signed variant of the operand type.
9822       resultType = GetSignedVectorType(resultType);
9823       break;
9824     } else {
9825       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9826         << resultType << Input.get()->getSourceRange());
9827     }
9828 
9829     // LNot always has type int. C99 6.5.3.3p5.
9830     // In C++, it's bool. C++ 5.3.1p8
9831     resultType = Context.getLogicalOperationType();
9832     break;
9833   case UO_Real:
9834   case UO_Imag:
9835     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9836     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9837     // complex l-values to ordinary l-values and all other values to r-values.
9838     if (Input.isInvalid()) return ExprError();
9839     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9840       if (Input.get()->getValueKind() != VK_RValue &&
9841           Input.get()->getObjectKind() == OK_Ordinary)
9842         VK = Input.get()->getValueKind();
9843     } else if (!getLangOpts().CPlusPlus) {
9844       // In C, a volatile scalar is read by __imag. In C++, it is not.
9845       Input = DefaultLvalueConversion(Input.get());
9846     }
9847     break;
9848   case UO_Extension:
9849     resultType = Input.get()->getType();
9850     VK = Input.get()->getValueKind();
9851     OK = Input.get()->getObjectKind();
9852     break;
9853   }
9854   if (resultType.isNull() || Input.isInvalid())
9855     return ExprError();
9856 
9857   // Check for array bounds violations in the operand of the UnaryOperator,
9858   // except for the '*' and '&' operators that have to be handled specially
9859   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9860   // that are explicitly defined as valid by the standard).
9861   if (Opc != UO_AddrOf && Opc != UO_Deref)
9862     CheckArrayAccess(Input.get());
9863 
9864   return new (Context)
9865       UnaryOperator(Input.get(), Opc, resultType, VK, OK, OpLoc);
9866 }
9867 
9868 /// \brief Determine whether the given expression is a qualified member
9869 /// access expression, of a form that could be turned into a pointer to member
9870 /// with the address-of operator.
9871 static bool isQualifiedMemberAccess(Expr *E) {
9872   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9873     if (!DRE->getQualifier())
9874       return false;
9875 
9876     ValueDecl *VD = DRE->getDecl();
9877     if (!VD->isCXXClassMember())
9878       return false;
9879 
9880     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9881       return true;
9882     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9883       return Method->isInstance();
9884 
9885     return false;
9886   }
9887 
9888   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9889     if (!ULE->getQualifier())
9890       return false;
9891 
9892     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9893                                            DEnd = ULE->decls_end();
9894          D != DEnd; ++D) {
9895       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9896         if (Method->isInstance())
9897           return true;
9898       } else {
9899         // Overload set does not contain methods.
9900         break;
9901       }
9902     }
9903 
9904     return false;
9905   }
9906 
9907   return false;
9908 }
9909 
9910 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9911                               UnaryOperatorKind Opc, Expr *Input) {
9912   // First things first: handle placeholders so that the
9913   // overloaded-operator check considers the right type.
9914   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9915     // Increment and decrement of pseudo-object references.
9916     if (pty->getKind() == BuiltinType::PseudoObject &&
9917         UnaryOperator::isIncrementDecrementOp(Opc))
9918       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9919 
9920     // extension is always a builtin operator.
9921     if (Opc == UO_Extension)
9922       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9923 
9924     // & gets special logic for several kinds of placeholder.
9925     // The builtin code knows what to do.
9926     if (Opc == UO_AddrOf &&
9927         (pty->getKind() == BuiltinType::Overload ||
9928          pty->getKind() == BuiltinType::UnknownAny ||
9929          pty->getKind() == BuiltinType::BoundMember))
9930       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9931 
9932     // Anything else needs to be handled now.
9933     ExprResult Result = CheckPlaceholderExpr(Input);
9934     if (Result.isInvalid()) return ExprError();
9935     Input = Result.get();
9936   }
9937 
9938   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9939       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9940       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9941     // Find all of the overloaded operators visible from this
9942     // point. We perform both an operator-name lookup from the local
9943     // scope and an argument-dependent lookup based on the types of
9944     // the arguments.
9945     UnresolvedSet<16> Functions;
9946     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9947     if (S && OverOp != OO_None)
9948       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9949                                    Functions);
9950 
9951     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9952   }
9953 
9954   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9955 }
9956 
9957 // Unary Operators.  'Tok' is the token for the operator.
9958 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9959                               tok::TokenKind Op, Expr *Input) {
9960   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9961 }
9962 
9963 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9964 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9965                                 LabelDecl *TheDecl) {
9966   TheDecl->markUsed(Context);
9967   // Create the AST node.  The address of a label always has type 'void*'.
9968   return new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9969                                      Context.getPointerType(Context.VoidTy));
9970 }
9971 
9972 /// Given the last statement in a statement-expression, check whether
9973 /// the result is a producing expression (like a call to an
9974 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9975 /// release out of the full-expression.  Otherwise, return null.
9976 /// Cannot fail.
9977 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9978   // Should always be wrapped with one of these.
9979   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9980   if (!cleanups) return nullptr;
9981 
9982   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9983   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9984     return nullptr;
9985 
9986   // Splice out the cast.  This shouldn't modify any interesting
9987   // features of the statement.
9988   Expr *producer = cast->getSubExpr();
9989   assert(producer->getType() == cast->getType());
9990   assert(producer->getValueKind() == cast->getValueKind());
9991   cleanups->setSubExpr(producer);
9992   return cleanups;
9993 }
9994 
9995 void Sema::ActOnStartStmtExpr() {
9996   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9997 }
9998 
9999 void Sema::ActOnStmtExprError() {
10000   // Note that function is also called by TreeTransform when leaving a
10001   // StmtExpr scope without rebuilding anything.
10002 
10003   DiscardCleanupsInEvaluationContext();
10004   PopExpressionEvaluationContext();
10005 }
10006 
10007 ExprResult
10008 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
10009                     SourceLocation RPLoc) { // "({..})"
10010   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
10011   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
10012 
10013   if (hasAnyUnrecoverableErrorsInThisFunction())
10014     DiscardCleanupsInEvaluationContext();
10015   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10016   PopExpressionEvaluationContext();
10017 
10018   bool isFileScope
10019     = (getCurFunctionOrMethodDecl() == nullptr) && (getCurBlock() == nullptr);
10020   if (isFileScope)
10021     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10022 
10023   // FIXME: there are a variety of strange constraints to enforce here, for
10024   // example, it is not possible to goto into a stmt expression apparently.
10025   // More semantic analysis is needed.
10026 
10027   // If there are sub-stmts in the compound stmt, take the type of the last one
10028   // as the type of the stmtexpr.
10029   QualType Ty = Context.VoidTy;
10030   bool StmtExprMayBindToTemp = false;
10031   if (!Compound->body_empty()) {
10032     Stmt *LastStmt = Compound->body_back();
10033     LabelStmt *LastLabelStmt = nullptr;
10034     // If LastStmt is a label, skip down through into the body.
10035     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10036       LastLabelStmt = Label;
10037       LastStmt = Label->getSubStmt();
10038     }
10039 
10040     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10041       // Do function/array conversion on the last expression, but not
10042       // lvalue-to-rvalue.  However, initialize an unqualified type.
10043       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10044       if (LastExpr.isInvalid())
10045         return ExprError();
10046       Ty = LastExpr.get()->getType().getUnqualifiedType();
10047 
10048       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10049         // In ARC, if the final expression ends in a consume, splice
10050         // the consume out and bind it later.  In the alternate case
10051         // (when dealing with a retainable type), the result
10052         // initialization will create a produce.  In both cases the
10053         // result will be +1, and we'll need to balance that out with
10054         // a bind.
10055         if (Expr *rebuiltLastStmt
10056               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10057           LastExpr = rebuiltLastStmt;
10058         } else {
10059           LastExpr = PerformCopyInitialization(
10060                             InitializedEntity::InitializeResult(LPLoc,
10061                                                                 Ty,
10062                                                                 false),
10063                                                    SourceLocation(),
10064                                                LastExpr);
10065         }
10066 
10067         if (LastExpr.isInvalid())
10068           return ExprError();
10069         if (LastExpr.get() != nullptr) {
10070           if (!LastLabelStmt)
10071             Compound->setLastStmt(LastExpr.get());
10072           else
10073             LastLabelStmt->setSubStmt(LastExpr.get());
10074           StmtExprMayBindToTemp = true;
10075         }
10076       }
10077     }
10078   }
10079 
10080   // FIXME: Check that expression type is complete/non-abstract; statement
10081   // expressions are not lvalues.
10082   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10083   if (StmtExprMayBindToTemp)
10084     return MaybeBindToTemporary(ResStmtExpr);
10085   return ResStmtExpr;
10086 }
10087 
10088 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10089                                       TypeSourceInfo *TInfo,
10090                                       OffsetOfComponent *CompPtr,
10091                                       unsigned NumComponents,
10092                                       SourceLocation RParenLoc) {
10093   QualType ArgTy = TInfo->getType();
10094   bool Dependent = ArgTy->isDependentType();
10095   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10096 
10097   // We must have at least one component that refers to the type, and the first
10098   // one is known to be a field designator.  Verify that the ArgTy represents
10099   // a struct/union/class.
10100   if (!Dependent && !ArgTy->isRecordType())
10101     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10102                        << ArgTy << TypeRange);
10103 
10104   // Type must be complete per C99 7.17p3 because a declaring a variable
10105   // with an incomplete type would be ill-formed.
10106   if (!Dependent
10107       && RequireCompleteType(BuiltinLoc, ArgTy,
10108                              diag::err_offsetof_incomplete_type, TypeRange))
10109     return ExprError();
10110 
10111   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10112   // GCC extension, diagnose them.
10113   // FIXME: This diagnostic isn't actually visible because the location is in
10114   // a system header!
10115   if (NumComponents != 1)
10116     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10117       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10118 
10119   bool DidWarnAboutNonPOD = false;
10120   QualType CurrentType = ArgTy;
10121   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10122   SmallVector<OffsetOfNode, 4> Comps;
10123   SmallVector<Expr*, 4> Exprs;
10124   for (unsigned i = 0; i != NumComponents; ++i) {
10125     const OffsetOfComponent &OC = CompPtr[i];
10126     if (OC.isBrackets) {
10127       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10128       if (!CurrentType->isDependentType()) {
10129         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10130         if(!AT)
10131           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10132                            << CurrentType);
10133         CurrentType = AT->getElementType();
10134       } else
10135         CurrentType = Context.DependentTy;
10136 
10137       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10138       if (IdxRval.isInvalid())
10139         return ExprError();
10140       Expr *Idx = IdxRval.get();
10141 
10142       // The expression must be an integral expression.
10143       // FIXME: An integral constant expression?
10144       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10145           !Idx->getType()->isIntegerType())
10146         return ExprError(Diag(Idx->getLocStart(),
10147                               diag::err_typecheck_subscript_not_integer)
10148                          << Idx->getSourceRange());
10149 
10150       // Record this array index.
10151       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10152       Exprs.push_back(Idx);
10153       continue;
10154     }
10155 
10156     // Offset of a field.
10157     if (CurrentType->isDependentType()) {
10158       // We have the offset of a field, but we can't look into the dependent
10159       // type. Just record the identifier of the field.
10160       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10161       CurrentType = Context.DependentTy;
10162       continue;
10163     }
10164 
10165     // We need to have a complete type to look into.
10166     if (RequireCompleteType(OC.LocStart, CurrentType,
10167                             diag::err_offsetof_incomplete_type))
10168       return ExprError();
10169 
10170     // Look for the designated field.
10171     const RecordType *RC = CurrentType->getAs<RecordType>();
10172     if (!RC)
10173       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10174                        << CurrentType);
10175     RecordDecl *RD = RC->getDecl();
10176 
10177     // C++ [lib.support.types]p5:
10178     //   The macro offsetof accepts a restricted set of type arguments in this
10179     //   International Standard. type shall be a POD structure or a POD union
10180     //   (clause 9).
10181     // C++11 [support.types]p4:
10182     //   If type is not a standard-layout class (Clause 9), the results are
10183     //   undefined.
10184     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10185       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10186       unsigned DiagID =
10187         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10188                             : diag::warn_offsetof_non_pod_type;
10189 
10190       if (!IsSafe && !DidWarnAboutNonPOD &&
10191           DiagRuntimeBehavior(BuiltinLoc, nullptr,
10192                               PDiag(DiagID)
10193                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10194                               << CurrentType))
10195         DidWarnAboutNonPOD = true;
10196     }
10197 
10198     // Look for the field.
10199     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10200     LookupQualifiedName(R, RD);
10201     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10202     IndirectFieldDecl *IndirectMemberDecl = nullptr;
10203     if (!MemberDecl) {
10204       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10205         MemberDecl = IndirectMemberDecl->getAnonField();
10206     }
10207 
10208     if (!MemberDecl)
10209       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10210                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10211                                                               OC.LocEnd));
10212 
10213     // C99 7.17p3:
10214     //   (If the specified member is a bit-field, the behavior is undefined.)
10215     //
10216     // We diagnose this as an error.
10217     if (MemberDecl->isBitField()) {
10218       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10219         << MemberDecl->getDeclName()
10220         << SourceRange(BuiltinLoc, RParenLoc);
10221       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10222       return ExprError();
10223     }
10224 
10225     RecordDecl *Parent = MemberDecl->getParent();
10226     if (IndirectMemberDecl)
10227       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10228 
10229     // If the member was found in a base class, introduce OffsetOfNodes for
10230     // the base class indirections.
10231     CXXBasePaths Paths;
10232     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10233       if (Paths.getDetectedVirtual()) {
10234         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10235           << MemberDecl->getDeclName()
10236           << SourceRange(BuiltinLoc, RParenLoc);
10237         return ExprError();
10238       }
10239 
10240       CXXBasePath &Path = Paths.front();
10241       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10242            B != BEnd; ++B)
10243         Comps.push_back(OffsetOfNode(B->Base));
10244     }
10245 
10246     if (IndirectMemberDecl) {
10247       for (auto *FI : IndirectMemberDecl->chain()) {
10248         assert(isa<FieldDecl>(FI));
10249         Comps.push_back(OffsetOfNode(OC.LocStart,
10250                                      cast<FieldDecl>(FI), OC.LocEnd));
10251       }
10252     } else
10253       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10254 
10255     CurrentType = MemberDecl->getType().getNonReferenceType();
10256   }
10257 
10258   return OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, TInfo,
10259                               Comps, Exprs, RParenLoc);
10260 }
10261 
10262 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10263                                       SourceLocation BuiltinLoc,
10264                                       SourceLocation TypeLoc,
10265                                       ParsedType ParsedArgTy,
10266                                       OffsetOfComponent *CompPtr,
10267                                       unsigned NumComponents,
10268                                       SourceLocation RParenLoc) {
10269 
10270   TypeSourceInfo *ArgTInfo;
10271   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10272   if (ArgTy.isNull())
10273     return ExprError();
10274 
10275   if (!ArgTInfo)
10276     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10277 
10278   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10279                               RParenLoc);
10280 }
10281 
10282 
10283 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10284                                  Expr *CondExpr,
10285                                  Expr *LHSExpr, Expr *RHSExpr,
10286                                  SourceLocation RPLoc) {
10287   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10288 
10289   ExprValueKind VK = VK_RValue;
10290   ExprObjectKind OK = OK_Ordinary;
10291   QualType resType;
10292   bool ValueDependent = false;
10293   bool CondIsTrue = false;
10294   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10295     resType = Context.DependentTy;
10296     ValueDependent = true;
10297   } else {
10298     // The conditional expression is required to be a constant expression.
10299     llvm::APSInt condEval(32);
10300     ExprResult CondICE
10301       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10302           diag::err_typecheck_choose_expr_requires_constant, false);
10303     if (CondICE.isInvalid())
10304       return ExprError();
10305     CondExpr = CondICE.get();
10306     CondIsTrue = condEval.getZExtValue();
10307 
10308     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10309     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10310 
10311     resType = ActiveExpr->getType();
10312     ValueDependent = ActiveExpr->isValueDependent();
10313     VK = ActiveExpr->getValueKind();
10314     OK = ActiveExpr->getObjectKind();
10315   }
10316 
10317   return new (Context)
10318       ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, VK, OK, RPLoc,
10319                  CondIsTrue, resType->isDependentType(), ValueDependent);
10320 }
10321 
10322 //===----------------------------------------------------------------------===//
10323 // Clang Extensions.
10324 //===----------------------------------------------------------------------===//
10325 
10326 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10327 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10328   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10329 
10330   if (LangOpts.CPlusPlus) {
10331     Decl *ManglingContextDecl;
10332     if (MangleNumberingContext *MCtx =
10333             getCurrentMangleNumberContext(Block->getDeclContext(),
10334                                           ManglingContextDecl)) {
10335       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10336       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10337     }
10338   }
10339 
10340   PushBlockScope(CurScope, Block);
10341   CurContext->addDecl(Block);
10342   if (CurScope)
10343     PushDeclContext(CurScope, Block);
10344   else
10345     CurContext = Block;
10346 
10347   getCurBlock()->HasImplicitReturnType = true;
10348 
10349   // Enter a new evaluation context to insulate the block from any
10350   // cleanups from the enclosing full-expression.
10351   PushExpressionEvaluationContext(PotentiallyEvaluated);
10352 }
10353 
10354 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10355                                Scope *CurScope) {
10356   assert(ParamInfo.getIdentifier() == nullptr &&
10357          "block-id should have no identifier!");
10358   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10359   BlockScopeInfo *CurBlock = getCurBlock();
10360 
10361   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10362   QualType T = Sig->getType();
10363 
10364   // FIXME: We should allow unexpanded parameter packs here, but that would,
10365   // in turn, make the block expression contain unexpanded parameter packs.
10366   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10367     // Drop the parameters.
10368     FunctionProtoType::ExtProtoInfo EPI;
10369     EPI.HasTrailingReturn = false;
10370     EPI.TypeQuals |= DeclSpec::TQ_const;
10371     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10372     Sig = Context.getTrivialTypeSourceInfo(T);
10373   }
10374 
10375   // GetTypeForDeclarator always produces a function type for a block
10376   // literal signature.  Furthermore, it is always a FunctionProtoType
10377   // unless the function was written with a typedef.
10378   assert(T->isFunctionType() &&
10379          "GetTypeForDeclarator made a non-function block signature");
10380 
10381   // Look for an explicit signature in that function type.
10382   FunctionProtoTypeLoc ExplicitSignature;
10383 
10384   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10385   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10386 
10387     // Check whether that explicit signature was synthesized by
10388     // GetTypeForDeclarator.  If so, don't save that as part of the
10389     // written signature.
10390     if (ExplicitSignature.getLocalRangeBegin() ==
10391         ExplicitSignature.getLocalRangeEnd()) {
10392       // This would be much cheaper if we stored TypeLocs instead of
10393       // TypeSourceInfos.
10394       TypeLoc Result = ExplicitSignature.getReturnLoc();
10395       unsigned Size = Result.getFullDataSize();
10396       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10397       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10398 
10399       ExplicitSignature = FunctionProtoTypeLoc();
10400     }
10401   }
10402 
10403   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10404   CurBlock->FunctionType = T;
10405 
10406   const FunctionType *Fn = T->getAs<FunctionType>();
10407   QualType RetTy = Fn->getReturnType();
10408   bool isVariadic =
10409     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10410 
10411   CurBlock->TheDecl->setIsVariadic(isVariadic);
10412 
10413   // Context.DependentTy is used as a placeholder for a missing block
10414   // return type.  TODO:  what should we do with declarators like:
10415   //   ^ * { ... }
10416   // If the answer is "apply template argument deduction"....
10417   if (RetTy != Context.DependentTy) {
10418     CurBlock->ReturnType = RetTy;
10419     CurBlock->TheDecl->setBlockMissingReturnType(false);
10420     CurBlock->HasImplicitReturnType = false;
10421   }
10422 
10423   // Push block parameters from the declarator if we had them.
10424   SmallVector<ParmVarDecl*, 8> Params;
10425   if (ExplicitSignature) {
10426     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10427       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10428       if (Param->getIdentifier() == nullptr &&
10429           !Param->isImplicit() &&
10430           !Param->isInvalidDecl() &&
10431           !getLangOpts().CPlusPlus)
10432         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10433       Params.push_back(Param);
10434     }
10435 
10436   // Fake up parameter variables if we have a typedef, like
10437   //   ^ fntype { ... }
10438   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10439     for (const auto &I : Fn->param_types()) {
10440       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10441           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10442       Params.push_back(Param);
10443     }
10444   }
10445 
10446   // Set the parameters on the block decl.
10447   if (!Params.empty()) {
10448     CurBlock->TheDecl->setParams(Params);
10449     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10450                              CurBlock->TheDecl->param_end(),
10451                              /*CheckParameterNames=*/false);
10452   }
10453 
10454   // Finally we can process decl attributes.
10455   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10456 
10457   // Put the parameter variables in scope.
10458   for (auto AI : CurBlock->TheDecl->params()) {
10459     AI->setOwningFunction(CurBlock->TheDecl);
10460 
10461     // If this has an identifier, add it to the scope stack.
10462     if (AI->getIdentifier()) {
10463       CheckShadow(CurBlock->TheScope, AI);
10464 
10465       PushOnScopeChains(AI, CurBlock->TheScope);
10466     }
10467   }
10468 }
10469 
10470 /// ActOnBlockError - If there is an error parsing a block, this callback
10471 /// is invoked to pop the information about the block from the action impl.
10472 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10473   // Leave the expression-evaluation context.
10474   DiscardCleanupsInEvaluationContext();
10475   PopExpressionEvaluationContext();
10476 
10477   // Pop off CurBlock, handle nested blocks.
10478   PopDeclContext();
10479   PopFunctionScopeInfo();
10480 }
10481 
10482 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10483 /// literal was successfully completed.  ^(int x){...}
10484 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10485                                     Stmt *Body, Scope *CurScope) {
10486   // If blocks are disabled, emit an error.
10487   if (!LangOpts.Blocks)
10488     Diag(CaretLoc, diag::err_blocks_disable);
10489 
10490   // Leave the expression-evaluation context.
10491   if (hasAnyUnrecoverableErrorsInThisFunction())
10492     DiscardCleanupsInEvaluationContext();
10493   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10494   PopExpressionEvaluationContext();
10495 
10496   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10497 
10498   if (BSI->HasImplicitReturnType)
10499     deduceClosureReturnType(*BSI);
10500 
10501   PopDeclContext();
10502 
10503   QualType RetTy = Context.VoidTy;
10504   if (!BSI->ReturnType.isNull())
10505     RetTy = BSI->ReturnType;
10506 
10507   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10508   QualType BlockTy;
10509 
10510   // Set the captured variables on the block.
10511   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10512   SmallVector<BlockDecl::Capture, 4> Captures;
10513   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10514     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10515     if (Cap.isThisCapture())
10516       continue;
10517     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10518                               Cap.isNested(), Cap.getInitExpr());
10519     Captures.push_back(NewCap);
10520   }
10521   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10522                             BSI->CXXThisCaptureIndex != 0);
10523 
10524   // If the user wrote a function type in some form, try to use that.
10525   if (!BSI->FunctionType.isNull()) {
10526     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10527 
10528     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10529     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10530 
10531     // Turn protoless block types into nullary block types.
10532     if (isa<FunctionNoProtoType>(FTy)) {
10533       FunctionProtoType::ExtProtoInfo EPI;
10534       EPI.ExtInfo = Ext;
10535       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10536 
10537     // Otherwise, if we don't need to change anything about the function type,
10538     // preserve its sugar structure.
10539     } else if (FTy->getReturnType() == RetTy &&
10540                (!NoReturn || FTy->getNoReturnAttr())) {
10541       BlockTy = BSI->FunctionType;
10542 
10543     // Otherwise, make the minimal modifications to the function type.
10544     } else {
10545       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10546       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10547       EPI.TypeQuals = 0; // FIXME: silently?
10548       EPI.ExtInfo = Ext;
10549       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10550     }
10551 
10552   // If we don't have a function type, just build one from nothing.
10553   } else {
10554     FunctionProtoType::ExtProtoInfo EPI;
10555     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10556     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10557   }
10558 
10559   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10560                            BSI->TheDecl->param_end());
10561   BlockTy = Context.getBlockPointerType(BlockTy);
10562 
10563   // If needed, diagnose invalid gotos and switches in the block.
10564   if (getCurFunction()->NeedsScopeChecking() &&
10565       !PP.isCodeCompletionEnabled())
10566     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10567 
10568   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10569 
10570   // Try to apply the named return value optimization. We have to check again
10571   // if we can do this, though, because blocks keep return statements around
10572   // to deduce an implicit return type.
10573   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10574       !BSI->TheDecl->isDependentContext())
10575     computeNRVO(Body, BSI);
10576 
10577   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10578   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10579   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10580 
10581   // If the block isn't obviously global, i.e. it captures anything at
10582   // all, then we need to do a few things in the surrounding context:
10583   if (Result->getBlockDecl()->hasCaptures()) {
10584     // First, this expression has a new cleanup object.
10585     ExprCleanupObjects.push_back(Result->getBlockDecl());
10586     ExprNeedsCleanups = true;
10587 
10588     // It also gets a branch-protected scope if any of the captured
10589     // variables needs destruction.
10590     for (const auto &CI : Result->getBlockDecl()->captures()) {
10591       const VarDecl *var = CI.getVariable();
10592       if (var->getType().isDestructedType() != QualType::DK_none) {
10593         getCurFunction()->setHasBranchProtectedScope();
10594         break;
10595       }
10596     }
10597   }
10598 
10599   return Result;
10600 }
10601 
10602 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10603                                         Expr *E, ParsedType Ty,
10604                                         SourceLocation RPLoc) {
10605   TypeSourceInfo *TInfo;
10606   GetTypeFromParser(Ty, &TInfo);
10607   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10608 }
10609 
10610 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10611                                 Expr *E, TypeSourceInfo *TInfo,
10612                                 SourceLocation RPLoc) {
10613   Expr *OrigExpr = E;
10614 
10615   // Get the va_list type
10616   QualType VaListType = Context.getBuiltinVaListType();
10617   if (VaListType->isArrayType()) {
10618     // Deal with implicit array decay; for example, on x86-64,
10619     // va_list is an array, but it's supposed to decay to
10620     // a pointer for va_arg.
10621     VaListType = Context.getArrayDecayedType(VaListType);
10622     // Make sure the input expression also decays appropriately.
10623     ExprResult Result = UsualUnaryConversions(E);
10624     if (Result.isInvalid())
10625       return ExprError();
10626     E = Result.get();
10627   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10628     // If va_list is a record type and we are compiling in C++ mode,
10629     // check the argument using reference binding.
10630     InitializedEntity Entity
10631       = InitializedEntity::InitializeParameter(Context,
10632           Context.getLValueReferenceType(VaListType), false);
10633     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10634     if (Init.isInvalid())
10635       return ExprError();
10636     E = Init.getAs<Expr>();
10637   } else {
10638     // Otherwise, the va_list argument must be an l-value because
10639     // it is modified by va_arg.
10640     if (!E->isTypeDependent() &&
10641         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10642       return ExprError();
10643   }
10644 
10645   if (!E->isTypeDependent() &&
10646       !Context.hasSameType(VaListType, E->getType())) {
10647     return ExprError(Diag(E->getLocStart(),
10648                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10649       << OrigExpr->getType() << E->getSourceRange());
10650   }
10651 
10652   if (!TInfo->getType()->isDependentType()) {
10653     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10654                             diag::err_second_parameter_to_va_arg_incomplete,
10655                             TInfo->getTypeLoc()))
10656       return ExprError();
10657 
10658     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10659                                TInfo->getType(),
10660                                diag::err_second_parameter_to_va_arg_abstract,
10661                                TInfo->getTypeLoc()))
10662       return ExprError();
10663 
10664     if (!TInfo->getType().isPODType(Context)) {
10665       Diag(TInfo->getTypeLoc().getBeginLoc(),
10666            TInfo->getType()->isObjCLifetimeType()
10667              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10668              : diag::warn_second_parameter_to_va_arg_not_pod)
10669         << TInfo->getType()
10670         << TInfo->getTypeLoc().getSourceRange();
10671     }
10672 
10673     // Check for va_arg where arguments of the given type will be promoted
10674     // (i.e. this va_arg is guaranteed to have undefined behavior).
10675     QualType PromoteType;
10676     if (TInfo->getType()->isPromotableIntegerType()) {
10677       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10678       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10679         PromoteType = QualType();
10680     }
10681     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10682       PromoteType = Context.DoubleTy;
10683     if (!PromoteType.isNull())
10684       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10685                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10686                           << TInfo->getType()
10687                           << PromoteType
10688                           << TInfo->getTypeLoc().getSourceRange());
10689   }
10690 
10691   QualType T = TInfo->getType().getNonLValueExprType(Context);
10692   return new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T);
10693 }
10694 
10695 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10696   // The type of __null will be int or long, depending on the size of
10697   // pointers on the target.
10698   QualType Ty;
10699   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10700   if (pw == Context.getTargetInfo().getIntWidth())
10701     Ty = Context.IntTy;
10702   else if (pw == Context.getTargetInfo().getLongWidth())
10703     Ty = Context.LongTy;
10704   else if (pw == Context.getTargetInfo().getLongLongWidth())
10705     Ty = Context.LongLongTy;
10706   else {
10707     llvm_unreachable("I don't know size of pointer!");
10708   }
10709 
10710   return new (Context) GNUNullExpr(Ty, TokenLoc);
10711 }
10712 
10713 bool
10714 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10715   if (!getLangOpts().ObjC1)
10716     return false;
10717 
10718   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10719   if (!PT)
10720     return false;
10721 
10722   if (!PT->isObjCIdType()) {
10723     // Check if the destination is the 'NSString' interface.
10724     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10725     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10726       return false;
10727   }
10728 
10729   // Ignore any parens, implicit casts (should only be
10730   // array-to-pointer decays), and not-so-opaque values.  The last is
10731   // important for making this trigger for property assignments.
10732   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10733   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10734     if (OV->getSourceExpr())
10735       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10736 
10737   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10738   if (!SL || !SL->isAscii())
10739     return false;
10740   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10741     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10742   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).get();
10743   return true;
10744 }
10745 
10746 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10747                                     SourceLocation Loc,
10748                                     QualType DstType, QualType SrcType,
10749                                     Expr *SrcExpr, AssignmentAction Action,
10750                                     bool *Complained) {
10751   if (Complained)
10752     *Complained = false;
10753 
10754   // Decode the result (notice that AST's are still created for extensions).
10755   bool CheckInferredResultType = false;
10756   bool isInvalid = false;
10757   unsigned DiagKind = 0;
10758   FixItHint Hint;
10759   ConversionFixItGenerator ConvHints;
10760   bool MayHaveConvFixit = false;
10761   bool MayHaveFunctionDiff = false;
10762 
10763   switch (ConvTy) {
10764   case Compatible:
10765       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10766       return false;
10767 
10768   case PointerToInt:
10769     DiagKind = diag::ext_typecheck_convert_pointer_int;
10770     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10771     MayHaveConvFixit = true;
10772     break;
10773   case IntToPointer:
10774     DiagKind = diag::ext_typecheck_convert_int_pointer;
10775     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10776     MayHaveConvFixit = true;
10777     break;
10778   case IncompatiblePointer:
10779       DiagKind =
10780         (Action == AA_Passing_CFAudited ?
10781           diag::err_arc_typecheck_convert_incompatible_pointer :
10782           diag::ext_typecheck_convert_incompatible_pointer);
10783     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10784       SrcType->isObjCObjectPointerType();
10785     if (Hint.isNull() && !CheckInferredResultType) {
10786       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10787     }
10788     else if (CheckInferredResultType) {
10789       SrcType = SrcType.getUnqualifiedType();
10790       DstType = DstType.getUnqualifiedType();
10791     }
10792     MayHaveConvFixit = true;
10793     break;
10794   case IncompatiblePointerSign:
10795     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10796     break;
10797   case FunctionVoidPointer:
10798     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10799     break;
10800   case IncompatiblePointerDiscardsQualifiers: {
10801     // Perform array-to-pointer decay if necessary.
10802     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10803 
10804     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10805     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10806     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10807       DiagKind = diag::err_typecheck_incompatible_address_space;
10808       break;
10809 
10810 
10811     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10812       DiagKind = diag::err_typecheck_incompatible_ownership;
10813       break;
10814     }
10815 
10816     llvm_unreachable("unknown error case for discarding qualifiers!");
10817     // fallthrough
10818   }
10819   case CompatiblePointerDiscardsQualifiers:
10820     // If the qualifiers lost were because we were applying the
10821     // (deprecated) C++ conversion from a string literal to a char*
10822     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10823     // Ideally, this check would be performed in
10824     // checkPointerTypesForAssignment. However, that would require a
10825     // bit of refactoring (so that the second argument is an
10826     // expression, rather than a type), which should be done as part
10827     // of a larger effort to fix checkPointerTypesForAssignment for
10828     // C++ semantics.
10829     if (getLangOpts().CPlusPlus &&
10830         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10831       return false;
10832     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10833     break;
10834   case IncompatibleNestedPointerQualifiers:
10835     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10836     break;
10837   case IntToBlockPointer:
10838     DiagKind = diag::err_int_to_block_pointer;
10839     break;
10840   case IncompatibleBlockPointer:
10841     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10842     break;
10843   case IncompatibleObjCQualifiedId:
10844     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10845     // it can give a more specific diagnostic.
10846     DiagKind = diag::warn_incompatible_qualified_id;
10847     break;
10848   case IncompatibleVectors:
10849     DiagKind = diag::warn_incompatible_vectors;
10850     break;
10851   case IncompatibleObjCWeakRef:
10852     DiagKind = diag::err_arc_weak_unavailable_assign;
10853     break;
10854   case Incompatible:
10855     DiagKind = diag::err_typecheck_convert_incompatible;
10856     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10857     MayHaveConvFixit = true;
10858     isInvalid = true;
10859     MayHaveFunctionDiff = true;
10860     break;
10861   }
10862 
10863   QualType FirstType, SecondType;
10864   switch (Action) {
10865   case AA_Assigning:
10866   case AA_Initializing:
10867     // The destination type comes first.
10868     FirstType = DstType;
10869     SecondType = SrcType;
10870     break;
10871 
10872   case AA_Returning:
10873   case AA_Passing:
10874   case AA_Passing_CFAudited:
10875   case AA_Converting:
10876   case AA_Sending:
10877   case AA_Casting:
10878     // The source type comes first.
10879     FirstType = SrcType;
10880     SecondType = DstType;
10881     break;
10882   }
10883 
10884   PartialDiagnostic FDiag = PDiag(DiagKind);
10885   if (Action == AA_Passing_CFAudited)
10886     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10887   else
10888     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10889 
10890   // If we can fix the conversion, suggest the FixIts.
10891   assert(ConvHints.isNull() || Hint.isNull());
10892   if (!ConvHints.isNull()) {
10893     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10894          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10895       FDiag << *HI;
10896   } else {
10897     FDiag << Hint;
10898   }
10899   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10900 
10901   if (MayHaveFunctionDiff)
10902     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10903 
10904   Diag(Loc, FDiag);
10905 
10906   if (SecondType == Context.OverloadTy)
10907     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10908                               FirstType);
10909 
10910   if (CheckInferredResultType)
10911     EmitRelatedResultTypeNote(SrcExpr);
10912 
10913   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10914     EmitRelatedResultTypeNoteForReturn(DstType);
10915 
10916   if (Complained)
10917     *Complained = true;
10918   return isInvalid;
10919 }
10920 
10921 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10922                                                  llvm::APSInt *Result) {
10923   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10924   public:
10925     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
10926       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10927     }
10928   } Diagnoser;
10929 
10930   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10931 }
10932 
10933 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10934                                                  llvm::APSInt *Result,
10935                                                  unsigned DiagID,
10936                                                  bool AllowFold) {
10937   class IDDiagnoser : public VerifyICEDiagnoser {
10938     unsigned DiagID;
10939 
10940   public:
10941     IDDiagnoser(unsigned DiagID)
10942       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10943 
10944     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
10945       S.Diag(Loc, DiagID) << SR;
10946     }
10947   } Diagnoser(DiagID);
10948 
10949   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10950 }
10951 
10952 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10953                                             SourceRange SR) {
10954   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10955 }
10956 
10957 ExprResult
10958 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10959                                       VerifyICEDiagnoser &Diagnoser,
10960                                       bool AllowFold) {
10961   SourceLocation DiagLoc = E->getLocStart();
10962 
10963   if (getLangOpts().CPlusPlus11) {
10964     // C++11 [expr.const]p5:
10965     //   If an expression of literal class type is used in a context where an
10966     //   integral constant expression is required, then that class type shall
10967     //   have a single non-explicit conversion function to an integral or
10968     //   unscoped enumeration type
10969     ExprResult Converted;
10970     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10971     public:
10972       CXX11ConvertDiagnoser(bool Silent)
10973           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10974                                 Silent, true) {}
10975 
10976       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10977                                            QualType T) override {
10978         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10979       }
10980 
10981       SemaDiagnosticBuilder diagnoseIncomplete(
10982           Sema &S, SourceLocation Loc, QualType T) override {
10983         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10984       }
10985 
10986       SemaDiagnosticBuilder diagnoseExplicitConv(
10987           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
10988         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10989       }
10990 
10991       SemaDiagnosticBuilder noteExplicitConv(
10992           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
10993         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10994                  << ConvTy->isEnumeralType() << ConvTy;
10995       }
10996 
10997       SemaDiagnosticBuilder diagnoseAmbiguous(
10998           Sema &S, SourceLocation Loc, QualType T) override {
10999         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
11000       }
11001 
11002       SemaDiagnosticBuilder noteAmbiguous(
11003           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
11004         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
11005                  << ConvTy->isEnumeralType() << ConvTy;
11006       }
11007 
11008       SemaDiagnosticBuilder diagnoseConversion(
11009           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
11010         llvm_unreachable("conversion functions are permitted");
11011       }
11012     } ConvertDiagnoser(Diagnoser.Suppress);
11013 
11014     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11015                                                     ConvertDiagnoser);
11016     if (Converted.isInvalid())
11017       return Converted;
11018     E = Converted.get();
11019     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11020       return ExprError();
11021   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11022     // An ICE must be of integral or unscoped enumeration type.
11023     if (!Diagnoser.Suppress)
11024       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11025     return ExprError();
11026   }
11027 
11028   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11029   // in the non-ICE case.
11030   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11031     if (Result)
11032       *Result = E->EvaluateKnownConstInt(Context);
11033     return E;
11034   }
11035 
11036   Expr::EvalResult EvalResult;
11037   SmallVector<PartialDiagnosticAt, 8> Notes;
11038   EvalResult.Diag = &Notes;
11039 
11040   // Try to evaluate the expression, and produce diagnostics explaining why it's
11041   // not a constant expression as a side-effect.
11042   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11043                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11044 
11045   // In C++11, we can rely on diagnostics being produced for any expression
11046   // which is not a constant expression. If no diagnostics were produced, then
11047   // this is a constant expression.
11048   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11049     if (Result)
11050       *Result = EvalResult.Val.getInt();
11051     return E;
11052   }
11053 
11054   // If our only note is the usual "invalid subexpression" note, just point
11055   // the caret at its location rather than producing an essentially
11056   // redundant note.
11057   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11058         diag::note_invalid_subexpr_in_const_expr) {
11059     DiagLoc = Notes[0].first;
11060     Notes.clear();
11061   }
11062 
11063   if (!Folded || !AllowFold) {
11064     if (!Diagnoser.Suppress) {
11065       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11066       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11067         Diag(Notes[I].first, Notes[I].second);
11068     }
11069 
11070     return ExprError();
11071   }
11072 
11073   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11074   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11075     Diag(Notes[I].first, Notes[I].second);
11076 
11077   if (Result)
11078     *Result = EvalResult.Val.getInt();
11079   return E;
11080 }
11081 
11082 namespace {
11083   // Handle the case where we conclude a expression which we speculatively
11084   // considered to be unevaluated is actually evaluated.
11085   class TransformToPE : public TreeTransform<TransformToPE> {
11086     typedef TreeTransform<TransformToPE> BaseTransform;
11087 
11088   public:
11089     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11090 
11091     // Make sure we redo semantic analysis
11092     bool AlwaysRebuild() { return true; }
11093 
11094     // Make sure we handle LabelStmts correctly.
11095     // FIXME: This does the right thing, but maybe we need a more general
11096     // fix to TreeTransform?
11097     StmtResult TransformLabelStmt(LabelStmt *S) {
11098       S->getDecl()->setStmt(nullptr);
11099       return BaseTransform::TransformLabelStmt(S);
11100     }
11101 
11102     // We need to special-case DeclRefExprs referring to FieldDecls which
11103     // are not part of a member pointer formation; normal TreeTransforming
11104     // doesn't catch this case because of the way we represent them in the AST.
11105     // FIXME: This is a bit ugly; is it really the best way to handle this
11106     // case?
11107     //
11108     // Error on DeclRefExprs referring to FieldDecls.
11109     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11110       if (isa<FieldDecl>(E->getDecl()) &&
11111           !SemaRef.isUnevaluatedContext())
11112         return SemaRef.Diag(E->getLocation(),
11113                             diag::err_invalid_non_static_member_use)
11114             << E->getDecl() << E->getSourceRange();
11115 
11116       return BaseTransform::TransformDeclRefExpr(E);
11117     }
11118 
11119     // Exception: filter out member pointer formation
11120     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11121       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11122         return E;
11123 
11124       return BaseTransform::TransformUnaryOperator(E);
11125     }
11126 
11127     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11128       // Lambdas never need to be transformed.
11129       return E;
11130     }
11131   };
11132 }
11133 
11134 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11135   assert(isUnevaluatedContext() &&
11136          "Should only transform unevaluated expressions");
11137   ExprEvalContexts.back().Context =
11138       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11139   if (isUnevaluatedContext())
11140     return E;
11141   return TransformToPE(*this).TransformExpr(E);
11142 }
11143 
11144 void
11145 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11146                                       Decl *LambdaContextDecl,
11147                                       bool IsDecltype) {
11148   ExprEvalContexts.push_back(
11149              ExpressionEvaluationContextRecord(NewContext,
11150                                                ExprCleanupObjects.size(),
11151                                                ExprNeedsCleanups,
11152                                                LambdaContextDecl,
11153                                                IsDecltype));
11154   ExprNeedsCleanups = false;
11155   if (!MaybeODRUseExprs.empty())
11156     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11157 }
11158 
11159 void
11160 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11161                                       ReuseLambdaContextDecl_t,
11162                                       bool IsDecltype) {
11163   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11164   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11165 }
11166 
11167 void Sema::PopExpressionEvaluationContext() {
11168   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11169 
11170   if (!Rec.Lambdas.empty()) {
11171     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11172       unsigned D;
11173       if (Rec.isUnevaluated()) {
11174         // C++11 [expr.prim.lambda]p2:
11175         //   A lambda-expression shall not appear in an unevaluated operand
11176         //   (Clause 5).
11177         D = diag::err_lambda_unevaluated_operand;
11178       } else {
11179         // C++1y [expr.const]p2:
11180         //   A conditional-expression e is a core constant expression unless the
11181         //   evaluation of e, following the rules of the abstract machine, would
11182         //   evaluate [...] a lambda-expression.
11183         D = diag::err_lambda_in_constant_expression;
11184       }
11185       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11186         Diag(Rec.Lambdas[I]->getLocStart(), D);
11187     } else {
11188       // Mark the capture expressions odr-used. This was deferred
11189       // during lambda expression creation.
11190       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11191         LambdaExpr *Lambda = Rec.Lambdas[I];
11192         for (LambdaExpr::capture_init_iterator
11193                   C = Lambda->capture_init_begin(),
11194                CEnd = Lambda->capture_init_end();
11195              C != CEnd; ++C) {
11196           MarkDeclarationsReferencedInExpr(*C);
11197         }
11198       }
11199     }
11200   }
11201 
11202   // When are coming out of an unevaluated context, clear out any
11203   // temporaries that we may have created as part of the evaluation of
11204   // the expression in that context: they aren't relevant because they
11205   // will never be constructed.
11206   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11207     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11208                              ExprCleanupObjects.end());
11209     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11210     CleanupVarDeclMarking();
11211     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11212   // Otherwise, merge the contexts together.
11213   } else {
11214     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11215     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11216                             Rec.SavedMaybeODRUseExprs.end());
11217   }
11218 
11219   // Pop the current expression evaluation context off the stack.
11220   ExprEvalContexts.pop_back();
11221 }
11222 
11223 void Sema::DiscardCleanupsInEvaluationContext() {
11224   ExprCleanupObjects.erase(
11225          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11226          ExprCleanupObjects.end());
11227   ExprNeedsCleanups = false;
11228   MaybeODRUseExprs.clear();
11229 }
11230 
11231 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11232   if (!E->getType()->isVariablyModifiedType())
11233     return E;
11234   return TransformToPotentiallyEvaluated(E);
11235 }
11236 
11237 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11238   // Do not mark anything as "used" within a dependent context; wait for
11239   // an instantiation.
11240   if (SemaRef.CurContext->isDependentContext())
11241     return false;
11242 
11243   switch (SemaRef.ExprEvalContexts.back().Context) {
11244     case Sema::Unevaluated:
11245     case Sema::UnevaluatedAbstract:
11246       // We are in an expression that is not potentially evaluated; do nothing.
11247       // (Depending on how you read the standard, we actually do need to do
11248       // something here for null pointer constants, but the standard's
11249       // definition of a null pointer constant is completely crazy.)
11250       return false;
11251 
11252     case Sema::ConstantEvaluated:
11253     case Sema::PotentiallyEvaluated:
11254       // We are in a potentially evaluated expression (or a constant-expression
11255       // in C++03); we need to do implicit template instantiation, implicitly
11256       // define class members, and mark most declarations as used.
11257       return true;
11258 
11259     case Sema::PotentiallyEvaluatedIfUsed:
11260       // Referenced declarations will only be used if the construct in the
11261       // containing expression is used.
11262       return false;
11263   }
11264   llvm_unreachable("Invalid context");
11265 }
11266 
11267 /// \brief Mark a function referenced, and check whether it is odr-used
11268 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11269 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11270   assert(Func && "No function?");
11271 
11272   Func->setReferenced();
11273 
11274   // C++11 [basic.def.odr]p3:
11275   //   A function whose name appears as a potentially-evaluated expression is
11276   //   odr-used if it is the unique lookup result or the selected member of a
11277   //   set of overloaded functions [...].
11278   //
11279   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11280   // can just check that here. Skip the rest of this function if we've already
11281   // marked the function as used.
11282   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11283     // C++11 [temp.inst]p3:
11284     //   Unless a function template specialization has been explicitly
11285     //   instantiated or explicitly specialized, the function template
11286     //   specialization is implicitly instantiated when the specialization is
11287     //   referenced in a context that requires a function definition to exist.
11288     //
11289     // We consider constexpr function templates to be referenced in a context
11290     // that requires a definition to exist whenever they are referenced.
11291     //
11292     // FIXME: This instantiates constexpr functions too frequently. If this is
11293     // really an unevaluated context (and we're not just in the definition of a
11294     // function template or overload resolution or other cases which we
11295     // incorrectly consider to be unevaluated contexts), and we're not in a
11296     // subexpression which we actually need to evaluate (for instance, a
11297     // template argument, array bound or an expression in a braced-init-list),
11298     // we are not permitted to instantiate this constexpr function definition.
11299     //
11300     // FIXME: This also implicitly defines special members too frequently. They
11301     // are only supposed to be implicitly defined if they are odr-used, but they
11302     // are not odr-used from constant expressions in unevaluated contexts.
11303     // However, they cannot be referenced if they are deleted, and they are
11304     // deleted whenever the implicit definition of the special member would
11305     // fail.
11306     if (!Func->isConstexpr() || Func->getBody())
11307       return;
11308     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11309     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11310       return;
11311   }
11312 
11313   // Note that this declaration has been used.
11314   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11315     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11316     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11317       if (Constructor->isDefaultConstructor()) {
11318         if (Constructor->isTrivial() && !Constructor->hasAttr<DLLExportAttr>())
11319           return;
11320         DefineImplicitDefaultConstructor(Loc, Constructor);
11321       } else if (Constructor->isCopyConstructor()) {
11322         DefineImplicitCopyConstructor(Loc, Constructor);
11323       } else if (Constructor->isMoveConstructor()) {
11324         DefineImplicitMoveConstructor(Loc, Constructor);
11325       }
11326     } else if (Constructor->getInheritedConstructor()) {
11327       DefineInheritingConstructor(Loc, Constructor);
11328     }
11329 
11330     MarkVTableUsed(Loc, Constructor->getParent());
11331   } else if (CXXDestructorDecl *Destructor =
11332                  dyn_cast<CXXDestructorDecl>(Func)) {
11333     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11334     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11335       DefineImplicitDestructor(Loc, Destructor);
11336     if (Destructor->isVirtual())
11337       MarkVTableUsed(Loc, Destructor->getParent());
11338   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11339     if (MethodDecl->isOverloadedOperator() &&
11340         MethodDecl->getOverloadedOperator() == OO_Equal) {
11341       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11342       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11343         if (MethodDecl->isCopyAssignmentOperator())
11344           DefineImplicitCopyAssignment(Loc, MethodDecl);
11345         else
11346           DefineImplicitMoveAssignment(Loc, MethodDecl);
11347       }
11348     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11349                MethodDecl->getParent()->isLambda()) {
11350       CXXConversionDecl *Conversion =
11351           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11352       if (Conversion->isLambdaToBlockPointerConversion())
11353         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11354       else
11355         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11356     } else if (MethodDecl->isVirtual())
11357       MarkVTableUsed(Loc, MethodDecl->getParent());
11358   }
11359 
11360   // Recursive functions should be marked when used from another function.
11361   // FIXME: Is this really right?
11362   if (CurContext == Func) return;
11363 
11364   // Resolve the exception specification for any function which is
11365   // used: CodeGen will need it.
11366   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11367   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11368     ResolveExceptionSpec(Loc, FPT);
11369 
11370   // Implicit instantiation of function templates and member functions of
11371   // class templates.
11372   if (Func->isImplicitlyInstantiable()) {
11373     bool AlreadyInstantiated = false;
11374     SourceLocation PointOfInstantiation = Loc;
11375     if (FunctionTemplateSpecializationInfo *SpecInfo
11376                               = Func->getTemplateSpecializationInfo()) {
11377       if (SpecInfo->getPointOfInstantiation().isInvalid())
11378         SpecInfo->setPointOfInstantiation(Loc);
11379       else if (SpecInfo->getTemplateSpecializationKind()
11380                  == TSK_ImplicitInstantiation) {
11381         AlreadyInstantiated = true;
11382         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11383       }
11384     } else if (MemberSpecializationInfo *MSInfo
11385                                 = Func->getMemberSpecializationInfo()) {
11386       if (MSInfo->getPointOfInstantiation().isInvalid())
11387         MSInfo->setPointOfInstantiation(Loc);
11388       else if (MSInfo->getTemplateSpecializationKind()
11389                  == TSK_ImplicitInstantiation) {
11390         AlreadyInstantiated = true;
11391         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11392       }
11393     }
11394 
11395     if (!AlreadyInstantiated || Func->isConstexpr()) {
11396       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11397           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11398           ActiveTemplateInstantiations.size())
11399         PendingLocalImplicitInstantiations.push_back(
11400             std::make_pair(Func, PointOfInstantiation));
11401       else if (Func->isConstexpr())
11402         // Do not defer instantiations of constexpr functions, to avoid the
11403         // expression evaluator needing to call back into Sema if it sees a
11404         // call to such a function.
11405         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11406       else {
11407         PendingInstantiations.push_back(std::make_pair(Func,
11408                                                        PointOfInstantiation));
11409         // Notify the consumer that a function was implicitly instantiated.
11410         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11411       }
11412     }
11413   } else {
11414     // Walk redefinitions, as some of them may be instantiable.
11415     for (auto i : Func->redecls()) {
11416       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11417         MarkFunctionReferenced(Loc, i);
11418     }
11419   }
11420 
11421   // Keep track of used but undefined functions.
11422   if (!Func->isDefined()) {
11423     if (mightHaveNonExternalLinkage(Func))
11424       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11425     else if (Func->getMostRecentDecl()->isInlined() &&
11426              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11427              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11428       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11429   }
11430 
11431   // Normally the most current decl is marked used while processing the use and
11432   // any subsequent decls are marked used by decl merging. This fails with
11433   // template instantiation since marking can happen at the end of the file
11434   // and, because of the two phase lookup, this function is called with at
11435   // decl in the middle of a decl chain. We loop to maintain the invariant
11436   // that once a decl is used, all decls after it are also used.
11437   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11438     F->markUsed(Context);
11439     if (F == Func)
11440       break;
11441   }
11442 }
11443 
11444 static void
11445 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11446                                    VarDecl *var, DeclContext *DC) {
11447   DeclContext *VarDC = var->getDeclContext();
11448 
11449   //  If the parameter still belongs to the translation unit, then
11450   //  we're actually just using one parameter in the declaration of
11451   //  the next.
11452   if (isa<ParmVarDecl>(var) &&
11453       isa<TranslationUnitDecl>(VarDC))
11454     return;
11455 
11456   // For C code, don't diagnose about capture if we're not actually in code
11457   // right now; it's impossible to write a non-constant expression outside of
11458   // function context, so we'll get other (more useful) diagnostics later.
11459   //
11460   // For C++, things get a bit more nasty... it would be nice to suppress this
11461   // diagnostic for certain cases like using a local variable in an array bound
11462   // for a member of a local class, but the correct predicate is not obvious.
11463   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11464     return;
11465 
11466   if (isa<CXXMethodDecl>(VarDC) &&
11467       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11468     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11469       << var->getIdentifier();
11470   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11471     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11472       << var->getIdentifier() << fn->getDeclName();
11473   } else if (isa<BlockDecl>(VarDC)) {
11474     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11475       << var->getIdentifier();
11476   } else {
11477     // FIXME: Is there any other context where a local variable can be
11478     // declared?
11479     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11480       << var->getIdentifier();
11481   }
11482 
11483   S.Diag(var->getLocation(), diag::note_entity_declared_at)
11484       << var->getIdentifier();
11485 
11486   // FIXME: Add additional diagnostic info about class etc. which prevents
11487   // capture.
11488 }
11489 
11490 
11491 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11492                                       bool &SubCapturesAreNested,
11493                                       QualType &CaptureType,
11494                                       QualType &DeclRefType) {
11495    // Check whether we've already captured it.
11496   if (CSI->CaptureMap.count(Var)) {
11497     // If we found a capture, any subcaptures are nested.
11498     SubCapturesAreNested = true;
11499 
11500     // Retrieve the capture type for this variable.
11501     CaptureType = CSI->getCapture(Var).getCaptureType();
11502 
11503     // Compute the type of an expression that refers to this variable.
11504     DeclRefType = CaptureType.getNonReferenceType();
11505 
11506     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11507     if (Cap.isCopyCapture() &&
11508         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11509       DeclRefType.addConst();
11510     return true;
11511   }
11512   return false;
11513 }
11514 
11515 // Only block literals, captured statements, and lambda expressions can
11516 // capture; other scopes don't work.
11517 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11518                                  SourceLocation Loc,
11519                                  const bool Diagnose, Sema &S) {
11520   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11521     return getLambdaAwareParentOfDeclContext(DC);
11522   else {
11523     if (Diagnose)
11524        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11525   }
11526   return nullptr;
11527 }
11528 
11529 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11530 // certain types of variables (unnamed, variably modified types etc.)
11531 // so check for eligibility.
11532 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11533                                  SourceLocation Loc,
11534                                  const bool Diagnose, Sema &S) {
11535 
11536   bool IsBlock = isa<BlockScopeInfo>(CSI);
11537   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11538 
11539   // Lambdas are not allowed to capture unnamed variables
11540   // (e.g. anonymous unions).
11541   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11542   // assuming that's the intent.
11543   if (IsLambda && !Var->getDeclName()) {
11544     if (Diagnose) {
11545       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11546       S.Diag(Var->getLocation(), diag::note_declared_at);
11547     }
11548     return false;
11549   }
11550 
11551   // Prohibit variably-modified types; they're difficult to deal with.
11552   if (Var->getType()->isVariablyModifiedType()) {
11553     if (Diagnose) {
11554       if (IsBlock)
11555         S.Diag(Loc, diag::err_ref_vm_type);
11556       else
11557         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11558       S.Diag(Var->getLocation(), diag::note_previous_decl)
11559         << Var->getDeclName();
11560     }
11561     return false;
11562   }
11563   // Prohibit structs with flexible array members too.
11564   // We cannot capture what is in the tail end of the struct.
11565   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11566     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11567       if (Diagnose) {
11568         if (IsBlock)
11569           S.Diag(Loc, diag::err_ref_flexarray_type);
11570         else
11571           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11572             << Var->getDeclName();
11573         S.Diag(Var->getLocation(), diag::note_previous_decl)
11574           << Var->getDeclName();
11575       }
11576       return false;
11577     }
11578   }
11579   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11580   // Lambdas and captured statements are not allowed to capture __block
11581   // variables; they don't support the expected semantics.
11582   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11583     if (Diagnose) {
11584       S.Diag(Loc, diag::err_capture_block_variable)
11585         << Var->getDeclName() << !IsLambda;
11586       S.Diag(Var->getLocation(), diag::note_previous_decl)
11587         << Var->getDeclName();
11588     }
11589     return false;
11590   }
11591 
11592   return true;
11593 }
11594 
11595 // Returns true if the capture by block was successful.
11596 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11597                                  SourceLocation Loc,
11598                                  const bool BuildAndDiagnose,
11599                                  QualType &CaptureType,
11600                                  QualType &DeclRefType,
11601                                  const bool Nested,
11602                                  Sema &S) {
11603   Expr *CopyExpr = nullptr;
11604   bool ByRef = false;
11605 
11606   // Blocks are not allowed to capture arrays.
11607   if (CaptureType->isArrayType()) {
11608     if (BuildAndDiagnose) {
11609       S.Diag(Loc, diag::err_ref_array_type);
11610       S.Diag(Var->getLocation(), diag::note_previous_decl)
11611       << Var->getDeclName();
11612     }
11613     return false;
11614   }
11615 
11616   // Forbid the block-capture of autoreleasing variables.
11617   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11618     if (BuildAndDiagnose) {
11619       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11620         << /*block*/ 0;
11621       S.Diag(Var->getLocation(), diag::note_previous_decl)
11622         << Var->getDeclName();
11623     }
11624     return false;
11625   }
11626   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11627   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11628     // Block capture by reference does not change the capture or
11629     // declaration reference types.
11630     ByRef = true;
11631   } else {
11632     // Block capture by copy introduces 'const'.
11633     CaptureType = CaptureType.getNonReferenceType().withConst();
11634     DeclRefType = CaptureType;
11635 
11636     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11637       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11638         // The capture logic needs the destructor, so make sure we mark it.
11639         // Usually this is unnecessary because most local variables have
11640         // their destructors marked at declaration time, but parameters are
11641         // an exception because it's technically only the call site that
11642         // actually requires the destructor.
11643         if (isa<ParmVarDecl>(Var))
11644           S.FinalizeVarWithDestructor(Var, Record);
11645 
11646         // Enter a new evaluation context to insulate the copy
11647         // full-expression.
11648         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11649 
11650         // According to the blocks spec, the capture of a variable from
11651         // the stack requires a const copy constructor.  This is not true
11652         // of the copy/move done to move a __block variable to the heap.
11653         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11654                                                   DeclRefType.withConst(),
11655                                                   VK_LValue, Loc);
11656 
11657         ExprResult Result
11658           = S.PerformCopyInitialization(
11659               InitializedEntity::InitializeBlock(Var->getLocation(),
11660                                                   CaptureType, false),
11661               Loc, DeclRef);
11662 
11663         // Build a full-expression copy expression if initialization
11664         // succeeded and used a non-trivial constructor.  Recover from
11665         // errors by pretending that the copy isn't necessary.
11666         if (!Result.isInvalid() &&
11667             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11668                 ->isTrivial()) {
11669           Result = S.MaybeCreateExprWithCleanups(Result);
11670           CopyExpr = Result.get();
11671         }
11672       }
11673     }
11674   }
11675 
11676   // Actually capture the variable.
11677   if (BuildAndDiagnose)
11678     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11679                     SourceLocation(), CaptureType, CopyExpr);
11680 
11681   return true;
11682 
11683 }
11684 
11685 
11686 /// \brief Capture the given variable in the captured region.
11687 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11688                                     VarDecl *Var,
11689                                     SourceLocation Loc,
11690                                     const bool BuildAndDiagnose,
11691                                     QualType &CaptureType,
11692                                     QualType &DeclRefType,
11693                                     const bool RefersToEnclosingLocal,
11694                                     Sema &S) {
11695 
11696   // By default, capture variables by reference.
11697   bool ByRef = true;
11698   // Using an LValue reference type is consistent with Lambdas (see below).
11699   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11700   Expr *CopyExpr = nullptr;
11701   if (BuildAndDiagnose) {
11702     // The current implementation assumes that all variables are captured
11703     // by references. Since there is no capture by copy, no expression
11704     // evaluation will be needed.
11705     RecordDecl *RD = RSI->TheRecordDecl;
11706 
11707     FieldDecl *Field
11708       = FieldDecl::Create(S.Context, RD, Loc, Loc, nullptr, CaptureType,
11709                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11710                           nullptr, false, ICIS_NoInit);
11711     Field->setImplicit(true);
11712     Field->setAccess(AS_private);
11713     RD->addDecl(Field);
11714 
11715     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11716                                             DeclRefType, VK_LValue, Loc);
11717     Var->setReferenced(true);
11718     Var->markUsed(S.Context);
11719   }
11720 
11721   // Actually capture the variable.
11722   if (BuildAndDiagnose)
11723     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11724                     SourceLocation(), CaptureType, CopyExpr);
11725 
11726 
11727   return true;
11728 }
11729 
11730 /// \brief Create a field within the lambda class for the variable
11731 ///  being captured.  Handle Array captures.
11732 static ExprResult addAsFieldToClosureType(Sema &S,
11733                                  LambdaScopeInfo *LSI,
11734                                   VarDecl *Var, QualType FieldType,
11735                                   QualType DeclRefType,
11736                                   SourceLocation Loc,
11737                                   bool RefersToEnclosingLocal) {
11738   CXXRecordDecl *Lambda = LSI->Lambda;
11739 
11740   // Build the non-static data member.
11741   FieldDecl *Field
11742     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, nullptr, FieldType,
11743                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11744                         nullptr, false, ICIS_NoInit);
11745   Field->setImplicit(true);
11746   Field->setAccess(AS_private);
11747   Lambda->addDecl(Field);
11748 
11749   // C++11 [expr.prim.lambda]p21:
11750   //   When the lambda-expression is evaluated, the entities that
11751   //   are captured by copy are used to direct-initialize each
11752   //   corresponding non-static data member of the resulting closure
11753   //   object. (For array members, the array elements are
11754   //   direct-initialized in increasing subscript order.) These
11755   //   initializations are performed in the (unspecified) order in
11756   //   which the non-static data members are declared.
11757 
11758   // Introduce a new evaluation context for the initialization, so
11759   // that temporaries introduced as part of the capture are retained
11760   // to be re-"exported" from the lambda expression itself.
11761   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11762 
11763   // C++ [expr.prim.labda]p12:
11764   //   An entity captured by a lambda-expression is odr-used (3.2) in
11765   //   the scope containing the lambda-expression.
11766   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11767                                           DeclRefType, VK_LValue, Loc);
11768   Var->setReferenced(true);
11769   Var->markUsed(S.Context);
11770 
11771   // When the field has array type, create index variables for each
11772   // dimension of the array. We use these index variables to subscript
11773   // the source array, and other clients (e.g., CodeGen) will perform
11774   // the necessary iteration with these index variables.
11775   SmallVector<VarDecl *, 4> IndexVariables;
11776   QualType BaseType = FieldType;
11777   QualType SizeType = S.Context.getSizeType();
11778   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11779   while (const ConstantArrayType *Array
11780                         = S.Context.getAsConstantArrayType(BaseType)) {
11781     // Create the iteration variable for this array index.
11782     IdentifierInfo *IterationVarName = nullptr;
11783     {
11784       SmallString<8> Str;
11785       llvm::raw_svector_ostream OS(Str);
11786       OS << "__i" << IndexVariables.size();
11787       IterationVarName = &S.Context.Idents.get(OS.str());
11788     }
11789     VarDecl *IterationVar
11790       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11791                         IterationVarName, SizeType,
11792                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11793                         SC_None);
11794     IndexVariables.push_back(IterationVar);
11795     LSI->ArrayIndexVars.push_back(IterationVar);
11796 
11797     // Create a reference to the iteration variable.
11798     ExprResult IterationVarRef
11799       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11800     assert(!IterationVarRef.isInvalid() &&
11801            "Reference to invented variable cannot fail!");
11802     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
11803     assert(!IterationVarRef.isInvalid() &&
11804            "Conversion of invented variable cannot fail!");
11805 
11806     // Subscript the array with this iteration variable.
11807     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11808                              Ref, Loc, IterationVarRef.get(), Loc);
11809     if (Subscript.isInvalid()) {
11810       S.CleanupVarDeclMarking();
11811       S.DiscardCleanupsInEvaluationContext();
11812       return ExprError();
11813     }
11814 
11815     Ref = Subscript.get();
11816     BaseType = Array->getElementType();
11817   }
11818 
11819   // Construct the entity that we will be initializing. For an array, this
11820   // will be first element in the array, which may require several levels
11821   // of array-subscript entities.
11822   SmallVector<InitializedEntity, 4> Entities;
11823   Entities.reserve(1 + IndexVariables.size());
11824   Entities.push_back(
11825     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11826         Field->getType(), Loc));
11827   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11828     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11829                                                             0,
11830                                                             Entities.back()));
11831 
11832   InitializationKind InitKind
11833     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11834   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11835   ExprResult Result(true);
11836   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11837     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11838 
11839   // If this initialization requires any cleanups (e.g., due to a
11840   // default argument to a copy constructor), note that for the
11841   // lambda.
11842   if (S.ExprNeedsCleanups)
11843     LSI->ExprNeedsCleanups = true;
11844 
11845   // Exit the expression evaluation context used for the capture.
11846   S.CleanupVarDeclMarking();
11847   S.DiscardCleanupsInEvaluationContext();
11848   return Result;
11849 }
11850 
11851 
11852 
11853 /// \brief Capture the given variable in the lambda.
11854 static bool captureInLambda(LambdaScopeInfo *LSI,
11855                             VarDecl *Var,
11856                             SourceLocation Loc,
11857                             const bool BuildAndDiagnose,
11858                             QualType &CaptureType,
11859                             QualType &DeclRefType,
11860                             const bool RefersToEnclosingLocal,
11861                             const Sema::TryCaptureKind Kind,
11862                             SourceLocation EllipsisLoc,
11863                             const bool IsTopScope,
11864                             Sema &S) {
11865 
11866   // Determine whether we are capturing by reference or by value.
11867   bool ByRef = false;
11868   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11869     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11870   } else {
11871     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11872   }
11873 
11874   // Compute the type of the field that will capture this variable.
11875   if (ByRef) {
11876     // C++11 [expr.prim.lambda]p15:
11877     //   An entity is captured by reference if it is implicitly or
11878     //   explicitly captured but not captured by copy. It is
11879     //   unspecified whether additional unnamed non-static data
11880     //   members are declared in the closure type for entities
11881     //   captured by reference.
11882     //
11883     // FIXME: It is not clear whether we want to build an lvalue reference
11884     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11885     // to do the former, while EDG does the latter. Core issue 1249 will
11886     // clarify, but for now we follow GCC because it's a more permissive and
11887     // easily defensible position.
11888     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11889   } else {
11890     // C++11 [expr.prim.lambda]p14:
11891     //   For each entity captured by copy, an unnamed non-static
11892     //   data member is declared in the closure type. The
11893     //   declaration order of these members is unspecified. The type
11894     //   of such a data member is the type of the corresponding
11895     //   captured entity if the entity is not a reference to an
11896     //   object, or the referenced type otherwise. [Note: If the
11897     //   captured entity is a reference to a function, the
11898     //   corresponding data member is also a reference to a
11899     //   function. - end note ]
11900     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11901       if (!RefType->getPointeeType()->isFunctionType())
11902         CaptureType = RefType->getPointeeType();
11903     }
11904 
11905     // Forbid the lambda copy-capture of autoreleasing variables.
11906     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11907       if (BuildAndDiagnose) {
11908         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11909         S.Diag(Var->getLocation(), diag::note_previous_decl)
11910           << Var->getDeclName();
11911       }
11912       return false;
11913     }
11914 
11915     // Make sure that by-copy captures are of a complete and non-abstract type.
11916     if (BuildAndDiagnose) {
11917       if (!CaptureType->isDependentType() &&
11918           S.RequireCompleteType(Loc, CaptureType,
11919                                 diag::err_capture_of_incomplete_type,
11920                                 Var->getDeclName()))
11921         return false;
11922 
11923       if (S.RequireNonAbstractType(Loc, CaptureType,
11924                                    diag::err_capture_of_abstract_type))
11925         return false;
11926     }
11927   }
11928 
11929   // Capture this variable in the lambda.
11930   Expr *CopyExpr = nullptr;
11931   if (BuildAndDiagnose) {
11932     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
11933                                         CaptureType, DeclRefType, Loc,
11934                                         RefersToEnclosingLocal);
11935     if (!Result.isInvalid())
11936       CopyExpr = Result.get();
11937   }
11938 
11939   // Compute the type of a reference to this captured variable.
11940   if (ByRef)
11941     DeclRefType = CaptureType.getNonReferenceType();
11942   else {
11943     // C++ [expr.prim.lambda]p5:
11944     //   The closure type for a lambda-expression has a public inline
11945     //   function call operator [...]. This function call operator is
11946     //   declared const (9.3.1) if and only if the lambda-expression’s
11947     //   parameter-declaration-clause is not followed by mutable.
11948     DeclRefType = CaptureType.getNonReferenceType();
11949     if (!LSI->Mutable && !CaptureType->isReferenceType())
11950       DeclRefType.addConst();
11951   }
11952 
11953   // Add the capture.
11954   if (BuildAndDiagnose)
11955     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
11956                     Loc, EllipsisLoc, CaptureType, CopyExpr);
11957 
11958   return true;
11959 }
11960 
11961 
11962 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
11963                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11964                               bool BuildAndDiagnose,
11965                               QualType &CaptureType,
11966                               QualType &DeclRefType,
11967 						                const unsigned *const FunctionScopeIndexToStopAt) {
11968   bool Nested = false;
11969 
11970   DeclContext *DC = CurContext;
11971   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
11972       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
11973   // We need to sync up the Declaration Context with the
11974   // FunctionScopeIndexToStopAt
11975   if (FunctionScopeIndexToStopAt) {
11976     unsigned FSIndex = FunctionScopes.size() - 1;
11977     while (FSIndex != MaxFunctionScopesIndex) {
11978       DC = getLambdaAwareParentOfDeclContext(DC);
11979       --FSIndex;
11980     }
11981   }
11982 
11983 
11984   // If the variable is declared in the current context (and is not an
11985   // init-capture), there is no need to capture it.
11986   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
11987   if (!Var->hasLocalStorage()) return true;
11988 
11989   // Walk up the stack to determine whether we can capture the variable,
11990   // performing the "simple" checks that don't depend on type. We stop when
11991   // we've either hit the declared scope of the variable or find an existing
11992   // capture of that variable.  We start from the innermost capturing-entity
11993   // (the DC) and ensure that all intervening capturing-entities
11994   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
11995   // declcontext can either capture the variable or have already captured
11996   // the variable.
11997   CaptureType = Var->getType();
11998   DeclRefType = CaptureType.getNonReferenceType();
11999   bool Explicit = (Kind != TryCapture_Implicit);
12000   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
12001   do {
12002     // Only block literals, captured statements, and lambda expressions can
12003     // capture; other scopes don't work.
12004     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
12005                                                               ExprLoc,
12006                                                               BuildAndDiagnose,
12007                                                               *this);
12008     if (!ParentDC) return true;
12009 
12010     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
12011     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
12012 
12013 
12014     // Check whether we've already captured it.
12015     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12016                                              DeclRefType))
12017       break;
12018     // If we are instantiating a generic lambda call operator body,
12019     // we do not want to capture new variables.  What was captured
12020     // during either a lambdas transformation or initial parsing
12021     // should be used.
12022     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12023       if (BuildAndDiagnose) {
12024         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12025         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12026           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12027           Diag(Var->getLocation(), diag::note_previous_decl)
12028              << Var->getDeclName();
12029           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12030         } else
12031           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12032       }
12033       return true;
12034     }
12035     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12036     // certain types of variables (unnamed, variably modified types etc.)
12037     // so check for eligibility.
12038     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12039        return true;
12040 
12041     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12042       // No capture-default, and this is not an explicit capture
12043       // so cannot capture this variable.
12044       if (BuildAndDiagnose) {
12045         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12046         Diag(Var->getLocation(), diag::note_previous_decl)
12047           << Var->getDeclName();
12048         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12049              diag::note_lambda_decl);
12050         // FIXME: If we error out because an outer lambda can not implicitly
12051         // capture a variable that an inner lambda explicitly captures, we
12052         // should have the inner lambda do the explicit capture - because
12053         // it makes for cleaner diagnostics later.  This would purely be done
12054         // so that the diagnostic does not misleadingly claim that a variable
12055         // can not be captured by a lambda implicitly even though it is captured
12056         // explicitly.  Suggestion:
12057         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12058         //    at the function head
12059         //  - cache the StartingDeclContext - this must be a lambda
12060         //  - captureInLambda in the innermost lambda the variable.
12061       }
12062       return true;
12063     }
12064 
12065     FunctionScopesIndex--;
12066     DC = ParentDC;
12067     Explicit = false;
12068   } while (!Var->getDeclContext()->Equals(DC));
12069 
12070   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12071   // computing the type of the capture at each step, checking type-specific
12072   // requirements, and adding captures if requested.
12073   // If the variable had already been captured previously, we start capturing
12074   // at the lambda nested within that one.
12075   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12076        ++I) {
12077     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12078 
12079     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12080       if (!captureInBlock(BSI, Var, ExprLoc,
12081                           BuildAndDiagnose, CaptureType,
12082                           DeclRefType, Nested, *this))
12083         return true;
12084       Nested = true;
12085     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12086       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12087                                    BuildAndDiagnose, CaptureType,
12088                                    DeclRefType, Nested, *this))
12089         return true;
12090       Nested = true;
12091     } else {
12092       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12093       if (!captureInLambda(LSI, Var, ExprLoc,
12094                            BuildAndDiagnose, CaptureType,
12095                            DeclRefType, Nested, Kind, EllipsisLoc,
12096                             /*IsTopScope*/I == N - 1, *this))
12097         return true;
12098       Nested = true;
12099     }
12100   }
12101   return false;
12102 }
12103 
12104 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12105                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12106   QualType CaptureType;
12107   QualType DeclRefType;
12108   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12109                             /*BuildAndDiagnose=*/true, CaptureType,
12110                             DeclRefType, nullptr);
12111 }
12112 
12113 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12114   QualType CaptureType;
12115   QualType DeclRefType;
12116 
12117   // Determine whether we can capture this variable.
12118   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12119                          /*BuildAndDiagnose=*/false, CaptureType,
12120                          DeclRefType, nullptr))
12121     return QualType();
12122 
12123   return DeclRefType;
12124 }
12125 
12126 
12127 
12128 // If either the type of the variable or the initializer is dependent,
12129 // return false. Otherwise, determine whether the variable is a constant
12130 // expression. Use this if you need to know if a variable that might or
12131 // might not be dependent is truly a constant expression.
12132 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12133     ASTContext &Context) {
12134 
12135   if (Var->getType()->isDependentType())
12136     return false;
12137   const VarDecl *DefVD = nullptr;
12138   Var->getAnyInitializer(DefVD);
12139   if (!DefVD)
12140     return false;
12141   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12142   Expr *Init = cast<Expr>(Eval->Value);
12143   if (Init->isValueDependent())
12144     return false;
12145   return IsVariableAConstantExpression(Var, Context);
12146 }
12147 
12148 
12149 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12150   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12151   // an object that satisfies the requirements for appearing in a
12152   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12153   // is immediately applied."  This function handles the lvalue-to-rvalue
12154   // conversion part.
12155   MaybeODRUseExprs.erase(E->IgnoreParens());
12156 
12157   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12158   // to a variable that is a constant expression, and if so, identify it as
12159   // a reference to a variable that does not involve an odr-use of that
12160   // variable.
12161   if (LambdaScopeInfo *LSI = getCurLambda()) {
12162     Expr *SansParensExpr = E->IgnoreParens();
12163     VarDecl *Var = nullptr;
12164     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12165       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12166     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12167       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12168 
12169     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12170       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12171   }
12172 }
12173 
12174 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12175   if (!Res.isUsable())
12176     return Res;
12177 
12178   // If a constant-expression is a reference to a variable where we delay
12179   // deciding whether it is an odr-use, just assume we will apply the
12180   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12181   // (a non-type template argument), we have special handling anyway.
12182   UpdateMarkingForLValueToRValue(Res.get());
12183   return Res;
12184 }
12185 
12186 void Sema::CleanupVarDeclMarking() {
12187   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12188                                         e = MaybeODRUseExprs.end();
12189        i != e; ++i) {
12190     VarDecl *Var;
12191     SourceLocation Loc;
12192     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12193       Var = cast<VarDecl>(DRE->getDecl());
12194       Loc = DRE->getLocation();
12195     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12196       Var = cast<VarDecl>(ME->getMemberDecl());
12197       Loc = ME->getMemberLoc();
12198     } else {
12199       llvm_unreachable("Unexpcted expression");
12200     }
12201 
12202     MarkVarDeclODRUsed(Var, Loc, *this,
12203                        /*MaxFunctionScopeIndex Pointer*/ nullptr);
12204   }
12205 
12206   MaybeODRUseExprs.clear();
12207 }
12208 
12209 
12210 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12211                                     VarDecl *Var, Expr *E) {
12212   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12213          "Invalid Expr argument to DoMarkVarDeclReferenced");
12214   Var->setReferenced();
12215 
12216   // If the context is not potentially evaluated, this is not an odr-use and
12217   // does not trigger instantiation.
12218   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12219     if (SemaRef.isUnevaluatedContext())
12220       return;
12221 
12222     // If we don't yet know whether this context is going to end up being an
12223     // evaluated context, and we're referencing a variable from an enclosing
12224     // scope, add a potential capture.
12225     //
12226     // FIXME: Is this necessary? These contexts are only used for default
12227     // arguments, where local variables can't be used.
12228     const bool RefersToEnclosingScope =
12229         (SemaRef.CurContext != Var->getDeclContext() &&
12230          Var->getDeclContext()->isFunctionOrMethod() &&
12231          Var->hasLocalStorage());
12232     if (!RefersToEnclosingScope)
12233       return;
12234 
12235     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12236       // If a variable could potentially be odr-used, defer marking it so
12237       // until we finish analyzing the full expression for any lvalue-to-rvalue
12238       // or discarded value conversions that would obviate odr-use.
12239       // Add it to the list of potential captures that will be analyzed
12240       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12241       // unless the variable is a reference that was initialized by a constant
12242       // expression (this will never need to be captured or odr-used).
12243       assert(E && "Capture variable should be used in an expression.");
12244       if (!Var->getType()->isReferenceType() ||
12245           !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12246         LSI->addPotentialCapture(E->IgnoreParens());
12247     }
12248     return;
12249   }
12250 
12251   VarTemplateSpecializationDecl *VarSpec =
12252       dyn_cast<VarTemplateSpecializationDecl>(Var);
12253   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12254          "Can't instantiate a partial template specialization.");
12255 
12256   // Perform implicit instantiation of static data members, static data member
12257   // templates of class templates, and variable template specializations. Delay
12258   // instantiations of variable templates, except for those that could be used
12259   // in a constant expression.
12260   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12261   if (isTemplateInstantiation(TSK)) {
12262     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12263 
12264     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12265       if (Var->getPointOfInstantiation().isInvalid()) {
12266         // This is a modification of an existing AST node. Notify listeners.
12267         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12268           L->StaticDataMemberInstantiated(Var);
12269       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12270         // Don't bother trying to instantiate it again, unless we might need
12271         // its initializer before we get to the end of the TU.
12272         TryInstantiating = false;
12273     }
12274 
12275     if (Var->getPointOfInstantiation().isInvalid())
12276       Var->setTemplateSpecializationKind(TSK, Loc);
12277 
12278     if (TryInstantiating) {
12279       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12280       bool InstantiationDependent = false;
12281       bool IsNonDependent =
12282           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12283                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12284                   : true;
12285 
12286       // Do not instantiate specializations that are still type-dependent.
12287       if (IsNonDependent) {
12288         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12289           // Do not defer instantiations of variables which could be used in a
12290           // constant expression.
12291           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12292         } else {
12293           SemaRef.PendingInstantiations
12294               .push_back(std::make_pair(Var, PointOfInstantiation));
12295         }
12296       }
12297     }
12298   }
12299 
12300   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12301   // the requirements for appearing in a constant expression (5.19) and, if
12302   // it is an object, the lvalue-to-rvalue conversion (4.1)
12303   // is immediately applied."  We check the first part here, and
12304   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12305   // Note that we use the C++11 definition everywhere because nothing in
12306   // C++03 depends on whether we get the C++03 version correct. The second
12307   // part does not apply to references, since they are not objects.
12308   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12309     // A reference initialized by a constant expression can never be
12310     // odr-used, so simply ignore it.
12311     if (!Var->getType()->isReferenceType())
12312       SemaRef.MaybeODRUseExprs.insert(E);
12313   } else
12314     MarkVarDeclODRUsed(Var, Loc, SemaRef,
12315                        /*MaxFunctionScopeIndex ptr*/ nullptr);
12316 }
12317 
12318 /// \brief Mark a variable referenced, and check whether it is odr-used
12319 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12320 /// used directly for normal expressions referring to VarDecl.
12321 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12322   DoMarkVarDeclReferenced(*this, Loc, Var, nullptr);
12323 }
12324 
12325 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12326                                Decl *D, Expr *E, bool OdrUse) {
12327   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12328     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12329     return;
12330   }
12331 
12332   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12333 
12334   // If this is a call to a method via a cast, also mark the method in the
12335   // derived class used in case codegen can devirtualize the call.
12336   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12337   if (!ME)
12338     return;
12339   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12340   if (!MD)
12341     return;
12342   const Expr *Base = ME->getBase();
12343   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12344   if (!MostDerivedClassDecl)
12345     return;
12346   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12347   if (!DM || DM->isPure())
12348     return;
12349   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12350 }
12351 
12352 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12353 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12354   // TODO: update this with DR# once a defect report is filed.
12355   // C++11 defect. The address of a pure member should not be an ODR use, even
12356   // if it's a qualified reference.
12357   bool OdrUse = true;
12358   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12359     if (Method->isVirtual())
12360       OdrUse = false;
12361   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12362 }
12363 
12364 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12365 void Sema::MarkMemberReferenced(MemberExpr *E) {
12366   // C++11 [basic.def.odr]p2:
12367   //   A non-overloaded function whose name appears as a potentially-evaluated
12368   //   expression or a member of a set of candidate functions, if selected by
12369   //   overload resolution when referred to from a potentially-evaluated
12370   //   expression, is odr-used, unless it is a pure virtual function and its
12371   //   name is not explicitly qualified.
12372   bool OdrUse = true;
12373   if (!E->hasQualifier()) {
12374     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12375       if (Method->isPure())
12376         OdrUse = false;
12377   }
12378   SourceLocation Loc = E->getMemberLoc().isValid() ?
12379                             E->getMemberLoc() : E->getLocStart();
12380   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12381 }
12382 
12383 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12384 /// marks the declaration referenced, and performs odr-use checking for
12385 /// functions and variables. This method should not be used when building a
12386 /// normal expression which refers to a variable.
12387 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12388   if (OdrUse) {
12389     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12390       MarkVariableReferenced(Loc, VD);
12391       return;
12392     }
12393     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12394       MarkFunctionReferenced(Loc, FD);
12395       return;
12396     }
12397   }
12398   D->setReferenced();
12399 }
12400 
12401 namespace {
12402   // Mark all of the declarations referenced
12403   // FIXME: Not fully implemented yet! We need to have a better understanding
12404   // of when we're entering
12405   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12406     Sema &S;
12407     SourceLocation Loc;
12408 
12409   public:
12410     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12411 
12412     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12413 
12414     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12415     bool TraverseRecordType(RecordType *T);
12416   };
12417 }
12418 
12419 bool MarkReferencedDecls::TraverseTemplateArgument(
12420     const TemplateArgument &Arg) {
12421   if (Arg.getKind() == TemplateArgument::Declaration) {
12422     if (Decl *D = Arg.getAsDecl())
12423       S.MarkAnyDeclReferenced(Loc, D, true);
12424   }
12425 
12426   return Inherited::TraverseTemplateArgument(Arg);
12427 }
12428 
12429 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12430   if (ClassTemplateSpecializationDecl *Spec
12431                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12432     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12433     return TraverseTemplateArguments(Args.data(), Args.size());
12434   }
12435 
12436   return true;
12437 }
12438 
12439 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12440   MarkReferencedDecls Marker(*this, Loc);
12441   Marker.TraverseType(Context.getCanonicalType(T));
12442 }
12443 
12444 namespace {
12445   /// \brief Helper class that marks all of the declarations referenced by
12446   /// potentially-evaluated subexpressions as "referenced".
12447   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12448     Sema &S;
12449     bool SkipLocalVariables;
12450 
12451   public:
12452     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12453 
12454     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12455       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12456 
12457     void VisitDeclRefExpr(DeclRefExpr *E) {
12458       // If we were asked not to visit local variables, don't.
12459       if (SkipLocalVariables) {
12460         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12461           if (VD->hasLocalStorage())
12462             return;
12463       }
12464 
12465       S.MarkDeclRefReferenced(E);
12466     }
12467 
12468     void VisitMemberExpr(MemberExpr *E) {
12469       S.MarkMemberReferenced(E);
12470       Inherited::VisitMemberExpr(E);
12471     }
12472 
12473     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12474       S.MarkFunctionReferenced(E->getLocStart(),
12475             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12476       Visit(E->getSubExpr());
12477     }
12478 
12479     void VisitCXXNewExpr(CXXNewExpr *E) {
12480       if (E->getOperatorNew())
12481         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12482       if (E->getOperatorDelete())
12483         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12484       Inherited::VisitCXXNewExpr(E);
12485     }
12486 
12487     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12488       if (E->getOperatorDelete())
12489         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12490       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12491       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12492         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12493         S.MarkFunctionReferenced(E->getLocStart(),
12494                                     S.LookupDestructor(Record));
12495       }
12496 
12497       Inherited::VisitCXXDeleteExpr(E);
12498     }
12499 
12500     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12501       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12502       Inherited::VisitCXXConstructExpr(E);
12503     }
12504 
12505     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12506       Visit(E->getExpr());
12507     }
12508 
12509     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12510       Inherited::VisitImplicitCastExpr(E);
12511 
12512       if (E->getCastKind() == CK_LValueToRValue)
12513         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12514     }
12515   };
12516 }
12517 
12518 /// \brief Mark any declarations that appear within this expression or any
12519 /// potentially-evaluated subexpressions as "referenced".
12520 ///
12521 /// \param SkipLocalVariables If true, don't mark local variables as
12522 /// 'referenced'.
12523 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12524                                             bool SkipLocalVariables) {
12525   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12526 }
12527 
12528 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12529 /// of the program being compiled.
12530 ///
12531 /// This routine emits the given diagnostic when the code currently being
12532 /// type-checked is "potentially evaluated", meaning that there is a
12533 /// possibility that the code will actually be executable. Code in sizeof()
12534 /// expressions, code used only during overload resolution, etc., are not
12535 /// potentially evaluated. This routine will suppress such diagnostics or,
12536 /// in the absolutely nutty case of potentially potentially evaluated
12537 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12538 /// later.
12539 ///
12540 /// This routine should be used for all diagnostics that describe the run-time
12541 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12542 /// Failure to do so will likely result in spurious diagnostics or failures
12543 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12544 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12545                                const PartialDiagnostic &PD) {
12546   switch (ExprEvalContexts.back().Context) {
12547   case Unevaluated:
12548   case UnevaluatedAbstract:
12549     // The argument will never be evaluated, so don't complain.
12550     break;
12551 
12552   case ConstantEvaluated:
12553     // Relevant diagnostics should be produced by constant evaluation.
12554     break;
12555 
12556   case PotentiallyEvaluated:
12557   case PotentiallyEvaluatedIfUsed:
12558     if (Statement && getCurFunctionOrMethodDecl()) {
12559       FunctionScopes.back()->PossiblyUnreachableDiags.
12560         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12561     }
12562     else
12563       Diag(Loc, PD);
12564 
12565     return true;
12566   }
12567 
12568   return false;
12569 }
12570 
12571 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12572                                CallExpr *CE, FunctionDecl *FD) {
12573   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12574     return false;
12575 
12576   // If we're inside a decltype's expression, don't check for a valid return
12577   // type or construct temporaries until we know whether this is the last call.
12578   if (ExprEvalContexts.back().IsDecltype) {
12579     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12580     return false;
12581   }
12582 
12583   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12584     FunctionDecl *FD;
12585     CallExpr *CE;
12586 
12587   public:
12588     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12589       : FD(FD), CE(CE) { }
12590 
12591     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12592       if (!FD) {
12593         S.Diag(Loc, diag::err_call_incomplete_return)
12594           << T << CE->getSourceRange();
12595         return;
12596       }
12597 
12598       S.Diag(Loc, diag::err_call_function_incomplete_return)
12599         << CE->getSourceRange() << FD->getDeclName() << T;
12600       S.Diag(FD->getLocation(), diag::note_entity_declared_at)
12601           << FD->getDeclName();
12602     }
12603   } Diagnoser(FD, CE);
12604 
12605   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12606     return true;
12607 
12608   return false;
12609 }
12610 
12611 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12612 // will prevent this condition from triggering, which is what we want.
12613 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12614   SourceLocation Loc;
12615 
12616   unsigned diagnostic = diag::warn_condition_is_assignment;
12617   bool IsOrAssign = false;
12618 
12619   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12620     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12621       return;
12622 
12623     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12624 
12625     // Greylist some idioms by putting them into a warning subcategory.
12626     if (ObjCMessageExpr *ME
12627           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12628       Selector Sel = ME->getSelector();
12629 
12630       // self = [<foo> init...]
12631       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12632         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12633 
12634       // <foo> = [<bar> nextObject]
12635       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12636         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12637     }
12638 
12639     Loc = Op->getOperatorLoc();
12640   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12641     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12642       return;
12643 
12644     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12645     Loc = Op->getOperatorLoc();
12646   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12647     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12648   else {
12649     // Not an assignment.
12650     return;
12651   }
12652 
12653   Diag(Loc, diagnostic) << E->getSourceRange();
12654 
12655   SourceLocation Open = E->getLocStart();
12656   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12657   Diag(Loc, diag::note_condition_assign_silence)
12658         << FixItHint::CreateInsertion(Open, "(")
12659         << FixItHint::CreateInsertion(Close, ")");
12660 
12661   if (IsOrAssign)
12662     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12663       << FixItHint::CreateReplacement(Loc, "!=");
12664   else
12665     Diag(Loc, diag::note_condition_assign_to_comparison)
12666       << FixItHint::CreateReplacement(Loc, "==");
12667 }
12668 
12669 /// \brief Redundant parentheses over an equality comparison can indicate
12670 /// that the user intended an assignment used as condition.
12671 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12672   // Don't warn if the parens came from a macro.
12673   SourceLocation parenLoc = ParenE->getLocStart();
12674   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12675     return;
12676   // Don't warn for dependent expressions.
12677   if (ParenE->isTypeDependent())
12678     return;
12679 
12680   Expr *E = ParenE->IgnoreParens();
12681 
12682   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12683     if (opE->getOpcode() == BO_EQ &&
12684         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12685                                                            == Expr::MLV_Valid) {
12686       SourceLocation Loc = opE->getOperatorLoc();
12687 
12688       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12689       SourceRange ParenERange = ParenE->getSourceRange();
12690       Diag(Loc, diag::note_equality_comparison_silence)
12691         << FixItHint::CreateRemoval(ParenERange.getBegin())
12692         << FixItHint::CreateRemoval(ParenERange.getEnd());
12693       Diag(Loc, diag::note_equality_comparison_to_assign)
12694         << FixItHint::CreateReplacement(Loc, "=");
12695     }
12696 }
12697 
12698 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12699   DiagnoseAssignmentAsCondition(E);
12700   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12701     DiagnoseEqualityWithExtraParens(parenE);
12702 
12703   ExprResult result = CheckPlaceholderExpr(E);
12704   if (result.isInvalid()) return ExprError();
12705   E = result.get();
12706 
12707   if (!E->isTypeDependent()) {
12708     if (getLangOpts().CPlusPlus)
12709       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12710 
12711     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12712     if (ERes.isInvalid())
12713       return ExprError();
12714     E = ERes.get();
12715 
12716     QualType T = E->getType();
12717     if (!T->isScalarType()) { // C99 6.8.4.1p1
12718       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12719         << T << E->getSourceRange();
12720       return ExprError();
12721     }
12722   }
12723 
12724   return E;
12725 }
12726 
12727 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12728                                        Expr *SubExpr) {
12729   if (!SubExpr)
12730     return ExprError();
12731 
12732   return CheckBooleanCondition(SubExpr, Loc);
12733 }
12734 
12735 namespace {
12736   /// A visitor for rebuilding a call to an __unknown_any expression
12737   /// to have an appropriate type.
12738   struct RebuildUnknownAnyFunction
12739     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12740 
12741     Sema &S;
12742 
12743     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12744 
12745     ExprResult VisitStmt(Stmt *S) {
12746       llvm_unreachable("unexpected statement!");
12747     }
12748 
12749     ExprResult VisitExpr(Expr *E) {
12750       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12751         << E->getSourceRange();
12752       return ExprError();
12753     }
12754 
12755     /// Rebuild an expression which simply semantically wraps another
12756     /// expression which it shares the type and value kind of.
12757     template <class T> ExprResult rebuildSugarExpr(T *E) {
12758       ExprResult SubResult = Visit(E->getSubExpr());
12759       if (SubResult.isInvalid()) return ExprError();
12760 
12761       Expr *SubExpr = SubResult.get();
12762       E->setSubExpr(SubExpr);
12763       E->setType(SubExpr->getType());
12764       E->setValueKind(SubExpr->getValueKind());
12765       assert(E->getObjectKind() == OK_Ordinary);
12766       return E;
12767     }
12768 
12769     ExprResult VisitParenExpr(ParenExpr *E) {
12770       return rebuildSugarExpr(E);
12771     }
12772 
12773     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12774       return rebuildSugarExpr(E);
12775     }
12776 
12777     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12778       ExprResult SubResult = Visit(E->getSubExpr());
12779       if (SubResult.isInvalid()) return ExprError();
12780 
12781       Expr *SubExpr = SubResult.get();
12782       E->setSubExpr(SubExpr);
12783       E->setType(S.Context.getPointerType(SubExpr->getType()));
12784       assert(E->getValueKind() == VK_RValue);
12785       assert(E->getObjectKind() == OK_Ordinary);
12786       return E;
12787     }
12788 
12789     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12790       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12791 
12792       E->setType(VD->getType());
12793 
12794       assert(E->getValueKind() == VK_RValue);
12795       if (S.getLangOpts().CPlusPlus &&
12796           !(isa<CXXMethodDecl>(VD) &&
12797             cast<CXXMethodDecl>(VD)->isInstance()))
12798         E->setValueKind(VK_LValue);
12799 
12800       return E;
12801     }
12802 
12803     ExprResult VisitMemberExpr(MemberExpr *E) {
12804       return resolveDecl(E, E->getMemberDecl());
12805     }
12806 
12807     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12808       return resolveDecl(E, E->getDecl());
12809     }
12810   };
12811 }
12812 
12813 /// Given a function expression of unknown-any type, try to rebuild it
12814 /// to have a function type.
12815 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12816   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12817   if (Result.isInvalid()) return ExprError();
12818   return S.DefaultFunctionArrayConversion(Result.get());
12819 }
12820 
12821 namespace {
12822   /// A visitor for rebuilding an expression of type __unknown_anytype
12823   /// into one which resolves the type directly on the referring
12824   /// expression.  Strict preservation of the original source
12825   /// structure is not a goal.
12826   struct RebuildUnknownAnyExpr
12827     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12828 
12829     Sema &S;
12830 
12831     /// The current destination type.
12832     QualType DestType;
12833 
12834     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12835       : S(S), DestType(CastType) {}
12836 
12837     ExprResult VisitStmt(Stmt *S) {
12838       llvm_unreachable("unexpected statement!");
12839     }
12840 
12841     ExprResult VisitExpr(Expr *E) {
12842       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12843         << E->getSourceRange();
12844       return ExprError();
12845     }
12846 
12847     ExprResult VisitCallExpr(CallExpr *E);
12848     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12849 
12850     /// Rebuild an expression which simply semantically wraps another
12851     /// expression which it shares the type and value kind of.
12852     template <class T> ExprResult rebuildSugarExpr(T *E) {
12853       ExprResult SubResult = Visit(E->getSubExpr());
12854       if (SubResult.isInvalid()) return ExprError();
12855       Expr *SubExpr = SubResult.get();
12856       E->setSubExpr(SubExpr);
12857       E->setType(SubExpr->getType());
12858       E->setValueKind(SubExpr->getValueKind());
12859       assert(E->getObjectKind() == OK_Ordinary);
12860       return E;
12861     }
12862 
12863     ExprResult VisitParenExpr(ParenExpr *E) {
12864       return rebuildSugarExpr(E);
12865     }
12866 
12867     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12868       return rebuildSugarExpr(E);
12869     }
12870 
12871     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12872       const PointerType *Ptr = DestType->getAs<PointerType>();
12873       if (!Ptr) {
12874         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12875           << E->getSourceRange();
12876         return ExprError();
12877       }
12878       assert(E->getValueKind() == VK_RValue);
12879       assert(E->getObjectKind() == OK_Ordinary);
12880       E->setType(DestType);
12881 
12882       // Build the sub-expression as if it were an object of the pointee type.
12883       DestType = Ptr->getPointeeType();
12884       ExprResult SubResult = Visit(E->getSubExpr());
12885       if (SubResult.isInvalid()) return ExprError();
12886       E->setSubExpr(SubResult.get());
12887       return E;
12888     }
12889 
12890     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12891 
12892     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12893 
12894     ExprResult VisitMemberExpr(MemberExpr *E) {
12895       return resolveDecl(E, E->getMemberDecl());
12896     }
12897 
12898     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12899       return resolveDecl(E, E->getDecl());
12900     }
12901   };
12902 }
12903 
12904 /// Rebuilds a call expression which yielded __unknown_anytype.
12905 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12906   Expr *CalleeExpr = E->getCallee();
12907 
12908   enum FnKind {
12909     FK_MemberFunction,
12910     FK_FunctionPointer,
12911     FK_BlockPointer
12912   };
12913 
12914   FnKind Kind;
12915   QualType CalleeType = CalleeExpr->getType();
12916   if (CalleeType == S.Context.BoundMemberTy) {
12917     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12918     Kind = FK_MemberFunction;
12919     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12920   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12921     CalleeType = Ptr->getPointeeType();
12922     Kind = FK_FunctionPointer;
12923   } else {
12924     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12925     Kind = FK_BlockPointer;
12926   }
12927   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12928 
12929   // Verify that this is a legal result type of a function.
12930   if (DestType->isArrayType() || DestType->isFunctionType()) {
12931     unsigned diagID = diag::err_func_returning_array_function;
12932     if (Kind == FK_BlockPointer)
12933       diagID = diag::err_block_returning_array_function;
12934 
12935     S.Diag(E->getExprLoc(), diagID)
12936       << DestType->isFunctionType() << DestType;
12937     return ExprError();
12938   }
12939 
12940   // Otherwise, go ahead and set DestType as the call's result.
12941   E->setType(DestType.getNonLValueExprType(S.Context));
12942   E->setValueKind(Expr::getValueKindForType(DestType));
12943   assert(E->getObjectKind() == OK_Ordinary);
12944 
12945   // Rebuild the function type, replacing the result type with DestType.
12946   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12947   if (Proto) {
12948     // __unknown_anytype(...) is a special case used by the debugger when
12949     // it has no idea what a function's signature is.
12950     //
12951     // We want to build this call essentially under the K&R
12952     // unprototyped rules, but making a FunctionNoProtoType in C++
12953     // would foul up all sorts of assumptions.  However, we cannot
12954     // simply pass all arguments as variadic arguments, nor can we
12955     // portably just call the function under a non-variadic type; see
12956     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12957     // However, it turns out that in practice it is generally safe to
12958     // call a function declared as "A foo(B,C,D);" under the prototype
12959     // "A foo(B,C,D,...);".  The only known exception is with the
12960     // Windows ABI, where any variadic function is implicitly cdecl
12961     // regardless of its normal CC.  Therefore we change the parameter
12962     // types to match the types of the arguments.
12963     //
12964     // This is a hack, but it is far superior to moving the
12965     // corresponding target-specific code from IR-gen to Sema/AST.
12966 
12967     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
12968     SmallVector<QualType, 8> ArgTypes;
12969     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12970       ArgTypes.reserve(E->getNumArgs());
12971       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12972         Expr *Arg = E->getArg(i);
12973         QualType ArgType = Arg->getType();
12974         if (E->isLValue()) {
12975           ArgType = S.Context.getLValueReferenceType(ArgType);
12976         } else if (E->isXValue()) {
12977           ArgType = S.Context.getRValueReferenceType(ArgType);
12978         }
12979         ArgTypes.push_back(ArgType);
12980       }
12981       ParamTypes = ArgTypes;
12982     }
12983     DestType = S.Context.getFunctionType(DestType, ParamTypes,
12984                                          Proto->getExtProtoInfo());
12985   } else {
12986     DestType = S.Context.getFunctionNoProtoType(DestType,
12987                                                 FnType->getExtInfo());
12988   }
12989 
12990   // Rebuild the appropriate pointer-to-function type.
12991   switch (Kind) {
12992   case FK_MemberFunction:
12993     // Nothing to do.
12994     break;
12995 
12996   case FK_FunctionPointer:
12997     DestType = S.Context.getPointerType(DestType);
12998     break;
12999 
13000   case FK_BlockPointer:
13001     DestType = S.Context.getBlockPointerType(DestType);
13002     break;
13003   }
13004 
13005   // Finally, we can recurse.
13006   ExprResult CalleeResult = Visit(CalleeExpr);
13007   if (!CalleeResult.isUsable()) return ExprError();
13008   E->setCallee(CalleeResult.get());
13009 
13010   // Bind a temporary if necessary.
13011   return S.MaybeBindToTemporary(E);
13012 }
13013 
13014 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13015   // Verify that this is a legal result type of a call.
13016   if (DestType->isArrayType() || DestType->isFunctionType()) {
13017     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13018       << DestType->isFunctionType() << DestType;
13019     return ExprError();
13020   }
13021 
13022   // Rewrite the method result type if available.
13023   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13024     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13025     Method->setReturnType(DestType);
13026   }
13027 
13028   // Change the type of the message.
13029   E->setType(DestType.getNonReferenceType());
13030   E->setValueKind(Expr::getValueKindForType(DestType));
13031 
13032   return S.MaybeBindToTemporary(E);
13033 }
13034 
13035 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13036   // The only case we should ever see here is a function-to-pointer decay.
13037   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13038     assert(E->getValueKind() == VK_RValue);
13039     assert(E->getObjectKind() == OK_Ordinary);
13040 
13041     E->setType(DestType);
13042 
13043     // Rebuild the sub-expression as the pointee (function) type.
13044     DestType = DestType->castAs<PointerType>()->getPointeeType();
13045 
13046     ExprResult Result = Visit(E->getSubExpr());
13047     if (!Result.isUsable()) return ExprError();
13048 
13049     E->setSubExpr(Result.get());
13050     return E;
13051   } else if (E->getCastKind() == CK_LValueToRValue) {
13052     assert(E->getValueKind() == VK_RValue);
13053     assert(E->getObjectKind() == OK_Ordinary);
13054 
13055     assert(isa<BlockPointerType>(E->getType()));
13056 
13057     E->setType(DestType);
13058 
13059     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13060     DestType = S.Context.getLValueReferenceType(DestType);
13061 
13062     ExprResult Result = Visit(E->getSubExpr());
13063     if (!Result.isUsable()) return ExprError();
13064 
13065     E->setSubExpr(Result.get());
13066     return E;
13067   } else {
13068     llvm_unreachable("Unhandled cast type!");
13069   }
13070 }
13071 
13072 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13073   ExprValueKind ValueKind = VK_LValue;
13074   QualType Type = DestType;
13075 
13076   // We know how to make this work for certain kinds of decls:
13077 
13078   //  - functions
13079   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13080     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13081       DestType = Ptr->getPointeeType();
13082       ExprResult Result = resolveDecl(E, VD);
13083       if (Result.isInvalid()) return ExprError();
13084       return S.ImpCastExprToType(Result.get(), Type,
13085                                  CK_FunctionToPointerDecay, VK_RValue);
13086     }
13087 
13088     if (!Type->isFunctionType()) {
13089       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13090         << VD << E->getSourceRange();
13091       return ExprError();
13092     }
13093 
13094     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13095       if (MD->isInstance()) {
13096         ValueKind = VK_RValue;
13097         Type = S.Context.BoundMemberTy;
13098       }
13099 
13100     // Function references aren't l-values in C.
13101     if (!S.getLangOpts().CPlusPlus)
13102       ValueKind = VK_RValue;
13103 
13104   //  - variables
13105   } else if (isa<VarDecl>(VD)) {
13106     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13107       Type = RefTy->getPointeeType();
13108     } else if (Type->isFunctionType()) {
13109       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13110         << VD << E->getSourceRange();
13111       return ExprError();
13112     }
13113 
13114   //  - nothing else
13115   } else {
13116     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13117       << VD << E->getSourceRange();
13118     return ExprError();
13119   }
13120 
13121   // Modifying the declaration like this is friendly to IR-gen but
13122   // also really dangerous.
13123   VD->setType(DestType);
13124   E->setType(Type);
13125   E->setValueKind(ValueKind);
13126   return E;
13127 }
13128 
13129 /// Check a cast of an unknown-any type.  We intentionally only
13130 /// trigger this for C-style casts.
13131 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13132                                      Expr *CastExpr, CastKind &CastKind,
13133                                      ExprValueKind &VK, CXXCastPath &Path) {
13134   // Rewrite the casted expression from scratch.
13135   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13136   if (!result.isUsable()) return ExprError();
13137 
13138   CastExpr = result.get();
13139   VK = CastExpr->getValueKind();
13140   CastKind = CK_NoOp;
13141 
13142   return CastExpr;
13143 }
13144 
13145 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13146   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13147 }
13148 
13149 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13150                                     Expr *arg, QualType &paramType) {
13151   // If the syntactic form of the argument is not an explicit cast of
13152   // any sort, just do default argument promotion.
13153   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13154   if (!castArg) {
13155     ExprResult result = DefaultArgumentPromotion(arg);
13156     if (result.isInvalid()) return ExprError();
13157     paramType = result.get()->getType();
13158     return result;
13159   }
13160 
13161   // Otherwise, use the type that was written in the explicit cast.
13162   assert(!arg->hasPlaceholderType());
13163   paramType = castArg->getTypeAsWritten();
13164 
13165   // Copy-initialize a parameter of that type.
13166   InitializedEntity entity =
13167     InitializedEntity::InitializeParameter(Context, paramType,
13168                                            /*consumed*/ false);
13169   return PerformCopyInitialization(entity, callLoc, arg);
13170 }
13171 
13172 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13173   Expr *orig = E;
13174   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13175   while (true) {
13176     E = E->IgnoreParenImpCasts();
13177     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13178       E = call->getCallee();
13179       diagID = diag::err_uncasted_call_of_unknown_any;
13180     } else {
13181       break;
13182     }
13183   }
13184 
13185   SourceLocation loc;
13186   NamedDecl *d;
13187   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13188     loc = ref->getLocation();
13189     d = ref->getDecl();
13190   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13191     loc = mem->getMemberLoc();
13192     d = mem->getMemberDecl();
13193   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13194     diagID = diag::err_uncasted_call_of_unknown_any;
13195     loc = msg->getSelectorStartLoc();
13196     d = msg->getMethodDecl();
13197     if (!d) {
13198       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13199         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13200         << orig->getSourceRange();
13201       return ExprError();
13202     }
13203   } else {
13204     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13205       << E->getSourceRange();
13206     return ExprError();
13207   }
13208 
13209   S.Diag(loc, diagID) << d << orig->getSourceRange();
13210 
13211   // Never recoverable.
13212   return ExprError();
13213 }
13214 
13215 /// Check for operands with placeholder types and complain if found.
13216 /// Returns true if there was an error and no recovery was possible.
13217 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13218   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13219   if (!placeholderType) return E;
13220 
13221   switch (placeholderType->getKind()) {
13222 
13223   // Overloaded expressions.
13224   case BuiltinType::Overload: {
13225     // Try to resolve a single function template specialization.
13226     // This is obligatory.
13227     ExprResult result = E;
13228     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13229       return result;
13230 
13231     // If that failed, try to recover with a call.
13232     } else {
13233       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13234                            /*complain*/ true);
13235       return result;
13236     }
13237   }
13238 
13239   // Bound member functions.
13240   case BuiltinType::BoundMember: {
13241     ExprResult result = E;
13242     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13243                          /*complain*/ true);
13244     return result;
13245   }
13246 
13247   // ARC unbridged casts.
13248   case BuiltinType::ARCUnbridgedCast: {
13249     Expr *realCast = stripARCUnbridgedCast(E);
13250     diagnoseARCUnbridgedCast(realCast);
13251     return realCast;
13252   }
13253 
13254   // Expressions of unknown type.
13255   case BuiltinType::UnknownAny:
13256     return diagnoseUnknownAnyExpr(*this, E);
13257 
13258   // Pseudo-objects.
13259   case BuiltinType::PseudoObject:
13260     return checkPseudoObjectRValue(E);
13261 
13262   case BuiltinType::BuiltinFn:
13263     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13264     return ExprError();
13265 
13266   // Everything else should be impossible.
13267 #define BUILTIN_TYPE(Id, SingletonId) \
13268   case BuiltinType::Id:
13269 #define PLACEHOLDER_TYPE(Id, SingletonId)
13270 #include "clang/AST/BuiltinTypes.def"
13271     break;
13272   }
13273 
13274   llvm_unreachable("invalid placeholder type!");
13275 }
13276 
13277 bool Sema::CheckCaseExpression(Expr *E) {
13278   if (E->isTypeDependent())
13279     return true;
13280   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13281     return E->getType()->isIntegralOrEnumerationType();
13282   return false;
13283 }
13284 
13285 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13286 ExprResult
13287 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13288   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13289          "Unknown Objective-C Boolean value!");
13290   QualType BoolT = Context.ObjCBuiltinBoolTy;
13291   if (!Context.getBOOLDecl()) {
13292     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13293                         Sema::LookupOrdinaryName);
13294     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13295       NamedDecl *ND = Result.getFoundDecl();
13296       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13297         Context.setBOOLDecl(TD);
13298     }
13299   }
13300   if (Context.getBOOLDecl())
13301     BoolT = Context.getBOOLType();
13302   return new (Context)
13303       ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes, BoolT, OpLoc);
13304 }
13305