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 = 0;
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(0);
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(),
227          diag::note_internal_decl_declared_here)
228     << D;
229 }
230 
231 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
232   const FunctionDecl *First = Cur->getFirstDecl();
233 
234   // Suggest "static" on the function, if possible.
235   if (!hasAnyExplicitStorageClass(First)) {
236     SourceLocation DeclBegin = First->getSourceRange().getBegin();
237     Diag(DeclBegin, diag::note_convert_inline_to_static)
238       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
239   }
240 }
241 
242 /// \brief Determine whether the use of this declaration is valid, and
243 /// emit any corresponding diagnostics.
244 ///
245 /// This routine diagnoses various problems with referencing
246 /// declarations that can occur when using a declaration. For example,
247 /// it might warn if a deprecated or unavailable declaration is being
248 /// used, or produce an error (and return true) if a C++0x deleted
249 /// function is being used.
250 ///
251 /// \returns true if there was an error (this declaration cannot be
252 /// referenced), false otherwise.
253 ///
254 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
255                              const ObjCInterfaceDecl *UnknownObjCClass) {
256   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
257     // If there were any diagnostics suppressed by template argument deduction,
258     // emit them now.
259     SuppressedDiagnosticsMap::iterator
260       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
261     if (Pos != SuppressedDiagnostics.end()) {
262       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
263       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
264         Diag(Suppressed[I].first, Suppressed[I].second);
265 
266       // Clear out the list of suppressed diagnostics, so that we don't emit
267       // them again for this specialization. However, we don't obsolete this
268       // entry from the table, because we want to avoid ever emitting these
269       // diagnostics again.
270       Suppressed.clear();
271     }
272 
273     // C++ [basic.start.main]p3:
274     //   The function 'main' shall not be used within a program.
275     if (cast<FunctionDecl>(D)->isMain())
276       Diag(Loc, diag::ext_main_used);
277   }
278 
279   // See if this is an auto-typed variable whose initializer we are parsing.
280   if (ParsingInitForAutoVars.count(D)) {
281     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
282       << D->getDeclName();
283     return true;
284   }
285 
286   // See if this is a deleted function.
287   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
288     if (FD->isDeleted()) {
289       Diag(Loc, diag::err_deleted_function_use);
290       NoteDeletedFunction(FD);
291       return true;
292     }
293 
294     // If the function has a deduced return type, and we can't deduce it,
295     // then we can't use it either.
296     if (getLangOpts().CPlusPlus1y && FD->getReturnType()->isUndeducedType() &&
297         DeduceReturnType(FD, Loc))
298       return true;
299   }
300   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
301 
302   DiagnoseUnusedOfDecl(*this, D, Loc);
303 
304   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
305 
306   return false;
307 }
308 
309 /// \brief Retrieve the message suffix that should be added to a
310 /// diagnostic complaining about the given function being deleted or
311 /// unavailable.
312 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
313   std::string Message;
314   if (FD->getAvailability(&Message))
315     return ": " + Message;
316 
317   return std::string();
318 }
319 
320 /// DiagnoseSentinelCalls - This routine checks whether a call or
321 /// message-send is to a declaration with the sentinel attribute, and
322 /// if so, it checks that the requirements of the sentinel are
323 /// satisfied.
324 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
325                                  ArrayRef<Expr *> Args) {
326   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
327   if (!attr)
328     return;
329 
330   // The number of formal parameters of the declaration.
331   unsigned numFormalParams;
332 
333   // The kind of declaration.  This is also an index into a %select in
334   // the diagnostic.
335   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
336 
337   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
338     numFormalParams = MD->param_size();
339     calleeType = CT_Method;
340   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
341     numFormalParams = FD->param_size();
342     calleeType = CT_Function;
343   } else if (isa<VarDecl>(D)) {
344     QualType type = cast<ValueDecl>(D)->getType();
345     const FunctionType *fn = 0;
346     if (const PointerType *ptr = type->getAs<PointerType>()) {
347       fn = ptr->getPointeeType()->getAs<FunctionType>();
348       if (!fn) return;
349       calleeType = CT_Function;
350     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
351       fn = ptr->getPointeeType()->castAs<FunctionType>();
352       calleeType = CT_Block;
353     } else {
354       return;
355     }
356 
357     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
358       numFormalParams = proto->getNumParams();
359     } else {
360       numFormalParams = 0;
361     }
362   } else {
363     return;
364   }
365 
366   // "nullPos" is the number of formal parameters at the end which
367   // effectively count as part of the variadic arguments.  This is
368   // useful if you would prefer to not have *any* formal parameters,
369   // but the language forces you to have at least one.
370   unsigned nullPos = attr->getNullPos();
371   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
372   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
373 
374   // The number of arguments which should follow the sentinel.
375   unsigned numArgsAfterSentinel = attr->getSentinel();
376 
377   // If there aren't enough arguments for all the formal parameters,
378   // the sentinel, and the args after the sentinel, complain.
379   if (Args.size() < numFormalParams + numArgsAfterSentinel + 1) {
380     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
381     Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
382     return;
383   }
384 
385   // Otherwise, find the sentinel expression.
386   Expr *sentinelExpr = Args[Args.size() - numArgsAfterSentinel - 1];
387   if (!sentinelExpr) return;
388   if (sentinelExpr->isValueDependent()) return;
389   if (Context.isSentinelNullExpr(sentinelExpr)) return;
390 
391   // Pick a reasonable string to insert.  Optimistically use 'nil' or
392   // 'NULL' if those are actually defined in the context.  Only use
393   // 'nil' for ObjC methods, where it's much more likely that the
394   // variadic arguments form a list of object pointers.
395   SourceLocation MissingNilLoc
396     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
397   std::string NullValue;
398   if (calleeType == CT_Method &&
399       PP.getIdentifierInfo("nil")->hasMacroDefinition())
400     NullValue = "nil";
401   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
402     NullValue = "NULL";
403   else
404     NullValue = "(void*) 0";
405 
406   if (MissingNilLoc.isInvalid())
407     Diag(Loc, diag::warn_missing_sentinel) << int(calleeType);
408   else
409     Diag(MissingNilLoc, diag::warn_missing_sentinel)
410       << int(calleeType)
411       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
412   Diag(D->getLocation(), diag::note_sentinel_here) << int(calleeType);
413 }
414 
415 SourceRange Sema::getExprRange(Expr *E) const {
416   return E ? E->getSourceRange() : SourceRange();
417 }
418 
419 //===----------------------------------------------------------------------===//
420 //  Standard Promotions and Conversions
421 //===----------------------------------------------------------------------===//
422 
423 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
424 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
425   // Handle any placeholder expressions which made it here.
426   if (E->getType()->isPlaceholderType()) {
427     ExprResult result = CheckPlaceholderExpr(E);
428     if (result.isInvalid()) return ExprError();
429     E = result.take();
430   }
431 
432   QualType Ty = E->getType();
433   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
434 
435   if (Ty->isFunctionType()) {
436     // If we are here, we are not calling a function but taking
437     // its address (which is not allowed in OpenCL v1.0 s6.8.a.3).
438     if (getLangOpts().OpenCL) {
439       Diag(E->getExprLoc(), diag::err_opencl_taking_function_address);
440       return ExprError();
441     }
442     E = ImpCastExprToType(E, Context.getPointerType(Ty),
443                           CK_FunctionToPointerDecay).take();
444   } else if (Ty->isArrayType()) {
445     // In C90 mode, arrays only promote to pointers if the array expression is
446     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
447     // type 'array of type' is converted to an expression that has type 'pointer
448     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
449     // that has type 'array of type' ...".  The relevant change is "an lvalue"
450     // (C90) to "an expression" (C99).
451     //
452     // C++ 4.2p1:
453     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
454     // T" can be converted to an rvalue of type "pointer to T".
455     //
456     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
457       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
458                             CK_ArrayToPointerDecay).take();
459   }
460   return Owned(E);
461 }
462 
463 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
464   // Check to see if we are dereferencing a null pointer.  If so,
465   // and if not volatile-qualified, this is undefined behavior that the
466   // optimizer will delete, so warn about it.  People sometimes try to use this
467   // to get a deterministic trap and are surprised by clang's behavior.  This
468   // only handles the pattern "*null", which is a very syntactic check.
469   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
470     if (UO->getOpcode() == UO_Deref &&
471         UO->getSubExpr()->IgnoreParenCasts()->
472           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
473         !UO->getType().isVolatileQualified()) {
474     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
475                           S.PDiag(diag::warn_indirection_through_null)
476                             << UO->getSubExpr()->getSourceRange());
477     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
478                         S.PDiag(diag::note_indirection_through_null));
479   }
480 }
481 
482 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
483                                     SourceLocation AssignLoc,
484                                     const Expr* RHS) {
485   const ObjCIvarDecl *IV = OIRE->getDecl();
486   if (!IV)
487     return;
488 
489   DeclarationName MemberName = IV->getDeclName();
490   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
491   if (!Member || !Member->isStr("isa"))
492     return;
493 
494   const Expr *Base = OIRE->getBase();
495   QualType BaseType = Base->getType();
496   if (OIRE->isArrow())
497     BaseType = BaseType->getPointeeType();
498   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
499     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
500       ObjCInterfaceDecl *ClassDeclared = 0;
501       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
502       if (!ClassDeclared->getSuperClass()
503           && (*ClassDeclared->ivar_begin()) == IV) {
504         if (RHS) {
505           NamedDecl *ObjectSetClass =
506             S.LookupSingleName(S.TUScope,
507                                &S.Context.Idents.get("object_setClass"),
508                                SourceLocation(), S.LookupOrdinaryName);
509           if (ObjectSetClass) {
510             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
511             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
512             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
513             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
514                                                      AssignLoc), ",") <<
515             FixItHint::CreateInsertion(RHSLocEnd, ")");
516           }
517           else
518             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
519         } else {
520           NamedDecl *ObjectGetClass =
521             S.LookupSingleName(S.TUScope,
522                                &S.Context.Idents.get("object_getClass"),
523                                SourceLocation(), S.LookupOrdinaryName);
524           if (ObjectGetClass)
525             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
526             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
527             FixItHint::CreateReplacement(
528                                          SourceRange(OIRE->getOpLoc(),
529                                                      OIRE->getLocEnd()), ")");
530           else
531             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
532         }
533         S.Diag(IV->getLocation(), diag::note_ivar_decl);
534       }
535     }
536 }
537 
538 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
539   // Handle any placeholder expressions which made it here.
540   if (E->getType()->isPlaceholderType()) {
541     ExprResult result = CheckPlaceholderExpr(E);
542     if (result.isInvalid()) return ExprError();
543     E = result.take();
544   }
545 
546   // C++ [conv.lval]p1:
547   //   A glvalue of a non-function, non-array type T can be
548   //   converted to a prvalue.
549   if (!E->isGLValue()) return Owned(E);
550 
551   QualType T = E->getType();
552   assert(!T.isNull() && "r-value conversion on typeless expression?");
553 
554   // We don't want to throw lvalue-to-rvalue casts on top of
555   // expressions of certain types in C++.
556   if (getLangOpts().CPlusPlus &&
557       (E->getType() == Context.OverloadTy ||
558        T->isDependentType() ||
559        T->isRecordType()))
560     return Owned(E);
561 
562   // The C standard is actually really unclear on this point, and
563   // DR106 tells us what the result should be but not why.  It's
564   // generally best to say that void types just doesn't undergo
565   // lvalue-to-rvalue at all.  Note that expressions of unqualified
566   // 'void' type are never l-values, but qualified void can be.
567   if (T->isVoidType())
568     return Owned(E);
569 
570   // OpenCL usually rejects direct accesses to values of 'half' type.
571   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
572       T->isHalfType()) {
573     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
574       << 0 << T;
575     return ExprError();
576   }
577 
578   CheckForNullPointerDereference(*this, E);
579   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
580     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
581                                      &Context.Idents.get("object_getClass"),
582                                      SourceLocation(), LookupOrdinaryName);
583     if (ObjectGetClass)
584       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
585         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
586         FixItHint::CreateReplacement(
587                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
588     else
589       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
590   }
591   else if (const ObjCIvarRefExpr *OIRE =
592             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
593     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
594 
595   // C++ [conv.lval]p1:
596   //   [...] If T is a non-class type, the type of the prvalue is the
597   //   cv-unqualified version of T. Otherwise, the type of the
598   //   rvalue is T.
599   //
600   // C99 6.3.2.1p2:
601   //   If the lvalue has qualified type, the value has the unqualified
602   //   version of the type of the lvalue; otherwise, the value has the
603   //   type of the lvalue.
604   if (T.hasQualifiers())
605     T = T.getUnqualifiedType();
606 
607   UpdateMarkingForLValueToRValue(E);
608 
609   // Loading a __weak object implicitly retains the value, so we need a cleanup to
610   // balance that.
611   if (getLangOpts().ObjCAutoRefCount &&
612       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
613     ExprNeedsCleanups = true;
614 
615   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
616                                                   E, 0, VK_RValue));
617 
618   // C11 6.3.2.1p2:
619   //   ... if the lvalue has atomic type, the value has the non-atomic version
620   //   of the type of the lvalue ...
621   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
622     T = Atomic->getValueType().getUnqualifiedType();
623     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
624                                          Res.get(), 0, VK_RValue));
625   }
626 
627   return Res;
628 }
629 
630 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
631   ExprResult Res = DefaultFunctionArrayConversion(E);
632   if (Res.isInvalid())
633     return ExprError();
634   Res = DefaultLvalueConversion(Res.take());
635   if (Res.isInvalid())
636     return ExprError();
637   return Res;
638 }
639 
640 /// CallExprUnaryConversions - a special case of an unary conversion
641 /// performed on a function designator of a call expression.
642 ExprResult Sema::CallExprUnaryConversions(Expr *E) {
643   QualType Ty = E->getType();
644   ExprResult Res = E;
645   // Only do implicit cast for a function type, but not for a pointer
646   // to function type.
647   if (Ty->isFunctionType()) {
648     Res = ImpCastExprToType(E, Context.getPointerType(Ty),
649                             CK_FunctionToPointerDecay).take();
650     if (Res.isInvalid())
651       return ExprError();
652   }
653   Res = DefaultLvalueConversion(Res.take());
654   if (Res.isInvalid())
655     return ExprError();
656   return Owned(Res.take());
657 }
658 
659 /// UsualUnaryConversions - Performs various conversions that are common to most
660 /// operators (C99 6.3). The conversions of array and function types are
661 /// sometimes suppressed. For example, the array->pointer conversion doesn't
662 /// apply if the array is an argument to the sizeof or address (&) operators.
663 /// In these instances, this routine should *not* be called.
664 ExprResult Sema::UsualUnaryConversions(Expr *E) {
665   // First, convert to an r-value.
666   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
667   if (Res.isInvalid())
668     return ExprError();
669   E = Res.take();
670 
671   QualType Ty = E->getType();
672   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
673 
674   // Half FP have to be promoted to float unless it is natively supported
675   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
676     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
677 
678   // Try to perform integral promotions if the object has a theoretically
679   // promotable type.
680   if (Ty->isIntegralOrUnscopedEnumerationType()) {
681     // C99 6.3.1.1p2:
682     //
683     //   The following may be used in an expression wherever an int or
684     //   unsigned int may be used:
685     //     - an object or expression with an integer type whose integer
686     //       conversion rank is less than or equal to the rank of int
687     //       and unsigned int.
688     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
689     //
690     //   If an int can represent all values of the original type, the
691     //   value is converted to an int; otherwise, it is converted to an
692     //   unsigned int. These are called the integer promotions. All
693     //   other types are unchanged by the integer promotions.
694 
695     QualType PTy = Context.isPromotableBitField(E);
696     if (!PTy.isNull()) {
697       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
698       return Owned(E);
699     }
700     if (Ty->isPromotableIntegerType()) {
701       QualType PT = Context.getPromotedIntegerType(Ty);
702       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
703       return Owned(E);
704     }
705   }
706   return Owned(E);
707 }
708 
709 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
710 /// do not have a prototype. Arguments that have type float or __fp16
711 /// are promoted to double. All other argument types are converted by
712 /// UsualUnaryConversions().
713 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
714   QualType Ty = E->getType();
715   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
716 
717   ExprResult Res = UsualUnaryConversions(E);
718   if (Res.isInvalid())
719     return ExprError();
720   E = Res.take();
721 
722   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
723   // double.
724   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
725   if (BTy && (BTy->getKind() == BuiltinType::Half ||
726               BTy->getKind() == BuiltinType::Float))
727     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
728 
729   // C++ performs lvalue-to-rvalue conversion as a default argument
730   // promotion, even on class types, but note:
731   //   C++11 [conv.lval]p2:
732   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
733   //     operand or a subexpression thereof the value contained in the
734   //     referenced object is not accessed. Otherwise, if the glvalue
735   //     has a class type, the conversion copy-initializes a temporary
736   //     of type T from the glvalue and the result of the conversion
737   //     is a prvalue for the temporary.
738   // FIXME: add some way to gate this entire thing for correctness in
739   // potentially potentially evaluated contexts.
740   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
741     ExprResult Temp = PerformCopyInitialization(
742                        InitializedEntity::InitializeTemporary(E->getType()),
743                                                 E->getExprLoc(),
744                                                 Owned(E));
745     if (Temp.isInvalid())
746       return ExprError();
747     E = Temp.get();
748   }
749 
750   return Owned(E);
751 }
752 
753 /// Determine the degree of POD-ness for an expression.
754 /// Incomplete types are considered POD, since this check can be performed
755 /// when we're in an unevaluated context.
756 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
757   if (Ty->isIncompleteType()) {
758     // C++11 [expr.call]p7:
759     //   After these conversions, if the argument does not have arithmetic,
760     //   enumeration, pointer, pointer to member, or class type, the program
761     //   is ill-formed.
762     //
763     // Since we've already performed array-to-pointer and function-to-pointer
764     // decay, the only such type in C++ is cv void. This also handles
765     // initializer lists as variadic arguments.
766     if (Ty->isVoidType())
767       return VAK_Invalid;
768 
769     if (Ty->isObjCObjectType())
770       return VAK_Invalid;
771     return VAK_Valid;
772   }
773 
774   if (Ty.isCXX98PODType(Context))
775     return VAK_Valid;
776 
777   // C++11 [expr.call]p7:
778   //   Passing a potentially-evaluated argument of class type (Clause 9)
779   //   having a non-trivial copy constructor, a non-trivial move constructor,
780   //   or a non-trivial destructor, with no corresponding parameter,
781   //   is conditionally-supported with implementation-defined semantics.
782   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
783     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
784       if (!Record->hasNonTrivialCopyConstructor() &&
785           !Record->hasNonTrivialMoveConstructor() &&
786           !Record->hasNonTrivialDestructor())
787         return VAK_ValidInCXX11;
788 
789   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
790     return VAK_Valid;
791 
792   if (Ty->isObjCObjectType())
793     return VAK_Invalid;
794 
795   // FIXME: In C++11, these cases are conditionally-supported, meaning we're
796   // permitted to reject them. We should consider doing so.
797   return VAK_Undefined;
798 }
799 
800 void Sema::checkVariadicArgument(const Expr *E, VariadicCallType CT) {
801   // Don't allow one to pass an Objective-C interface to a vararg.
802   const QualType &Ty = E->getType();
803   VarArgKind VAK = isValidVarArgType(Ty);
804 
805   // Complain about passing non-POD types through varargs.
806   switch (VAK) {
807   case VAK_ValidInCXX11:
808     DiagRuntimeBehavior(
809         E->getLocStart(), 0,
810         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
811           << Ty << CT);
812     // Fall through.
813   case VAK_Valid:
814     if (Ty->isRecordType()) {
815       // This is unlikely to be what the user intended. If the class has a
816       // 'c_str' member function, the user probably meant to call that.
817       DiagRuntimeBehavior(E->getLocStart(), 0,
818                           PDiag(diag::warn_pass_class_arg_to_vararg)
819                             << Ty << CT << hasCStrMethod(E) << ".c_str()");
820     }
821     break;
822 
823   case VAK_Undefined:
824     DiagRuntimeBehavior(
825         E->getLocStart(), 0,
826         PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
827           << getLangOpts().CPlusPlus11 << Ty << CT);
828     break;
829 
830   case VAK_Invalid:
831     if (Ty->isObjCObjectType())
832       DiagRuntimeBehavior(
833           E->getLocStart(), 0,
834           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
835             << Ty << CT);
836     else
837       Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg)
838         << isa<InitListExpr>(E) << Ty << CT;
839     break;
840   }
841 }
842 
843 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
844 /// will create a trap if the resulting type is not a POD type.
845 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
846                                                   FunctionDecl *FDecl) {
847   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
848     // Strip the unbridged-cast placeholder expression off, if applicable.
849     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
850         (CT == VariadicMethod ||
851          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
852       E = stripARCUnbridgedCast(E);
853 
854     // Otherwise, do normal placeholder checking.
855     } else {
856       ExprResult ExprRes = CheckPlaceholderExpr(E);
857       if (ExprRes.isInvalid())
858         return ExprError();
859       E = ExprRes.take();
860     }
861   }
862 
863   ExprResult ExprRes = DefaultArgumentPromotion(E);
864   if (ExprRes.isInvalid())
865     return ExprError();
866   E = ExprRes.take();
867 
868   // Diagnostics regarding non-POD argument types are
869   // emitted along with format string checking in Sema::CheckFunctionCall().
870   if (isValidVarArgType(E->getType()) == VAK_Undefined) {
871     // Turn this into a trap.
872     CXXScopeSpec SS;
873     SourceLocation TemplateKWLoc;
874     UnqualifiedId Name;
875     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
876                        E->getLocStart());
877     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
878                                           Name, true, false);
879     if (TrapFn.isInvalid())
880       return ExprError();
881 
882     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
883                                     E->getLocStart(), None,
884                                     E->getLocEnd());
885     if (Call.isInvalid())
886       return ExprError();
887 
888     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
889                                   Call.get(), E);
890     if (Comma.isInvalid())
891       return ExprError();
892     return Comma.get();
893   }
894 
895   if (!getLangOpts().CPlusPlus &&
896       RequireCompleteType(E->getExprLoc(), E->getType(),
897                           diag::err_call_incomplete_argument))
898     return ExprError();
899 
900   return Owned(E);
901 }
902 
903 /// \brief Converts an integer to complex float type.  Helper function of
904 /// UsualArithmeticConversions()
905 ///
906 /// \return false if the integer expression is an integer type and is
907 /// successfully converted to the complex type.
908 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
909                                                   ExprResult &ComplexExpr,
910                                                   QualType IntTy,
911                                                   QualType ComplexTy,
912                                                   bool SkipCast) {
913   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
914   if (SkipCast) return false;
915   if (IntTy->isIntegerType()) {
916     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
917     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
918     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
919                                   CK_FloatingRealToComplex);
920   } else {
921     assert(IntTy->isComplexIntegerType());
922     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
923                                   CK_IntegralComplexToFloatingComplex);
924   }
925   return false;
926 }
927 
928 /// \brief Takes two complex float types and converts them to the same type.
929 /// Helper function of UsualArithmeticConversions()
930 static QualType
931 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
932                                             ExprResult &RHS, QualType LHSType,
933                                             QualType RHSType,
934                                             bool IsCompAssign) {
935   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
936 
937   if (order < 0) {
938     // _Complex float -> _Complex double
939     if (!IsCompAssign)
940       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
941     return RHSType;
942   }
943   if (order > 0)
944     // _Complex float -> _Complex double
945     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
946   return LHSType;
947 }
948 
949 /// \brief Converts otherExpr to complex float and promotes complexExpr if
950 /// necessary.  Helper function of UsualArithmeticConversions()
951 static QualType handleOtherComplexFloatConversion(Sema &S,
952                                                   ExprResult &ComplexExpr,
953                                                   ExprResult &OtherExpr,
954                                                   QualType ComplexTy,
955                                                   QualType OtherTy,
956                                                   bool ConvertComplexExpr,
957                                                   bool ConvertOtherExpr) {
958   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
959 
960   // If just the complexExpr is complex, the otherExpr needs to be converted,
961   // and the complexExpr might need to be promoted.
962   if (order > 0) { // complexExpr is wider
963     // float -> _Complex double
964     if (ConvertOtherExpr) {
965       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
966       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
967       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
968                                       CK_FloatingRealToComplex);
969     }
970     return ComplexTy;
971   }
972 
973   // otherTy is at least as wide.  Find its corresponding complex type.
974   QualType result = (order == 0 ? ComplexTy :
975                                   S.Context.getComplexType(OtherTy));
976 
977   // double -> _Complex double
978   if (ConvertOtherExpr)
979     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
980                                     CK_FloatingRealToComplex);
981 
982   // _Complex float -> _Complex double
983   if (ConvertComplexExpr && order < 0)
984     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
985                                       CK_FloatingComplexCast);
986 
987   return result;
988 }
989 
990 /// \brief Handle arithmetic conversion with complex types.  Helper function of
991 /// UsualArithmeticConversions()
992 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
993                                              ExprResult &RHS, QualType LHSType,
994                                              QualType RHSType,
995                                              bool IsCompAssign) {
996   // if we have an integer operand, the result is the complex type.
997   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
998                                              /*skipCast*/false))
999     return LHSType;
1000   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
1001                                              /*skipCast*/IsCompAssign))
1002     return RHSType;
1003 
1004   // This handles complex/complex, complex/float, or float/complex.
1005   // When both operands are complex, the shorter operand is converted to the
1006   // type of the longer, and that is the type of the result. This corresponds
1007   // to what is done when combining two real floating-point operands.
1008   // The fun begins when size promotion occur across type domains.
1009   // From H&S 6.3.4: When one operand is complex and the other is a real
1010   // floating-point type, the less precise type is converted, within it's
1011   // real or complex domain, to the precision of the other type. For example,
1012   // when combining a "long double" with a "double _Complex", the
1013   // "double _Complex" is promoted to "long double _Complex".
1014 
1015   bool LHSComplexFloat = LHSType->isComplexType();
1016   bool RHSComplexFloat = RHSType->isComplexType();
1017 
1018   // If both are complex, just cast to the more precise type.
1019   if (LHSComplexFloat && RHSComplexFloat)
1020     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
1021                                                        LHSType, RHSType,
1022                                                        IsCompAssign);
1023 
1024   // If only one operand is complex, promote it if necessary and convert the
1025   // other operand to complex.
1026   if (LHSComplexFloat)
1027     return handleOtherComplexFloatConversion(
1028         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
1029         /*convertOtherExpr*/ true);
1030 
1031   assert(RHSComplexFloat);
1032   return handleOtherComplexFloatConversion(
1033       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
1034       /*convertOtherExpr*/ !IsCompAssign);
1035 }
1036 
1037 /// \brief Hande arithmetic conversion from integer to float.  Helper function
1038 /// of UsualArithmeticConversions()
1039 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
1040                                            ExprResult &IntExpr,
1041                                            QualType FloatTy, QualType IntTy,
1042                                            bool ConvertFloat, bool ConvertInt) {
1043   if (IntTy->isIntegerType()) {
1044     if (ConvertInt)
1045       // Convert intExpr to the lhs floating point type.
1046       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
1047                                     CK_IntegralToFloating);
1048     return FloatTy;
1049   }
1050 
1051   // Convert both sides to the appropriate complex float.
1052   assert(IntTy->isComplexIntegerType());
1053   QualType result = S.Context.getComplexType(FloatTy);
1054 
1055   // _Complex int -> _Complex float
1056   if (ConvertInt)
1057     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
1058                                   CK_IntegralComplexToFloatingComplex);
1059 
1060   // float -> _Complex float
1061   if (ConvertFloat)
1062     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
1063                                     CK_FloatingRealToComplex);
1064 
1065   return result;
1066 }
1067 
1068 /// \brief Handle arithmethic conversion with floating point types.  Helper
1069 /// function of UsualArithmeticConversions()
1070 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
1071                                       ExprResult &RHS, QualType LHSType,
1072                                       QualType RHSType, bool IsCompAssign) {
1073   bool LHSFloat = LHSType->isRealFloatingType();
1074   bool RHSFloat = RHSType->isRealFloatingType();
1075 
1076   // If we have two real floating types, convert the smaller operand
1077   // to the bigger result.
1078   if (LHSFloat && RHSFloat) {
1079     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1080     if (order > 0) {
1081       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1082       return LHSType;
1083     }
1084 
1085     assert(order < 0 && "illegal float comparison");
1086     if (!IsCompAssign)
1087       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1088     return RHSType;
1089   }
1090 
1091   if (LHSFloat)
1092     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1093                                       /*convertFloat=*/!IsCompAssign,
1094                                       /*convertInt=*/ true);
1095   assert(RHSFloat);
1096   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1097                                     /*convertInt=*/ true,
1098                                     /*convertFloat=*/!IsCompAssign);
1099 }
1100 
1101 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1102 
1103 namespace {
1104 /// These helper callbacks are placed in an anonymous namespace to
1105 /// permit their use as function template parameters.
1106 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1107   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1108 }
1109 
1110 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1111   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1112                              CK_IntegralComplexCast);
1113 }
1114 }
1115 
1116 /// \brief Handle integer arithmetic conversions.  Helper function of
1117 /// UsualArithmeticConversions()
1118 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1119 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1120                                         ExprResult &RHS, QualType LHSType,
1121                                         QualType RHSType, bool IsCompAssign) {
1122   // The rules for this case are in C99 6.3.1.8
1123   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1124   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1125   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1126   if (LHSSigned == RHSSigned) {
1127     // Same signedness; use the higher-ranked type
1128     if (order >= 0) {
1129       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1130       return LHSType;
1131     } else if (!IsCompAssign)
1132       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1133     return RHSType;
1134   } else if (order != (LHSSigned ? 1 : -1)) {
1135     // The unsigned type has greater than or equal rank to the
1136     // signed type, so use the unsigned type
1137     if (RHSSigned) {
1138       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1139       return LHSType;
1140     } else if (!IsCompAssign)
1141       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1142     return RHSType;
1143   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1144     // The two types are different widths; if we are here, that
1145     // means the signed type is larger than the unsigned type, so
1146     // use the signed type.
1147     if (LHSSigned) {
1148       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1149       return LHSType;
1150     } else if (!IsCompAssign)
1151       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1152     return RHSType;
1153   } else {
1154     // The signed type is higher-ranked than the unsigned type,
1155     // but isn't actually any bigger (like unsigned int and long
1156     // on most 32-bit systems).  Use the unsigned type corresponding
1157     // to the signed type.
1158     QualType result =
1159       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1160     RHS = (*doRHSCast)(S, RHS.take(), result);
1161     if (!IsCompAssign)
1162       LHS = (*doLHSCast)(S, LHS.take(), result);
1163     return result;
1164   }
1165 }
1166 
1167 /// \brief Handle conversions with GCC complex int extension.  Helper function
1168 /// of UsualArithmeticConversions()
1169 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1170                                            ExprResult &RHS, QualType LHSType,
1171                                            QualType RHSType,
1172                                            bool IsCompAssign) {
1173   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1174   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1175 
1176   if (LHSComplexInt && RHSComplexInt) {
1177     QualType LHSEltType = LHSComplexInt->getElementType();
1178     QualType RHSEltType = RHSComplexInt->getElementType();
1179     QualType ScalarType =
1180       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1181         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1182 
1183     return S.Context.getComplexType(ScalarType);
1184   }
1185 
1186   if (LHSComplexInt) {
1187     QualType LHSEltType = LHSComplexInt->getElementType();
1188     QualType ScalarType =
1189       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1190         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1191     QualType ComplexType = S.Context.getComplexType(ScalarType);
1192     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1193                               CK_IntegralRealToComplex);
1194 
1195     return ComplexType;
1196   }
1197 
1198   assert(RHSComplexInt);
1199 
1200   QualType RHSEltType = RHSComplexInt->getElementType();
1201   QualType ScalarType =
1202     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1203       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1204   QualType ComplexType = S.Context.getComplexType(ScalarType);
1205 
1206   if (!IsCompAssign)
1207     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1208                               CK_IntegralRealToComplex);
1209   return ComplexType;
1210 }
1211 
1212 /// UsualArithmeticConversions - Performs various conversions that are common to
1213 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1214 /// routine returns the first non-arithmetic type found. The client is
1215 /// responsible for emitting appropriate error diagnostics.
1216 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1217                                           bool IsCompAssign) {
1218   if (!IsCompAssign) {
1219     LHS = UsualUnaryConversions(LHS.take());
1220     if (LHS.isInvalid())
1221       return QualType();
1222   }
1223 
1224   RHS = UsualUnaryConversions(RHS.take());
1225   if (RHS.isInvalid())
1226     return QualType();
1227 
1228   // For conversion purposes, we ignore any qualifiers.
1229   // For example, "const float" and "float" are equivalent.
1230   QualType LHSType =
1231     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1232   QualType RHSType =
1233     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1234 
1235   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1236   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1237     LHSType = AtomicLHS->getValueType();
1238 
1239   // If both types are identical, no conversion is needed.
1240   if (LHSType == RHSType)
1241     return LHSType;
1242 
1243   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1244   // The caller can deal with this (e.g. pointer + int).
1245   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1246     return QualType();
1247 
1248   // Apply unary and bitfield promotions to the LHS's type.
1249   QualType LHSUnpromotedType = LHSType;
1250   if (LHSType->isPromotableIntegerType())
1251     LHSType = Context.getPromotedIntegerType(LHSType);
1252   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1253   if (!LHSBitfieldPromoteTy.isNull())
1254     LHSType = LHSBitfieldPromoteTy;
1255   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1256     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1257 
1258   // If both types are identical, no conversion is needed.
1259   if (LHSType == RHSType)
1260     return LHSType;
1261 
1262   // At this point, we have two different arithmetic types.
1263 
1264   // Handle complex types first (C99 6.3.1.8p1).
1265   if (LHSType->isComplexType() || RHSType->isComplexType())
1266     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1267                                         IsCompAssign);
1268 
1269   // Now handle "real" floating types (i.e. float, double, long double).
1270   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1271     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1272                                  IsCompAssign);
1273 
1274   // Handle GCC complex int extension.
1275   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1276     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1277                                       IsCompAssign);
1278 
1279   // Finally, we have two differing integer types.
1280   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1281            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1282 }
1283 
1284 
1285 //===----------------------------------------------------------------------===//
1286 //  Semantic Analysis for various Expression Types
1287 //===----------------------------------------------------------------------===//
1288 
1289 
1290 ExprResult
1291 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1292                                 SourceLocation DefaultLoc,
1293                                 SourceLocation RParenLoc,
1294                                 Expr *ControllingExpr,
1295                                 ArrayRef<ParsedType> ArgTypes,
1296                                 ArrayRef<Expr *> ArgExprs) {
1297   unsigned NumAssocs = ArgTypes.size();
1298   assert(NumAssocs == ArgExprs.size());
1299 
1300   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1301   for (unsigned i = 0; i < NumAssocs; ++i) {
1302     if (ArgTypes[i])
1303       (void) GetTypeFromParser(ArgTypes[i], &Types[i]);
1304     else
1305       Types[i] = 0;
1306   }
1307 
1308   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1309                                              ControllingExpr,
1310                                              llvm::makeArrayRef(Types, NumAssocs),
1311                                              ArgExprs);
1312   delete [] Types;
1313   return ER;
1314 }
1315 
1316 ExprResult
1317 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1318                                  SourceLocation DefaultLoc,
1319                                  SourceLocation RParenLoc,
1320                                  Expr *ControllingExpr,
1321                                  ArrayRef<TypeSourceInfo *> Types,
1322                                  ArrayRef<Expr *> Exprs) {
1323   unsigned NumAssocs = Types.size();
1324   assert(NumAssocs == Exprs.size());
1325   if (ControllingExpr->getType()->isPlaceholderType()) {
1326     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1327     if (result.isInvalid()) return ExprError();
1328     ControllingExpr = result.take();
1329   }
1330 
1331   bool TypeErrorFound = false,
1332        IsResultDependent = ControllingExpr->isTypeDependent(),
1333        ContainsUnexpandedParameterPack
1334          = ControllingExpr->containsUnexpandedParameterPack();
1335 
1336   for (unsigned i = 0; i < NumAssocs; ++i) {
1337     if (Exprs[i]->containsUnexpandedParameterPack())
1338       ContainsUnexpandedParameterPack = true;
1339 
1340     if (Types[i]) {
1341       if (Types[i]->getType()->containsUnexpandedParameterPack())
1342         ContainsUnexpandedParameterPack = true;
1343 
1344       if (Types[i]->getType()->isDependentType()) {
1345         IsResultDependent = true;
1346       } else {
1347         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1348         // complete object type other than a variably modified type."
1349         unsigned D = 0;
1350         if (Types[i]->getType()->isIncompleteType())
1351           D = diag::err_assoc_type_incomplete;
1352         else if (!Types[i]->getType()->isObjectType())
1353           D = diag::err_assoc_type_nonobject;
1354         else if (Types[i]->getType()->isVariablyModifiedType())
1355           D = diag::err_assoc_type_variably_modified;
1356 
1357         if (D != 0) {
1358           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1359             << Types[i]->getTypeLoc().getSourceRange()
1360             << Types[i]->getType();
1361           TypeErrorFound = true;
1362         }
1363 
1364         // C11 6.5.1.1p2 "No two generic associations in the same generic
1365         // selection shall specify compatible types."
1366         for (unsigned j = i+1; j < NumAssocs; ++j)
1367           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1368               Context.typesAreCompatible(Types[i]->getType(),
1369                                          Types[j]->getType())) {
1370             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1371                  diag::err_assoc_compatible_types)
1372               << Types[j]->getTypeLoc().getSourceRange()
1373               << Types[j]->getType()
1374               << Types[i]->getType();
1375             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1376                  diag::note_compat_assoc)
1377               << Types[i]->getTypeLoc().getSourceRange()
1378               << Types[i]->getType();
1379             TypeErrorFound = true;
1380           }
1381       }
1382     }
1383   }
1384   if (TypeErrorFound)
1385     return ExprError();
1386 
1387   // If we determined that the generic selection is result-dependent, don't
1388   // try to compute the result expression.
1389   if (IsResultDependent)
1390     return Owned(new (Context) GenericSelectionExpr(
1391                    Context, KeyLoc, ControllingExpr,
1392                    Types, Exprs,
1393                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1394 
1395   SmallVector<unsigned, 1> CompatIndices;
1396   unsigned DefaultIndex = -1U;
1397   for (unsigned i = 0; i < NumAssocs; ++i) {
1398     if (!Types[i])
1399       DefaultIndex = i;
1400     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1401                                         Types[i]->getType()))
1402       CompatIndices.push_back(i);
1403   }
1404 
1405   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1406   // type compatible with at most one of the types named in its generic
1407   // association list."
1408   if (CompatIndices.size() > 1) {
1409     // We strip parens here because the controlling expression is typically
1410     // parenthesized in macro definitions.
1411     ControllingExpr = ControllingExpr->IgnoreParens();
1412     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1413       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1414       << (unsigned) CompatIndices.size();
1415     for (SmallVectorImpl<unsigned>::iterator I = CompatIndices.begin(),
1416          E = CompatIndices.end(); I != E; ++I) {
1417       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1418            diag::note_compat_assoc)
1419         << Types[*I]->getTypeLoc().getSourceRange()
1420         << Types[*I]->getType();
1421     }
1422     return ExprError();
1423   }
1424 
1425   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1426   // its controlling expression shall have type compatible with exactly one of
1427   // the types named in its generic association list."
1428   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1429     // We strip parens here because the controlling expression is typically
1430     // parenthesized in macro definitions.
1431     ControllingExpr = ControllingExpr->IgnoreParens();
1432     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1433       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1434     return ExprError();
1435   }
1436 
1437   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1438   // type name that is compatible with the type of the controlling expression,
1439   // then the result expression of the generic selection is the expression
1440   // in that generic association. Otherwise, the result expression of the
1441   // generic selection is the expression in the default generic association."
1442   unsigned ResultIndex =
1443     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1444 
1445   return Owned(new (Context) GenericSelectionExpr(
1446                  Context, KeyLoc, ControllingExpr,
1447                  Types, Exprs,
1448                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1449                  ResultIndex));
1450 }
1451 
1452 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1453 /// location of the token and the offset of the ud-suffix within it.
1454 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1455                                      unsigned Offset) {
1456   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1457                                         S.getLangOpts());
1458 }
1459 
1460 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1461 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1462 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1463                                                  IdentifierInfo *UDSuffix,
1464                                                  SourceLocation UDSuffixLoc,
1465                                                  ArrayRef<Expr*> Args,
1466                                                  SourceLocation LitEndLoc) {
1467   assert(Args.size() <= 2 && "too many arguments for literal operator");
1468 
1469   QualType ArgTy[2];
1470   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1471     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1472     if (ArgTy[ArgIdx]->isArrayType())
1473       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1474   }
1475 
1476   DeclarationName OpName =
1477     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1478   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1479   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1480 
1481   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1482   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1483                               /*AllowRaw*/false, /*AllowTemplate*/false,
1484                               /*AllowStringTemplate*/false) == Sema::LOLR_Error)
1485     return ExprError();
1486 
1487   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1488 }
1489 
1490 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1491 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1492 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1493 /// multiple tokens.  However, the common case is that StringToks points to one
1494 /// string.
1495 ///
1496 ExprResult
1497 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1498                          Scope *UDLScope) {
1499   assert(NumStringToks && "Must have at least one string!");
1500 
1501   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1502   if (Literal.hadError)
1503     return ExprError();
1504 
1505   SmallVector<SourceLocation, 4> StringTokLocs;
1506   for (unsigned i = 0; i != NumStringToks; ++i)
1507     StringTokLocs.push_back(StringToks[i].getLocation());
1508 
1509   QualType CharTy = Context.CharTy;
1510   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1511   if (Literal.isWide()) {
1512     CharTy = Context.getWideCharType();
1513     Kind = StringLiteral::Wide;
1514   } else if (Literal.isUTF8()) {
1515     Kind = StringLiteral::UTF8;
1516   } else if (Literal.isUTF16()) {
1517     CharTy = Context.Char16Ty;
1518     Kind = StringLiteral::UTF16;
1519   } else if (Literal.isUTF32()) {
1520     CharTy = Context.Char32Ty;
1521     Kind = StringLiteral::UTF32;
1522   } else if (Literal.isPascal()) {
1523     CharTy = Context.UnsignedCharTy;
1524   }
1525 
1526   QualType CharTyConst = CharTy;
1527   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1528   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1529     CharTyConst.addConst();
1530 
1531   // Get an array type for the string, according to C99 6.4.5.  This includes
1532   // the nul terminator character as well as the string length for pascal
1533   // strings.
1534   QualType StrTy = Context.getConstantArrayType(CharTyConst,
1535                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1536                                  ArrayType::Normal, 0);
1537 
1538   // OpenCL v1.1 s6.5.3: a string literal is in the constant address space.
1539   if (getLangOpts().OpenCL) {
1540     StrTy = Context.getAddrSpaceQualType(StrTy, LangAS::opencl_constant);
1541   }
1542 
1543   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1544   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1545                                              Kind, Literal.Pascal, StrTy,
1546                                              &StringTokLocs[0],
1547                                              StringTokLocs.size());
1548   if (Literal.getUDSuffix().empty())
1549     return Owned(Lit);
1550 
1551   // We're building a user-defined literal.
1552   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1553   SourceLocation UDSuffixLoc =
1554     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1555                    Literal.getUDSuffixOffset());
1556 
1557   // Make sure we're allowed user-defined literals here.
1558   if (!UDLScope)
1559     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1560 
1561   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1562   //   operator "" X (str, len)
1563   QualType SizeType = Context.getSizeType();
1564 
1565   DeclarationName OpName =
1566     Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1567   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1568   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1569 
1570   QualType ArgTy[] = {
1571     Context.getArrayDecayedType(StrTy), SizeType
1572   };
1573 
1574   LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
1575   switch (LookupLiteralOperator(UDLScope, R, ArgTy,
1576                                 /*AllowRaw*/false, /*AllowTemplate*/false,
1577                                 /*AllowStringTemplate*/true)) {
1578 
1579   case LOLR_Cooked: {
1580     llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1581     IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1582                                                     StringTokLocs[0]);
1583     Expr *Args[] = { Lit, LenArg };
1584 
1585     return BuildLiteralOperatorCall(R, OpNameInfo, Args, StringTokLocs.back());
1586   }
1587 
1588   case LOLR_StringTemplate: {
1589     TemplateArgumentListInfo ExplicitArgs;
1590 
1591     unsigned CharBits = Context.getIntWidth(CharTy);
1592     bool CharIsUnsigned = CharTy->isUnsignedIntegerType();
1593     llvm::APSInt Value(CharBits, CharIsUnsigned);
1594 
1595     TemplateArgument TypeArg(CharTy);
1596     TemplateArgumentLocInfo TypeArgInfo(Context.getTrivialTypeSourceInfo(CharTy));
1597     ExplicitArgs.addArgument(TemplateArgumentLoc(TypeArg, TypeArgInfo));
1598 
1599     for (unsigned I = 0, N = Lit->getLength(); I != N; ++I) {
1600       Value = Lit->getCodeUnit(I);
1601       TemplateArgument Arg(Context, Value, CharTy);
1602       TemplateArgumentLocInfo ArgInfo;
1603       ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
1604     }
1605     return BuildLiteralOperatorCall(R, OpNameInfo, None, StringTokLocs.back(),
1606                                     &ExplicitArgs);
1607   }
1608   case LOLR_Raw:
1609   case LOLR_Template:
1610     llvm_unreachable("unexpected literal operator lookup result");
1611   case LOLR_Error:
1612     return ExprError();
1613   }
1614   llvm_unreachable("unexpected literal operator lookup result");
1615 }
1616 
1617 ExprResult
1618 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1619                        SourceLocation Loc,
1620                        const CXXScopeSpec *SS) {
1621   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1622   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1623 }
1624 
1625 /// BuildDeclRefExpr - Build an expression that references a
1626 /// declaration that does not require a closure capture.
1627 ExprResult
1628 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1629                        const DeclarationNameInfo &NameInfo,
1630                        const CXXScopeSpec *SS, NamedDecl *FoundD,
1631                        const TemplateArgumentListInfo *TemplateArgs) {
1632   if (getLangOpts().CUDA)
1633     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1634       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1635         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1636                            CalleeTarget = IdentifyCUDATarget(Callee);
1637         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1638           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1639             << CalleeTarget << D->getIdentifier() << CallerTarget;
1640           Diag(D->getLocation(), diag::note_previous_decl)
1641             << D->getIdentifier();
1642           return ExprError();
1643         }
1644       }
1645 
1646   bool refersToEnclosingScope =
1647     (CurContext != D->getDeclContext() &&
1648      D->getDeclContext()->isFunctionOrMethod()) ||
1649     (isa<VarDecl>(D) &&
1650      cast<VarDecl>(D)->isInitCapture());
1651 
1652   DeclRefExpr *E;
1653   if (isa<VarTemplateSpecializationDecl>(D)) {
1654     VarTemplateSpecializationDecl *VarSpec =
1655         cast<VarTemplateSpecializationDecl>(D);
1656 
1657     E = DeclRefExpr::Create(
1658         Context,
1659         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1660         VarSpec->getTemplateKeywordLoc(), D, refersToEnclosingScope,
1661         NameInfo.getLoc(), Ty, VK, FoundD, TemplateArgs);
1662   } else {
1663     assert(!TemplateArgs && "No template arguments for non-variable"
1664                             " template specialization references");
1665     E = DeclRefExpr::Create(
1666         Context,
1667         SS ? SS->getWithLocInContext(Context) : NestedNameSpecifierLoc(),
1668         SourceLocation(), D, refersToEnclosingScope, NameInfo, Ty, VK, FoundD);
1669   }
1670 
1671   MarkDeclRefReferenced(E);
1672 
1673   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1674       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1675     DiagnosticsEngine::Level Level =
1676       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1677                                E->getLocStart());
1678     if (Level != DiagnosticsEngine::Ignored)
1679       recordUseOfEvaluatedWeak(E);
1680   }
1681 
1682   // Just in case we're building an illegal pointer-to-member.
1683   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1684   if (FD && FD->isBitField())
1685     E->setObjectKind(OK_BitField);
1686 
1687   return Owned(E);
1688 }
1689 
1690 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1691 /// possibly a list of template arguments.
1692 ///
1693 /// If this produces template arguments, it is permitted to call
1694 /// DecomposeTemplateName.
1695 ///
1696 /// This actually loses a lot of source location information for
1697 /// non-standard name kinds; we should consider preserving that in
1698 /// some way.
1699 void
1700 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1701                              TemplateArgumentListInfo &Buffer,
1702                              DeclarationNameInfo &NameInfo,
1703                              const TemplateArgumentListInfo *&TemplateArgs) {
1704   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1705     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1706     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1707 
1708     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1709                                        Id.TemplateId->NumArgs);
1710     translateTemplateArguments(TemplateArgsPtr, Buffer);
1711 
1712     TemplateName TName = Id.TemplateId->Template.get();
1713     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1714     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1715     TemplateArgs = &Buffer;
1716   } else {
1717     NameInfo = GetNameFromUnqualifiedId(Id);
1718     TemplateArgs = 0;
1719   }
1720 }
1721 
1722 /// Diagnose an empty lookup.
1723 ///
1724 /// \return false if new lookup candidates were found
1725 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1726                                CorrectionCandidateCallback &CCC,
1727                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1728                                ArrayRef<Expr *> Args) {
1729   DeclarationName Name = R.getLookupName();
1730 
1731   unsigned diagnostic = diag::err_undeclared_var_use;
1732   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1733   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1734       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1735       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1736     diagnostic = diag::err_undeclared_use;
1737     diagnostic_suggest = diag::err_undeclared_use_suggest;
1738   }
1739 
1740   // If the original lookup was an unqualified lookup, fake an
1741   // unqualified lookup.  This is useful when (for example) the
1742   // original lookup would not have found something because it was a
1743   // dependent name.
1744   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1745     ? CurContext : 0;
1746   while (DC) {
1747     if (isa<CXXRecordDecl>(DC)) {
1748       LookupQualifiedName(R, DC);
1749 
1750       if (!R.empty()) {
1751         // Don't give errors about ambiguities in this lookup.
1752         R.suppressDiagnostics();
1753 
1754         // During a default argument instantiation the CurContext points
1755         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1756         // function parameter list, hence add an explicit check.
1757         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1758                               ActiveTemplateInstantiations.back().Kind ==
1759             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1760         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1761         bool isInstance = CurMethod &&
1762                           CurMethod->isInstance() &&
1763                           DC == CurMethod->getParent() && !isDefaultArgument;
1764 
1765 
1766         // Give a code modification hint to insert 'this->'.
1767         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1768         // Actually quite difficult!
1769         if (getLangOpts().MSVCCompat)
1770           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1771         if (isInstance) {
1772           Diag(R.getNameLoc(), diagnostic) << Name
1773             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1774           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1775               CallsUndergoingInstantiation.back()->getCallee());
1776 
1777           CXXMethodDecl *DepMethod;
1778           if (CurMethod->isDependentContext())
1779             DepMethod = CurMethod;
1780           else if (CurMethod->getTemplatedKind() ==
1781               FunctionDecl::TK_FunctionTemplateSpecialization)
1782             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1783                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1784           else
1785             DepMethod = cast<CXXMethodDecl>(
1786                 CurMethod->getInstantiatedFromMemberFunction());
1787           assert(DepMethod && "No template pattern found");
1788 
1789           QualType DepThisType = DepMethod->getThisType(Context);
1790           CheckCXXThisCapture(R.getNameLoc());
1791           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1792                                      R.getNameLoc(), DepThisType, false);
1793           TemplateArgumentListInfo TList;
1794           if (ULE->hasExplicitTemplateArgs())
1795             ULE->copyTemplateArgumentsInto(TList);
1796 
1797           CXXScopeSpec SS;
1798           SS.Adopt(ULE->getQualifierLoc());
1799           CXXDependentScopeMemberExpr *DepExpr =
1800               CXXDependentScopeMemberExpr::Create(
1801                   Context, DepThis, DepThisType, true, SourceLocation(),
1802                   SS.getWithLocInContext(Context),
1803                   ULE->getTemplateKeywordLoc(), 0,
1804                   R.getLookupNameInfo(),
1805                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1806           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1807         } else {
1808           Diag(R.getNameLoc(), diagnostic) << Name;
1809         }
1810 
1811         // Do we really want to note all of these?
1812         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1813           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1814 
1815         // Return true if we are inside a default argument instantiation
1816         // and the found name refers to an instance member function, otherwise
1817         // the function calling DiagnoseEmptyLookup will try to create an
1818         // implicit member call and this is wrong for default argument.
1819         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1820           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1821           return true;
1822         }
1823 
1824         // Tell the callee to try to recover.
1825         return false;
1826       }
1827 
1828       R.clear();
1829     }
1830 
1831     // In Microsoft mode, if we are performing lookup from within a friend
1832     // function definition declared at class scope then we must set
1833     // DC to the lexical parent to be able to search into the parent
1834     // class.
1835     if (getLangOpts().MSVCCompat && isa<FunctionDecl>(DC) &&
1836         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1837         DC->getLexicalParent()->isRecord())
1838       DC = DC->getLexicalParent();
1839     else
1840       DC = DC->getParent();
1841   }
1842 
1843   // We didn't find anything, so try to correct for a typo.
1844   TypoCorrection Corrected;
1845   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1846                                     S, &SS, CCC, CTK_ErrorRecovery))) {
1847     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1848     bool DroppedSpecifier =
1849         Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
1850     R.setLookupName(Corrected.getCorrection());
1851 
1852     bool AcceptableWithRecovery = false;
1853     bool AcceptableWithoutRecovery = false;
1854     NamedDecl *ND = Corrected.getCorrectionDecl();
1855     if (ND) {
1856       if (Corrected.isOverloaded()) {
1857         OverloadCandidateSet OCS(R.getNameLoc(),
1858                                  OverloadCandidateSet::CSK_Normal);
1859         OverloadCandidateSet::iterator Best;
1860         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1861                                         CDEnd = Corrected.end();
1862              CD != CDEnd; ++CD) {
1863           if (FunctionTemplateDecl *FTD =
1864                    dyn_cast<FunctionTemplateDecl>(*CD))
1865             AddTemplateOverloadCandidate(
1866                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1867                 Args, OCS);
1868           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1869             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1870               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1871                                    Args, OCS);
1872         }
1873         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1874         case OR_Success:
1875           ND = Best->Function;
1876           Corrected.setCorrectionDecl(ND);
1877           break;
1878         default:
1879           // FIXME: Arbitrarily pick the first declaration for the note.
1880           Corrected.setCorrectionDecl(ND);
1881           break;
1882         }
1883       }
1884       R.addDecl(ND);
1885 
1886       AcceptableWithRecovery =
1887           isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND);
1888       // FIXME: If we ended up with a typo for a type name or
1889       // Objective-C class name, we're in trouble because the parser
1890       // is in the wrong place to recover. Suggest the typo
1891       // correction, but don't make it a fix-it since we're not going
1892       // to recover well anyway.
1893       AcceptableWithoutRecovery =
1894           isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
1895     } else {
1896       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1897       // because we aren't able to recover.
1898       AcceptableWithoutRecovery = true;
1899     }
1900 
1901     if (AcceptableWithRecovery || AcceptableWithoutRecovery) {
1902       unsigned NoteID = (Corrected.getCorrectionDecl() &&
1903                          isa<ImplicitParamDecl>(Corrected.getCorrectionDecl()))
1904                             ? diag::note_implicit_param_decl
1905                             : diag::note_previous_decl;
1906       if (SS.isEmpty())
1907         diagnoseTypo(Corrected, PDiag(diagnostic_suggest) << Name,
1908                      PDiag(NoteID), AcceptableWithRecovery);
1909       else
1910         diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
1911                                   << Name << computeDeclContext(SS, false)
1912                                   << DroppedSpecifier << SS.getRange(),
1913                      PDiag(NoteID), AcceptableWithRecovery);
1914 
1915       // Tell the callee whether to try to recover.
1916       return !AcceptableWithRecovery;
1917     }
1918   }
1919   R.clear();
1920 
1921   // Emit a special diagnostic for failed member lookups.
1922   // FIXME: computing the declaration context might fail here (?)
1923   if (!SS.isEmpty()) {
1924     Diag(R.getNameLoc(), diag::err_no_member)
1925       << Name << computeDeclContext(SS, false)
1926       << SS.getRange();
1927     return true;
1928   }
1929 
1930   // Give up, we can't recover.
1931   Diag(R.getNameLoc(), diagnostic) << Name;
1932   return true;
1933 }
1934 
1935 ExprResult Sema::ActOnIdExpression(Scope *S,
1936                                    CXXScopeSpec &SS,
1937                                    SourceLocation TemplateKWLoc,
1938                                    UnqualifiedId &Id,
1939                                    bool HasTrailingLParen,
1940                                    bool IsAddressOfOperand,
1941                                    CorrectionCandidateCallback *CCC,
1942                                    bool IsInlineAsmIdentifier) {
1943   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1944          "cannot be direct & operand and have a trailing lparen");
1945   if (SS.isInvalid())
1946     return ExprError();
1947 
1948   TemplateArgumentListInfo TemplateArgsBuffer;
1949 
1950   // Decompose the UnqualifiedId into the following data.
1951   DeclarationNameInfo NameInfo;
1952   const TemplateArgumentListInfo *TemplateArgs;
1953   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1954 
1955   DeclarationName Name = NameInfo.getName();
1956   IdentifierInfo *II = Name.getAsIdentifierInfo();
1957   SourceLocation NameLoc = NameInfo.getLoc();
1958 
1959   // C++ [temp.dep.expr]p3:
1960   //   An id-expression is type-dependent if it contains:
1961   //     -- an identifier that was declared with a dependent type,
1962   //        (note: handled after lookup)
1963   //     -- a template-id that is dependent,
1964   //        (note: handled in BuildTemplateIdExpr)
1965   //     -- a conversion-function-id that specifies a dependent type,
1966   //     -- a nested-name-specifier that contains a class-name that
1967   //        names a dependent type.
1968   // Determine whether this is a member of an unknown specialization;
1969   // we need to handle these differently.
1970   bool DependentID = false;
1971   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1972       Name.getCXXNameType()->isDependentType()) {
1973     DependentID = true;
1974   } else if (SS.isSet()) {
1975     if (DeclContext *DC = computeDeclContext(SS, false)) {
1976       if (RequireCompleteDeclContext(SS, DC))
1977         return ExprError();
1978     } else {
1979       DependentID = true;
1980     }
1981   }
1982 
1983   if (DependentID)
1984     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1985                                       IsAddressOfOperand, TemplateArgs);
1986 
1987   // Perform the required lookup.
1988   LookupResult R(*this, NameInfo,
1989                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1990                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1991   if (TemplateArgs) {
1992     // Lookup the template name again to correctly establish the context in
1993     // which it was found. This is really unfortunate as we already did the
1994     // lookup to determine that it was a template name in the first place. If
1995     // this becomes a performance hit, we can work harder to preserve those
1996     // results until we get here but it's likely not worth it.
1997     bool MemberOfUnknownSpecialization;
1998     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1999                        MemberOfUnknownSpecialization);
2000 
2001     if (MemberOfUnknownSpecialization ||
2002         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
2003       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2004                                         IsAddressOfOperand, TemplateArgs);
2005   } else {
2006     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
2007     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
2008 
2009     // If the result might be in a dependent base class, this is a dependent
2010     // id-expression.
2011     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2012       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
2013                                         IsAddressOfOperand, TemplateArgs);
2014 
2015     // If this reference is in an Objective-C method, then we need to do
2016     // some special Objective-C lookup, too.
2017     if (IvarLookupFollowUp) {
2018       ExprResult E(LookupInObjCMethod(R, S, II, true));
2019       if (E.isInvalid())
2020         return ExprError();
2021 
2022       if (Expr *Ex = E.takeAs<Expr>())
2023         return Owned(Ex);
2024     }
2025   }
2026 
2027   if (R.isAmbiguous())
2028     return ExprError();
2029 
2030   // Determine whether this name might be a candidate for
2031   // argument-dependent lookup.
2032   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
2033 
2034   if (R.empty() && !ADL) {
2035 
2036     // Otherwise, this could be an implicitly declared function reference (legal
2037     // in C90, extension in C99, forbidden in C++).
2038     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
2039       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
2040       if (D) R.addDecl(D);
2041     }
2042 
2043     // If this name wasn't predeclared and if this is not a function
2044     // call, diagnose the problem.
2045     if (R.empty()) {
2046       // In Microsoft mode, if we are inside a template class member function
2047       // whose parent class has dependent base classes, and we can't resolve
2048       // an unqualified identifier, then assume the identifier is a member of a
2049       // dependent base class.  The goal is to postpone name lookup to
2050       // instantiation time to be able to search into the type dependent base
2051       // classes.
2052       // FIXME: If we want 100% compatibility with MSVC, we will have delay all
2053       // unqualified name lookup.  Any name lookup during template parsing means
2054       // clang might find something that MSVC doesn't.  For now, we only handle
2055       // the common case of members of a dependent base class.
2056       if (SS.isEmpty() && getLangOpts().MSVCCompat) {
2057         CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext);
2058         if (MD && MD->isInstance() && MD->getParent()->hasAnyDependentBases()) {
2059           QualType ThisType = MD->getThisType(Context);
2060           // Since the 'this' expression is synthesized, we don't need to
2061           // perform the double-lookup check.
2062           NamedDecl *FirstQualifierInScope = 0;
2063           return Owned(CXXDependentScopeMemberExpr::Create(
2064               Context, /*This=*/0, ThisType, /*IsArrow=*/true,
2065               /*Op=*/SourceLocation(), SS.getWithLocInContext(Context),
2066               TemplateKWLoc, FirstQualifierInScope, NameInfo, TemplateArgs));
2067         }
2068       }
2069 
2070       // Don't diagnose an empty lookup for inline assmebly.
2071       if (IsInlineAsmIdentifier)
2072         return ExprError();
2073 
2074       CorrectionCandidateCallback DefaultValidator;
2075       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
2076         return ExprError();
2077 
2078       assert(!R.empty() &&
2079              "DiagnoseEmptyLookup returned false but added no results");
2080 
2081       // If we found an Objective-C instance variable, let
2082       // LookupInObjCMethod build the appropriate expression to
2083       // reference the ivar.
2084       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
2085         R.clear();
2086         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
2087         // In a hopelessly buggy code, Objective-C instance variable
2088         // lookup fails and no expression will be built to reference it.
2089         if (!E.isInvalid() && !E.get())
2090           return ExprError();
2091         return E;
2092       }
2093     }
2094   }
2095 
2096   // This is guaranteed from this point on.
2097   assert(!R.empty() || ADL);
2098 
2099   // Check whether this might be a C++ implicit instance member access.
2100   // C++ [class.mfct.non-static]p3:
2101   //   When an id-expression that is not part of a class member access
2102   //   syntax and not used to form a pointer to member is used in the
2103   //   body of a non-static member function of class X, if name lookup
2104   //   resolves the name in the id-expression to a non-static non-type
2105   //   member of some class C, the id-expression is transformed into a
2106   //   class member access expression using (*this) as the
2107   //   postfix-expression to the left of the . operator.
2108   //
2109   // But we don't actually need to do this for '&' operands if R
2110   // resolved to a function or overloaded function set, because the
2111   // expression is ill-formed if it actually works out to be a
2112   // non-static member function:
2113   //
2114   // C++ [expr.ref]p4:
2115   //   Otherwise, if E1.E2 refers to a non-static member function. . .
2116   //   [t]he expression can be used only as the left-hand operand of a
2117   //   member function call.
2118   //
2119   // There are other safeguards against such uses, but it's important
2120   // to get this right here so that we don't end up making a
2121   // spuriously dependent expression if we're inside a dependent
2122   // instance method.
2123   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
2124     bool MightBeImplicitMember;
2125     if (!IsAddressOfOperand)
2126       MightBeImplicitMember = true;
2127     else if (!SS.isEmpty())
2128       MightBeImplicitMember = false;
2129     else if (R.isOverloadedResult())
2130       MightBeImplicitMember = false;
2131     else if (R.isUnresolvableResult())
2132       MightBeImplicitMember = true;
2133     else
2134       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2135                               isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2136                               isa<MSPropertyDecl>(R.getFoundDecl());
2137 
2138     if (MightBeImplicitMember)
2139       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2140                                              R, TemplateArgs);
2141   }
2142 
2143   if (TemplateArgs || TemplateKWLoc.isValid()) {
2144 
2145     // In C++1y, if this is a variable template id, then check it
2146     // in BuildTemplateIdExpr().
2147     // The single lookup result must be a variable template declaration.
2148     if (Id.getKind() == UnqualifiedId::IK_TemplateId && Id.TemplateId &&
2149         Id.TemplateId->Kind == TNK_Var_template) {
2150       assert(R.getAsSingle<VarTemplateDecl>() &&
2151              "There should only be one declaration found.");
2152     }
2153 
2154     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
2155   }
2156 
2157   return BuildDeclarationNameExpr(SS, R, ADL);
2158 }
2159 
2160 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2161 /// declaration name, generally during template instantiation.
2162 /// There's a large number of things which don't need to be done along
2163 /// this path.
2164 ExprResult
2165 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2166                                         const DeclarationNameInfo &NameInfo,
2167                                         bool IsAddressOfOperand) {
2168   DeclContext *DC = computeDeclContext(SS, false);
2169   if (!DC)
2170     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2171                                      NameInfo, /*TemplateArgs=*/0);
2172 
2173   if (RequireCompleteDeclContext(SS, DC))
2174     return ExprError();
2175 
2176   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2177   LookupQualifiedName(R, DC);
2178 
2179   if (R.isAmbiguous())
2180     return ExprError();
2181 
2182   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2183     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2184                                      NameInfo, /*TemplateArgs=*/0);
2185 
2186   if (R.empty()) {
2187     Diag(NameInfo.getLoc(), diag::err_no_member)
2188       << NameInfo.getName() << DC << SS.getRange();
2189     return ExprError();
2190   }
2191 
2192   // Defend against this resolving to an implicit member access. We usually
2193   // won't get here if this might be a legitimate a class member (we end up in
2194   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2195   // a pointer-to-member or in an unevaluated context in C++11.
2196   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2197     return BuildPossibleImplicitMemberExpr(SS,
2198                                            /*TemplateKWLoc=*/SourceLocation(),
2199                                            R, /*TemplateArgs=*/0);
2200 
2201   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2202 }
2203 
2204 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2205 /// detected that we're currently inside an ObjC method.  Perform some
2206 /// additional lookup.
2207 ///
2208 /// Ideally, most of this would be done by lookup, but there's
2209 /// actually quite a lot of extra work involved.
2210 ///
2211 /// Returns a null sentinel to indicate trivial success.
2212 ExprResult
2213 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2214                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2215   SourceLocation Loc = Lookup.getNameLoc();
2216   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2217 
2218   // Check for error condition which is already reported.
2219   if (!CurMethod)
2220     return ExprError();
2221 
2222   // There are two cases to handle here.  1) scoped lookup could have failed,
2223   // in which case we should look for an ivar.  2) scoped lookup could have
2224   // found a decl, but that decl is outside the current instance method (i.e.
2225   // a global variable).  In these two cases, we do a lookup for an ivar with
2226   // this name, if the lookup sucedes, we replace it our current decl.
2227 
2228   // If we're in a class method, we don't normally want to look for
2229   // ivars.  But if we don't find anything else, and there's an
2230   // ivar, that's an error.
2231   bool IsClassMethod = CurMethod->isClassMethod();
2232 
2233   bool LookForIvars;
2234   if (Lookup.empty())
2235     LookForIvars = true;
2236   else if (IsClassMethod)
2237     LookForIvars = false;
2238   else
2239     LookForIvars = (Lookup.isSingleResult() &&
2240                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2241   ObjCInterfaceDecl *IFace = 0;
2242   if (LookForIvars) {
2243     IFace = CurMethod->getClassInterface();
2244     ObjCInterfaceDecl *ClassDeclared;
2245     ObjCIvarDecl *IV = 0;
2246     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2247       // Diagnose using an ivar in a class method.
2248       if (IsClassMethod)
2249         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2250                          << IV->getDeclName());
2251 
2252       // If we're referencing an invalid decl, just return this as a silent
2253       // error node.  The error diagnostic was already emitted on the decl.
2254       if (IV->isInvalidDecl())
2255         return ExprError();
2256 
2257       // Check if referencing a field with __attribute__((deprecated)).
2258       if (DiagnoseUseOfDecl(IV, Loc))
2259         return ExprError();
2260 
2261       // Diagnose the use of an ivar outside of the declaring class.
2262       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2263           !declaresSameEntity(ClassDeclared, IFace) &&
2264           !getLangOpts().DebuggerSupport)
2265         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2266 
2267       // FIXME: This should use a new expr for a direct reference, don't
2268       // turn this into Self->ivar, just return a BareIVarExpr or something.
2269       IdentifierInfo &II = Context.Idents.get("self");
2270       UnqualifiedId SelfName;
2271       SelfName.setIdentifier(&II, SourceLocation());
2272       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2273       CXXScopeSpec SelfScopeSpec;
2274       SourceLocation TemplateKWLoc;
2275       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2276                                               SelfName, false, false);
2277       if (SelfExpr.isInvalid())
2278         return ExprError();
2279 
2280       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2281       if (SelfExpr.isInvalid())
2282         return ExprError();
2283 
2284       MarkAnyDeclReferenced(Loc, IV, true);
2285 
2286       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2287       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2288           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2289         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2290 
2291       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2292                                                               Loc, IV->getLocation(),
2293                                                               SelfExpr.take(),
2294                                                               true, true);
2295 
2296       if (getLangOpts().ObjCAutoRefCount) {
2297         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2298           DiagnosticsEngine::Level Level =
2299             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2300           if (Level != DiagnosticsEngine::Ignored)
2301             recordUseOfEvaluatedWeak(Result);
2302         }
2303         if (CurContext->isClosure())
2304           Diag(Loc, diag::warn_implicitly_retains_self)
2305             << FixItHint::CreateInsertion(Loc, "self->");
2306       }
2307 
2308       return Owned(Result);
2309     }
2310   } else if (CurMethod->isInstanceMethod()) {
2311     // We should warn if a local variable hides an ivar.
2312     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2313       ObjCInterfaceDecl *ClassDeclared;
2314       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2315         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2316             declaresSameEntity(IFace, ClassDeclared))
2317           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2318       }
2319     }
2320   } else if (Lookup.isSingleResult() &&
2321              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2322     // If accessing a stand-alone ivar in a class method, this is an error.
2323     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2324       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2325                        << IV->getDeclName());
2326   }
2327 
2328   if (Lookup.empty() && II && AllowBuiltinCreation) {
2329     // FIXME. Consolidate this with similar code in LookupName.
2330     if (unsigned BuiltinID = II->getBuiltinID()) {
2331       if (!(getLangOpts().CPlusPlus &&
2332             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2333         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2334                                            S, Lookup.isForRedeclaration(),
2335                                            Lookup.getNameLoc());
2336         if (D) Lookup.addDecl(D);
2337       }
2338     }
2339   }
2340   // Sentinel value saying that we didn't do anything special.
2341   return Owned((Expr*) 0);
2342 }
2343 
2344 /// \brief Cast a base object to a member's actual type.
2345 ///
2346 /// Logically this happens in three phases:
2347 ///
2348 /// * First we cast from the base type to the naming class.
2349 ///   The naming class is the class into which we were looking
2350 ///   when we found the member;  it's the qualifier type if a
2351 ///   qualifier was provided, and otherwise it's the base type.
2352 ///
2353 /// * Next we cast from the naming class to the declaring class.
2354 ///   If the member we found was brought into a class's scope by
2355 ///   a using declaration, this is that class;  otherwise it's
2356 ///   the class declaring the member.
2357 ///
2358 /// * Finally we cast from the declaring class to the "true"
2359 ///   declaring class of the member.  This conversion does not
2360 ///   obey access control.
2361 ExprResult
2362 Sema::PerformObjectMemberConversion(Expr *From,
2363                                     NestedNameSpecifier *Qualifier,
2364                                     NamedDecl *FoundDecl,
2365                                     NamedDecl *Member) {
2366   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2367   if (!RD)
2368     return Owned(From);
2369 
2370   QualType DestRecordType;
2371   QualType DestType;
2372   QualType FromRecordType;
2373   QualType FromType = From->getType();
2374   bool PointerConversions = false;
2375   if (isa<FieldDecl>(Member)) {
2376     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2377 
2378     if (FromType->getAs<PointerType>()) {
2379       DestType = Context.getPointerType(DestRecordType);
2380       FromRecordType = FromType->getPointeeType();
2381       PointerConversions = true;
2382     } else {
2383       DestType = DestRecordType;
2384       FromRecordType = FromType;
2385     }
2386   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2387     if (Method->isStatic())
2388       return Owned(From);
2389 
2390     DestType = Method->getThisType(Context);
2391     DestRecordType = DestType->getPointeeType();
2392 
2393     if (FromType->getAs<PointerType>()) {
2394       FromRecordType = FromType->getPointeeType();
2395       PointerConversions = true;
2396     } else {
2397       FromRecordType = FromType;
2398       DestType = DestRecordType;
2399     }
2400   } else {
2401     // No conversion necessary.
2402     return Owned(From);
2403   }
2404 
2405   if (DestType->isDependentType() || FromType->isDependentType())
2406     return Owned(From);
2407 
2408   // If the unqualified types are the same, no conversion is necessary.
2409   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2410     return Owned(From);
2411 
2412   SourceRange FromRange = From->getSourceRange();
2413   SourceLocation FromLoc = FromRange.getBegin();
2414 
2415   ExprValueKind VK = From->getValueKind();
2416 
2417   // C++ [class.member.lookup]p8:
2418   //   [...] Ambiguities can often be resolved by qualifying a name with its
2419   //   class name.
2420   //
2421   // If the member was a qualified name and the qualified referred to a
2422   // specific base subobject type, we'll cast to that intermediate type
2423   // first and then to the object in which the member is declared. That allows
2424   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2425   //
2426   //   class Base { public: int x; };
2427   //   class Derived1 : public Base { };
2428   //   class Derived2 : public Base { };
2429   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2430   //
2431   //   void VeryDerived::f() {
2432   //     x = 17; // error: ambiguous base subobjects
2433   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2434   //   }
2435   if (Qualifier && Qualifier->getAsType()) {
2436     QualType QType = QualType(Qualifier->getAsType(), 0);
2437     assert(QType->isRecordType() && "lookup done with non-record type");
2438 
2439     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2440 
2441     // In C++98, the qualifier type doesn't actually have to be a base
2442     // type of the object type, in which case we just ignore it.
2443     // Otherwise build the appropriate casts.
2444     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2445       CXXCastPath BasePath;
2446       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2447                                        FromLoc, FromRange, &BasePath))
2448         return ExprError();
2449 
2450       if (PointerConversions)
2451         QType = Context.getPointerType(QType);
2452       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2453                                VK, &BasePath).take();
2454 
2455       FromType = QType;
2456       FromRecordType = QRecordType;
2457 
2458       // If the qualifier type was the same as the destination type,
2459       // we're done.
2460       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2461         return Owned(From);
2462     }
2463   }
2464 
2465   bool IgnoreAccess = false;
2466 
2467   // If we actually found the member through a using declaration, cast
2468   // down to the using declaration's type.
2469   //
2470   // Pointer equality is fine here because only one declaration of a
2471   // class ever has member declarations.
2472   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2473     assert(isa<UsingShadowDecl>(FoundDecl));
2474     QualType URecordType = Context.getTypeDeclType(
2475                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2476 
2477     // We only need to do this if the naming-class to declaring-class
2478     // conversion is non-trivial.
2479     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2480       assert(IsDerivedFrom(FromRecordType, URecordType));
2481       CXXCastPath BasePath;
2482       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2483                                        FromLoc, FromRange, &BasePath))
2484         return ExprError();
2485 
2486       QualType UType = URecordType;
2487       if (PointerConversions)
2488         UType = Context.getPointerType(UType);
2489       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2490                                VK, &BasePath).take();
2491       FromType = UType;
2492       FromRecordType = URecordType;
2493     }
2494 
2495     // We don't do access control for the conversion from the
2496     // declaring class to the true declaring class.
2497     IgnoreAccess = true;
2498   }
2499 
2500   CXXCastPath BasePath;
2501   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2502                                    FromLoc, FromRange, &BasePath,
2503                                    IgnoreAccess))
2504     return ExprError();
2505 
2506   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2507                            VK, &BasePath);
2508 }
2509 
2510 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2511                                       const LookupResult &R,
2512                                       bool HasTrailingLParen) {
2513   // Only when used directly as the postfix-expression of a call.
2514   if (!HasTrailingLParen)
2515     return false;
2516 
2517   // Never if a scope specifier was provided.
2518   if (SS.isSet())
2519     return false;
2520 
2521   // Only in C++ or ObjC++.
2522   if (!getLangOpts().CPlusPlus)
2523     return false;
2524 
2525   // Turn off ADL when we find certain kinds of declarations during
2526   // normal lookup:
2527   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2528     NamedDecl *D = *I;
2529 
2530     // C++0x [basic.lookup.argdep]p3:
2531     //     -- a declaration of a class member
2532     // Since using decls preserve this property, we check this on the
2533     // original decl.
2534     if (D->isCXXClassMember())
2535       return false;
2536 
2537     // C++0x [basic.lookup.argdep]p3:
2538     //     -- a block-scope function declaration that is not a
2539     //        using-declaration
2540     // NOTE: we also trigger this for function templates (in fact, we
2541     // don't check the decl type at all, since all other decl types
2542     // turn off ADL anyway).
2543     if (isa<UsingShadowDecl>(D))
2544       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2545     else if (D->getLexicalDeclContext()->isFunctionOrMethod())
2546       return false;
2547 
2548     // C++0x [basic.lookup.argdep]p3:
2549     //     -- a declaration that is neither a function or a function
2550     //        template
2551     // And also for builtin functions.
2552     if (isa<FunctionDecl>(D)) {
2553       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2554 
2555       // But also builtin functions.
2556       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2557         return false;
2558     } else if (!isa<FunctionTemplateDecl>(D))
2559       return false;
2560   }
2561 
2562   return true;
2563 }
2564 
2565 
2566 /// Diagnoses obvious problems with the use of the given declaration
2567 /// as an expression.  This is only actually called for lookups that
2568 /// were not overloaded, and it doesn't promise that the declaration
2569 /// will in fact be used.
2570 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2571   if (isa<TypedefNameDecl>(D)) {
2572     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2573     return true;
2574   }
2575 
2576   if (isa<ObjCInterfaceDecl>(D)) {
2577     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2578     return true;
2579   }
2580 
2581   if (isa<NamespaceDecl>(D)) {
2582     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2583     return true;
2584   }
2585 
2586   return false;
2587 }
2588 
2589 ExprResult
2590 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2591                                LookupResult &R,
2592                                bool NeedsADL) {
2593   // If this is a single, fully-resolved result and we don't need ADL,
2594   // just build an ordinary singleton decl ref.
2595   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2596     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2597                                     R.getRepresentativeDecl());
2598 
2599   // We only need to check the declaration if there's exactly one
2600   // result, because in the overloaded case the results can only be
2601   // functions and function templates.
2602   if (R.isSingleResult() &&
2603       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2604     return ExprError();
2605 
2606   // Otherwise, just build an unresolved lookup expression.  Suppress
2607   // any lookup-related diagnostics; we'll hash these out later, when
2608   // we've picked a target.
2609   R.suppressDiagnostics();
2610 
2611   UnresolvedLookupExpr *ULE
2612     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2613                                    SS.getWithLocInContext(Context),
2614                                    R.getLookupNameInfo(),
2615                                    NeedsADL, R.isOverloadedResult(),
2616                                    R.begin(), R.end());
2617 
2618   return Owned(ULE);
2619 }
2620 
2621 /// \brief Complete semantic analysis for a reference to the given declaration.
2622 ExprResult Sema::BuildDeclarationNameExpr(
2623     const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
2624     NamedDecl *FoundD, const TemplateArgumentListInfo *TemplateArgs) {
2625   assert(D && "Cannot refer to a NULL declaration");
2626   assert(!isa<FunctionTemplateDecl>(D) &&
2627          "Cannot refer unambiguously to a function template");
2628 
2629   SourceLocation Loc = NameInfo.getLoc();
2630   if (CheckDeclInExpr(*this, Loc, D))
2631     return ExprError();
2632 
2633   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2634     // Specifically diagnose references to class templates that are missing
2635     // a template argument list.
2636     Diag(Loc, diag::err_template_decl_ref) << (isa<VarTemplateDecl>(D) ? 1 : 0)
2637                                            << Template << SS.getRange();
2638     Diag(Template->getLocation(), diag::note_template_decl_here);
2639     return ExprError();
2640   }
2641 
2642   // Make sure that we're referring to a value.
2643   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2644   if (!VD) {
2645     Diag(Loc, diag::err_ref_non_value)
2646       << D << SS.getRange();
2647     Diag(D->getLocation(), diag::note_declared_at);
2648     return ExprError();
2649   }
2650 
2651   // Check whether this declaration can be used. Note that we suppress
2652   // this check when we're going to perform argument-dependent lookup
2653   // on this function name, because this might not be the function
2654   // that overload resolution actually selects.
2655   if (DiagnoseUseOfDecl(VD, Loc))
2656     return ExprError();
2657 
2658   // Only create DeclRefExpr's for valid Decl's.
2659   if (VD->isInvalidDecl())
2660     return ExprError();
2661 
2662   // Handle members of anonymous structs and unions.  If we got here,
2663   // and the reference is to a class member indirect field, then this
2664   // must be the subject of a pointer-to-member expression.
2665   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2666     if (!indirectField->isCXXClassMember())
2667       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2668                                                       indirectField);
2669 
2670   {
2671     QualType type = VD->getType();
2672     ExprValueKind valueKind = VK_RValue;
2673 
2674     switch (D->getKind()) {
2675     // Ignore all the non-ValueDecl kinds.
2676 #define ABSTRACT_DECL(kind)
2677 #define VALUE(type, base)
2678 #define DECL(type, base) \
2679     case Decl::type:
2680 #include "clang/AST/DeclNodes.inc"
2681       llvm_unreachable("invalid value decl kind");
2682 
2683     // These shouldn't make it here.
2684     case Decl::ObjCAtDefsField:
2685     case Decl::ObjCIvar:
2686       llvm_unreachable("forming non-member reference to ivar?");
2687 
2688     // Enum constants are always r-values and never references.
2689     // Unresolved using declarations are dependent.
2690     case Decl::EnumConstant:
2691     case Decl::UnresolvedUsingValue:
2692       valueKind = VK_RValue;
2693       break;
2694 
2695     // Fields and indirect fields that got here must be for
2696     // pointer-to-member expressions; we just call them l-values for
2697     // internal consistency, because this subexpression doesn't really
2698     // exist in the high-level semantics.
2699     case Decl::Field:
2700     case Decl::IndirectField:
2701       assert(getLangOpts().CPlusPlus &&
2702              "building reference to field in C?");
2703 
2704       // These can't have reference type in well-formed programs, but
2705       // for internal consistency we do this anyway.
2706       type = type.getNonReferenceType();
2707       valueKind = VK_LValue;
2708       break;
2709 
2710     // Non-type template parameters are either l-values or r-values
2711     // depending on the type.
2712     case Decl::NonTypeTemplateParm: {
2713       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2714         type = reftype->getPointeeType();
2715         valueKind = VK_LValue; // even if the parameter is an r-value reference
2716         break;
2717       }
2718 
2719       // For non-references, we need to strip qualifiers just in case
2720       // the template parameter was declared as 'const int' or whatever.
2721       valueKind = VK_RValue;
2722       type = type.getUnqualifiedType();
2723       break;
2724     }
2725 
2726     case Decl::Var:
2727     case Decl::VarTemplateSpecialization:
2728     case Decl::VarTemplatePartialSpecialization:
2729       // In C, "extern void blah;" is valid and is an r-value.
2730       if (!getLangOpts().CPlusPlus &&
2731           !type.hasQualifiers() &&
2732           type->isVoidType()) {
2733         valueKind = VK_RValue;
2734         break;
2735       }
2736       // fallthrough
2737 
2738     case Decl::ImplicitParam:
2739     case Decl::ParmVar: {
2740       // These are always l-values.
2741       valueKind = VK_LValue;
2742       type = type.getNonReferenceType();
2743 
2744       // FIXME: Does the addition of const really only apply in
2745       // potentially-evaluated contexts? Since the variable isn't actually
2746       // captured in an unevaluated context, it seems that the answer is no.
2747       if (!isUnevaluatedContext()) {
2748         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2749         if (!CapturedType.isNull())
2750           type = CapturedType;
2751       }
2752 
2753       break;
2754     }
2755 
2756     case Decl::Function: {
2757       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2758         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2759           type = Context.BuiltinFnTy;
2760           valueKind = VK_RValue;
2761           break;
2762         }
2763       }
2764 
2765       const FunctionType *fty = type->castAs<FunctionType>();
2766 
2767       // If we're referring to a function with an __unknown_anytype
2768       // result type, make the entire expression __unknown_anytype.
2769       if (fty->getReturnType() == Context.UnknownAnyTy) {
2770         type = Context.UnknownAnyTy;
2771         valueKind = VK_RValue;
2772         break;
2773       }
2774 
2775       // Functions are l-values in C++.
2776       if (getLangOpts().CPlusPlus) {
2777         valueKind = VK_LValue;
2778         break;
2779       }
2780 
2781       // C99 DR 316 says that, if a function type comes from a
2782       // function definition (without a prototype), that type is only
2783       // used for checking compatibility. Therefore, when referencing
2784       // the function, we pretend that we don't have the full function
2785       // type.
2786       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2787           isa<FunctionProtoType>(fty))
2788         type = Context.getFunctionNoProtoType(fty->getReturnType(),
2789                                               fty->getExtInfo());
2790 
2791       // Functions are r-values in C.
2792       valueKind = VK_RValue;
2793       break;
2794     }
2795 
2796     case Decl::MSProperty:
2797       valueKind = VK_LValue;
2798       break;
2799 
2800     case Decl::CXXMethod:
2801       // If we're referring to a method with an __unknown_anytype
2802       // result type, make the entire expression __unknown_anytype.
2803       // This should only be possible with a type written directly.
2804       if (const FunctionProtoType *proto
2805             = dyn_cast<FunctionProtoType>(VD->getType()))
2806         if (proto->getReturnType() == Context.UnknownAnyTy) {
2807           type = Context.UnknownAnyTy;
2808           valueKind = VK_RValue;
2809           break;
2810         }
2811 
2812       // C++ methods are l-values if static, r-values if non-static.
2813       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2814         valueKind = VK_LValue;
2815         break;
2816       }
2817       // fallthrough
2818 
2819     case Decl::CXXConversion:
2820     case Decl::CXXDestructor:
2821     case Decl::CXXConstructor:
2822       valueKind = VK_RValue;
2823       break;
2824     }
2825 
2826     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD,
2827                             TemplateArgs);
2828   }
2829 }
2830 
2831 ExprResult Sema::BuildPredefinedExpr(SourceLocation Loc,
2832                                      PredefinedExpr::IdentType IT) {
2833   // Pick the current block, lambda, captured statement or function.
2834   Decl *currentDecl = 0;
2835   if (const BlockScopeInfo *BSI = getCurBlock())
2836     currentDecl = BSI->TheDecl;
2837   else if (const LambdaScopeInfo *LSI = getCurLambda())
2838     currentDecl = LSI->CallOperator;
2839   else if (const CapturedRegionScopeInfo *CSI = getCurCapturedRegion())
2840     currentDecl = CSI->TheCapturedDecl;
2841   else
2842     currentDecl = getCurFunctionOrMethodDecl();
2843 
2844   if (!currentDecl) {
2845     Diag(Loc, diag::ext_predef_outside_function);
2846     currentDecl = Context.getTranslationUnitDecl();
2847   }
2848 
2849   QualType ResTy;
2850   if (cast<DeclContext>(currentDecl)->isDependentContext())
2851     ResTy = Context.DependentTy;
2852   else {
2853     // Pre-defined identifiers are of type char[x], where x is the length of
2854     // the string.
2855     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2856 
2857     llvm::APInt LengthI(32, Length + 1);
2858     if (IT == PredefinedExpr::LFunction)
2859       ResTy = Context.WideCharTy.withConst();
2860     else
2861       ResTy = Context.CharTy.withConst();
2862     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2863   }
2864 
2865   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2866 }
2867 
2868 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2869   PredefinedExpr::IdentType IT;
2870 
2871   switch (Kind) {
2872   default: llvm_unreachable("Unknown simple primary expr!");
2873   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2874   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2875   case tok::kw___FUNCDNAME__: IT = PredefinedExpr::FuncDName; break; // [MS]
2876   case tok::kw___FUNCSIG__: IT = PredefinedExpr::FuncSig; break; // [MS]
2877   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2878   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2879   }
2880 
2881   return BuildPredefinedExpr(Loc, IT);
2882 }
2883 
2884 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2885   SmallString<16> CharBuffer;
2886   bool Invalid = false;
2887   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2888   if (Invalid)
2889     return ExprError();
2890 
2891   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2892                             PP, Tok.getKind());
2893   if (Literal.hadError())
2894     return ExprError();
2895 
2896   QualType Ty;
2897   if (Literal.isWide())
2898     Ty = Context.WideCharTy; // L'x' -> wchar_t in C and C++.
2899   else if (Literal.isUTF16())
2900     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2901   else if (Literal.isUTF32())
2902     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2903   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2904     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2905   else
2906     Ty = Context.CharTy;  // 'x' -> char in C++
2907 
2908   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2909   if (Literal.isWide())
2910     Kind = CharacterLiteral::Wide;
2911   else if (Literal.isUTF16())
2912     Kind = CharacterLiteral::UTF16;
2913   else if (Literal.isUTF32())
2914     Kind = CharacterLiteral::UTF32;
2915 
2916   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2917                                              Tok.getLocation());
2918 
2919   if (Literal.getUDSuffix().empty())
2920     return Owned(Lit);
2921 
2922   // We're building a user-defined literal.
2923   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2924   SourceLocation UDSuffixLoc =
2925     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2926 
2927   // Make sure we're allowed user-defined literals here.
2928   if (!UDLScope)
2929     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2930 
2931   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2932   //   operator "" X (ch)
2933   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2934                                         Lit, Tok.getLocation());
2935 }
2936 
2937 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2938   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2939   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2940                                       Context.IntTy, Loc));
2941 }
2942 
2943 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2944                                   QualType Ty, SourceLocation Loc) {
2945   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2946 
2947   using llvm::APFloat;
2948   APFloat Val(Format);
2949 
2950   APFloat::opStatus result = Literal.GetFloatValue(Val);
2951 
2952   // Overflow is always an error, but underflow is only an error if
2953   // we underflowed to zero (APFloat reports denormals as underflow).
2954   if ((result & APFloat::opOverflow) ||
2955       ((result & APFloat::opUnderflow) && Val.isZero())) {
2956     unsigned diagnostic;
2957     SmallString<20> buffer;
2958     if (result & APFloat::opOverflow) {
2959       diagnostic = diag::warn_float_overflow;
2960       APFloat::getLargest(Format).toString(buffer);
2961     } else {
2962       diagnostic = diag::warn_float_underflow;
2963       APFloat::getSmallest(Format).toString(buffer);
2964     }
2965 
2966     S.Diag(Loc, diagnostic)
2967       << Ty
2968       << StringRef(buffer.data(), buffer.size());
2969   }
2970 
2971   bool isExact = (result == APFloat::opOK);
2972   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2973 }
2974 
2975 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2976   // Fast path for a single digit (which is quite common).  A single digit
2977   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2978   if (Tok.getLength() == 1) {
2979     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2980     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2981   }
2982 
2983   SmallString<128> SpellingBuffer;
2984   // NumericLiteralParser wants to overread by one character.  Add padding to
2985   // the buffer in case the token is copied to the buffer.  If getSpelling()
2986   // returns a StringRef to the memory buffer, it should have a null char at
2987   // the EOF, so it is also safe.
2988   SpellingBuffer.resize(Tok.getLength() + 1);
2989 
2990   // Get the spelling of the token, which eliminates trigraphs, etc.
2991   bool Invalid = false;
2992   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2993   if (Invalid)
2994     return ExprError();
2995 
2996   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2997   if (Literal.hadError)
2998     return ExprError();
2999 
3000   if (Literal.hasUDSuffix()) {
3001     // We're building a user-defined literal.
3002     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
3003     SourceLocation UDSuffixLoc =
3004       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
3005 
3006     // Make sure we're allowed user-defined literals here.
3007     if (!UDLScope)
3008       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
3009 
3010     QualType CookedTy;
3011     if (Literal.isFloatingLiteral()) {
3012       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
3013       // long double, the literal is treated as a call of the form
3014       //   operator "" X (f L)
3015       CookedTy = Context.LongDoubleTy;
3016     } else {
3017       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
3018       // unsigned long long, the literal is treated as a call of the form
3019       //   operator "" X (n ULL)
3020       CookedTy = Context.UnsignedLongLongTy;
3021     }
3022 
3023     DeclarationName OpName =
3024       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
3025     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
3026     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
3027 
3028     SourceLocation TokLoc = Tok.getLocation();
3029 
3030     // Perform literal operator lookup to determine if we're building a raw
3031     // literal or a cooked one.
3032     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
3033     switch (LookupLiteralOperator(UDLScope, R, CookedTy,
3034                                   /*AllowRaw*/true, /*AllowTemplate*/true,
3035                                   /*AllowStringTemplate*/false)) {
3036     case LOLR_Error:
3037       return ExprError();
3038 
3039     case LOLR_Cooked: {
3040       Expr *Lit;
3041       if (Literal.isFloatingLiteral()) {
3042         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
3043       } else {
3044         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
3045         if (Literal.GetIntegerValue(ResultVal))
3046           Diag(Tok.getLocation(), diag::err_integer_too_large);
3047         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
3048                                      Tok.getLocation());
3049       }
3050       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3051     }
3052 
3053     case LOLR_Raw: {
3054       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
3055       // literal is treated as a call of the form
3056       //   operator "" X ("n")
3057       unsigned Length = Literal.getUDSuffixOffset();
3058       QualType StrTy = Context.getConstantArrayType(
3059           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
3060           ArrayType::Normal, 0);
3061       Expr *Lit = StringLiteral::Create(
3062           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
3063           /*Pascal*/false, StrTy, &TokLoc, 1);
3064       return BuildLiteralOperatorCall(R, OpNameInfo, Lit, TokLoc);
3065     }
3066 
3067     case LOLR_Template: {
3068       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
3069       // template), L is treated as a call fo the form
3070       //   operator "" X <'c1', 'c2', ... 'ck'>()
3071       // where n is the source character sequence c1 c2 ... ck.
3072       TemplateArgumentListInfo ExplicitArgs;
3073       unsigned CharBits = Context.getIntWidth(Context.CharTy);
3074       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
3075       llvm::APSInt Value(CharBits, CharIsUnsigned);
3076       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
3077         Value = TokSpelling[I];
3078         TemplateArgument Arg(Context, Value, Context.CharTy);
3079         TemplateArgumentLocInfo ArgInfo;
3080         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
3081       }
3082       return BuildLiteralOperatorCall(R, OpNameInfo, None, TokLoc,
3083                                       &ExplicitArgs);
3084     }
3085     case LOLR_StringTemplate:
3086       llvm_unreachable("unexpected literal operator lookup result");
3087     }
3088   }
3089 
3090   Expr *Res;
3091 
3092   if (Literal.isFloatingLiteral()) {
3093     QualType Ty;
3094     if (Literal.isFloat)
3095       Ty = Context.FloatTy;
3096     else if (!Literal.isLong)
3097       Ty = Context.DoubleTy;
3098     else
3099       Ty = Context.LongDoubleTy;
3100 
3101     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
3102 
3103     if (Ty == Context.DoubleTy) {
3104       if (getLangOpts().SinglePrecisionConstants) {
3105         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3106       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
3107         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
3108         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
3109       }
3110     }
3111   } else if (!Literal.isIntegerLiteral()) {
3112     return ExprError();
3113   } else {
3114     QualType Ty;
3115 
3116     // 'long long' is a C99 or C++11 feature.
3117     if (!getLangOpts().C99 && Literal.isLongLong) {
3118       if (getLangOpts().CPlusPlus)
3119         Diag(Tok.getLocation(),
3120              getLangOpts().CPlusPlus11 ?
3121              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
3122       else
3123         Diag(Tok.getLocation(), diag::ext_c99_longlong);
3124     }
3125 
3126     // Get the value in the widest-possible width.
3127     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
3128     // The microsoft literal suffix extensions support 128-bit literals, which
3129     // may be wider than [u]intmax_t.
3130     // FIXME: Actually, they don't. We seem to have accidentally invented the
3131     //        i128 suffix.
3132     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
3133         PP.getTargetInfo().hasInt128Type())
3134       MaxWidth = 128;
3135     llvm::APInt ResultVal(MaxWidth, 0);
3136 
3137     if (Literal.GetIntegerValue(ResultVal)) {
3138       // If this value didn't fit into uintmax_t, error and force to ull.
3139       Diag(Tok.getLocation(), diag::err_integer_too_large);
3140       Ty = Context.UnsignedLongLongTy;
3141       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
3142              "long long is not intmax_t?");
3143     } else {
3144       // If this value fits into a ULL, try to figure out what else it fits into
3145       // according to the rules of C99 6.4.4.1p5.
3146 
3147       // Octal, Hexadecimal, and integers with a U suffix are allowed to
3148       // be an unsigned int.
3149       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
3150 
3151       // Check from smallest to largest, picking the smallest type we can.
3152       unsigned Width = 0;
3153       if (!Literal.isLong && !Literal.isLongLong) {
3154         // Are int/unsigned possibilities?
3155         unsigned IntSize = Context.getTargetInfo().getIntWidth();
3156 
3157         // Does it fit in a unsigned int?
3158         if (ResultVal.isIntN(IntSize)) {
3159           // Does it fit in a signed int?
3160           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
3161             Ty = Context.IntTy;
3162           else if (AllowUnsigned)
3163             Ty = Context.UnsignedIntTy;
3164           Width = IntSize;
3165         }
3166       }
3167 
3168       // Are long/unsigned long possibilities?
3169       if (Ty.isNull() && !Literal.isLongLong) {
3170         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3171 
3172         // Does it fit in a unsigned long?
3173         if (ResultVal.isIntN(LongSize)) {
3174           // Does it fit in a signed long?
3175           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3176             Ty = Context.LongTy;
3177           else if (AllowUnsigned)
3178             Ty = Context.UnsignedLongTy;
3179           Width = LongSize;
3180         }
3181       }
3182 
3183       // Check long long if needed.
3184       if (Ty.isNull()) {
3185         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3186 
3187         // Does it fit in a unsigned long long?
3188         if (ResultVal.isIntN(LongLongSize)) {
3189           // Does it fit in a signed long long?
3190           // To be compatible with MSVC, hex integer literals ending with the
3191           // LL or i64 suffix are always signed in Microsoft mode.
3192           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3193               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3194             Ty = Context.LongLongTy;
3195           else if (AllowUnsigned)
3196             Ty = Context.UnsignedLongLongTy;
3197           Width = LongLongSize;
3198         }
3199       }
3200 
3201       // If it doesn't fit in unsigned long long, and we're using Microsoft
3202       // extensions, then its a 128-bit integer literal.
3203       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3204           PP.getTargetInfo().hasInt128Type()) {
3205         if (Literal.isUnsigned)
3206           Ty = Context.UnsignedInt128Ty;
3207         else
3208           Ty = Context.Int128Ty;
3209         Width = 128;
3210       }
3211 
3212       // If we still couldn't decide a type, we probably have something that
3213       // does not fit in a signed long long, but has no U suffix.
3214       if (Ty.isNull()) {
3215         Diag(Tok.getLocation(), diag::ext_integer_too_large_for_signed);
3216         Ty = Context.UnsignedLongLongTy;
3217         Width = Context.getTargetInfo().getLongLongWidth();
3218       }
3219 
3220       if (ResultVal.getBitWidth() != Width)
3221         ResultVal = ResultVal.trunc(Width);
3222     }
3223     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3224   }
3225 
3226   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3227   if (Literal.isImaginary)
3228     Res = new (Context) ImaginaryLiteral(Res,
3229                                         Context.getComplexType(Res->getType()));
3230 
3231   return Owned(Res);
3232 }
3233 
3234 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3235   assert((E != 0) && "ActOnParenExpr() missing expr");
3236   return Owned(new (Context) ParenExpr(L, R, E));
3237 }
3238 
3239 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3240                                          SourceLocation Loc,
3241                                          SourceRange ArgRange) {
3242   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3243   // scalar or vector data type argument..."
3244   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3245   // type (C99 6.2.5p18) or void.
3246   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3247     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3248       << T << ArgRange;
3249     return true;
3250   }
3251 
3252   assert((T->isVoidType() || !T->isIncompleteType()) &&
3253          "Scalar types should always be complete");
3254   return false;
3255 }
3256 
3257 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3258                                            SourceLocation Loc,
3259                                            SourceRange ArgRange,
3260                                            UnaryExprOrTypeTrait TraitKind) {
3261   // Invalid types must be hard errors for SFINAE in C++.
3262   if (S.LangOpts.CPlusPlus)
3263     return true;
3264 
3265   // C99 6.5.3.4p1:
3266   if (T->isFunctionType() &&
3267       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3268     // sizeof(function)/alignof(function) is allowed as an extension.
3269     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3270       << TraitKind << ArgRange;
3271     return false;
3272   }
3273 
3274   // Allow sizeof(void)/alignof(void) as an extension, unless in OpenCL where
3275   // this is an error (OpenCL v1.1 s6.3.k)
3276   if (T->isVoidType()) {
3277     unsigned DiagID = S.LangOpts.OpenCL ? diag::err_opencl_sizeof_alignof_type
3278                                         : diag::ext_sizeof_alignof_void_type;
3279     S.Diag(Loc, DiagID) << TraitKind << ArgRange;
3280     return false;
3281   }
3282 
3283   return true;
3284 }
3285 
3286 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3287                                              SourceLocation Loc,
3288                                              SourceRange ArgRange,
3289                                              UnaryExprOrTypeTrait TraitKind) {
3290   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3291   // runtime doesn't allow it.
3292   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3293     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3294       << T << (TraitKind == UETT_SizeOf)
3295       << ArgRange;
3296     return true;
3297   }
3298 
3299   return false;
3300 }
3301 
3302 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3303 /// pointer type is equal to T) and emit a warning if it is.
3304 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3305                                      Expr *E) {
3306   // Don't warn if the operation changed the type.
3307   if (T != E->getType())
3308     return;
3309 
3310   // Now look for array decays.
3311   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3312   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3313     return;
3314 
3315   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3316                                              << ICE->getType()
3317                                              << ICE->getSubExpr()->getType();
3318 }
3319 
3320 /// \brief Check the constraints on expression operands to unary type expression
3321 /// and type traits.
3322 ///
3323 /// Completes any types necessary and validates the constraints on the operand
3324 /// expression. The logic mostly mirrors the type-based overload, but may modify
3325 /// the expression as it completes the type for that expression through template
3326 /// instantiation, etc.
3327 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3328                                             UnaryExprOrTypeTrait ExprKind) {
3329   QualType ExprTy = E->getType();
3330   assert(!ExprTy->isReferenceType());
3331 
3332   if (ExprKind == UETT_VecStep)
3333     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3334                                         E->getSourceRange());
3335 
3336   // Whitelist some types as extensions
3337   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3338                                       E->getSourceRange(), ExprKind))
3339     return false;
3340 
3341   if (RequireCompleteExprType(E,
3342                               diag::err_sizeof_alignof_incomplete_type,
3343                               ExprKind, E->getSourceRange()))
3344     return true;
3345 
3346   // Completing the expression's type may have changed it.
3347   ExprTy = E->getType();
3348   assert(!ExprTy->isReferenceType());
3349 
3350   if (ExprTy->isFunctionType()) {
3351     Diag(E->getExprLoc(), diag::err_sizeof_alignof_function_type)
3352       << ExprKind << E->getSourceRange();
3353     return true;
3354   }
3355 
3356   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3357                                        E->getSourceRange(), ExprKind))
3358     return true;
3359 
3360   if (ExprKind == UETT_SizeOf) {
3361     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3362       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3363         QualType OType = PVD->getOriginalType();
3364         QualType Type = PVD->getType();
3365         if (Type->isPointerType() && OType->isArrayType()) {
3366           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3367             << Type << OType;
3368           Diag(PVD->getLocation(), diag::note_declared_at);
3369         }
3370       }
3371     }
3372 
3373     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3374     // decays into a pointer and returns an unintended result. This is most
3375     // likely a typo for "sizeof(array) op x".
3376     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3377       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3378                                BO->getLHS());
3379       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3380                                BO->getRHS());
3381     }
3382   }
3383 
3384   return false;
3385 }
3386 
3387 /// \brief Check the constraints on operands to unary expression and type
3388 /// traits.
3389 ///
3390 /// This will complete any types necessary, and validate the various constraints
3391 /// on those operands.
3392 ///
3393 /// The UsualUnaryConversions() function is *not* called by this routine.
3394 /// C99 6.3.2.1p[2-4] all state:
3395 ///   Except when it is the operand of the sizeof operator ...
3396 ///
3397 /// C++ [expr.sizeof]p4
3398 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3399 ///   standard conversions are not applied to the operand of sizeof.
3400 ///
3401 /// This policy is followed for all of the unary trait expressions.
3402 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3403                                             SourceLocation OpLoc,
3404                                             SourceRange ExprRange,
3405                                             UnaryExprOrTypeTrait ExprKind) {
3406   if (ExprType->isDependentType())
3407     return false;
3408 
3409   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3410   //   the result is the size of the referenced type."
3411   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3412   //   result shall be the alignment of the referenced type."
3413   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3414     ExprType = Ref->getPointeeType();
3415 
3416   if (ExprKind == UETT_VecStep)
3417     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3418 
3419   // Whitelist some types as extensions
3420   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3421                                       ExprKind))
3422     return false;
3423 
3424   if (RequireCompleteType(OpLoc, ExprType,
3425                           diag::err_sizeof_alignof_incomplete_type,
3426                           ExprKind, ExprRange))
3427     return true;
3428 
3429   if (ExprType->isFunctionType()) {
3430     Diag(OpLoc, diag::err_sizeof_alignof_function_type)
3431       << ExprKind << ExprRange;
3432     return true;
3433   }
3434 
3435   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3436                                        ExprKind))
3437     return true;
3438 
3439   return false;
3440 }
3441 
3442 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3443   E = E->IgnoreParens();
3444 
3445   // Cannot know anything else if the expression is dependent.
3446   if (E->isTypeDependent())
3447     return false;
3448 
3449   if (E->getObjectKind() == OK_BitField) {
3450     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3451        << 1 << E->getSourceRange();
3452     return true;
3453   }
3454 
3455   ValueDecl *D = 0;
3456   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3457     D = DRE->getDecl();
3458   } else if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3459     D = ME->getMemberDecl();
3460   }
3461 
3462   // If it's a field, require the containing struct to have a
3463   // complete definition so that we can compute the layout.
3464   //
3465   // This requires a very particular set of circumstances.  For a
3466   // field to be contained within an incomplete type, we must in the
3467   // process of parsing that type.  To have an expression refer to a
3468   // field, it must be an id-expression or a member-expression, but
3469   // the latter are always ill-formed when the base type is
3470   // incomplete, including only being partially complete.  An
3471   // id-expression can never refer to a field in C because fields
3472   // are not in the ordinary namespace.  In C++, an id-expression
3473   // can implicitly be a member access, but only if there's an
3474   // implicit 'this' value, and all such contexts are subject to
3475   // delayed parsing --- except for trailing return types in C++11.
3476   // And if an id-expression referring to a field occurs in a
3477   // context that lacks a 'this' value, it's ill-formed --- except,
3478   // again, in C++11, where such references are allowed in an
3479   // unevaluated context.  So C++11 introduces some new complexity.
3480   //
3481   // For the record, since __alignof__ on expressions is a GCC
3482   // extension, GCC seems to permit this but always gives the
3483   // nonsensical answer 0.
3484   //
3485   // We don't really need the layout here --- we could instead just
3486   // directly check for all the appropriate alignment-lowing
3487   // attributes --- but that would require duplicating a lot of
3488   // logic that just isn't worth duplicating for such a marginal
3489   // use-case.
3490   if (FieldDecl *FD = dyn_cast_or_null<FieldDecl>(D)) {
3491     // Fast path this check, since we at least know the record has a
3492     // definition if we can find a member of it.
3493     if (!FD->getParent()->isCompleteDefinition()) {
3494       S.Diag(E->getExprLoc(), diag::err_alignof_member_of_incomplete_type)
3495         << E->getSourceRange();
3496       return true;
3497     }
3498 
3499     // Otherwise, if it's a field, and the field doesn't have
3500     // reference type, then it must have a complete type (or be a
3501     // flexible array member, which we explicitly want to
3502     // white-list anyway), which makes the following checks trivial.
3503     if (!FD->getType()->isReferenceType())
3504       return false;
3505   }
3506 
3507   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3508 }
3509 
3510 bool Sema::CheckVecStepExpr(Expr *E) {
3511   E = E->IgnoreParens();
3512 
3513   // Cannot know anything else if the expression is dependent.
3514   if (E->isTypeDependent())
3515     return false;
3516 
3517   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3518 }
3519 
3520 /// \brief Build a sizeof or alignof expression given a type operand.
3521 ExprResult
3522 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3523                                      SourceLocation OpLoc,
3524                                      UnaryExprOrTypeTrait ExprKind,
3525                                      SourceRange R) {
3526   if (!TInfo)
3527     return ExprError();
3528 
3529   QualType T = TInfo->getType();
3530 
3531   if (!T->isDependentType() &&
3532       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3533     return ExprError();
3534 
3535   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3536   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3537                                                       Context.getSizeType(),
3538                                                       OpLoc, R.getEnd()));
3539 }
3540 
3541 /// \brief Build a sizeof or alignof expression given an expression
3542 /// operand.
3543 ExprResult
3544 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3545                                      UnaryExprOrTypeTrait ExprKind) {
3546   ExprResult PE = CheckPlaceholderExpr(E);
3547   if (PE.isInvalid())
3548     return ExprError();
3549 
3550   E = PE.get();
3551 
3552   // Verify that the operand is valid.
3553   bool isInvalid = false;
3554   if (E->isTypeDependent()) {
3555     // Delay type-checking for type-dependent expressions.
3556   } else if (ExprKind == UETT_AlignOf) {
3557     isInvalid = CheckAlignOfExpr(*this, E);
3558   } else if (ExprKind == UETT_VecStep) {
3559     isInvalid = CheckVecStepExpr(E);
3560   } else if (E->refersToBitField()) {  // C99 6.5.3.4p1.
3561     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3562     isInvalid = true;
3563   } else {
3564     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3565   }
3566 
3567   if (isInvalid)
3568     return ExprError();
3569 
3570   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3571     PE = TransformToPotentiallyEvaluated(E);
3572     if (PE.isInvalid()) return ExprError();
3573     E = PE.take();
3574   }
3575 
3576   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3577   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3578       ExprKind, E, Context.getSizeType(), OpLoc,
3579       E->getSourceRange().getEnd()));
3580 }
3581 
3582 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3583 /// expr and the same for @c alignof and @c __alignof
3584 /// Note that the ArgRange is invalid if isType is false.
3585 ExprResult
3586 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3587                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3588                                     void *TyOrEx, const SourceRange &ArgRange) {
3589   // If error parsing type, ignore.
3590   if (TyOrEx == 0) return ExprError();
3591 
3592   if (IsType) {
3593     TypeSourceInfo *TInfo;
3594     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3595     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3596   }
3597 
3598   Expr *ArgEx = (Expr *)TyOrEx;
3599   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3600   return Result;
3601 }
3602 
3603 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3604                                      bool IsReal) {
3605   if (V.get()->isTypeDependent())
3606     return S.Context.DependentTy;
3607 
3608   // _Real and _Imag are only l-values for normal l-values.
3609   if (V.get()->getObjectKind() != OK_Ordinary) {
3610     V = S.DefaultLvalueConversion(V.take());
3611     if (V.isInvalid())
3612       return QualType();
3613   }
3614 
3615   // These operators return the element type of a complex type.
3616   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3617     return CT->getElementType();
3618 
3619   // Otherwise they pass through real integer and floating point types here.
3620   if (V.get()->getType()->isArithmeticType())
3621     return V.get()->getType();
3622 
3623   // Test for placeholders.
3624   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3625   if (PR.isInvalid()) return QualType();
3626   if (PR.get() != V.get()) {
3627     V = PR;
3628     return CheckRealImagOperand(S, V, Loc, IsReal);
3629   }
3630 
3631   // Reject anything else.
3632   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3633     << (IsReal ? "__real" : "__imag");
3634   return QualType();
3635 }
3636 
3637 
3638 
3639 ExprResult
3640 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3641                           tok::TokenKind Kind, Expr *Input) {
3642   UnaryOperatorKind Opc;
3643   switch (Kind) {
3644   default: llvm_unreachable("Unknown unary op!");
3645   case tok::plusplus:   Opc = UO_PostInc; break;
3646   case tok::minusminus: Opc = UO_PostDec; break;
3647   }
3648 
3649   // Since this might is a postfix expression, get rid of ParenListExprs.
3650   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3651   if (Result.isInvalid()) return ExprError();
3652   Input = Result.take();
3653 
3654   return BuildUnaryOp(S, OpLoc, Opc, Input);
3655 }
3656 
3657 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3658 ///
3659 /// \return true on error
3660 static bool checkArithmeticOnObjCPointer(Sema &S,
3661                                          SourceLocation opLoc,
3662                                          Expr *op) {
3663   assert(op->getType()->isObjCObjectPointerType());
3664   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic() &&
3665       !S.LangOpts.ObjCSubscriptingLegacyRuntime)
3666     return false;
3667 
3668   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3669     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3670     << op->getSourceRange();
3671   return true;
3672 }
3673 
3674 ExprResult
3675 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3676                               Expr *idx, SourceLocation rbLoc) {
3677   // Since this might be a postfix expression, get rid of ParenListExprs.
3678   if (isa<ParenListExpr>(base)) {
3679     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3680     if (result.isInvalid()) return ExprError();
3681     base = result.take();
3682   }
3683 
3684   // Handle any non-overload placeholder types in the base and index
3685   // expressions.  We can't handle overloads here because the other
3686   // operand might be an overloadable type, in which case the overload
3687   // resolution for the operator overload should get the first crack
3688   // at the overload.
3689   if (base->getType()->isNonOverloadPlaceholderType()) {
3690     ExprResult result = CheckPlaceholderExpr(base);
3691     if (result.isInvalid()) return ExprError();
3692     base = result.take();
3693   }
3694   if (idx->getType()->isNonOverloadPlaceholderType()) {
3695     ExprResult result = CheckPlaceholderExpr(idx);
3696     if (result.isInvalid()) return ExprError();
3697     idx = result.take();
3698   }
3699 
3700   // Build an unanalyzed expression if either operand is type-dependent.
3701   if (getLangOpts().CPlusPlus &&
3702       (base->isTypeDependent() || idx->isTypeDependent())) {
3703     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3704                                                   Context.DependentTy,
3705                                                   VK_LValue, OK_Ordinary,
3706                                                   rbLoc));
3707   }
3708 
3709   // Use C++ overloaded-operator rules if either operand has record
3710   // type.  The spec says to do this if either type is *overloadable*,
3711   // but enum types can't declare subscript operators or conversion
3712   // operators, so there's nothing interesting for overload resolution
3713   // to do if there aren't any record types involved.
3714   //
3715   // ObjC pointers have their own subscripting logic that is not tied
3716   // to overload resolution and so should not take this path.
3717   if (getLangOpts().CPlusPlus &&
3718       (base->getType()->isRecordType() ||
3719        (!base->getType()->isObjCObjectPointerType() &&
3720         idx->getType()->isRecordType()))) {
3721     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3722   }
3723 
3724   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3725 }
3726 
3727 ExprResult
3728 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3729                                       Expr *Idx, SourceLocation RLoc) {
3730   Expr *LHSExp = Base;
3731   Expr *RHSExp = Idx;
3732 
3733   // Perform default conversions.
3734   if (!LHSExp->getType()->getAs<VectorType>()) {
3735     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3736     if (Result.isInvalid())
3737       return ExprError();
3738     LHSExp = Result.take();
3739   }
3740   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3741   if (Result.isInvalid())
3742     return ExprError();
3743   RHSExp = Result.take();
3744 
3745   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3746   ExprValueKind VK = VK_LValue;
3747   ExprObjectKind OK = OK_Ordinary;
3748 
3749   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3750   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3751   // in the subscript position. As a result, we need to derive the array base
3752   // and index from the expression types.
3753   Expr *BaseExpr, *IndexExpr;
3754   QualType ResultType;
3755   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3756     BaseExpr = LHSExp;
3757     IndexExpr = RHSExp;
3758     ResultType = Context.DependentTy;
3759   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3760     BaseExpr = LHSExp;
3761     IndexExpr = RHSExp;
3762     ResultType = PTy->getPointeeType();
3763   } else if (const ObjCObjectPointerType *PTy =
3764                LHSTy->getAs<ObjCObjectPointerType>()) {
3765     BaseExpr = LHSExp;
3766     IndexExpr = RHSExp;
3767 
3768     // Use custom logic if this should be the pseudo-object subscript
3769     // expression.
3770     if (!LangOpts.isSubscriptPointerArithmetic())
3771       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3772 
3773     ResultType = PTy->getPointeeType();
3774   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3775      // Handle the uncommon case of "123[Ptr]".
3776     BaseExpr = RHSExp;
3777     IndexExpr = LHSExp;
3778     ResultType = PTy->getPointeeType();
3779   } else if (const ObjCObjectPointerType *PTy =
3780                RHSTy->getAs<ObjCObjectPointerType>()) {
3781      // Handle the uncommon case of "123[Ptr]".
3782     BaseExpr = RHSExp;
3783     IndexExpr = LHSExp;
3784     ResultType = PTy->getPointeeType();
3785     if (!LangOpts.isSubscriptPointerArithmetic()) {
3786       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3787         << ResultType << BaseExpr->getSourceRange();
3788       return ExprError();
3789     }
3790   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3791     BaseExpr = LHSExp;    // vectors: V[123]
3792     IndexExpr = RHSExp;
3793     VK = LHSExp->getValueKind();
3794     if (VK != VK_RValue)
3795       OK = OK_VectorComponent;
3796 
3797     // FIXME: need to deal with const...
3798     ResultType = VTy->getElementType();
3799   } else if (LHSTy->isArrayType()) {
3800     // If we see an array that wasn't promoted by
3801     // DefaultFunctionArrayLvalueConversion, it must be an array that
3802     // wasn't promoted because of the C90 rule that doesn't
3803     // allow promoting non-lvalue arrays.  Warn, then
3804     // force the promotion here.
3805     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3806         LHSExp->getSourceRange();
3807     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3808                                CK_ArrayToPointerDecay).take();
3809     LHSTy = LHSExp->getType();
3810 
3811     BaseExpr = LHSExp;
3812     IndexExpr = RHSExp;
3813     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3814   } else if (RHSTy->isArrayType()) {
3815     // Same as previous, except for 123[f().a] case
3816     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3817         RHSExp->getSourceRange();
3818     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3819                                CK_ArrayToPointerDecay).take();
3820     RHSTy = RHSExp->getType();
3821 
3822     BaseExpr = RHSExp;
3823     IndexExpr = LHSExp;
3824     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3825   } else {
3826     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3827        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3828   }
3829   // C99 6.5.2.1p1
3830   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3831     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3832                      << IndexExpr->getSourceRange());
3833 
3834   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3835        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3836          && !IndexExpr->isTypeDependent())
3837     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3838 
3839   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3840   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3841   // type. Note that Functions are not objects, and that (in C99 parlance)
3842   // incomplete types are not object types.
3843   if (ResultType->isFunctionType()) {
3844     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3845       << ResultType << BaseExpr->getSourceRange();
3846     return ExprError();
3847   }
3848 
3849   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3850     // GNU extension: subscripting on pointer to void
3851     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3852       << BaseExpr->getSourceRange();
3853 
3854     // C forbids expressions of unqualified void type from being l-values.
3855     // See IsCForbiddenLValueType.
3856     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3857   } else if (!ResultType->isDependentType() &&
3858       RequireCompleteType(LLoc, ResultType,
3859                           diag::err_subscript_incomplete_type, BaseExpr))
3860     return ExprError();
3861 
3862   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3863          !ResultType.isCForbiddenLValueType());
3864 
3865   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3866                                                 ResultType, VK, OK, RLoc));
3867 }
3868 
3869 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3870                                         FunctionDecl *FD,
3871                                         ParmVarDecl *Param) {
3872   if (Param->hasUnparsedDefaultArg()) {
3873     Diag(CallLoc,
3874          diag::err_use_of_default_argument_to_function_declared_later) <<
3875       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3876     Diag(UnparsedDefaultArgLocs[Param],
3877          diag::note_default_argument_declared_here);
3878     return ExprError();
3879   }
3880 
3881   if (Param->hasUninstantiatedDefaultArg()) {
3882     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3883 
3884     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3885                                                  Param);
3886 
3887     // Instantiate the expression.
3888     MultiLevelTemplateArgumentList MutiLevelArgList
3889       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3890 
3891     InstantiatingTemplate Inst(*this, CallLoc, Param,
3892                                MutiLevelArgList.getInnermost());
3893     if (Inst.isInvalid())
3894       return ExprError();
3895 
3896     ExprResult Result;
3897     {
3898       // C++ [dcl.fct.default]p5:
3899       //   The names in the [default argument] expression are bound, and
3900       //   the semantic constraints are checked, at the point where the
3901       //   default argument expression appears.
3902       ContextRAII SavedContext(*this, FD);
3903       LocalInstantiationScope Local(*this);
3904       Result = SubstExpr(UninstExpr, MutiLevelArgList);
3905     }
3906     if (Result.isInvalid())
3907       return ExprError();
3908 
3909     // Check the expression as an initializer for the parameter.
3910     InitializedEntity Entity
3911       = InitializedEntity::InitializeParameter(Context, Param);
3912     InitializationKind Kind
3913       = InitializationKind::CreateCopy(Param->getLocation(),
3914              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3915     Expr *ResultE = Result.takeAs<Expr>();
3916 
3917     InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3918     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3919     if (Result.isInvalid())
3920       return ExprError();
3921 
3922     Expr *Arg = Result.takeAs<Expr>();
3923     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3924     // Build the default argument expression.
3925     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3926   }
3927 
3928   // If the default expression creates temporaries, we need to
3929   // push them to the current stack of expression temporaries so they'll
3930   // be properly destroyed.
3931   // FIXME: We should really be rebuilding the default argument with new
3932   // bound temporaries; see the comment in PR5810.
3933   // We don't need to do that with block decls, though, because
3934   // blocks in default argument expression can never capture anything.
3935   if (isa<ExprWithCleanups>(Param->getInit())) {
3936     // Set the "needs cleanups" bit regardless of whether there are
3937     // any explicit objects.
3938     ExprNeedsCleanups = true;
3939 
3940     // Append all the objects to the cleanup list.  Right now, this
3941     // should always be a no-op, because blocks in default argument
3942     // expressions should never be able to capture anything.
3943     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3944            "default argument expression has capturing blocks?");
3945   }
3946 
3947   // We already type-checked the argument, so we know it works.
3948   // Just mark all of the declarations in this potentially-evaluated expression
3949   // as being "referenced".
3950   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3951                                    /*SkipLocalVariables=*/true);
3952   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3953 }
3954 
3955 
3956 Sema::VariadicCallType
3957 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3958                           Expr *Fn) {
3959   if (Proto && Proto->isVariadic()) {
3960     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3961       return VariadicConstructor;
3962     else if (Fn && Fn->getType()->isBlockPointerType())
3963       return VariadicBlock;
3964     else if (FDecl) {
3965       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3966         if (Method->isInstance())
3967           return VariadicMethod;
3968     } else if (Fn && Fn->getType() == Context.BoundMemberTy)
3969       return VariadicMethod;
3970     return VariadicFunction;
3971   }
3972   return VariadicDoesNotApply;
3973 }
3974 
3975 namespace {
3976 class FunctionCallCCC : public FunctionCallFilterCCC {
3977 public:
3978   FunctionCallCCC(Sema &SemaRef, const IdentifierInfo *FuncName,
3979                   unsigned NumArgs, MemberExpr *ME)
3980       : FunctionCallFilterCCC(SemaRef, NumArgs, false, ME),
3981         FunctionName(FuncName) {}
3982 
3983   bool ValidateCandidate(const TypoCorrection &candidate) override {
3984     if (!candidate.getCorrectionSpecifier() ||
3985         candidate.getCorrectionAsIdentifierInfo() != FunctionName) {
3986       return false;
3987     }
3988 
3989     return FunctionCallFilterCCC::ValidateCandidate(candidate);
3990   }
3991 
3992 private:
3993   const IdentifierInfo *const FunctionName;
3994 };
3995 }
3996 
3997 static TypoCorrection TryTypoCorrectionForCall(Sema &S, Expr *Fn,
3998                                                FunctionDecl *FDecl,
3999                                                ArrayRef<Expr *> Args) {
4000   MemberExpr *ME = dyn_cast<MemberExpr>(Fn);
4001   DeclarationName FuncName = FDecl->getDeclName();
4002   SourceLocation NameLoc = ME ? ME->getMemberLoc() : Fn->getLocStart();
4003   FunctionCallCCC CCC(S, FuncName.getAsIdentifierInfo(), Args.size(), ME);
4004 
4005   if (TypoCorrection Corrected = S.CorrectTypo(
4006           DeclarationNameInfo(FuncName, NameLoc), Sema::LookupOrdinaryName,
4007           S.getScopeForContext(S.CurContext), NULL, CCC,
4008           Sema::CTK_ErrorRecovery)) {
4009     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
4010       if (Corrected.isOverloaded()) {
4011         OverloadCandidateSet OCS(NameLoc, OverloadCandidateSet::CSK_Normal);
4012         OverloadCandidateSet::iterator Best;
4013         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
4014                                            CDEnd = Corrected.end();
4015              CD != CDEnd; ++CD) {
4016           if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
4017             S.AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none), Args,
4018                                    OCS);
4019         }
4020         switch (OCS.BestViableFunction(S, NameLoc, Best)) {
4021         case OR_Success:
4022           ND = Best->Function;
4023           Corrected.setCorrectionDecl(ND);
4024           break;
4025         default:
4026           break;
4027         }
4028       }
4029       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
4030         return Corrected;
4031       }
4032     }
4033   }
4034   return TypoCorrection();
4035 }
4036 
4037 /// ConvertArgumentsForCall - Converts the arguments specified in
4038 /// Args/NumArgs to the parameter types of the function FDecl with
4039 /// function prototype Proto. Call is the call expression itself, and
4040 /// Fn is the function expression. For a C++ member function, this
4041 /// routine does not attempt to convert the object argument. Returns
4042 /// true if the call is ill-formed.
4043 bool
4044 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
4045                               FunctionDecl *FDecl,
4046                               const FunctionProtoType *Proto,
4047                               ArrayRef<Expr *> Args,
4048                               SourceLocation RParenLoc,
4049                               bool IsExecConfig) {
4050   // Bail out early if calling a builtin with custom typechecking.
4051   // We don't need to do this in the
4052   if (FDecl)
4053     if (unsigned ID = FDecl->getBuiltinID())
4054       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
4055         return false;
4056 
4057   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
4058   // assignment, to the types of the corresponding parameter, ...
4059   unsigned NumParams = Proto->getNumParams();
4060   bool Invalid = false;
4061   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumParams;
4062   unsigned FnKind = Fn->getType()->isBlockPointerType()
4063                        ? 1 /* block */
4064                        : (IsExecConfig ? 3 /* kernel function (exec config) */
4065                                        : 0 /* function */);
4066 
4067   // If too few arguments are available (and we don't have default
4068   // arguments for the remaining parameters), don't make the call.
4069   if (Args.size() < NumParams) {
4070     if (Args.size() < MinArgs) {
4071       TypoCorrection TC;
4072       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4073         unsigned diag_id =
4074             MinArgs == NumParams && !Proto->isVariadic()
4075                 ? diag::err_typecheck_call_too_few_args_suggest
4076                 : diag::err_typecheck_call_too_few_args_at_least_suggest;
4077         diagnoseTypo(TC, PDiag(diag_id) << FnKind << MinArgs
4078                                         << static_cast<unsigned>(Args.size())
4079                                         << TC.getCorrectionRange());
4080       } else if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
4081         Diag(RParenLoc,
4082              MinArgs == NumParams && !Proto->isVariadic()
4083                  ? diag::err_typecheck_call_too_few_args_one
4084                  : diag::err_typecheck_call_too_few_args_at_least_one)
4085             << FnKind << FDecl->getParamDecl(0) << Fn->getSourceRange();
4086       else
4087         Diag(RParenLoc, MinArgs == NumParams && !Proto->isVariadic()
4088                             ? diag::err_typecheck_call_too_few_args
4089                             : diag::err_typecheck_call_too_few_args_at_least)
4090             << FnKind << MinArgs << static_cast<unsigned>(Args.size())
4091             << Fn->getSourceRange();
4092 
4093       // Emit the location of the prototype.
4094       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4095         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4096           << FDecl;
4097 
4098       return true;
4099     }
4100     Call->setNumArgs(Context, NumParams);
4101   }
4102 
4103   // If too many are passed and not variadic, error on the extras and drop
4104   // them.
4105   if (Args.size() > NumParams) {
4106     if (!Proto->isVariadic()) {
4107       TypoCorrection TC;
4108       if (FDecl && (TC = TryTypoCorrectionForCall(*this, Fn, FDecl, Args))) {
4109         unsigned diag_id =
4110             MinArgs == NumParams && !Proto->isVariadic()
4111                 ? diag::err_typecheck_call_too_many_args_suggest
4112                 : diag::err_typecheck_call_too_many_args_at_most_suggest;
4113         diagnoseTypo(TC, PDiag(diag_id) << FnKind << NumParams
4114                                         << static_cast<unsigned>(Args.size())
4115                                         << TC.getCorrectionRange());
4116       } else if (NumParams == 1 && FDecl &&
4117                  FDecl->getParamDecl(0)->getDeclName())
4118         Diag(Args[NumParams]->getLocStart(),
4119              MinArgs == NumParams
4120                  ? diag::err_typecheck_call_too_many_args_one
4121                  : diag::err_typecheck_call_too_many_args_at_most_one)
4122             << FnKind << FDecl->getParamDecl(0)
4123             << static_cast<unsigned>(Args.size()) << Fn->getSourceRange()
4124             << SourceRange(Args[NumParams]->getLocStart(),
4125                            Args.back()->getLocEnd());
4126       else
4127         Diag(Args[NumParams]->getLocStart(),
4128              MinArgs == NumParams
4129                  ? diag::err_typecheck_call_too_many_args
4130                  : diag::err_typecheck_call_too_many_args_at_most)
4131             << FnKind << NumParams << static_cast<unsigned>(Args.size())
4132             << Fn->getSourceRange()
4133             << SourceRange(Args[NumParams]->getLocStart(),
4134                            Args.back()->getLocEnd());
4135 
4136       // Emit the location of the prototype.
4137       if (!TC && FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
4138         Diag(FDecl->getLocStart(), diag::note_callee_decl)
4139           << FDecl;
4140 
4141       // This deletes the extra arguments.
4142       Call->setNumArgs(Context, NumParams);
4143       return true;
4144     }
4145   }
4146   SmallVector<Expr *, 8> AllArgs;
4147   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
4148 
4149   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
4150                                    Proto, 0, Args, AllArgs, CallType);
4151   if (Invalid)
4152     return true;
4153   unsigned TotalNumArgs = AllArgs.size();
4154   for (unsigned i = 0; i < TotalNumArgs; ++i)
4155     Call->setArg(i, AllArgs[i]);
4156 
4157   return false;
4158 }
4159 
4160 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl,
4161                                   const FunctionProtoType *Proto,
4162                                   unsigned FirstParam, ArrayRef<Expr *> Args,
4163                                   SmallVectorImpl<Expr *> &AllArgs,
4164                                   VariadicCallType CallType, bool AllowExplicit,
4165                                   bool IsListInitialization) {
4166   unsigned NumParams = Proto->getNumParams();
4167   unsigned NumArgsToCheck = Args.size();
4168   bool Invalid = false;
4169   if (Args.size() != NumParams)
4170     // Use default arguments for missing arguments
4171     NumArgsToCheck = NumParams;
4172   unsigned ArgIx = 0;
4173   // Continue to check argument types (even if we have too few/many args).
4174   for (unsigned i = FirstParam; i != NumArgsToCheck; i++) {
4175     QualType ProtoArgType = Proto->getParamType(i);
4176 
4177     Expr *Arg;
4178     ParmVarDecl *Param;
4179     if (ArgIx < Args.size()) {
4180       Arg = Args[ArgIx++];
4181 
4182       if (RequireCompleteType(Arg->getLocStart(),
4183                               ProtoArgType,
4184                               diag::err_call_incomplete_argument, Arg))
4185         return true;
4186 
4187       // Pass the argument
4188       Param = 0;
4189       if (FDecl && i < FDecl->getNumParams())
4190         Param = FDecl->getParamDecl(i);
4191 
4192       // Strip the unbridged-cast placeholder expression off, if applicable.
4193       bool CFAudited = false;
4194       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
4195           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4196           (!Param || !Param->hasAttr<CFConsumedAttr>()))
4197         Arg = stripARCUnbridgedCast(Arg);
4198       else if (getLangOpts().ObjCAutoRefCount &&
4199                FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
4200                (!Param || !Param->hasAttr<CFConsumedAttr>()))
4201         CFAudited = true;
4202 
4203       InitializedEntity Entity =
4204           Param ? InitializedEntity::InitializeParameter(Context, Param,
4205                                                          ProtoArgType)
4206                 : InitializedEntity::InitializeParameter(
4207                       Context, ProtoArgType, Proto->isParamConsumed(i));
4208 
4209       // Remember that parameter belongs to a CF audited API.
4210       if (CFAudited)
4211         Entity.setParameterCFAudited();
4212 
4213       ExprResult ArgE = PerformCopyInitialization(Entity,
4214                                                   SourceLocation(),
4215                                                   Owned(Arg),
4216                                                   IsListInitialization,
4217                                                   AllowExplicit);
4218       if (ArgE.isInvalid())
4219         return true;
4220 
4221       Arg = ArgE.takeAs<Expr>();
4222     } else {
4223       assert(FDecl && "can't use default arguments without a known callee");
4224       Param = FDecl->getParamDecl(i);
4225 
4226       ExprResult ArgExpr =
4227         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
4228       if (ArgExpr.isInvalid())
4229         return true;
4230 
4231       Arg = ArgExpr.takeAs<Expr>();
4232     }
4233 
4234     // Check for array bounds violations for each argument to the call. This
4235     // check only triggers warnings when the argument isn't a more complex Expr
4236     // with its own checking, such as a BinaryOperator.
4237     CheckArrayAccess(Arg);
4238 
4239     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
4240     CheckStaticArrayArgument(CallLoc, Param, Arg);
4241 
4242     AllArgs.push_back(Arg);
4243   }
4244 
4245   // If this is a variadic call, handle args passed through "...".
4246   if (CallType != VariadicDoesNotApply) {
4247     // Assume that extern "C" functions with variadic arguments that
4248     // return __unknown_anytype aren't *really* variadic.
4249     if (Proto->getReturnType() == Context.UnknownAnyTy && FDecl &&
4250         FDecl->isExternC()) {
4251       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4252         QualType paramType; // ignored
4253         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
4254         Invalid |= arg.isInvalid();
4255         AllArgs.push_back(arg.take());
4256       }
4257 
4258     // Otherwise do argument promotion, (C99 6.5.2.2p7).
4259     } else {
4260       for (unsigned i = ArgIx, e = Args.size(); i != e; ++i) {
4261         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
4262                                                           FDecl);
4263         Invalid |= Arg.isInvalid();
4264         AllArgs.push_back(Arg.take());
4265       }
4266     }
4267 
4268     // Check for array bounds violations.
4269     for (unsigned i = ArgIx, e = Args.size(); i != e; ++i)
4270       CheckArrayAccess(Args[i]);
4271   }
4272   return Invalid;
4273 }
4274 
4275 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
4276   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
4277   if (DecayedTypeLoc DTL = TL.getAs<DecayedTypeLoc>())
4278     TL = DTL.getOriginalLoc();
4279   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
4280     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
4281       << ATL.getLocalSourceRange();
4282 }
4283 
4284 /// CheckStaticArrayArgument - If the given argument corresponds to a static
4285 /// array parameter, check that it is non-null, and that if it is formed by
4286 /// array-to-pointer decay, the underlying array is sufficiently large.
4287 ///
4288 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
4289 /// array type derivation, then for each call to the function, the value of the
4290 /// corresponding actual argument shall provide access to the first element of
4291 /// an array with at least as many elements as specified by the size expression.
4292 void
4293 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
4294                                ParmVarDecl *Param,
4295                                const Expr *ArgExpr) {
4296   // Static array parameters are not supported in C++.
4297   if (!Param || getLangOpts().CPlusPlus)
4298     return;
4299 
4300   QualType OrigTy = Param->getOriginalType();
4301 
4302   const ArrayType *AT = Context.getAsArrayType(OrigTy);
4303   if (!AT || AT->getSizeModifier() != ArrayType::Static)
4304     return;
4305 
4306   if (ArgExpr->isNullPointerConstant(Context,
4307                                      Expr::NPC_NeverValueDependent)) {
4308     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4309     DiagnoseCalleeStaticArrayParam(*this, Param);
4310     return;
4311   }
4312 
4313   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4314   if (!CAT)
4315     return;
4316 
4317   const ConstantArrayType *ArgCAT =
4318     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4319   if (!ArgCAT)
4320     return;
4321 
4322   if (ArgCAT->getSize().ult(CAT->getSize())) {
4323     Diag(CallLoc, diag::warn_static_array_too_small)
4324       << ArgExpr->getSourceRange()
4325       << (unsigned) ArgCAT->getSize().getZExtValue()
4326       << (unsigned) CAT->getSize().getZExtValue();
4327     DiagnoseCalleeStaticArrayParam(*this, Param);
4328   }
4329 }
4330 
4331 /// Given a function expression of unknown-any type, try to rebuild it
4332 /// to have a function type.
4333 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4334 
4335 /// Is the given type a placeholder that we need to lower out
4336 /// immediately during argument processing?
4337 static bool isPlaceholderToRemoveAsArg(QualType type) {
4338   // Placeholders are never sugared.
4339   const BuiltinType *placeholder = dyn_cast<BuiltinType>(type);
4340   if (!placeholder) return false;
4341 
4342   switch (placeholder->getKind()) {
4343   // Ignore all the non-placeholder types.
4344 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID)
4345 #define BUILTIN_TYPE(ID, SINGLETON_ID) case BuiltinType::ID:
4346 #include "clang/AST/BuiltinTypes.def"
4347     return false;
4348 
4349   // We cannot lower out overload sets; they might validly be resolved
4350   // by the call machinery.
4351   case BuiltinType::Overload:
4352     return false;
4353 
4354   // Unbridged casts in ARC can be handled in some call positions and
4355   // should be left in place.
4356   case BuiltinType::ARCUnbridgedCast:
4357     return false;
4358 
4359   // Pseudo-objects should be converted as soon as possible.
4360   case BuiltinType::PseudoObject:
4361     return true;
4362 
4363   // The debugger mode could theoretically but currently does not try
4364   // to resolve unknown-typed arguments based on known parameter types.
4365   case BuiltinType::UnknownAny:
4366     return true;
4367 
4368   // These are always invalid as call arguments and should be reported.
4369   case BuiltinType::BoundMember:
4370   case BuiltinType::BuiltinFn:
4371     return true;
4372   }
4373   llvm_unreachable("bad builtin type kind");
4374 }
4375 
4376 /// Check an argument list for placeholders that we won't try to
4377 /// handle later.
4378 static bool checkArgsForPlaceholders(Sema &S, MultiExprArg args) {
4379   // Apply this processing to all the arguments at once instead of
4380   // dying at the first failure.
4381   bool hasInvalid = false;
4382   for (size_t i = 0, e = args.size(); i != e; i++) {
4383     if (isPlaceholderToRemoveAsArg(args[i]->getType())) {
4384       ExprResult result = S.CheckPlaceholderExpr(args[i]);
4385       if (result.isInvalid()) hasInvalid = true;
4386       else args[i] = result.take();
4387     }
4388   }
4389   return hasInvalid;
4390 }
4391 
4392 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4393 /// This provides the location of the left/right parens and a list of comma
4394 /// locations.
4395 ExprResult
4396 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4397                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4398                     Expr *ExecConfig, bool IsExecConfig) {
4399   // Since this might be a postfix expression, get rid of ParenListExprs.
4400   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4401   if (Result.isInvalid()) return ExprError();
4402   Fn = Result.take();
4403 
4404   if (checkArgsForPlaceholders(*this, ArgExprs))
4405     return ExprError();
4406 
4407   if (getLangOpts().CPlusPlus) {
4408     // If this is a pseudo-destructor expression, build the call immediately.
4409     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4410       if (!ArgExprs.empty()) {
4411         // Pseudo-destructor calls should not have any arguments.
4412         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4413           << FixItHint::CreateRemoval(
4414                                     SourceRange(ArgExprs[0]->getLocStart(),
4415                                                 ArgExprs.back()->getLocEnd()));
4416       }
4417 
4418       return Owned(new (Context) CallExpr(Context, Fn, None,
4419                                           Context.VoidTy, VK_RValue,
4420                                           RParenLoc));
4421     }
4422     if (Fn->getType() == Context.PseudoObjectTy) {
4423       ExprResult result = CheckPlaceholderExpr(Fn);
4424       if (result.isInvalid()) return ExprError();
4425       Fn = result.take();
4426     }
4427 
4428     // Determine whether this is a dependent call inside a C++ template,
4429     // in which case we won't do any semantic analysis now.
4430     // FIXME: Will need to cache the results of name lookup (including ADL) in
4431     // Fn.
4432     bool Dependent = false;
4433     if (Fn->isTypeDependent())
4434       Dependent = true;
4435     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4436       Dependent = true;
4437 
4438     if (Dependent) {
4439       if (ExecConfig) {
4440         return Owned(new (Context) CUDAKernelCallExpr(
4441             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4442             Context.DependentTy, VK_RValue, RParenLoc));
4443       } else {
4444         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4445                                             Context.DependentTy, VK_RValue,
4446                                             RParenLoc));
4447       }
4448     }
4449 
4450     // Determine whether this is a call to an object (C++ [over.call.object]).
4451     if (Fn->getType()->isRecordType())
4452       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4453                                                 ArgExprs, RParenLoc));
4454 
4455     if (Fn->getType() == Context.UnknownAnyTy) {
4456       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4457       if (result.isInvalid()) return ExprError();
4458       Fn = result.take();
4459     }
4460 
4461     if (Fn->getType() == Context.BoundMemberTy) {
4462       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs, RParenLoc);
4463     }
4464   }
4465 
4466   // Check for overloaded calls.  This can happen even in C due to extensions.
4467   if (Fn->getType() == Context.OverloadTy) {
4468     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4469 
4470     // We aren't supposed to apply this logic for if there's an '&' involved.
4471     if (!find.HasFormOfMemberPointer) {
4472       OverloadExpr *ovl = find.Expression;
4473       if (isa<UnresolvedLookupExpr>(ovl)) {
4474         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4475         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs,
4476                                        RParenLoc, ExecConfig);
4477       } else {
4478         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs,
4479                                          RParenLoc);
4480       }
4481     }
4482   }
4483 
4484   // If we're directly calling a function, get the appropriate declaration.
4485   if (Fn->getType() == Context.UnknownAnyTy) {
4486     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4487     if (result.isInvalid()) return ExprError();
4488     Fn = result.take();
4489   }
4490 
4491   Expr *NakedFn = Fn->IgnoreParens();
4492 
4493   NamedDecl *NDecl = 0;
4494   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4495     if (UnOp->getOpcode() == UO_AddrOf)
4496       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4497 
4498   if (isa<DeclRefExpr>(NakedFn))
4499     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4500   else if (isa<MemberExpr>(NakedFn))
4501     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4502 
4503   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NDecl)) {
4504     if (FD->hasAttr<EnableIfAttr>()) {
4505       if (const EnableIfAttr *Attr = CheckEnableIf(FD, ArgExprs, true)) {
4506         Diag(Fn->getLocStart(),
4507              isa<CXXMethodDecl>(FD) ?
4508                  diag::err_ovl_no_viable_member_function_in_call :
4509                  diag::err_ovl_no_viable_function_in_call)
4510           << FD << FD->getSourceRange();
4511         Diag(FD->getLocation(),
4512              diag::note_ovl_candidate_disabled_by_enable_if_attr)
4513             << Attr->getCond()->getSourceRange() << Attr->getMessage();
4514       }
4515     }
4516   }
4517 
4518   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs, RParenLoc,
4519                                ExecConfig, IsExecConfig);
4520 }
4521 
4522 ExprResult
4523 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4524                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4525   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4526   if (!ConfigDecl)
4527     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4528                           << "cudaConfigureCall");
4529   QualType ConfigQTy = ConfigDecl->getType();
4530 
4531   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4532       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4533   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4534 
4535   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4536                        /*IsExecConfig=*/true);
4537 }
4538 
4539 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4540 ///
4541 /// __builtin_astype( value, dst type )
4542 ///
4543 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4544                                  SourceLocation BuiltinLoc,
4545                                  SourceLocation RParenLoc) {
4546   ExprValueKind VK = VK_RValue;
4547   ExprObjectKind OK = OK_Ordinary;
4548   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4549   QualType SrcTy = E->getType();
4550   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4551     return ExprError(Diag(BuiltinLoc,
4552                           diag::err_invalid_astype_of_different_size)
4553                      << DstTy
4554                      << SrcTy
4555                      << E->getSourceRange());
4556   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4557                RParenLoc));
4558 }
4559 
4560 /// ActOnConvertVectorExpr - create a new convert-vector expression from the
4561 /// provided arguments.
4562 ///
4563 /// __builtin_convertvector( value, dst type )
4564 ///
4565 ExprResult Sema::ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy,
4566                                         SourceLocation BuiltinLoc,
4567                                         SourceLocation RParenLoc) {
4568   TypeSourceInfo *TInfo;
4569   GetTypeFromParser(ParsedDestTy, &TInfo);
4570   return SemaConvertVectorExpr(E, TInfo, BuiltinLoc, RParenLoc);
4571 }
4572 
4573 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4574 /// i.e. an expression not of \p OverloadTy.  The expression should
4575 /// unary-convert to an expression of function-pointer or
4576 /// block-pointer type.
4577 ///
4578 /// \param NDecl the declaration being called, if available
4579 ExprResult
4580 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4581                             SourceLocation LParenLoc,
4582                             ArrayRef<Expr *> Args,
4583                             SourceLocation RParenLoc,
4584                             Expr *Config, bool IsExecConfig) {
4585   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4586   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4587 
4588   // Promote the function operand.
4589   // We special-case function promotion here because we only allow promoting
4590   // builtin functions to function pointers in the callee of a call.
4591   ExprResult Result;
4592   if (BuiltinID &&
4593       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4594     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4595                                CK_BuiltinFnToFnPtr).take();
4596   } else {
4597     Result = CallExprUnaryConversions(Fn);
4598   }
4599   if (Result.isInvalid())
4600     return ExprError();
4601   Fn = Result.take();
4602 
4603   // Make the call expr early, before semantic checks.  This guarantees cleanup
4604   // of arguments and function on error.
4605   CallExpr *TheCall;
4606   if (Config)
4607     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4608                                                cast<CallExpr>(Config), Args,
4609                                                Context.BoolTy, VK_RValue,
4610                                                RParenLoc);
4611   else
4612     TheCall = new (Context) CallExpr(Context, Fn, Args, Context.BoolTy,
4613                                      VK_RValue, RParenLoc);
4614 
4615   // Bail out early if calling a builtin with custom typechecking.
4616   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4617     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4618 
4619  retry:
4620   const FunctionType *FuncT;
4621   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4622     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4623     // have type pointer to function".
4624     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4625     if (FuncT == 0)
4626       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4627                          << Fn->getType() << Fn->getSourceRange());
4628   } else if (const BlockPointerType *BPT =
4629                Fn->getType()->getAs<BlockPointerType>()) {
4630     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4631   } else {
4632     // Handle calls to expressions of unknown-any type.
4633     if (Fn->getType() == Context.UnknownAnyTy) {
4634       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4635       if (rewrite.isInvalid()) return ExprError();
4636       Fn = rewrite.take();
4637       TheCall->setCallee(Fn);
4638       goto retry;
4639     }
4640 
4641     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4642       << Fn->getType() << Fn->getSourceRange());
4643   }
4644 
4645   if (getLangOpts().CUDA) {
4646     if (Config) {
4647       // CUDA: Kernel calls must be to global functions
4648       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4649         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4650             << FDecl->getName() << Fn->getSourceRange());
4651 
4652       // CUDA: Kernel function must have 'void' return type
4653       if (!FuncT->getReturnType()->isVoidType())
4654         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4655             << Fn->getType() << Fn->getSourceRange());
4656     } else {
4657       // CUDA: Calls to global functions must be configured
4658       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4659         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4660             << FDecl->getName() << Fn->getSourceRange());
4661     }
4662   }
4663 
4664   // Check for a valid return type
4665   if (CheckCallReturnType(FuncT->getReturnType(), Fn->getLocStart(), TheCall,
4666                           FDecl))
4667     return ExprError();
4668 
4669   // We know the result type of the call, set it.
4670   TheCall->setType(FuncT->getCallResultType(Context));
4671   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getReturnType()));
4672 
4673   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4674   if (Proto) {
4675     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, RParenLoc,
4676                                 IsExecConfig))
4677       return ExprError();
4678   } else {
4679     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4680 
4681     if (FDecl) {
4682       // Check if we have too few/too many template arguments, based
4683       // on our knowledge of the function definition.
4684       const FunctionDecl *Def = 0;
4685       if (FDecl->hasBody(Def) && Args.size() != Def->param_size()) {
4686         Proto = Def->getType()->getAs<FunctionProtoType>();
4687        if (!Proto || !(Proto->isVariadic() && Args.size() >= Def->param_size()))
4688           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4689           << (Args.size() > Def->param_size()) << FDecl << Fn->getSourceRange();
4690       }
4691 
4692       // If the function we're calling isn't a function prototype, but we have
4693       // a function prototype from a prior declaratiom, use that prototype.
4694       if (!FDecl->hasPrototype())
4695         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4696     }
4697 
4698     // Promote the arguments (C99 6.5.2.2p6).
4699     for (unsigned i = 0, e = Args.size(); i != e; i++) {
4700       Expr *Arg = Args[i];
4701 
4702       if (Proto && i < Proto->getNumParams()) {
4703         InitializedEntity Entity = InitializedEntity::InitializeParameter(
4704             Context, Proto->getParamType(i), Proto->isParamConsumed(i));
4705         ExprResult ArgE = PerformCopyInitialization(Entity,
4706                                                     SourceLocation(),
4707                                                     Owned(Arg));
4708         if (ArgE.isInvalid())
4709           return true;
4710 
4711         Arg = ArgE.takeAs<Expr>();
4712 
4713       } else {
4714         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4715 
4716         if (ArgE.isInvalid())
4717           return true;
4718 
4719         Arg = ArgE.takeAs<Expr>();
4720       }
4721 
4722       if (RequireCompleteType(Arg->getLocStart(),
4723                               Arg->getType(),
4724                               diag::err_call_incomplete_argument, Arg))
4725         return ExprError();
4726 
4727       TheCall->setArg(i, Arg);
4728     }
4729   }
4730 
4731   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4732     if (!Method->isStatic())
4733       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4734         << Fn->getSourceRange());
4735 
4736   // Check for sentinels
4737   if (NDecl)
4738     DiagnoseSentinelCalls(NDecl, LParenLoc, Args);
4739 
4740   // Do special checking on direct calls to functions.
4741   if (FDecl) {
4742     if (CheckFunctionCall(FDecl, TheCall, Proto))
4743       return ExprError();
4744 
4745     if (BuiltinID)
4746       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4747   } else if (NDecl) {
4748     if (CheckPointerCall(NDecl, TheCall, Proto))
4749       return ExprError();
4750   } else {
4751     if (CheckOtherCall(TheCall, Proto))
4752       return ExprError();
4753   }
4754 
4755   return MaybeBindToTemporary(TheCall);
4756 }
4757 
4758 ExprResult
4759 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4760                            SourceLocation RParenLoc, Expr *InitExpr) {
4761   assert(Ty && "ActOnCompoundLiteral(): missing type");
4762   // FIXME: put back this assert when initializers are worked out.
4763   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4764 
4765   TypeSourceInfo *TInfo;
4766   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4767   if (!TInfo)
4768     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4769 
4770   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4771 }
4772 
4773 ExprResult
4774 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4775                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4776   QualType literalType = TInfo->getType();
4777 
4778   if (literalType->isArrayType()) {
4779     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4780           diag::err_illegal_decl_array_incomplete_type,
4781           SourceRange(LParenLoc,
4782                       LiteralExpr->getSourceRange().getEnd())))
4783       return ExprError();
4784     if (literalType->isVariableArrayType())
4785       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4786         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4787   } else if (!literalType->isDependentType() &&
4788              RequireCompleteType(LParenLoc, literalType,
4789                diag::err_typecheck_decl_incomplete_type,
4790                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4791     return ExprError();
4792 
4793   InitializedEntity Entity
4794     = InitializedEntity::InitializeCompoundLiteralInit(TInfo);
4795   InitializationKind Kind
4796     = InitializationKind::CreateCStyleCast(LParenLoc,
4797                                            SourceRange(LParenLoc, RParenLoc),
4798                                            /*InitList=*/true);
4799   InitializationSequence InitSeq(*this, Entity, Kind, LiteralExpr);
4800   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4801                                       &literalType);
4802   if (Result.isInvalid())
4803     return ExprError();
4804   LiteralExpr = Result.get();
4805 
4806   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4807   if (isFileScope &&
4808       !LiteralExpr->isTypeDependent() &&
4809       !LiteralExpr->isValueDependent() &&
4810       !literalType->isDependentType()) { // 6.5.2.5p3
4811     if (CheckForConstantInitializer(LiteralExpr, literalType))
4812       return ExprError();
4813   }
4814 
4815   // In C, compound literals are l-values for some reason.
4816   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4817 
4818   return MaybeBindToTemporary(
4819            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4820                                              VK, LiteralExpr, isFileScope));
4821 }
4822 
4823 ExprResult
4824 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4825                     SourceLocation RBraceLoc) {
4826   // Immediately handle non-overload placeholders.  Overloads can be
4827   // resolved contextually, but everything else here can't.
4828   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4829     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4830       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4831 
4832       // Ignore failures; dropping the entire initializer list because
4833       // of one failure would be terrible for indexing/etc.
4834       if (result.isInvalid()) continue;
4835 
4836       InitArgList[I] = result.take();
4837     }
4838   }
4839 
4840   // Semantic analysis for initializers is done by ActOnDeclarator() and
4841   // CheckInitializer() - it requires knowledge of the object being intialized.
4842 
4843   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4844                                                RBraceLoc);
4845   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4846   return Owned(E);
4847 }
4848 
4849 /// Do an explicit extend of the given block pointer if we're in ARC.
4850 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4851   assert(E.get()->getType()->isBlockPointerType());
4852   assert(E.get()->isRValue());
4853 
4854   // Only do this in an r-value context.
4855   if (!S.getLangOpts().ObjCAutoRefCount) return;
4856 
4857   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4858                                CK_ARCExtendBlockObject, E.get(),
4859                                /*base path*/ 0, VK_RValue);
4860   S.ExprNeedsCleanups = true;
4861 }
4862 
4863 /// Prepare a conversion of the given expression to an ObjC object
4864 /// pointer type.
4865 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4866   QualType type = E.get()->getType();
4867   if (type->isObjCObjectPointerType()) {
4868     return CK_BitCast;
4869   } else if (type->isBlockPointerType()) {
4870     maybeExtendBlockObject(*this, E);
4871     return CK_BlockPointerToObjCPointerCast;
4872   } else {
4873     assert(type->isPointerType());
4874     return CK_CPointerToObjCPointerCast;
4875   }
4876 }
4877 
4878 /// Prepares for a scalar cast, performing all the necessary stages
4879 /// except the final cast and returning the kind required.
4880 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4881   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4882   // Also, callers should have filtered out the invalid cases with
4883   // pointers.  Everything else should be possible.
4884 
4885   QualType SrcTy = Src.get()->getType();
4886   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4887     return CK_NoOp;
4888 
4889   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4890   case Type::STK_MemberPointer:
4891     llvm_unreachable("member pointer type in C");
4892 
4893   case Type::STK_CPointer:
4894   case Type::STK_BlockPointer:
4895   case Type::STK_ObjCObjectPointer:
4896     switch (DestTy->getScalarTypeKind()) {
4897     case Type::STK_CPointer: {
4898       unsigned SrcAS = SrcTy->getPointeeType().getAddressSpace();
4899       unsigned DestAS = DestTy->getPointeeType().getAddressSpace();
4900       if (SrcAS != DestAS)
4901         return CK_AddressSpaceConversion;
4902       return CK_BitCast;
4903     }
4904     case Type::STK_BlockPointer:
4905       return (SrcKind == Type::STK_BlockPointer
4906                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4907     case Type::STK_ObjCObjectPointer:
4908       if (SrcKind == Type::STK_ObjCObjectPointer)
4909         return CK_BitCast;
4910       if (SrcKind == Type::STK_CPointer)
4911         return CK_CPointerToObjCPointerCast;
4912       maybeExtendBlockObject(*this, Src);
4913       return CK_BlockPointerToObjCPointerCast;
4914     case Type::STK_Bool:
4915       return CK_PointerToBoolean;
4916     case Type::STK_Integral:
4917       return CK_PointerToIntegral;
4918     case Type::STK_Floating:
4919     case Type::STK_FloatingComplex:
4920     case Type::STK_IntegralComplex:
4921     case Type::STK_MemberPointer:
4922       llvm_unreachable("illegal cast from pointer");
4923     }
4924     llvm_unreachable("Should have returned before this");
4925 
4926   case Type::STK_Bool: // casting from bool is like casting from an integer
4927   case Type::STK_Integral:
4928     switch (DestTy->getScalarTypeKind()) {
4929     case Type::STK_CPointer:
4930     case Type::STK_ObjCObjectPointer:
4931     case Type::STK_BlockPointer:
4932       if (Src.get()->isNullPointerConstant(Context,
4933                                            Expr::NPC_ValueDependentIsNull))
4934         return CK_NullToPointer;
4935       return CK_IntegralToPointer;
4936     case Type::STK_Bool:
4937       return CK_IntegralToBoolean;
4938     case Type::STK_Integral:
4939       return CK_IntegralCast;
4940     case Type::STK_Floating:
4941       return CK_IntegralToFloating;
4942     case Type::STK_IntegralComplex:
4943       Src = ImpCastExprToType(Src.take(),
4944                               DestTy->castAs<ComplexType>()->getElementType(),
4945                               CK_IntegralCast);
4946       return CK_IntegralRealToComplex;
4947     case Type::STK_FloatingComplex:
4948       Src = ImpCastExprToType(Src.take(),
4949                               DestTy->castAs<ComplexType>()->getElementType(),
4950                               CK_IntegralToFloating);
4951       return CK_FloatingRealToComplex;
4952     case Type::STK_MemberPointer:
4953       llvm_unreachable("member pointer type in C");
4954     }
4955     llvm_unreachable("Should have returned before this");
4956 
4957   case Type::STK_Floating:
4958     switch (DestTy->getScalarTypeKind()) {
4959     case Type::STK_Floating:
4960       return CK_FloatingCast;
4961     case Type::STK_Bool:
4962       return CK_FloatingToBoolean;
4963     case Type::STK_Integral:
4964       return CK_FloatingToIntegral;
4965     case Type::STK_FloatingComplex:
4966       Src = ImpCastExprToType(Src.take(),
4967                               DestTy->castAs<ComplexType>()->getElementType(),
4968                               CK_FloatingCast);
4969       return CK_FloatingRealToComplex;
4970     case Type::STK_IntegralComplex:
4971       Src = ImpCastExprToType(Src.take(),
4972                               DestTy->castAs<ComplexType>()->getElementType(),
4973                               CK_FloatingToIntegral);
4974       return CK_IntegralRealToComplex;
4975     case Type::STK_CPointer:
4976     case Type::STK_ObjCObjectPointer:
4977     case Type::STK_BlockPointer:
4978       llvm_unreachable("valid float->pointer cast?");
4979     case Type::STK_MemberPointer:
4980       llvm_unreachable("member pointer type in C");
4981     }
4982     llvm_unreachable("Should have returned before this");
4983 
4984   case Type::STK_FloatingComplex:
4985     switch (DestTy->getScalarTypeKind()) {
4986     case Type::STK_FloatingComplex:
4987       return CK_FloatingComplexCast;
4988     case Type::STK_IntegralComplex:
4989       return CK_FloatingComplexToIntegralComplex;
4990     case Type::STK_Floating: {
4991       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4992       if (Context.hasSameType(ET, DestTy))
4993         return CK_FloatingComplexToReal;
4994       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4995       return CK_FloatingCast;
4996     }
4997     case Type::STK_Bool:
4998       return CK_FloatingComplexToBoolean;
4999     case Type::STK_Integral:
5000       Src = ImpCastExprToType(Src.take(),
5001                               SrcTy->castAs<ComplexType>()->getElementType(),
5002                               CK_FloatingComplexToReal);
5003       return CK_FloatingToIntegral;
5004     case Type::STK_CPointer:
5005     case Type::STK_ObjCObjectPointer:
5006     case Type::STK_BlockPointer:
5007       llvm_unreachable("valid complex float->pointer cast?");
5008     case Type::STK_MemberPointer:
5009       llvm_unreachable("member pointer type in C");
5010     }
5011     llvm_unreachable("Should have returned before this");
5012 
5013   case Type::STK_IntegralComplex:
5014     switch (DestTy->getScalarTypeKind()) {
5015     case Type::STK_FloatingComplex:
5016       return CK_IntegralComplexToFloatingComplex;
5017     case Type::STK_IntegralComplex:
5018       return CK_IntegralComplexCast;
5019     case Type::STK_Integral: {
5020       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
5021       if (Context.hasSameType(ET, DestTy))
5022         return CK_IntegralComplexToReal;
5023       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
5024       return CK_IntegralCast;
5025     }
5026     case Type::STK_Bool:
5027       return CK_IntegralComplexToBoolean;
5028     case Type::STK_Floating:
5029       Src = ImpCastExprToType(Src.take(),
5030                               SrcTy->castAs<ComplexType>()->getElementType(),
5031                               CK_IntegralComplexToReal);
5032       return CK_IntegralToFloating;
5033     case Type::STK_CPointer:
5034     case Type::STK_ObjCObjectPointer:
5035     case Type::STK_BlockPointer:
5036       llvm_unreachable("valid complex int->pointer cast?");
5037     case Type::STK_MemberPointer:
5038       llvm_unreachable("member pointer type in C");
5039     }
5040     llvm_unreachable("Should have returned before this");
5041   }
5042 
5043   llvm_unreachable("Unhandled scalar cast");
5044 }
5045 
5046 static bool breakDownVectorType(QualType type, uint64_t &len,
5047                                 QualType &eltType) {
5048   // Vectors are simple.
5049   if (const VectorType *vecType = type->getAs<VectorType>()) {
5050     len = vecType->getNumElements();
5051     eltType = vecType->getElementType();
5052     assert(eltType->isScalarType());
5053     return true;
5054   }
5055 
5056   // We allow lax conversion to and from non-vector types, but only if
5057   // they're real types (i.e. non-complex, non-pointer scalar types).
5058   if (!type->isRealType()) return false;
5059 
5060   len = 1;
5061   eltType = type;
5062   return true;
5063 }
5064 
5065 static bool VectorTypesMatch(Sema &S, QualType srcTy, QualType destTy) {
5066   uint64_t srcLen, destLen;
5067   QualType srcElt, destElt;
5068   if (!breakDownVectorType(srcTy, srcLen, srcElt)) return false;
5069   if (!breakDownVectorType(destTy, destLen, destElt)) return false;
5070 
5071   // ASTContext::getTypeSize will return the size rounded up to a
5072   // power of 2, so instead of using that, we need to use the raw
5073   // element size multiplied by the element count.
5074   uint64_t srcEltSize = S.Context.getTypeSize(srcElt);
5075   uint64_t destEltSize = S.Context.getTypeSize(destElt);
5076 
5077   return (srcLen * srcEltSize == destLen * destEltSize);
5078 }
5079 
5080 /// Is this a legal conversion between two known vector types?
5081 bool Sema::isLaxVectorConversion(QualType srcTy, QualType destTy) {
5082   assert(destTy->isVectorType() || srcTy->isVectorType());
5083 
5084   if (!Context.getLangOpts().LaxVectorConversions)
5085     return false;
5086   return VectorTypesMatch(*this, srcTy, destTy);
5087 }
5088 
5089 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
5090                            CastKind &Kind) {
5091   assert(VectorTy->isVectorType() && "Not a vector type!");
5092 
5093   if (Ty->isVectorType() || Ty->isIntegerType()) {
5094     if (!VectorTypesMatch(*this, Ty, VectorTy))
5095       return Diag(R.getBegin(),
5096                   Ty->isVectorType() ?
5097                   diag::err_invalid_conversion_between_vectors :
5098                   diag::err_invalid_conversion_between_vector_and_integer)
5099         << VectorTy << Ty << R;
5100   } else
5101     return Diag(R.getBegin(),
5102                 diag::err_invalid_conversion_between_vector_and_scalar)
5103       << VectorTy << Ty << R;
5104 
5105   Kind = CK_BitCast;
5106   return false;
5107 }
5108 
5109 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
5110                                     Expr *CastExpr, CastKind &Kind) {
5111   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
5112 
5113   QualType SrcTy = CastExpr->getType();
5114 
5115   // If SrcTy is a VectorType, the total size must match to explicitly cast to
5116   // an ExtVectorType.
5117   // In OpenCL, casts between vectors of different types are not allowed.
5118   // (See OpenCL 6.2).
5119   if (SrcTy->isVectorType()) {
5120     if (!VectorTypesMatch(*this, SrcTy, DestTy)
5121         || (getLangOpts().OpenCL &&
5122             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
5123       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
5124         << DestTy << SrcTy << R;
5125       return ExprError();
5126     }
5127     Kind = CK_BitCast;
5128     return Owned(CastExpr);
5129   }
5130 
5131   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
5132   // conversion will take place first from scalar to elt type, and then
5133   // splat from elt type to vector.
5134   if (SrcTy->isPointerType())
5135     return Diag(R.getBegin(),
5136                 diag::err_invalid_conversion_between_vector_and_scalar)
5137       << DestTy << SrcTy << R;
5138 
5139   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
5140   ExprResult CastExprRes = Owned(CastExpr);
5141   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
5142   if (CastExprRes.isInvalid())
5143     return ExprError();
5144   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
5145 
5146   Kind = CK_VectorSplat;
5147   return Owned(CastExpr);
5148 }
5149 
5150 ExprResult
5151 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
5152                     Declarator &D, ParsedType &Ty,
5153                     SourceLocation RParenLoc, Expr *CastExpr) {
5154   assert(!D.isInvalidType() && (CastExpr != 0) &&
5155          "ActOnCastExpr(): missing type or expr");
5156 
5157   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
5158   if (D.isInvalidType())
5159     return ExprError();
5160 
5161   if (getLangOpts().CPlusPlus) {
5162     // Check that there are no default arguments (C++ only).
5163     CheckExtraCXXDefaultArguments(D);
5164   }
5165 
5166   checkUnusedDeclAttributes(D);
5167 
5168   QualType castType = castTInfo->getType();
5169   Ty = CreateParsedType(castType, castTInfo);
5170 
5171   bool isVectorLiteral = false;
5172 
5173   // Check for an altivec or OpenCL literal,
5174   // i.e. all the elements are integer constants.
5175   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
5176   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
5177   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
5178        && castType->isVectorType() && (PE || PLE)) {
5179     if (PLE && PLE->getNumExprs() == 0) {
5180       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
5181       return ExprError();
5182     }
5183     if (PE || PLE->getNumExprs() == 1) {
5184       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
5185       if (!E->getType()->isVectorType())
5186         isVectorLiteral = true;
5187     }
5188     else
5189       isVectorLiteral = true;
5190   }
5191 
5192   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
5193   // then handle it as such.
5194   if (isVectorLiteral)
5195     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
5196 
5197   // If the Expr being casted is a ParenListExpr, handle it specially.
5198   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
5199   // sequence of BinOp comma operators.
5200   if (isa<ParenListExpr>(CastExpr)) {
5201     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
5202     if (Result.isInvalid()) return ExprError();
5203     CastExpr = Result.take();
5204   }
5205 
5206   if (getLangOpts().CPlusPlus && !castType->isVoidType() &&
5207       !getSourceManager().isInSystemMacro(LParenLoc))
5208     Diag(LParenLoc, diag::warn_old_style_cast) << CastExpr->getSourceRange();
5209 
5210   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
5211 }
5212 
5213 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
5214                                     SourceLocation RParenLoc, Expr *E,
5215                                     TypeSourceInfo *TInfo) {
5216   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
5217          "Expected paren or paren list expression");
5218 
5219   Expr **exprs;
5220   unsigned numExprs;
5221   Expr *subExpr;
5222   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
5223   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
5224     LiteralLParenLoc = PE->getLParenLoc();
5225     LiteralRParenLoc = PE->getRParenLoc();
5226     exprs = PE->getExprs();
5227     numExprs = PE->getNumExprs();
5228   } else { // isa<ParenExpr> by assertion at function entrance
5229     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
5230     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
5231     subExpr = cast<ParenExpr>(E)->getSubExpr();
5232     exprs = &subExpr;
5233     numExprs = 1;
5234   }
5235 
5236   QualType Ty = TInfo->getType();
5237   assert(Ty->isVectorType() && "Expected vector type");
5238 
5239   SmallVector<Expr *, 8> initExprs;
5240   const VectorType *VTy = Ty->getAs<VectorType>();
5241   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
5242 
5243   // '(...)' form of vector initialization in AltiVec: the number of
5244   // initializers must be one or must match the size of the vector.
5245   // If a single value is specified in the initializer then it will be
5246   // replicated to all the components of the vector
5247   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
5248     // The number of initializers must be one or must match the size of the
5249     // vector. If a single value is specified in the initializer then it will
5250     // be replicated to all the components of the vector
5251     if (numExprs == 1) {
5252       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5253       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5254       if (Literal.isInvalid())
5255         return ExprError();
5256       Literal = ImpCastExprToType(Literal.take(), ElemTy,
5257                                   PrepareScalarCast(Literal, ElemTy));
5258       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5259     }
5260     else if (numExprs < numElems) {
5261       Diag(E->getExprLoc(),
5262            diag::err_incorrect_number_of_vector_initializers);
5263       return ExprError();
5264     }
5265     else
5266       initExprs.append(exprs, exprs + numExprs);
5267   }
5268   else {
5269     // For OpenCL, when the number of initializers is a single value,
5270     // it will be replicated to all components of the vector.
5271     if (getLangOpts().OpenCL &&
5272         VTy->getVectorKind() == VectorType::GenericVector &&
5273         numExprs == 1) {
5274         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
5275         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
5276         if (Literal.isInvalid())
5277           return ExprError();
5278         Literal = ImpCastExprToType(Literal.take(), ElemTy,
5279                                     PrepareScalarCast(Literal, ElemTy));
5280         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
5281     }
5282 
5283     initExprs.append(exprs, exprs + numExprs);
5284   }
5285   // FIXME: This means that pretty-printing the final AST will produce curly
5286   // braces instead of the original commas.
5287   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
5288                                                    initExprs, LiteralRParenLoc);
5289   initE->setType(Ty);
5290   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
5291 }
5292 
5293 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
5294 /// the ParenListExpr into a sequence of comma binary operators.
5295 ExprResult
5296 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
5297   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
5298   if (!E)
5299     return Owned(OrigExpr);
5300 
5301   ExprResult Result(E->getExpr(0));
5302 
5303   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
5304     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
5305                         E->getExpr(i));
5306 
5307   if (Result.isInvalid()) return ExprError();
5308 
5309   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
5310 }
5311 
5312 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
5313                                     SourceLocation R,
5314                                     MultiExprArg Val) {
5315   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
5316   return Owned(expr);
5317 }
5318 
5319 /// \brief Emit a specialized diagnostic when one expression is a null pointer
5320 /// constant and the other is not a pointer.  Returns true if a diagnostic is
5321 /// emitted.
5322 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
5323                                       SourceLocation QuestionLoc) {
5324   Expr *NullExpr = LHSExpr;
5325   Expr *NonPointerExpr = RHSExpr;
5326   Expr::NullPointerConstantKind NullKind =
5327       NullExpr->isNullPointerConstant(Context,
5328                                       Expr::NPC_ValueDependentIsNotNull);
5329 
5330   if (NullKind == Expr::NPCK_NotNull) {
5331     NullExpr = RHSExpr;
5332     NonPointerExpr = LHSExpr;
5333     NullKind =
5334         NullExpr->isNullPointerConstant(Context,
5335                                         Expr::NPC_ValueDependentIsNotNull);
5336   }
5337 
5338   if (NullKind == Expr::NPCK_NotNull)
5339     return false;
5340 
5341   if (NullKind == Expr::NPCK_ZeroExpression)
5342     return false;
5343 
5344   if (NullKind == Expr::NPCK_ZeroLiteral) {
5345     // In this case, check to make sure that we got here from a "NULL"
5346     // string in the source code.
5347     NullExpr = NullExpr->IgnoreParenImpCasts();
5348     SourceLocation loc = NullExpr->getExprLoc();
5349     if (!findMacroSpelling(loc, "NULL"))
5350       return false;
5351   }
5352 
5353   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
5354   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
5355       << NonPointerExpr->getType() << DiagType
5356       << NonPointerExpr->getSourceRange();
5357   return true;
5358 }
5359 
5360 /// \brief Return false if the condition expression is valid, true otherwise.
5361 static bool checkCondition(Sema &S, Expr *Cond) {
5362   QualType CondTy = Cond->getType();
5363 
5364   // C99 6.5.15p2
5365   if (CondTy->isScalarType()) return false;
5366 
5367   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
5368   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
5369     return false;
5370 
5371   // Emit the proper error message.
5372   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
5373                               diag::err_typecheck_cond_expect_scalar :
5374                               diag::err_typecheck_cond_expect_scalar_or_vector)
5375     << CondTy;
5376   return true;
5377 }
5378 
5379 /// \brief Return false if the two expressions can be converted to a vector,
5380 /// true otherwise
5381 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
5382                                                     ExprResult &RHS,
5383                                                     QualType CondTy) {
5384   // Both operands should be of scalar type.
5385   if (!LHS.get()->getType()->isScalarType()) {
5386     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5387       << CondTy;
5388     return true;
5389   }
5390   if (!RHS.get()->getType()->isScalarType()) {
5391     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
5392       << CondTy;
5393     return true;
5394   }
5395 
5396   // Implicity convert these scalars to the type of the condition.
5397   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
5398   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
5399   return false;
5400 }
5401 
5402 /// \brief Handle when one or both operands are void type.
5403 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
5404                                          ExprResult &RHS) {
5405     Expr *LHSExpr = LHS.get();
5406     Expr *RHSExpr = RHS.get();
5407 
5408     if (!LHSExpr->getType()->isVoidType())
5409       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5410         << RHSExpr->getSourceRange();
5411     if (!RHSExpr->getType()->isVoidType())
5412       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
5413         << LHSExpr->getSourceRange();
5414     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
5415     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
5416     return S.Context.VoidTy;
5417 }
5418 
5419 /// \brief Return false if the NullExpr can be promoted to PointerTy,
5420 /// true otherwise.
5421 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
5422                                         QualType PointerTy) {
5423   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
5424       !NullExpr.get()->isNullPointerConstant(S.Context,
5425                                             Expr::NPC_ValueDependentIsNull))
5426     return true;
5427 
5428   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
5429   return false;
5430 }
5431 
5432 /// \brief Checks compatibility between two pointers and return the resulting
5433 /// type.
5434 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
5435                                                      ExprResult &RHS,
5436                                                      SourceLocation Loc) {
5437   QualType LHSTy = LHS.get()->getType();
5438   QualType RHSTy = RHS.get()->getType();
5439 
5440   if (S.Context.hasSameType(LHSTy, RHSTy)) {
5441     // Two identical pointers types are always compatible.
5442     return LHSTy;
5443   }
5444 
5445   QualType lhptee, rhptee;
5446 
5447   // Get the pointee types.
5448   bool IsBlockPointer = false;
5449   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5450     lhptee = LHSBTy->getPointeeType();
5451     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5452     IsBlockPointer = true;
5453   } else {
5454     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5455     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5456   }
5457 
5458   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5459   // differently qualified versions of compatible types, the result type is
5460   // a pointer to an appropriately qualified version of the composite
5461   // type.
5462 
5463   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5464   // clause doesn't make sense for our extensions. E.g. address space 2 should
5465   // be incompatible with address space 3: they may live on different devices or
5466   // anything.
5467   Qualifiers lhQual = lhptee.getQualifiers();
5468   Qualifiers rhQual = rhptee.getQualifiers();
5469 
5470   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5471   lhQual.removeCVRQualifiers();
5472   rhQual.removeCVRQualifiers();
5473 
5474   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5475   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5476 
5477   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5478 
5479   if (CompositeTy.isNull()) {
5480     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5481       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5482       << RHS.get()->getSourceRange();
5483     // In this situation, we assume void* type. No especially good
5484     // reason, but this is what gcc does, and we do have to pick
5485     // to get a consistent AST.
5486     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5487     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5488     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5489     return incompatTy;
5490   }
5491 
5492   // The pointer types are compatible.
5493   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5494   if (IsBlockPointer)
5495     ResultTy = S.Context.getBlockPointerType(ResultTy);
5496   else
5497     ResultTy = S.Context.getPointerType(ResultTy);
5498 
5499   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5500   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5501   return ResultTy;
5502 }
5503 
5504 /// \brief Return the resulting type when the operands are both block pointers.
5505 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5506                                                           ExprResult &LHS,
5507                                                           ExprResult &RHS,
5508                                                           SourceLocation Loc) {
5509   QualType LHSTy = LHS.get()->getType();
5510   QualType RHSTy = RHS.get()->getType();
5511 
5512   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5513     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5514       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5515       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5516       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5517       return destType;
5518     }
5519     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5520       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5521       << RHS.get()->getSourceRange();
5522     return QualType();
5523   }
5524 
5525   // We have 2 block pointer types.
5526   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5527 }
5528 
5529 /// \brief Return the resulting type when the operands are both pointers.
5530 static QualType
5531 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5532                                             ExprResult &RHS,
5533                                             SourceLocation Loc) {
5534   // get the pointer types
5535   QualType LHSTy = LHS.get()->getType();
5536   QualType RHSTy = RHS.get()->getType();
5537 
5538   // get the "pointed to" types
5539   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5540   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5541 
5542   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5543   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5544     // Figure out necessary qualifiers (C99 6.5.15p6)
5545     QualType destPointee
5546       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5547     QualType destType = S.Context.getPointerType(destPointee);
5548     // Add qualifiers if necessary.
5549     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5550     // Promote to void*.
5551     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5552     return destType;
5553   }
5554   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5555     QualType destPointee
5556       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5557     QualType destType = S.Context.getPointerType(destPointee);
5558     // Add qualifiers if necessary.
5559     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5560     // Promote to void*.
5561     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5562     return destType;
5563   }
5564 
5565   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5566 }
5567 
5568 /// \brief Return false if the first expression is not an integer and the second
5569 /// expression is not a pointer, true otherwise.
5570 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5571                                         Expr* PointerExpr, SourceLocation Loc,
5572                                         bool IsIntFirstExpr) {
5573   if (!PointerExpr->getType()->isPointerType() ||
5574       !Int.get()->getType()->isIntegerType())
5575     return false;
5576 
5577   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5578   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5579 
5580   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5581     << Expr1->getType() << Expr2->getType()
5582     << Expr1->getSourceRange() << Expr2->getSourceRange();
5583   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5584                             CK_IntegralToPointer);
5585   return true;
5586 }
5587 
5588 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5589 /// In that case, LHS = cond.
5590 /// C99 6.5.15
5591 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5592                                         ExprResult &RHS, ExprValueKind &VK,
5593                                         ExprObjectKind &OK,
5594                                         SourceLocation QuestionLoc) {
5595 
5596   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5597   if (!LHSResult.isUsable()) return QualType();
5598   LHS = LHSResult;
5599 
5600   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5601   if (!RHSResult.isUsable()) return QualType();
5602   RHS = RHSResult;
5603 
5604   // C++ is sufficiently different to merit its own checker.
5605   if (getLangOpts().CPlusPlus)
5606     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5607 
5608   VK = VK_RValue;
5609   OK = OK_Ordinary;
5610 
5611   // First, check the condition.
5612   Cond = UsualUnaryConversions(Cond.take());
5613   if (Cond.isInvalid())
5614     return QualType();
5615   if (checkCondition(*this, Cond.get()))
5616     return QualType();
5617 
5618   // Now check the two expressions.
5619   if (LHS.get()->getType()->isVectorType() ||
5620       RHS.get()->getType()->isVectorType())
5621     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5622 
5623   UsualArithmeticConversions(LHS, RHS);
5624   if (LHS.isInvalid() || RHS.isInvalid())
5625     return QualType();
5626 
5627   QualType CondTy = Cond.get()->getType();
5628   QualType LHSTy = LHS.get()->getType();
5629   QualType RHSTy = RHS.get()->getType();
5630 
5631   // If the condition is a vector, and both operands are scalar,
5632   // attempt to implicity convert them to the vector type to act like the
5633   // built in select. (OpenCL v1.1 s6.3.i)
5634   if (getLangOpts().OpenCL && CondTy->isVectorType())
5635     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5636       return QualType();
5637 
5638   // If both operands have arithmetic type, do the usual arithmetic conversions
5639   // to find a common type: C99 6.5.15p3,5.
5640   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType())
5641     return LHS.get()->getType();
5642 
5643   // If both operands are the same structure or union type, the result is that
5644   // type.
5645   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5646     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5647       if (LHSRT->getDecl() == RHSRT->getDecl())
5648         // "If both the operands have structure or union type, the result has
5649         // that type."  This implies that CV qualifiers are dropped.
5650         return LHSTy.getUnqualifiedType();
5651     // FIXME: Type of conditional expression must be complete in C mode.
5652   }
5653 
5654   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5655   // The following || allows only one side to be void (a GCC-ism).
5656   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5657     return checkConditionalVoidType(*this, LHS, RHS);
5658   }
5659 
5660   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5661   // the type of the other operand."
5662   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5663   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5664 
5665   // All objective-c pointer type analysis is done here.
5666   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5667                                                         QuestionLoc);
5668   if (LHS.isInvalid() || RHS.isInvalid())
5669     return QualType();
5670   if (!compositeType.isNull())
5671     return compositeType;
5672 
5673 
5674   // Handle block pointer types.
5675   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5676     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5677                                                      QuestionLoc);
5678 
5679   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5680   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5681     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5682                                                        QuestionLoc);
5683 
5684   // GCC compatibility: soften pointer/integer mismatch.  Note that
5685   // null pointers have been filtered out by this point.
5686   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5687       /*isIntFirstExpr=*/true))
5688     return RHSTy;
5689   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5690       /*isIntFirstExpr=*/false))
5691     return LHSTy;
5692 
5693   // Emit a better diagnostic if one of the expressions is a null pointer
5694   // constant and the other is not a pointer type. In this case, the user most
5695   // likely forgot to take the address of the other expression.
5696   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5697     return QualType();
5698 
5699   // Otherwise, the operands are not compatible.
5700   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5701     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5702     << RHS.get()->getSourceRange();
5703   return QualType();
5704 }
5705 
5706 /// FindCompositeObjCPointerType - Helper method to find composite type of
5707 /// two objective-c pointer types of the two input expressions.
5708 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5709                                             SourceLocation QuestionLoc) {
5710   QualType LHSTy = LHS.get()->getType();
5711   QualType RHSTy = RHS.get()->getType();
5712 
5713   // Handle things like Class and struct objc_class*.  Here we case the result
5714   // to the pseudo-builtin, because that will be implicitly cast back to the
5715   // redefinition type if an attempt is made to access its fields.
5716   if (LHSTy->isObjCClassType() &&
5717       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5718     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5719     return LHSTy;
5720   }
5721   if (RHSTy->isObjCClassType() &&
5722       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5723     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5724     return RHSTy;
5725   }
5726   // And the same for struct objc_object* / id
5727   if (LHSTy->isObjCIdType() &&
5728       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5729     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5730     return LHSTy;
5731   }
5732   if (RHSTy->isObjCIdType() &&
5733       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5734     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5735     return RHSTy;
5736   }
5737   // And the same for struct objc_selector* / SEL
5738   if (Context.isObjCSelType(LHSTy) &&
5739       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5740     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5741     return LHSTy;
5742   }
5743   if (Context.isObjCSelType(RHSTy) &&
5744       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5745     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5746     return RHSTy;
5747   }
5748   // Check constraints for Objective-C object pointers types.
5749   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5750 
5751     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5752       // Two identical object pointer types are always compatible.
5753       return LHSTy;
5754     }
5755     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5756     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5757     QualType compositeType = LHSTy;
5758 
5759     // If both operands are interfaces and either operand can be
5760     // assigned to the other, use that type as the composite
5761     // type. This allows
5762     //   xxx ? (A*) a : (B*) b
5763     // where B is a subclass of A.
5764     //
5765     // Additionally, as for assignment, if either type is 'id'
5766     // allow silent coercion. Finally, if the types are
5767     // incompatible then make sure to use 'id' as the composite
5768     // type so the result is acceptable for sending messages to.
5769 
5770     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5771     // It could return the composite type.
5772     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5773       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5774     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5775       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5776     } else if ((LHSTy->isObjCQualifiedIdType() ||
5777                 RHSTy->isObjCQualifiedIdType()) &&
5778                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5779       // Need to handle "id<xx>" explicitly.
5780       // GCC allows qualified id and any Objective-C type to devolve to
5781       // id. Currently localizing to here until clear this should be
5782       // part of ObjCQualifiedIdTypesAreCompatible.
5783       compositeType = Context.getObjCIdType();
5784     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5785       compositeType = Context.getObjCIdType();
5786     } else if (!(compositeType =
5787                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5788       ;
5789     else {
5790       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5791       << LHSTy << RHSTy
5792       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5793       QualType incompatTy = Context.getObjCIdType();
5794       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5795       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5796       return incompatTy;
5797     }
5798     // The object pointer types are compatible.
5799     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5800     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5801     return compositeType;
5802   }
5803   // Check Objective-C object pointer types and 'void *'
5804   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5805     if (getLangOpts().ObjCAutoRefCount) {
5806       // ARC forbids the implicit conversion of object pointers to 'void *',
5807       // so these types are not compatible.
5808       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5809           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5810       LHS = RHS = true;
5811       return QualType();
5812     }
5813     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5814     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5815     QualType destPointee
5816     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5817     QualType destType = Context.getPointerType(destPointee);
5818     // Add qualifiers if necessary.
5819     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5820     // Promote to void*.
5821     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5822     return destType;
5823   }
5824   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5825     if (getLangOpts().ObjCAutoRefCount) {
5826       // ARC forbids the implicit conversion of object pointers to 'void *',
5827       // so these types are not compatible.
5828       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5829           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5830       LHS = RHS = true;
5831       return QualType();
5832     }
5833     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5834     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5835     QualType destPointee
5836     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5837     QualType destType = Context.getPointerType(destPointee);
5838     // Add qualifiers if necessary.
5839     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5840     // Promote to void*.
5841     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5842     return destType;
5843   }
5844   return QualType();
5845 }
5846 
5847 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5848 /// ParenRange in parentheses.
5849 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5850                                const PartialDiagnostic &Note,
5851                                SourceRange ParenRange) {
5852   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5853   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5854       EndLoc.isValid()) {
5855     Self.Diag(Loc, Note)
5856       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5857       << FixItHint::CreateInsertion(EndLoc, ")");
5858   } else {
5859     // We can't display the parentheses, so just show the bare note.
5860     Self.Diag(Loc, Note) << ParenRange;
5861   }
5862 }
5863 
5864 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5865   return Opc >= BO_Mul && Opc <= BO_Shr;
5866 }
5867 
5868 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5869 /// expression, either using a built-in or overloaded operator,
5870 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5871 /// expression.
5872 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5873                                    Expr **RHSExprs) {
5874   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5875   E = E->IgnoreImpCasts();
5876   E = E->IgnoreConversionOperator();
5877   E = E->IgnoreImpCasts();
5878 
5879   // Built-in binary operator.
5880   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5881     if (IsArithmeticOp(OP->getOpcode())) {
5882       *Opcode = OP->getOpcode();
5883       *RHSExprs = OP->getRHS();
5884       return true;
5885     }
5886   }
5887 
5888   // Overloaded operator.
5889   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5890     if (Call->getNumArgs() != 2)
5891       return false;
5892 
5893     // Make sure this is really a binary operator that is safe to pass into
5894     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5895     OverloadedOperatorKind OO = Call->getOperator();
5896     if (OO < OO_Plus || OO > OO_Arrow ||
5897         OO == OO_PlusPlus || OO == OO_MinusMinus)
5898       return false;
5899 
5900     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5901     if (IsArithmeticOp(OpKind)) {
5902       *Opcode = OpKind;
5903       *RHSExprs = Call->getArg(1);
5904       return true;
5905     }
5906   }
5907 
5908   return false;
5909 }
5910 
5911 static bool IsLogicOp(BinaryOperatorKind Opc) {
5912   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5913 }
5914 
5915 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5916 /// or is a logical expression such as (x==y) which has int type, but is
5917 /// commonly interpreted as boolean.
5918 static bool ExprLooksBoolean(Expr *E) {
5919   E = E->IgnoreParenImpCasts();
5920 
5921   if (E->getType()->isBooleanType())
5922     return true;
5923   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5924     return IsLogicOp(OP->getOpcode());
5925   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5926     return OP->getOpcode() == UO_LNot;
5927 
5928   return false;
5929 }
5930 
5931 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5932 /// and binary operator are mixed in a way that suggests the programmer assumed
5933 /// the conditional operator has higher precedence, for example:
5934 /// "int x = a + someBinaryCondition ? 1 : 2".
5935 static void DiagnoseConditionalPrecedence(Sema &Self,
5936                                           SourceLocation OpLoc,
5937                                           Expr *Condition,
5938                                           Expr *LHSExpr,
5939                                           Expr *RHSExpr) {
5940   BinaryOperatorKind CondOpcode;
5941   Expr *CondRHS;
5942 
5943   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5944     return;
5945   if (!ExprLooksBoolean(CondRHS))
5946     return;
5947 
5948   // The condition is an arithmetic binary expression, with a right-
5949   // hand side that looks boolean, so warn.
5950 
5951   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5952       << Condition->getSourceRange()
5953       << BinaryOperator::getOpcodeStr(CondOpcode);
5954 
5955   SuggestParentheses(Self, OpLoc,
5956     Self.PDiag(diag::note_precedence_silence)
5957       << BinaryOperator::getOpcodeStr(CondOpcode),
5958     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5959 
5960   SuggestParentheses(Self, OpLoc,
5961     Self.PDiag(diag::note_precedence_conditional_first),
5962     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5963 }
5964 
5965 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5966 /// in the case of a the GNU conditional expr extension.
5967 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5968                                     SourceLocation ColonLoc,
5969                                     Expr *CondExpr, Expr *LHSExpr,
5970                                     Expr *RHSExpr) {
5971   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5972   // was the condition.
5973   OpaqueValueExpr *opaqueValue = 0;
5974   Expr *commonExpr = 0;
5975   if (LHSExpr == 0) {
5976     commonExpr = CondExpr;
5977     // Lower out placeholder types first.  This is important so that we don't
5978     // try to capture a placeholder. This happens in few cases in C++; such
5979     // as Objective-C++'s dictionary subscripting syntax.
5980     if (commonExpr->hasPlaceholderType()) {
5981       ExprResult result = CheckPlaceholderExpr(commonExpr);
5982       if (!result.isUsable()) return ExprError();
5983       commonExpr = result.take();
5984     }
5985     // We usually want to apply unary conversions *before* saving, except
5986     // in the special case of a C++ l-value conditional.
5987     if (!(getLangOpts().CPlusPlus
5988           && !commonExpr->isTypeDependent()
5989           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5990           && commonExpr->isGLValue()
5991           && commonExpr->isOrdinaryOrBitFieldObject()
5992           && RHSExpr->isOrdinaryOrBitFieldObject()
5993           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5994       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5995       if (commonRes.isInvalid())
5996         return ExprError();
5997       commonExpr = commonRes.take();
5998     }
5999 
6000     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
6001                                                 commonExpr->getType(),
6002                                                 commonExpr->getValueKind(),
6003                                                 commonExpr->getObjectKind(),
6004                                                 commonExpr);
6005     LHSExpr = CondExpr = opaqueValue;
6006   }
6007 
6008   ExprValueKind VK = VK_RValue;
6009   ExprObjectKind OK = OK_Ordinary;
6010   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
6011   QualType result = CheckConditionalOperands(Cond, LHS, RHS,
6012                                              VK, OK, QuestionLoc);
6013   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
6014       RHS.isInvalid())
6015     return ExprError();
6016 
6017   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
6018                                 RHS.get());
6019 
6020   if (!commonExpr)
6021     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
6022                                                    LHS.take(), ColonLoc,
6023                                                    RHS.take(), result, VK, OK));
6024 
6025   return Owned(new (Context)
6026     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
6027                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
6028                               OK));
6029 }
6030 
6031 // checkPointerTypesForAssignment - This is a very tricky routine (despite
6032 // being closely modeled after the C99 spec:-). The odd characteristic of this
6033 // routine is it effectively iqnores the qualifiers on the top level pointee.
6034 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
6035 // FIXME: add a couple examples in this comment.
6036 static Sema::AssignConvertType
6037 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
6038   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6039   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6040 
6041   // get the "pointed to" type (ignoring qualifiers at the top level)
6042   const Type *lhptee, *rhptee;
6043   Qualifiers lhq, rhq;
6044   std::tie(lhptee, lhq) =
6045       cast<PointerType>(LHSType)->getPointeeType().split().asPair();
6046   std::tie(rhptee, rhq) =
6047       cast<PointerType>(RHSType)->getPointeeType().split().asPair();
6048 
6049   Sema::AssignConvertType ConvTy = Sema::Compatible;
6050 
6051   // C99 6.5.16.1p1: This following citation is common to constraints
6052   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
6053   // qualifiers of the type *pointed to* by the right;
6054 
6055   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
6056   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
6057       lhq.compatiblyIncludesObjCLifetime(rhq)) {
6058     // Ignore lifetime for further calculation.
6059     lhq.removeObjCLifetime();
6060     rhq.removeObjCLifetime();
6061   }
6062 
6063   if (!lhq.compatiblyIncludes(rhq)) {
6064     // Treat address-space mismatches as fatal.  TODO: address subspaces
6065     if (lhq.getAddressSpace() != rhq.getAddressSpace())
6066       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6067 
6068     // It's okay to add or remove GC or lifetime qualifiers when converting to
6069     // and from void*.
6070     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
6071                         .compatiblyIncludes(
6072                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
6073              && (lhptee->isVoidType() || rhptee->isVoidType()))
6074       ; // keep old
6075 
6076     // Treat lifetime mismatches as fatal.
6077     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
6078       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
6079 
6080     // For GCC compatibility, other qualifier mismatches are treated
6081     // as still compatible in C.
6082     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6083   }
6084 
6085   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
6086   // incomplete type and the other is a pointer to a qualified or unqualified
6087   // version of void...
6088   if (lhptee->isVoidType()) {
6089     if (rhptee->isIncompleteOrObjectType())
6090       return ConvTy;
6091 
6092     // As an extension, we allow cast to/from void* to function pointer.
6093     assert(rhptee->isFunctionType());
6094     return Sema::FunctionVoidPointer;
6095   }
6096 
6097   if (rhptee->isVoidType()) {
6098     if (lhptee->isIncompleteOrObjectType())
6099       return ConvTy;
6100 
6101     // As an extension, we allow cast to/from void* to function pointer.
6102     assert(lhptee->isFunctionType());
6103     return Sema::FunctionVoidPointer;
6104   }
6105 
6106   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
6107   // unqualified versions of compatible types, ...
6108   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
6109   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
6110     // Check if the pointee types are compatible ignoring the sign.
6111     // We explicitly check for char so that we catch "char" vs
6112     // "unsigned char" on systems where "char" is unsigned.
6113     if (lhptee->isCharType())
6114       ltrans = S.Context.UnsignedCharTy;
6115     else if (lhptee->hasSignedIntegerRepresentation())
6116       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
6117 
6118     if (rhptee->isCharType())
6119       rtrans = S.Context.UnsignedCharTy;
6120     else if (rhptee->hasSignedIntegerRepresentation())
6121       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
6122 
6123     if (ltrans == rtrans) {
6124       // Types are compatible ignoring the sign. Qualifier incompatibility
6125       // takes priority over sign incompatibility because the sign
6126       // warning can be disabled.
6127       if (ConvTy != Sema::Compatible)
6128         return ConvTy;
6129 
6130       return Sema::IncompatiblePointerSign;
6131     }
6132 
6133     // If we are a multi-level pointer, it's possible that our issue is simply
6134     // one of qualification - e.g. char ** -> const char ** is not allowed. If
6135     // the eventual target type is the same and the pointers have the same
6136     // level of indirection, this must be the issue.
6137     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
6138       do {
6139         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
6140         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
6141       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
6142 
6143       if (lhptee == rhptee)
6144         return Sema::IncompatibleNestedPointerQualifiers;
6145     }
6146 
6147     // General pointer incompatibility takes priority over qualifiers.
6148     return Sema::IncompatiblePointer;
6149   }
6150   if (!S.getLangOpts().CPlusPlus &&
6151       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
6152     return Sema::IncompatiblePointer;
6153   return ConvTy;
6154 }
6155 
6156 /// checkBlockPointerTypesForAssignment - This routine determines whether two
6157 /// block pointer types are compatible or whether a block and normal pointer
6158 /// are compatible. It is more restrict than comparing two function pointer
6159 // types.
6160 static Sema::AssignConvertType
6161 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
6162                                     QualType RHSType) {
6163   assert(LHSType.isCanonical() && "LHS not canonicalized!");
6164   assert(RHSType.isCanonical() && "RHS not canonicalized!");
6165 
6166   QualType lhptee, rhptee;
6167 
6168   // get the "pointed to" type (ignoring qualifiers at the top level)
6169   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
6170   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
6171 
6172   // In C++, the types have to match exactly.
6173   if (S.getLangOpts().CPlusPlus)
6174     return Sema::IncompatibleBlockPointer;
6175 
6176   Sema::AssignConvertType ConvTy = Sema::Compatible;
6177 
6178   // For blocks we enforce that qualifiers are identical.
6179   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
6180     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
6181 
6182   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
6183     return Sema::IncompatibleBlockPointer;
6184 
6185   return ConvTy;
6186 }
6187 
6188 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
6189 /// for assignment compatibility.
6190 static Sema::AssignConvertType
6191 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
6192                                    QualType RHSType) {
6193   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
6194   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
6195 
6196   if (LHSType->isObjCBuiltinType()) {
6197     // Class is not compatible with ObjC object pointers.
6198     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
6199         !RHSType->isObjCQualifiedClassType())
6200       return Sema::IncompatiblePointer;
6201     return Sema::Compatible;
6202   }
6203   if (RHSType->isObjCBuiltinType()) {
6204     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
6205         !LHSType->isObjCQualifiedClassType())
6206       return Sema::IncompatiblePointer;
6207     return Sema::Compatible;
6208   }
6209   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6210   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
6211 
6212   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
6213       // make an exception for id<P>
6214       !LHSType->isObjCQualifiedIdType())
6215     return Sema::CompatiblePointerDiscardsQualifiers;
6216 
6217   if (S.Context.typesAreCompatible(LHSType, RHSType))
6218     return Sema::Compatible;
6219   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
6220     return Sema::IncompatibleObjCQualifiedId;
6221   return Sema::IncompatiblePointer;
6222 }
6223 
6224 Sema::AssignConvertType
6225 Sema::CheckAssignmentConstraints(SourceLocation Loc,
6226                                  QualType LHSType, QualType RHSType) {
6227   // Fake up an opaque expression.  We don't actually care about what
6228   // cast operations are required, so if CheckAssignmentConstraints
6229   // adds casts to this they'll be wasted, but fortunately that doesn't
6230   // usually happen on valid code.
6231   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
6232   ExprResult RHSPtr = &RHSExpr;
6233   CastKind K = CK_Invalid;
6234 
6235   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
6236 }
6237 
6238 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
6239 /// has code to accommodate several GCC extensions when type checking
6240 /// pointers. Here are some objectionable examples that GCC considers warnings:
6241 ///
6242 ///  int a, *pint;
6243 ///  short *pshort;
6244 ///  struct foo *pfoo;
6245 ///
6246 ///  pint = pshort; // warning: assignment from incompatible pointer type
6247 ///  a = pint; // warning: assignment makes integer from pointer without a cast
6248 ///  pint = a; // warning: assignment makes pointer from integer without a cast
6249 ///  pint = pfoo; // warning: assignment from incompatible pointer type
6250 ///
6251 /// As a result, the code for dealing with pointers is more complex than the
6252 /// C99 spec dictates.
6253 ///
6254 /// Sets 'Kind' for any result kind except Incompatible.
6255 Sema::AssignConvertType
6256 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6257                                  CastKind &Kind) {
6258   QualType RHSType = RHS.get()->getType();
6259   QualType OrigLHSType = LHSType;
6260 
6261   // Get canonical types.  We're not formatting these types, just comparing
6262   // them.
6263   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
6264   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
6265 
6266   // Common case: no conversion required.
6267   if (LHSType == RHSType) {
6268     Kind = CK_NoOp;
6269     return Compatible;
6270   }
6271 
6272   // If we have an atomic type, try a non-atomic assignment, then just add an
6273   // atomic qualification step.
6274   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
6275     Sema::AssignConvertType result =
6276       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
6277     if (result != Compatible)
6278       return result;
6279     if (Kind != CK_NoOp)
6280       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
6281     Kind = CK_NonAtomicToAtomic;
6282     return Compatible;
6283   }
6284 
6285   // If the left-hand side is a reference type, then we are in a
6286   // (rare!) case where we've allowed the use of references in C,
6287   // e.g., as a parameter type in a built-in function. In this case,
6288   // just make sure that the type referenced is compatible with the
6289   // right-hand side type. The caller is responsible for adjusting
6290   // LHSType so that the resulting expression does not have reference
6291   // type.
6292   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
6293     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
6294       Kind = CK_LValueBitCast;
6295       return Compatible;
6296     }
6297     return Incompatible;
6298   }
6299 
6300   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
6301   // to the same ExtVector type.
6302   if (LHSType->isExtVectorType()) {
6303     if (RHSType->isExtVectorType())
6304       return Incompatible;
6305     if (RHSType->isArithmeticType()) {
6306       // CK_VectorSplat does T -> vector T, so first cast to the
6307       // element type.
6308       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
6309       if (elType != RHSType) {
6310         Kind = PrepareScalarCast(RHS, elType);
6311         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
6312       }
6313       Kind = CK_VectorSplat;
6314       return Compatible;
6315     }
6316   }
6317 
6318   // Conversions to or from vector type.
6319   if (LHSType->isVectorType() || RHSType->isVectorType()) {
6320     if (LHSType->isVectorType() && RHSType->isVectorType()) {
6321       // Allow assignments of an AltiVec vector type to an equivalent GCC
6322       // vector type and vice versa
6323       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6324         Kind = CK_BitCast;
6325         return Compatible;
6326       }
6327 
6328       // If we are allowing lax vector conversions, and LHS and RHS are both
6329       // vectors, the total size only needs to be the same. This is a bitcast;
6330       // no bits are changed but the result type is different.
6331       if (isLaxVectorConversion(RHSType, LHSType)) {
6332         Kind = CK_BitCast;
6333         return IncompatibleVectors;
6334       }
6335     }
6336     return Incompatible;
6337   }
6338 
6339   // Arithmetic conversions.
6340   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
6341       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
6342     Kind = PrepareScalarCast(RHS, LHSType);
6343     return Compatible;
6344   }
6345 
6346   // Conversions to normal pointers.
6347   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
6348     // U* -> T*
6349     if (isa<PointerType>(RHSType)) {
6350       Kind = CK_BitCast;
6351       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
6352     }
6353 
6354     // int -> T*
6355     if (RHSType->isIntegerType()) {
6356       Kind = CK_IntegralToPointer; // FIXME: null?
6357       return IntToPointer;
6358     }
6359 
6360     // C pointers are not compatible with ObjC object pointers,
6361     // with two exceptions:
6362     if (isa<ObjCObjectPointerType>(RHSType)) {
6363       //  - conversions to void*
6364       if (LHSPointer->getPointeeType()->isVoidType()) {
6365         Kind = CK_BitCast;
6366         return Compatible;
6367       }
6368 
6369       //  - conversions from 'Class' to the redefinition type
6370       if (RHSType->isObjCClassType() &&
6371           Context.hasSameType(LHSType,
6372                               Context.getObjCClassRedefinitionType())) {
6373         Kind = CK_BitCast;
6374         return Compatible;
6375       }
6376 
6377       Kind = CK_BitCast;
6378       return IncompatiblePointer;
6379     }
6380 
6381     // U^ -> void*
6382     if (RHSType->getAs<BlockPointerType>()) {
6383       if (LHSPointer->getPointeeType()->isVoidType()) {
6384         Kind = CK_BitCast;
6385         return Compatible;
6386       }
6387     }
6388 
6389     return Incompatible;
6390   }
6391 
6392   // Conversions to block pointers.
6393   if (isa<BlockPointerType>(LHSType)) {
6394     // U^ -> T^
6395     if (RHSType->isBlockPointerType()) {
6396       Kind = CK_BitCast;
6397       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
6398     }
6399 
6400     // int or null -> T^
6401     if (RHSType->isIntegerType()) {
6402       Kind = CK_IntegralToPointer; // FIXME: null
6403       return IntToBlockPointer;
6404     }
6405 
6406     // id -> T^
6407     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
6408       Kind = CK_AnyPointerToBlockPointerCast;
6409       return Compatible;
6410     }
6411 
6412     // void* -> T^
6413     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
6414       if (RHSPT->getPointeeType()->isVoidType()) {
6415         Kind = CK_AnyPointerToBlockPointerCast;
6416         return Compatible;
6417       }
6418 
6419     return Incompatible;
6420   }
6421 
6422   // Conversions to Objective-C pointers.
6423   if (isa<ObjCObjectPointerType>(LHSType)) {
6424     // A* -> B*
6425     if (RHSType->isObjCObjectPointerType()) {
6426       Kind = CK_BitCast;
6427       Sema::AssignConvertType result =
6428         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
6429       if (getLangOpts().ObjCAutoRefCount &&
6430           result == Compatible &&
6431           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
6432         result = IncompatibleObjCWeakRef;
6433       return result;
6434     }
6435 
6436     // int or null -> A*
6437     if (RHSType->isIntegerType()) {
6438       Kind = CK_IntegralToPointer; // FIXME: null
6439       return IntToPointer;
6440     }
6441 
6442     // In general, C pointers are not compatible with ObjC object pointers,
6443     // with two exceptions:
6444     if (isa<PointerType>(RHSType)) {
6445       Kind = CK_CPointerToObjCPointerCast;
6446 
6447       //  - conversions from 'void*'
6448       if (RHSType->isVoidPointerType()) {
6449         return Compatible;
6450       }
6451 
6452       //  - conversions to 'Class' from its redefinition type
6453       if (LHSType->isObjCClassType() &&
6454           Context.hasSameType(RHSType,
6455                               Context.getObjCClassRedefinitionType())) {
6456         return Compatible;
6457       }
6458 
6459       return IncompatiblePointer;
6460     }
6461 
6462     // T^ -> A*
6463     if (RHSType->isBlockPointerType()) {
6464       maybeExtendBlockObject(*this, RHS);
6465       Kind = CK_BlockPointerToObjCPointerCast;
6466       return Compatible;
6467     }
6468 
6469     return Incompatible;
6470   }
6471 
6472   // Conversions from pointers that are not covered by the above.
6473   if (isa<PointerType>(RHSType)) {
6474     // T* -> _Bool
6475     if (LHSType == Context.BoolTy) {
6476       Kind = CK_PointerToBoolean;
6477       return Compatible;
6478     }
6479 
6480     // T* -> int
6481     if (LHSType->isIntegerType()) {
6482       Kind = CK_PointerToIntegral;
6483       return PointerToInt;
6484     }
6485 
6486     return Incompatible;
6487   }
6488 
6489   // Conversions from Objective-C pointers that are not covered by the above.
6490   if (isa<ObjCObjectPointerType>(RHSType)) {
6491     // T* -> _Bool
6492     if (LHSType == Context.BoolTy) {
6493       Kind = CK_PointerToBoolean;
6494       return Compatible;
6495     }
6496 
6497     // T* -> int
6498     if (LHSType->isIntegerType()) {
6499       Kind = CK_PointerToIntegral;
6500       return PointerToInt;
6501     }
6502 
6503     return Incompatible;
6504   }
6505 
6506   // struct A -> struct B
6507   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6508     if (Context.typesAreCompatible(LHSType, RHSType)) {
6509       Kind = CK_NoOp;
6510       return Compatible;
6511     }
6512   }
6513 
6514   return Incompatible;
6515 }
6516 
6517 /// \brief Constructs a transparent union from an expression that is
6518 /// used to initialize the transparent union.
6519 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6520                                       ExprResult &EResult, QualType UnionType,
6521                                       FieldDecl *Field) {
6522   // Build an initializer list that designates the appropriate member
6523   // of the transparent union.
6524   Expr *E = EResult.take();
6525   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6526                                                    E, SourceLocation());
6527   Initializer->setType(UnionType);
6528   Initializer->setInitializedFieldInUnion(Field);
6529 
6530   // Build a compound literal constructing a value of the transparent
6531   // union type from this initializer list.
6532   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6533   EResult = S.Owned(
6534     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6535                                 VK_RValue, Initializer, false));
6536 }
6537 
6538 Sema::AssignConvertType
6539 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6540                                                ExprResult &RHS) {
6541   QualType RHSType = RHS.get()->getType();
6542 
6543   // If the ArgType is a Union type, we want to handle a potential
6544   // transparent_union GCC extension.
6545   const RecordType *UT = ArgType->getAsUnionType();
6546   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6547     return Incompatible;
6548 
6549   // The field to initialize within the transparent union.
6550   RecordDecl *UD = UT->getDecl();
6551   FieldDecl *InitField = 0;
6552   // It's compatible if the expression matches any of the fields.
6553   for (auto *it : UD->fields()) {
6554     if (it->getType()->isPointerType()) {
6555       // If the transparent union contains a pointer type, we allow:
6556       // 1) void pointer
6557       // 2) null pointer constant
6558       if (RHSType->isPointerType())
6559         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6560           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6561           InitField = it;
6562           break;
6563         }
6564 
6565       if (RHS.get()->isNullPointerConstant(Context,
6566                                            Expr::NPC_ValueDependentIsNull)) {
6567         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6568                                 CK_NullToPointer);
6569         InitField = it;
6570         break;
6571       }
6572     }
6573 
6574     CastKind Kind = CK_Invalid;
6575     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6576           == Compatible) {
6577       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6578       InitField = it;
6579       break;
6580     }
6581   }
6582 
6583   if (!InitField)
6584     return Incompatible;
6585 
6586   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6587   return Compatible;
6588 }
6589 
6590 Sema::AssignConvertType
6591 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6592                                        bool Diagnose,
6593                                        bool DiagnoseCFAudited) {
6594   if (getLangOpts().CPlusPlus) {
6595     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6596       // C++ 5.17p3: If the left operand is not of class type, the
6597       // expression is implicitly converted (C++ 4) to the
6598       // cv-unqualified type of the left operand.
6599       ExprResult Res;
6600       if (Diagnose) {
6601         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6602                                         AA_Assigning);
6603       } else {
6604         ImplicitConversionSequence ICS =
6605             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6606                                   /*SuppressUserConversions=*/false,
6607                                   /*AllowExplicit=*/false,
6608                                   /*InOverloadResolution=*/false,
6609                                   /*CStyle=*/false,
6610                                   /*AllowObjCWritebackConversion=*/false);
6611         if (ICS.isFailure())
6612           return Incompatible;
6613         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6614                                         ICS, AA_Assigning);
6615       }
6616       if (Res.isInvalid())
6617         return Incompatible;
6618       Sema::AssignConvertType result = Compatible;
6619       if (getLangOpts().ObjCAutoRefCount &&
6620           !CheckObjCARCUnavailableWeakConversion(LHSType,
6621                                                  RHS.get()->getType()))
6622         result = IncompatibleObjCWeakRef;
6623       RHS = Res;
6624       return result;
6625     }
6626 
6627     // FIXME: Currently, we fall through and treat C++ classes like C
6628     // structures.
6629     // FIXME: We also fall through for atomics; not sure what should
6630     // happen there, though.
6631   }
6632 
6633   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6634   // a null pointer constant.
6635   if ((LHSType->isPointerType() || LHSType->isObjCObjectPointerType() ||
6636        LHSType->isBlockPointerType()) &&
6637       RHS.get()->isNullPointerConstant(Context,
6638                                        Expr::NPC_ValueDependentIsNull)) {
6639     CastKind Kind;
6640     CXXCastPath Path;
6641     CheckPointerConversion(RHS.get(), LHSType, Kind, Path, false);
6642     RHS = ImpCastExprToType(RHS.take(), LHSType, Kind, VK_RValue, &Path);
6643     return Compatible;
6644   }
6645 
6646   // This check seems unnatural, however it is necessary to ensure the proper
6647   // conversion of functions/arrays. If the conversion were done for all
6648   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6649   // expressions that suppress this implicit conversion (&, sizeof).
6650   //
6651   // Suppress this for references: C++ 8.5.3p5.
6652   if (!LHSType->isReferenceType()) {
6653     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6654     if (RHS.isInvalid())
6655       return Incompatible;
6656   }
6657 
6658   CastKind Kind = CK_Invalid;
6659   Sema::AssignConvertType result =
6660     CheckAssignmentConstraints(LHSType, RHS, Kind);
6661 
6662   // C99 6.5.16.1p2: The value of the right operand is converted to the
6663   // type of the assignment expression.
6664   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6665   // so that we can use references in built-in functions even in C.
6666   // The getNonReferenceType() call makes sure that the resulting expression
6667   // does not have reference type.
6668   if (result != Incompatible && RHS.get()->getType() != LHSType) {
6669     QualType Ty = LHSType.getNonLValueExprType(Context);
6670     Expr *E = RHS.take();
6671     if (getLangOpts().ObjCAutoRefCount)
6672       CheckObjCARCConversion(SourceRange(), Ty, E, CCK_ImplicitConversion,
6673                              DiagnoseCFAudited);
6674     if (getLangOpts().ObjC1 &&
6675         (CheckObjCBridgeRelatedConversions(E->getLocStart(),
6676                                           LHSType, E->getType(), E) ||
6677          ConversionToObjCStringLiteralCheck(LHSType, E))) {
6678       RHS = Owned(E);
6679       return Compatible;
6680     }
6681 
6682     RHS = ImpCastExprToType(E, Ty, Kind);
6683   }
6684   return result;
6685 }
6686 
6687 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6688                                ExprResult &RHS) {
6689   Diag(Loc, diag::err_typecheck_invalid_operands)
6690     << LHS.get()->getType() << RHS.get()->getType()
6691     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6692   return QualType();
6693 }
6694 
6695 /// Try to convert a value of non-vector type to a vector type by converting
6696 /// the type to the element type of the vector and then performing a splat.
6697 /// If the language is OpenCL, we only use conversions that promote scalar
6698 /// rank; for C, Obj-C, and C++ we allow any real scalar conversion except
6699 /// for float->int.
6700 ///
6701 /// \param scalar - if non-null, actually perform the conversions
6702 /// \return true if the operation fails (but without diagnosing the failure)
6703 static bool tryVectorConvertAndSplat(Sema &S, ExprResult *scalar,
6704                                      QualType scalarTy,
6705                                      QualType vectorEltTy,
6706                                      QualType vectorTy) {
6707   // The conversion to apply to the scalar before splatting it,
6708   // if necessary.
6709   CastKind scalarCast = CK_Invalid;
6710 
6711   if (vectorEltTy->isIntegralType(S.Context)) {
6712     if (!scalarTy->isIntegralType(S.Context))
6713       return true;
6714     if (S.getLangOpts().OpenCL &&
6715         S.Context.getIntegerTypeOrder(vectorEltTy, scalarTy) < 0)
6716       return true;
6717     scalarCast = CK_IntegralCast;
6718   } else if (vectorEltTy->isRealFloatingType()) {
6719     if (scalarTy->isRealFloatingType()) {
6720       if (S.getLangOpts().OpenCL &&
6721           S.Context.getFloatingTypeOrder(vectorEltTy, scalarTy) < 0)
6722         return true;
6723       scalarCast = CK_FloatingCast;
6724     }
6725     else if (scalarTy->isIntegralType(S.Context))
6726       scalarCast = CK_IntegralToFloating;
6727     else
6728       return true;
6729   } else {
6730     return true;
6731   }
6732 
6733   // Adjust scalar if desired.
6734   if (scalar) {
6735     if (scalarCast != CK_Invalid)
6736       *scalar = S.ImpCastExprToType(scalar->take(), vectorEltTy, scalarCast);
6737     *scalar = S.ImpCastExprToType(scalar->take(), vectorTy, CK_VectorSplat);
6738   }
6739   return false;
6740 }
6741 
6742 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6743                                    SourceLocation Loc, bool IsCompAssign) {
6744   if (!IsCompAssign) {
6745     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6746     if (LHS.isInvalid())
6747       return QualType();
6748   }
6749   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6750   if (RHS.isInvalid())
6751     return QualType();
6752 
6753   // For conversion purposes, we ignore any qualifiers.
6754   // For example, "const float" and "float" are equivalent.
6755   QualType LHSType = LHS.get()->getType().getUnqualifiedType();
6756   QualType RHSType = RHS.get()->getType().getUnqualifiedType();
6757 
6758   // If the vector types are identical, return.
6759   if (Context.hasSameType(LHSType, RHSType))
6760     return LHSType;
6761 
6762   const VectorType *LHSVecType = LHSType->getAs<VectorType>();
6763   const VectorType *RHSVecType = RHSType->getAs<VectorType>();
6764   assert(LHSVecType || RHSVecType);
6765 
6766   // If we have compatible AltiVec and GCC vector types, use the AltiVec type.
6767   if (LHSVecType && RHSVecType &&
6768       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6769     if (isa<ExtVectorType>(LHSVecType)) {
6770       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6771       return LHSType;
6772     }
6773 
6774     if (!IsCompAssign)
6775       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6776     return RHSType;
6777   }
6778 
6779   // If there's an ext-vector type and a scalar, try to convert the scalar to
6780   // the vector element type and splat.
6781   if (!RHSVecType && isa<ExtVectorType>(LHSVecType)) {
6782     if (!tryVectorConvertAndSplat(*this, &RHS, RHSType,
6783                                   LHSVecType->getElementType(), LHSType))
6784       return LHSType;
6785   }
6786   if (!LHSVecType && isa<ExtVectorType>(RHSVecType)) {
6787     if (!tryVectorConvertAndSplat(*this, (IsCompAssign ? 0 : &LHS), LHSType,
6788                                   RHSVecType->getElementType(), RHSType))
6789       return RHSType;
6790   }
6791 
6792   // If we're allowing lax vector conversions, only the total (data) size
6793   // needs to be the same.
6794   // FIXME: Should we really be allowing this?
6795   // FIXME: We really just pick the LHS type arbitrarily?
6796   if (isLaxVectorConversion(RHSType, LHSType)) {
6797     QualType resultType = LHSType;
6798     RHS = ImpCastExprToType(RHS.take(), resultType, CK_BitCast);
6799     return resultType;
6800   }
6801 
6802   // Okay, the expression is invalid.
6803 
6804   // If there's a non-vector, non-real operand, diagnose that.
6805   if ((!RHSVecType && !RHSType->isRealType()) ||
6806       (!LHSVecType && !LHSType->isRealType())) {
6807     Diag(Loc, diag::err_typecheck_vector_not_convertable_non_scalar)
6808       << LHSType << RHSType
6809       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6810     return QualType();
6811   }
6812 
6813   // Otherwise, use the generic diagnostic.
6814   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6815     << LHSType << RHSType
6816     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6817   return QualType();
6818 }
6819 
6820 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6821 // expression.  These are mainly cases where the null pointer is used as an
6822 // integer instead of a pointer.
6823 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6824                                 SourceLocation Loc, bool IsCompare) {
6825   // The canonical way to check for a GNU null is with isNullPointerConstant,
6826   // but we use a bit of a hack here for speed; this is a relatively
6827   // hot path, and isNullPointerConstant is slow.
6828   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6829   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6830 
6831   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6832 
6833   // Avoid analyzing cases where the result will either be invalid (and
6834   // diagnosed as such) or entirely valid and not something to warn about.
6835   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6836       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6837     return;
6838 
6839   // Comparison operations would not make sense with a null pointer no matter
6840   // what the other expression is.
6841   if (!IsCompare) {
6842     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6843         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6844         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6845     return;
6846   }
6847 
6848   // The rest of the operations only make sense with a null pointer
6849   // if the other expression is a pointer.
6850   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6851       NonNullType->canDecayToPointerType())
6852     return;
6853 
6854   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6855       << LHSNull /* LHS is NULL */ << NonNullType
6856       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6857 }
6858 
6859 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6860                                            SourceLocation Loc,
6861                                            bool IsCompAssign, bool IsDiv) {
6862   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6863 
6864   if (LHS.get()->getType()->isVectorType() ||
6865       RHS.get()->getType()->isVectorType())
6866     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6867 
6868   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6869   if (LHS.isInvalid() || RHS.isInvalid())
6870     return QualType();
6871 
6872 
6873   if (compType.isNull() || !compType->isArithmeticType())
6874     return InvalidOperands(Loc, LHS, RHS);
6875 
6876   // Check for division by zero.
6877   llvm::APSInt RHSValue;
6878   if (IsDiv && !RHS.get()->isValueDependent() &&
6879       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6880     DiagRuntimeBehavior(Loc, RHS.get(),
6881                         PDiag(diag::warn_division_by_zero)
6882                           << RHS.get()->getSourceRange());
6883 
6884   return compType;
6885 }
6886 
6887 QualType Sema::CheckRemainderOperands(
6888   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6889   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6890 
6891   if (LHS.get()->getType()->isVectorType() ||
6892       RHS.get()->getType()->isVectorType()) {
6893     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6894         RHS.get()->getType()->hasIntegerRepresentation())
6895       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6896     return InvalidOperands(Loc, LHS, RHS);
6897   }
6898 
6899   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6900   if (LHS.isInvalid() || RHS.isInvalid())
6901     return QualType();
6902 
6903   if (compType.isNull() || !compType->isIntegerType())
6904     return InvalidOperands(Loc, LHS, RHS);
6905 
6906   // Check for remainder by zero.
6907   llvm::APSInt RHSValue;
6908   if (!RHS.get()->isValueDependent() &&
6909       RHS.get()->EvaluateAsInt(RHSValue, Context) && RHSValue == 0)
6910     DiagRuntimeBehavior(Loc, RHS.get(),
6911                         PDiag(diag::warn_remainder_by_zero)
6912                           << RHS.get()->getSourceRange());
6913 
6914   return compType;
6915 }
6916 
6917 /// \brief Diagnose invalid arithmetic on two void pointers.
6918 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6919                                                 Expr *LHSExpr, Expr *RHSExpr) {
6920   S.Diag(Loc, S.getLangOpts().CPlusPlus
6921                 ? diag::err_typecheck_pointer_arith_void_type
6922                 : diag::ext_gnu_void_ptr)
6923     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6924                             << RHSExpr->getSourceRange();
6925 }
6926 
6927 /// \brief Diagnose invalid arithmetic on a void pointer.
6928 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6929                                             Expr *Pointer) {
6930   S.Diag(Loc, S.getLangOpts().CPlusPlus
6931                 ? diag::err_typecheck_pointer_arith_void_type
6932                 : diag::ext_gnu_void_ptr)
6933     << 0 /* one pointer */ << Pointer->getSourceRange();
6934 }
6935 
6936 /// \brief Diagnose invalid arithmetic on two function pointers.
6937 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6938                                                     Expr *LHS, Expr *RHS) {
6939   assert(LHS->getType()->isAnyPointerType());
6940   assert(RHS->getType()->isAnyPointerType());
6941   S.Diag(Loc, S.getLangOpts().CPlusPlus
6942                 ? diag::err_typecheck_pointer_arith_function_type
6943                 : diag::ext_gnu_ptr_func_arith)
6944     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6945     // We only show the second type if it differs from the first.
6946     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6947                                                    RHS->getType())
6948     << RHS->getType()->getPointeeType()
6949     << LHS->getSourceRange() << RHS->getSourceRange();
6950 }
6951 
6952 /// \brief Diagnose invalid arithmetic on a function pointer.
6953 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6954                                                 Expr *Pointer) {
6955   assert(Pointer->getType()->isAnyPointerType());
6956   S.Diag(Loc, S.getLangOpts().CPlusPlus
6957                 ? diag::err_typecheck_pointer_arith_function_type
6958                 : diag::ext_gnu_ptr_func_arith)
6959     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6960     << 0 /* one pointer, so only one type */
6961     << Pointer->getSourceRange();
6962 }
6963 
6964 /// \brief Emit error if Operand is incomplete pointer type
6965 ///
6966 /// \returns True if pointer has incomplete type
6967 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6968                                                  Expr *Operand) {
6969   assert(Operand->getType()->isAnyPointerType() &&
6970          !Operand->getType()->isDependentType());
6971   QualType PointeeTy = Operand->getType()->getPointeeType();
6972   return S.RequireCompleteType(Loc, PointeeTy,
6973                                diag::err_typecheck_arithmetic_incomplete_type,
6974                                PointeeTy, Operand->getSourceRange());
6975 }
6976 
6977 /// \brief Check the validity of an arithmetic pointer operand.
6978 ///
6979 /// If the operand has pointer type, this code will check for pointer types
6980 /// which are invalid in arithmetic operations. These will be diagnosed
6981 /// appropriately, including whether or not the use is supported as an
6982 /// extension.
6983 ///
6984 /// \returns True when the operand is valid to use (even if as an extension).
6985 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6986                                             Expr *Operand) {
6987   if (!Operand->getType()->isAnyPointerType()) return true;
6988 
6989   QualType PointeeTy = Operand->getType()->getPointeeType();
6990   if (PointeeTy->isVoidType()) {
6991     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6992     return !S.getLangOpts().CPlusPlus;
6993   }
6994   if (PointeeTy->isFunctionType()) {
6995     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6996     return !S.getLangOpts().CPlusPlus;
6997   }
6998 
6999   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
7000 
7001   return true;
7002 }
7003 
7004 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
7005 /// operands.
7006 ///
7007 /// This routine will diagnose any invalid arithmetic on pointer operands much
7008 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
7009 /// for emitting a single diagnostic even for operations where both LHS and RHS
7010 /// are (potentially problematic) pointers.
7011 ///
7012 /// \returns True when the operand is valid to use (even if as an extension).
7013 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
7014                                                 Expr *LHSExpr, Expr *RHSExpr) {
7015   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
7016   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
7017   if (!isLHSPointer && !isRHSPointer) return true;
7018 
7019   QualType LHSPointeeTy, RHSPointeeTy;
7020   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
7021   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
7022 
7023   // Check for arithmetic on pointers to incomplete types.
7024   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
7025   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
7026   if (isLHSVoidPtr || isRHSVoidPtr) {
7027     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
7028     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
7029     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
7030 
7031     return !S.getLangOpts().CPlusPlus;
7032   }
7033 
7034   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
7035   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
7036   if (isLHSFuncPtr || isRHSFuncPtr) {
7037     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
7038     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
7039                                                                 RHSExpr);
7040     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
7041 
7042     return !S.getLangOpts().CPlusPlus;
7043   }
7044 
7045   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
7046     return false;
7047   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
7048     return false;
7049 
7050   return true;
7051 }
7052 
7053 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
7054 /// literal.
7055 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
7056                                   Expr *LHSExpr, Expr *RHSExpr) {
7057   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
7058   Expr* IndexExpr = RHSExpr;
7059   if (!StrExpr) {
7060     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
7061     IndexExpr = LHSExpr;
7062   }
7063 
7064   bool IsStringPlusInt = StrExpr &&
7065       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
7066   if (!IsStringPlusInt)
7067     return;
7068 
7069   llvm::APSInt index;
7070   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
7071     unsigned StrLenWithNull = StrExpr->getLength() + 1;
7072     if (index.isNonNegative() &&
7073         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
7074                               index.isUnsigned()))
7075       return;
7076   }
7077 
7078   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7079   Self.Diag(OpLoc, diag::warn_string_plus_int)
7080       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
7081 
7082   // Only print a fixit for "str" + int, not for int + "str".
7083   if (IndexExpr == RHSExpr) {
7084     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7085     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7086         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7087         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7088         << FixItHint::CreateInsertion(EndLoc, "]");
7089   } else
7090     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7091 }
7092 
7093 /// \brief Emit a warning when adding a char literal to a string.
7094 static void diagnoseStringPlusChar(Sema &Self, SourceLocation OpLoc,
7095                                    Expr *LHSExpr, Expr *RHSExpr) {
7096   const DeclRefExpr *StringRefExpr =
7097       dyn_cast<DeclRefExpr>(LHSExpr->IgnoreImpCasts());
7098   const CharacterLiteral *CharExpr =
7099       dyn_cast<CharacterLiteral>(RHSExpr->IgnoreImpCasts());
7100   if (!StringRefExpr) {
7101     StringRefExpr = dyn_cast<DeclRefExpr>(RHSExpr->IgnoreImpCasts());
7102     CharExpr = dyn_cast<CharacterLiteral>(LHSExpr->IgnoreImpCasts());
7103   }
7104 
7105   if (!CharExpr || !StringRefExpr)
7106     return;
7107 
7108   const QualType StringType = StringRefExpr->getType();
7109 
7110   // Return if not a PointerType.
7111   if (!StringType->isAnyPointerType())
7112     return;
7113 
7114   // Return if not a CharacterType.
7115   if (!StringType->getPointeeType()->isAnyCharacterType())
7116     return;
7117 
7118   ASTContext &Ctx = Self.getASTContext();
7119   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
7120 
7121   const QualType CharType = CharExpr->getType();
7122   if (!CharType->isAnyCharacterType() &&
7123       CharType->isIntegerType() &&
7124       llvm::isUIntN(Ctx.getCharWidth(), CharExpr->getValue())) {
7125     Self.Diag(OpLoc, diag::warn_string_plus_char)
7126         << DiagRange << Ctx.CharTy;
7127   } else {
7128     Self.Diag(OpLoc, diag::warn_string_plus_char)
7129         << DiagRange << CharExpr->getType();
7130   }
7131 
7132   // Only print a fixit for str + char, not for char + str.
7133   if (isa<CharacterLiteral>(RHSExpr->IgnoreImpCasts())) {
7134     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
7135     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence)
7136         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
7137         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
7138         << FixItHint::CreateInsertion(EndLoc, "]");
7139   } else {
7140     Self.Diag(OpLoc, diag::note_string_plus_scalar_silence);
7141   }
7142 }
7143 
7144 /// \brief Emit error when two pointers are incompatible.
7145 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
7146                                            Expr *LHSExpr, Expr *RHSExpr) {
7147   assert(LHSExpr->getType()->isAnyPointerType());
7148   assert(RHSExpr->getType()->isAnyPointerType());
7149   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
7150     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
7151     << RHSExpr->getSourceRange();
7152 }
7153 
7154 QualType Sema::CheckAdditionOperands( // C99 6.5.6
7155     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
7156     QualType* CompLHSTy) {
7157   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7158 
7159   if (LHS.get()->getType()->isVectorType() ||
7160       RHS.get()->getType()->isVectorType()) {
7161     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7162     if (CompLHSTy) *CompLHSTy = compType;
7163     return compType;
7164   }
7165 
7166   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7167   if (LHS.isInvalid() || RHS.isInvalid())
7168     return QualType();
7169 
7170   // Diagnose "string literal" '+' int and string '+' "char literal".
7171   if (Opc == BO_Add) {
7172     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
7173     diagnoseStringPlusChar(*this, Loc, LHS.get(), RHS.get());
7174   }
7175 
7176   // handle the common case first (both operands are arithmetic).
7177   if (!compType.isNull() && compType->isArithmeticType()) {
7178     if (CompLHSTy) *CompLHSTy = compType;
7179     return compType;
7180   }
7181 
7182   // Type-checking.  Ultimately the pointer's going to be in PExp;
7183   // note that we bias towards the LHS being the pointer.
7184   Expr *PExp = LHS.get(), *IExp = RHS.get();
7185 
7186   bool isObjCPointer;
7187   if (PExp->getType()->isPointerType()) {
7188     isObjCPointer = false;
7189   } else if (PExp->getType()->isObjCObjectPointerType()) {
7190     isObjCPointer = true;
7191   } else {
7192     std::swap(PExp, IExp);
7193     if (PExp->getType()->isPointerType()) {
7194       isObjCPointer = false;
7195     } else if (PExp->getType()->isObjCObjectPointerType()) {
7196       isObjCPointer = true;
7197     } else {
7198       return InvalidOperands(Loc, LHS, RHS);
7199     }
7200   }
7201   assert(PExp->getType()->isAnyPointerType());
7202 
7203   if (!IExp->getType()->isIntegerType())
7204     return InvalidOperands(Loc, LHS, RHS);
7205 
7206   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
7207     return QualType();
7208 
7209   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
7210     return QualType();
7211 
7212   // Check array bounds for pointer arithemtic
7213   CheckArrayAccess(PExp, IExp);
7214 
7215   if (CompLHSTy) {
7216     QualType LHSTy = Context.isPromotableBitField(LHS.get());
7217     if (LHSTy.isNull()) {
7218       LHSTy = LHS.get()->getType();
7219       if (LHSTy->isPromotableIntegerType())
7220         LHSTy = Context.getPromotedIntegerType(LHSTy);
7221     }
7222     *CompLHSTy = LHSTy;
7223   }
7224 
7225   return PExp->getType();
7226 }
7227 
7228 // C99 6.5.6
7229 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
7230                                         SourceLocation Loc,
7231                                         QualType* CompLHSTy) {
7232   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7233 
7234   if (LHS.get()->getType()->isVectorType() ||
7235       RHS.get()->getType()->isVectorType()) {
7236     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
7237     if (CompLHSTy) *CompLHSTy = compType;
7238     return compType;
7239   }
7240 
7241   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
7242   if (LHS.isInvalid() || RHS.isInvalid())
7243     return QualType();
7244 
7245   // Enforce type constraints: C99 6.5.6p3.
7246 
7247   // Handle the common case first (both operands are arithmetic).
7248   if (!compType.isNull() && compType->isArithmeticType()) {
7249     if (CompLHSTy) *CompLHSTy = compType;
7250     return compType;
7251   }
7252 
7253   // Either ptr - int   or   ptr - ptr.
7254   if (LHS.get()->getType()->isAnyPointerType()) {
7255     QualType lpointee = LHS.get()->getType()->getPointeeType();
7256 
7257     // Diagnose bad cases where we step over interface counts.
7258     if (LHS.get()->getType()->isObjCObjectPointerType() &&
7259         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
7260       return QualType();
7261 
7262     // The result type of a pointer-int computation is the pointer type.
7263     if (RHS.get()->getType()->isIntegerType()) {
7264       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
7265         return QualType();
7266 
7267       // Check array bounds for pointer arithemtic
7268       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
7269                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
7270 
7271       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7272       return LHS.get()->getType();
7273     }
7274 
7275     // Handle pointer-pointer subtractions.
7276     if (const PointerType *RHSPTy
7277           = RHS.get()->getType()->getAs<PointerType>()) {
7278       QualType rpointee = RHSPTy->getPointeeType();
7279 
7280       if (getLangOpts().CPlusPlus) {
7281         // Pointee types must be the same: C++ [expr.add]
7282         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
7283           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7284         }
7285       } else {
7286         // Pointee types must be compatible C99 6.5.6p3
7287         if (!Context.typesAreCompatible(
7288                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
7289                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
7290           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
7291           return QualType();
7292         }
7293       }
7294 
7295       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
7296                                                LHS.get(), RHS.get()))
7297         return QualType();
7298 
7299       // The pointee type may have zero size.  As an extension, a structure or
7300       // union may have zero size or an array may have zero length.  In this
7301       // case subtraction does not make sense.
7302       if (!rpointee->isVoidType() && !rpointee->isFunctionType()) {
7303         CharUnits ElementSize = Context.getTypeSizeInChars(rpointee);
7304         if (ElementSize.isZero()) {
7305           Diag(Loc,diag::warn_sub_ptr_zero_size_types)
7306             << rpointee.getUnqualifiedType()
7307             << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7308         }
7309       }
7310 
7311       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
7312       return Context.getPointerDiffType();
7313     }
7314   }
7315 
7316   return InvalidOperands(Loc, LHS, RHS);
7317 }
7318 
7319 static bool isScopedEnumerationType(QualType T) {
7320   if (const EnumType *ET = dyn_cast<EnumType>(T))
7321     return ET->getDecl()->isScoped();
7322   return false;
7323 }
7324 
7325 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
7326                                    SourceLocation Loc, unsigned Opc,
7327                                    QualType LHSType) {
7328   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
7329   // so skip remaining warnings as we don't want to modify values within Sema.
7330   if (S.getLangOpts().OpenCL)
7331     return;
7332 
7333   llvm::APSInt Right;
7334   // Check right/shifter operand
7335   if (RHS.get()->isValueDependent() ||
7336       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
7337     return;
7338 
7339   if (Right.isNegative()) {
7340     S.DiagRuntimeBehavior(Loc, RHS.get(),
7341                           S.PDiag(diag::warn_shift_negative)
7342                             << RHS.get()->getSourceRange());
7343     return;
7344   }
7345   llvm::APInt LeftBits(Right.getBitWidth(),
7346                        S.Context.getTypeSize(LHS.get()->getType()));
7347   if (Right.uge(LeftBits)) {
7348     S.DiagRuntimeBehavior(Loc, RHS.get(),
7349                           S.PDiag(diag::warn_shift_gt_typewidth)
7350                             << RHS.get()->getSourceRange());
7351     return;
7352   }
7353   if (Opc != BO_Shl)
7354     return;
7355 
7356   // When left shifting an ICE which is signed, we can check for overflow which
7357   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
7358   // integers have defined behavior modulo one more than the maximum value
7359   // representable in the result type, so never warn for those.
7360   llvm::APSInt Left;
7361   if (LHS.get()->isValueDependent() ||
7362       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
7363       LHSType->hasUnsignedIntegerRepresentation())
7364     return;
7365   llvm::APInt ResultBits =
7366       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
7367   if (LeftBits.uge(ResultBits))
7368     return;
7369   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
7370   Result = Result.shl(Right);
7371 
7372   // Print the bit representation of the signed integer as an unsigned
7373   // hexadecimal number.
7374   SmallString<40> HexResult;
7375   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
7376 
7377   // If we are only missing a sign bit, this is less likely to result in actual
7378   // bugs -- if the result is cast back to an unsigned type, it will have the
7379   // expected value. Thus we place this behind a different warning that can be
7380   // turned off separately if needed.
7381   if (LeftBits == ResultBits - 1) {
7382     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
7383         << HexResult.str() << LHSType
7384         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7385     return;
7386   }
7387 
7388   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
7389     << HexResult.str() << Result.getMinSignedBits() << LHSType
7390     << Left.getBitWidth() << LHS.get()->getSourceRange()
7391     << RHS.get()->getSourceRange();
7392 }
7393 
7394 // C99 6.5.7
7395 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
7396                                   SourceLocation Loc, unsigned Opc,
7397                                   bool IsCompAssign) {
7398   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7399 
7400   // Vector shifts promote their scalar inputs to vector type.
7401   if (LHS.get()->getType()->isVectorType() ||
7402       RHS.get()->getType()->isVectorType())
7403     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7404 
7405   // Shifts don't perform usual arithmetic conversions, they just do integer
7406   // promotions on each operand. C99 6.5.7p3
7407 
7408   // For the LHS, do usual unary conversions, but then reset them away
7409   // if this is a compound assignment.
7410   ExprResult OldLHS = LHS;
7411   LHS = UsualUnaryConversions(LHS.take());
7412   if (LHS.isInvalid())
7413     return QualType();
7414   QualType LHSType = LHS.get()->getType();
7415   if (IsCompAssign) LHS = OldLHS;
7416 
7417   // The RHS is simpler.
7418   RHS = UsualUnaryConversions(RHS.take());
7419   if (RHS.isInvalid())
7420     return QualType();
7421   QualType RHSType = RHS.get()->getType();
7422 
7423   // C99 6.5.7p2: Each of the operands shall have integer type.
7424   if (!LHSType->hasIntegerRepresentation() ||
7425       !RHSType->hasIntegerRepresentation())
7426     return InvalidOperands(Loc, LHS, RHS);
7427 
7428   // C++0x: Don't allow scoped enums. FIXME: Use something better than
7429   // hasIntegerRepresentation() above instead of this.
7430   if (isScopedEnumerationType(LHSType) ||
7431       isScopedEnumerationType(RHSType)) {
7432     return InvalidOperands(Loc, LHS, RHS);
7433   }
7434   // Sanity-check shift operands
7435   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
7436 
7437   // "The type of the result is that of the promoted left operand."
7438   return LHSType;
7439 }
7440 
7441 static bool IsWithinTemplateSpecialization(Decl *D) {
7442   if (DeclContext *DC = D->getDeclContext()) {
7443     if (isa<ClassTemplateSpecializationDecl>(DC))
7444       return true;
7445     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
7446       return FD->isFunctionTemplateSpecialization();
7447   }
7448   return false;
7449 }
7450 
7451 /// If two different enums are compared, raise a warning.
7452 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
7453                                 Expr *RHS) {
7454   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
7455   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
7456 
7457   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
7458   if (!LHSEnumType)
7459     return;
7460   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
7461   if (!RHSEnumType)
7462     return;
7463 
7464   // Ignore anonymous enums.
7465   if (!LHSEnumType->getDecl()->getIdentifier())
7466     return;
7467   if (!RHSEnumType->getDecl()->getIdentifier())
7468     return;
7469 
7470   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
7471     return;
7472 
7473   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
7474       << LHSStrippedType << RHSStrippedType
7475       << LHS->getSourceRange() << RHS->getSourceRange();
7476 }
7477 
7478 /// \brief Diagnose bad pointer comparisons.
7479 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
7480                                               ExprResult &LHS, ExprResult &RHS,
7481                                               bool IsError) {
7482   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
7483                       : diag::ext_typecheck_comparison_of_distinct_pointers)
7484     << LHS.get()->getType() << RHS.get()->getType()
7485     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7486 }
7487 
7488 /// \brief Returns false if the pointers are converted to a composite type,
7489 /// true otherwise.
7490 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
7491                                            ExprResult &LHS, ExprResult &RHS) {
7492   // C++ [expr.rel]p2:
7493   //   [...] Pointer conversions (4.10) and qualification
7494   //   conversions (4.4) are performed on pointer operands (or on
7495   //   a pointer operand and a null pointer constant) to bring
7496   //   them to their composite pointer type. [...]
7497   //
7498   // C++ [expr.eq]p1 uses the same notion for (in)equality
7499   // comparisons of pointers.
7500 
7501   // C++ [expr.eq]p2:
7502   //   In addition, pointers to members can be compared, or a pointer to
7503   //   member and a null pointer constant. Pointer to member conversions
7504   //   (4.11) and qualification conversions (4.4) are performed to bring
7505   //   them to a common type. If one operand is a null pointer constant,
7506   //   the common type is the type of the other operand. Otherwise, the
7507   //   common type is a pointer to member type similar (4.4) to the type
7508   //   of one of the operands, with a cv-qualification signature (4.4)
7509   //   that is the union of the cv-qualification signatures of the operand
7510   //   types.
7511 
7512   QualType LHSType = LHS.get()->getType();
7513   QualType RHSType = RHS.get()->getType();
7514   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
7515          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
7516 
7517   bool NonStandardCompositeType = false;
7518   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
7519   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
7520   if (T.isNull()) {
7521     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
7522     return true;
7523   }
7524 
7525   if (NonStandardCompositeType)
7526     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
7527       << LHSType << RHSType << T << LHS.get()->getSourceRange()
7528       << RHS.get()->getSourceRange();
7529 
7530   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
7531   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
7532   return false;
7533 }
7534 
7535 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
7536                                                     ExprResult &LHS,
7537                                                     ExprResult &RHS,
7538                                                     bool IsError) {
7539   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
7540                       : diag::ext_typecheck_comparison_of_fptr_to_void)
7541     << LHS.get()->getType() << RHS.get()->getType()
7542     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
7543 }
7544 
7545 static bool isObjCObjectLiteral(ExprResult &E) {
7546   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
7547   case Stmt::ObjCArrayLiteralClass:
7548   case Stmt::ObjCDictionaryLiteralClass:
7549   case Stmt::ObjCStringLiteralClass:
7550   case Stmt::ObjCBoxedExprClass:
7551     return true;
7552   default:
7553     // Note that ObjCBoolLiteral is NOT an object literal!
7554     return false;
7555   }
7556 }
7557 
7558 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
7559   const ObjCObjectPointerType *Type =
7560     LHS->getType()->getAs<ObjCObjectPointerType>();
7561 
7562   // If this is not actually an Objective-C object, bail out.
7563   if (!Type)
7564     return false;
7565 
7566   // Get the LHS object's interface type.
7567   QualType InterfaceType = Type->getPointeeType();
7568   if (const ObjCObjectType *iQFaceTy =
7569       InterfaceType->getAsObjCQualifiedInterfaceType())
7570     InterfaceType = iQFaceTy->getBaseType();
7571 
7572   // If the RHS isn't an Objective-C object, bail out.
7573   if (!RHS->getType()->isObjCObjectPointerType())
7574     return false;
7575 
7576   // Try to find the -isEqual: method.
7577   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7578   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7579                                                       InterfaceType,
7580                                                       /*instance=*/true);
7581   if (!Method) {
7582     if (Type->isObjCIdType()) {
7583       // For 'id', just check the global pool.
7584       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7585                                                   /*receiverId=*/true,
7586                                                   /*warn=*/false);
7587     } else {
7588       // Check protocols.
7589       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7590                                              /*instance=*/true);
7591     }
7592   }
7593 
7594   if (!Method)
7595     return false;
7596 
7597   QualType T = Method->param_begin()[0]->getType();
7598   if (!T->isObjCObjectPointerType())
7599     return false;
7600 
7601   QualType R = Method->getReturnType();
7602   if (!R->isScalarType())
7603     return false;
7604 
7605   return true;
7606 }
7607 
7608 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7609   FromE = FromE->IgnoreParenImpCasts();
7610   switch (FromE->getStmtClass()) {
7611     default:
7612       break;
7613     case Stmt::ObjCStringLiteralClass:
7614       // "string literal"
7615       return LK_String;
7616     case Stmt::ObjCArrayLiteralClass:
7617       // "array literal"
7618       return LK_Array;
7619     case Stmt::ObjCDictionaryLiteralClass:
7620       // "dictionary literal"
7621       return LK_Dictionary;
7622     case Stmt::BlockExprClass:
7623       return LK_Block;
7624     case Stmt::ObjCBoxedExprClass: {
7625       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7626       switch (Inner->getStmtClass()) {
7627         case Stmt::IntegerLiteralClass:
7628         case Stmt::FloatingLiteralClass:
7629         case Stmt::CharacterLiteralClass:
7630         case Stmt::ObjCBoolLiteralExprClass:
7631         case Stmt::CXXBoolLiteralExprClass:
7632           // "numeric literal"
7633           return LK_Numeric;
7634         case Stmt::ImplicitCastExprClass: {
7635           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7636           // Boolean literals can be represented by implicit casts.
7637           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7638             return LK_Numeric;
7639           break;
7640         }
7641         default:
7642           break;
7643       }
7644       return LK_Boxed;
7645     }
7646   }
7647   return LK_None;
7648 }
7649 
7650 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7651                                           ExprResult &LHS, ExprResult &RHS,
7652                                           BinaryOperator::Opcode Opc){
7653   Expr *Literal;
7654   Expr *Other;
7655   if (isObjCObjectLiteral(LHS)) {
7656     Literal = LHS.get();
7657     Other = RHS.get();
7658   } else {
7659     Literal = RHS.get();
7660     Other = LHS.get();
7661   }
7662 
7663   // Don't warn on comparisons against nil.
7664   Other = Other->IgnoreParenCasts();
7665   if (Other->isNullPointerConstant(S.getASTContext(),
7666                                    Expr::NPC_ValueDependentIsNotNull))
7667     return;
7668 
7669   // This should be kept in sync with warn_objc_literal_comparison.
7670   // LK_String should always be after the other literals, since it has its own
7671   // warning flag.
7672   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7673   assert(LiteralKind != Sema::LK_Block);
7674   if (LiteralKind == Sema::LK_None) {
7675     llvm_unreachable("Unknown Objective-C object literal kind");
7676   }
7677 
7678   if (LiteralKind == Sema::LK_String)
7679     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7680       << Literal->getSourceRange();
7681   else
7682     S.Diag(Loc, diag::warn_objc_literal_comparison)
7683       << LiteralKind << Literal->getSourceRange();
7684 
7685   if (BinaryOperator::isEqualityOp(Opc) &&
7686       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7687     SourceLocation Start = LHS.get()->getLocStart();
7688     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7689     CharSourceRange OpRange =
7690       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7691 
7692     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7693       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7694       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7695       << FixItHint::CreateInsertion(End, "]");
7696   }
7697 }
7698 
7699 static void diagnoseLogicalNotOnLHSofComparison(Sema &S, ExprResult &LHS,
7700                                                 ExprResult &RHS,
7701                                                 SourceLocation Loc,
7702                                                 unsigned OpaqueOpc) {
7703   // This checking requires bools.
7704   if (!S.getLangOpts().Bool) return;
7705 
7706   // Check that left hand side is !something.
7707   UnaryOperator *UO = dyn_cast<UnaryOperator>(LHS.get()->IgnoreImpCasts());
7708   if (!UO || UO->getOpcode() != UO_LNot) return;
7709 
7710   // Only check if the right hand side is non-bool arithmetic type.
7711   if (RHS.get()->getType()->isBooleanType()) return;
7712 
7713   // Make sure that the something in !something is not bool.
7714   Expr *SubExpr = UO->getSubExpr()->IgnoreImpCasts();
7715   if (SubExpr->getType()->isBooleanType()) return;
7716 
7717   // Emit warning.
7718   S.Diag(UO->getOperatorLoc(), diag::warn_logical_not_on_lhs_of_comparison)
7719       << Loc;
7720 
7721   // First note suggest !(x < y)
7722   SourceLocation FirstOpen = SubExpr->getLocStart();
7723   SourceLocation FirstClose = RHS.get()->getLocEnd();
7724   FirstClose = S.getPreprocessor().getLocForEndOfToken(FirstClose);
7725   if (FirstClose.isInvalid())
7726     FirstOpen = SourceLocation();
7727   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_fix)
7728       << FixItHint::CreateInsertion(FirstOpen, "(")
7729       << FixItHint::CreateInsertion(FirstClose, ")");
7730 
7731   // Second note suggests (!x) < y
7732   SourceLocation SecondOpen = LHS.get()->getLocStart();
7733   SourceLocation SecondClose = LHS.get()->getLocEnd();
7734   SecondClose = S.getPreprocessor().getLocForEndOfToken(SecondClose);
7735   if (SecondClose.isInvalid())
7736     SecondOpen = SourceLocation();
7737   S.Diag(UO->getOperatorLoc(), diag::note_logical_not_silence_with_parens)
7738       << FixItHint::CreateInsertion(SecondOpen, "(")
7739       << FixItHint::CreateInsertion(SecondClose, ")");
7740 }
7741 
7742 // Get the decl for a simple expression: a reference to a variable,
7743 // an implicit C++ field reference, or an implicit ObjC ivar reference.
7744 static ValueDecl *getCompareDecl(Expr *E) {
7745   if (DeclRefExpr* DR = dyn_cast<DeclRefExpr>(E))
7746     return DR->getDecl();
7747   if (ObjCIvarRefExpr* Ivar = dyn_cast<ObjCIvarRefExpr>(E)) {
7748     if (Ivar->isFreeIvar())
7749       return Ivar->getDecl();
7750   }
7751   if (MemberExpr* Mem = dyn_cast<MemberExpr>(E)) {
7752     if (Mem->isImplicitAccess())
7753       return Mem->getMemberDecl();
7754   }
7755   return 0;
7756 }
7757 
7758 // C99 6.5.8, C++ [expr.rel]
7759 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7760                                     SourceLocation Loc, unsigned OpaqueOpc,
7761                                     bool IsRelational) {
7762   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7763 
7764   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7765 
7766   // Handle vector comparisons separately.
7767   if (LHS.get()->getType()->isVectorType() ||
7768       RHS.get()->getType()->isVectorType())
7769     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7770 
7771   QualType LHSType = LHS.get()->getType();
7772   QualType RHSType = RHS.get()->getType();
7773 
7774   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7775   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7776 
7777   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7778   diagnoseLogicalNotOnLHSofComparison(*this, LHS, RHS, Loc, OpaqueOpc);
7779 
7780   if (!LHSType->hasFloatingRepresentation() &&
7781       !(LHSType->isBlockPointerType() && IsRelational) &&
7782       !LHS.get()->getLocStart().isMacroID() &&
7783       !RHS.get()->getLocStart().isMacroID() &&
7784       ActiveTemplateInstantiations.empty()) {
7785     // For non-floating point types, check for self-comparisons of the form
7786     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7787     // often indicate logic errors in the program.
7788     //
7789     // NOTE: Don't warn about comparison expressions resulting from macro
7790     // expansion. Also don't warn about comparisons which are only self
7791     // comparisons within a template specialization. The warnings should catch
7792     // obvious cases in the definition of the template anyways. The idea is to
7793     // warn when the typed comparison operator will always evaluate to the same
7794     // result.
7795     ValueDecl *DL = getCompareDecl(LHSStripped);
7796     ValueDecl *DR = getCompareDecl(RHSStripped);
7797     if (DL && DR && DL == DR && !IsWithinTemplateSpecialization(DL)) {
7798       DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7799                           << 0 // self-
7800                           << (Opc == BO_EQ
7801                               || Opc == BO_LE
7802                               || Opc == BO_GE));
7803     } else if (DL && DR && LHSType->isArrayType() && RHSType->isArrayType() &&
7804                !DL->getType()->isReferenceType() &&
7805                !DR->getType()->isReferenceType()) {
7806         // what is it always going to eval to?
7807         char always_evals_to;
7808         switch(Opc) {
7809         case BO_EQ: // e.g. array1 == array2
7810           always_evals_to = 0; // false
7811           break;
7812         case BO_NE: // e.g. array1 != array2
7813           always_evals_to = 1; // true
7814           break;
7815         default:
7816           // best we can say is 'a constant'
7817           always_evals_to = 2; // e.g. array1 <= array2
7818           break;
7819         }
7820         DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7821                             << 1 // array
7822                             << always_evals_to);
7823     }
7824 
7825     if (isa<CastExpr>(LHSStripped))
7826       LHSStripped = LHSStripped->IgnoreParenCasts();
7827     if (isa<CastExpr>(RHSStripped))
7828       RHSStripped = RHSStripped->IgnoreParenCasts();
7829 
7830     // Warn about comparisons against a string constant (unless the other
7831     // operand is null), the user probably wants strcmp.
7832     Expr *literalString = 0;
7833     Expr *literalStringStripped = 0;
7834     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7835         !RHSStripped->isNullPointerConstant(Context,
7836                                             Expr::NPC_ValueDependentIsNull)) {
7837       literalString = LHS.get();
7838       literalStringStripped = LHSStripped;
7839     } else if ((isa<StringLiteral>(RHSStripped) ||
7840                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7841                !LHSStripped->isNullPointerConstant(Context,
7842                                             Expr::NPC_ValueDependentIsNull)) {
7843       literalString = RHS.get();
7844       literalStringStripped = RHSStripped;
7845     }
7846 
7847     if (literalString) {
7848       DiagRuntimeBehavior(Loc, 0,
7849         PDiag(diag::warn_stringcompare)
7850           << isa<ObjCEncodeExpr>(literalStringStripped)
7851           << literalString->getSourceRange());
7852     }
7853   }
7854 
7855   // C99 6.5.8p3 / C99 6.5.9p4
7856   UsualArithmeticConversions(LHS, RHS);
7857   if (LHS.isInvalid() || RHS.isInvalid())
7858     return QualType();
7859 
7860   LHSType = LHS.get()->getType();
7861   RHSType = RHS.get()->getType();
7862 
7863   // The result of comparisons is 'bool' in C++, 'int' in C.
7864   QualType ResultTy = Context.getLogicalOperationType();
7865 
7866   if (IsRelational) {
7867     if (LHSType->isRealType() && RHSType->isRealType())
7868       return ResultTy;
7869   } else {
7870     // Check for comparisons of floating point operands using != and ==.
7871     if (LHSType->hasFloatingRepresentation())
7872       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7873 
7874     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7875       return ResultTy;
7876   }
7877 
7878   const Expr::NullPointerConstantKind LHSNullKind =
7879       LHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7880   const Expr::NullPointerConstantKind RHSNullKind =
7881       RHS.get()->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull);
7882   bool LHSIsNull = LHSNullKind != Expr::NPCK_NotNull;
7883   bool RHSIsNull = RHSNullKind != Expr::NPCK_NotNull;
7884 
7885   if (!IsRelational && LHSIsNull != RHSIsNull) {
7886     bool IsEquality = Opc == BO_EQ;
7887     if (RHSIsNull)
7888       DiagnoseAlwaysNonNullPointer(LHS.get(), RHSNullKind, IsEquality,
7889                                    RHS.get()->getSourceRange());
7890     else
7891       DiagnoseAlwaysNonNullPointer(RHS.get(), LHSNullKind, IsEquality,
7892                                    LHS.get()->getSourceRange());
7893   }
7894 
7895   // All of the following pointer-related warnings are GCC extensions, except
7896   // when handling null pointer constants.
7897   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7898     QualType LCanPointeeTy =
7899       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7900     QualType RCanPointeeTy =
7901       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7902 
7903     if (getLangOpts().CPlusPlus) {
7904       if (LCanPointeeTy == RCanPointeeTy)
7905         return ResultTy;
7906       if (!IsRelational &&
7907           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7908         // Valid unless comparison between non-null pointer and function pointer
7909         // This is a gcc extension compatibility comparison.
7910         // In a SFINAE context, we treat this as a hard error to maintain
7911         // conformance with the C++ standard.
7912         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7913             && !LHSIsNull && !RHSIsNull) {
7914           diagnoseFunctionPointerToVoidComparison(
7915               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7916 
7917           if (isSFINAEContext())
7918             return QualType();
7919 
7920           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7921           return ResultTy;
7922         }
7923       }
7924 
7925       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7926         return QualType();
7927       else
7928         return ResultTy;
7929     }
7930     // C99 6.5.9p2 and C99 6.5.8p2
7931     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7932                                    RCanPointeeTy.getUnqualifiedType())) {
7933       // Valid unless a relational comparison of function pointers
7934       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7935         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7936           << LHSType << RHSType << LHS.get()->getSourceRange()
7937           << RHS.get()->getSourceRange();
7938       }
7939     } else if (!IsRelational &&
7940                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7941       // Valid unless comparison between non-null pointer and function pointer
7942       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7943           && !LHSIsNull && !RHSIsNull)
7944         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7945                                                 /*isError*/false);
7946     } else {
7947       // Invalid
7948       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7949     }
7950     if (LCanPointeeTy != RCanPointeeTy) {
7951       unsigned AddrSpaceL = LCanPointeeTy.getAddressSpace();
7952       unsigned AddrSpaceR = RCanPointeeTy.getAddressSpace();
7953       CastKind Kind = AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion
7954                                                : CK_BitCast;
7955       if (LHSIsNull && !RHSIsNull)
7956         LHS = ImpCastExprToType(LHS.take(), RHSType, Kind);
7957       else
7958         RHS = ImpCastExprToType(RHS.take(), LHSType, Kind);
7959     }
7960     return ResultTy;
7961   }
7962 
7963   if (getLangOpts().CPlusPlus) {
7964     // Comparison of nullptr_t with itself.
7965     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7966       return ResultTy;
7967 
7968     // Comparison of pointers with null pointer constants and equality
7969     // comparisons of member pointers to null pointer constants.
7970     if (RHSIsNull &&
7971         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7972          (!IsRelational &&
7973           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7974       RHS = ImpCastExprToType(RHS.take(), LHSType,
7975                         LHSType->isMemberPointerType()
7976                           ? CK_NullToMemberPointer
7977                           : CK_NullToPointer);
7978       return ResultTy;
7979     }
7980     if (LHSIsNull &&
7981         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7982          (!IsRelational &&
7983           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7984       LHS = ImpCastExprToType(LHS.take(), RHSType,
7985                         RHSType->isMemberPointerType()
7986                           ? CK_NullToMemberPointer
7987                           : CK_NullToPointer);
7988       return ResultTy;
7989     }
7990 
7991     // Comparison of member pointers.
7992     if (!IsRelational &&
7993         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7994       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7995         return QualType();
7996       else
7997         return ResultTy;
7998     }
7999 
8000     // Handle scoped enumeration types specifically, since they don't promote
8001     // to integers.
8002     if (LHS.get()->getType()->isEnumeralType() &&
8003         Context.hasSameUnqualifiedType(LHS.get()->getType(),
8004                                        RHS.get()->getType()))
8005       return ResultTy;
8006   }
8007 
8008   // Handle block pointer types.
8009   if (!IsRelational && LHSType->isBlockPointerType() &&
8010       RHSType->isBlockPointerType()) {
8011     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
8012     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
8013 
8014     if (!LHSIsNull && !RHSIsNull &&
8015         !Context.typesAreCompatible(lpointee, rpointee)) {
8016       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8017         << LHSType << RHSType << LHS.get()->getSourceRange()
8018         << RHS.get()->getSourceRange();
8019     }
8020     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
8021     return ResultTy;
8022   }
8023 
8024   // Allow block pointers to be compared with null pointer constants.
8025   if (!IsRelational
8026       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
8027           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
8028     if (!LHSIsNull && !RHSIsNull) {
8029       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
8030              ->getPointeeType()->isVoidType())
8031             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
8032                 ->getPointeeType()->isVoidType())))
8033         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
8034           << LHSType << RHSType << LHS.get()->getSourceRange()
8035           << RHS.get()->getSourceRange();
8036     }
8037     if (LHSIsNull && !RHSIsNull)
8038       LHS = ImpCastExprToType(LHS.take(), RHSType,
8039                               RHSType->isPointerType() ? CK_BitCast
8040                                 : CK_AnyPointerToBlockPointerCast);
8041     else
8042       RHS = ImpCastExprToType(RHS.take(), LHSType,
8043                               LHSType->isPointerType() ? CK_BitCast
8044                                 : CK_AnyPointerToBlockPointerCast);
8045     return ResultTy;
8046   }
8047 
8048   if (LHSType->isObjCObjectPointerType() ||
8049       RHSType->isObjCObjectPointerType()) {
8050     const PointerType *LPT = LHSType->getAs<PointerType>();
8051     const PointerType *RPT = RHSType->getAs<PointerType>();
8052     if (LPT || RPT) {
8053       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
8054       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
8055 
8056       if (!LPtrToVoid && !RPtrToVoid &&
8057           !Context.typesAreCompatible(LHSType, RHSType)) {
8058         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8059                                           /*isError*/false);
8060       }
8061       if (LHSIsNull && !RHSIsNull) {
8062         Expr *E = LHS.take();
8063         if (getLangOpts().ObjCAutoRefCount)
8064           CheckObjCARCConversion(SourceRange(), RHSType, E, CCK_ImplicitConversion);
8065         LHS = ImpCastExprToType(E, RHSType,
8066                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8067       }
8068       else {
8069         Expr *E = RHS.take();
8070         if (getLangOpts().ObjCAutoRefCount)
8071           CheckObjCARCConversion(SourceRange(), LHSType, E, CCK_ImplicitConversion);
8072         RHS = ImpCastExprToType(E, LHSType,
8073                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
8074       }
8075       return ResultTy;
8076     }
8077     if (LHSType->isObjCObjectPointerType() &&
8078         RHSType->isObjCObjectPointerType()) {
8079       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
8080         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
8081                                           /*isError*/false);
8082       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
8083         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
8084 
8085       if (LHSIsNull && !RHSIsNull)
8086         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
8087       else
8088         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
8089       return ResultTy;
8090     }
8091   }
8092   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
8093       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
8094     unsigned DiagID = 0;
8095     bool isError = false;
8096     if (LangOpts.DebuggerSupport) {
8097       // Under a debugger, allow the comparison of pointers to integers,
8098       // since users tend to want to compare addresses.
8099     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
8100         (RHSIsNull && RHSType->isIntegerType())) {
8101       if (IsRelational && !getLangOpts().CPlusPlus)
8102         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
8103     } else if (IsRelational && !getLangOpts().CPlusPlus)
8104       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
8105     else if (getLangOpts().CPlusPlus) {
8106       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
8107       isError = true;
8108     } else
8109       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
8110 
8111     if (DiagID) {
8112       Diag(Loc, DiagID)
8113         << LHSType << RHSType << LHS.get()->getSourceRange()
8114         << RHS.get()->getSourceRange();
8115       if (isError)
8116         return QualType();
8117     }
8118 
8119     if (LHSType->isIntegerType())
8120       LHS = ImpCastExprToType(LHS.take(), RHSType,
8121                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8122     else
8123       RHS = ImpCastExprToType(RHS.take(), LHSType,
8124                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
8125     return ResultTy;
8126   }
8127 
8128   // Handle block pointers.
8129   if (!IsRelational && RHSIsNull
8130       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
8131     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
8132     return ResultTy;
8133   }
8134   if (!IsRelational && LHSIsNull
8135       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
8136     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
8137     return ResultTy;
8138   }
8139 
8140   return InvalidOperands(Loc, LHS, RHS);
8141 }
8142 
8143 
8144 // Return a signed type that is of identical size and number of elements.
8145 // For floating point vectors, return an integer type of identical size
8146 // and number of elements.
8147 QualType Sema::GetSignedVectorType(QualType V) {
8148   const VectorType *VTy = V->getAs<VectorType>();
8149   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
8150   if (TypeSize == Context.getTypeSize(Context.CharTy))
8151     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
8152   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
8153     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
8154   else if (TypeSize == Context.getTypeSize(Context.IntTy))
8155     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
8156   else if (TypeSize == Context.getTypeSize(Context.LongTy))
8157     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
8158   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
8159          "Unhandled vector element size in vector compare");
8160   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
8161 }
8162 
8163 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
8164 /// operates on extended vector types.  Instead of producing an IntTy result,
8165 /// like a scalar comparison, a vector comparison produces a vector of integer
8166 /// types.
8167 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
8168                                           SourceLocation Loc,
8169                                           bool IsRelational) {
8170   // Check to make sure we're operating on vectors of the same type and width,
8171   // Allowing one side to be a scalar of element type.
8172   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
8173   if (vType.isNull())
8174     return vType;
8175 
8176   QualType LHSType = LHS.get()->getType();
8177 
8178   // If AltiVec, the comparison results in a numeric type, i.e.
8179   // bool for C++, int for C
8180   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
8181     return Context.getLogicalOperationType();
8182 
8183   // For non-floating point types, check for self-comparisons of the form
8184   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
8185   // often indicate logic errors in the program.
8186   if (!LHSType->hasFloatingRepresentation() &&
8187       ActiveTemplateInstantiations.empty()) {
8188     if (DeclRefExpr* DRL
8189           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
8190       if (DeclRefExpr* DRR
8191             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
8192         if (DRL->getDecl() == DRR->getDecl())
8193           DiagRuntimeBehavior(Loc, 0,
8194                               PDiag(diag::warn_comparison_always)
8195                                 << 0 // self-
8196                                 << 2 // "a constant"
8197                               );
8198   }
8199 
8200   // Check for comparisons of floating point operands using != and ==.
8201   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
8202     assert (RHS.get()->getType()->hasFloatingRepresentation());
8203     CheckFloatComparison(Loc, LHS.get(), RHS.get());
8204   }
8205 
8206   // Return a signed type for the vector.
8207   return GetSignedVectorType(LHSType);
8208 }
8209 
8210 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
8211                                           SourceLocation Loc) {
8212   // Ensure that either both operands are of the same vector type, or
8213   // one operand is of a vector type and the other is of its element type.
8214   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
8215   if (vType.isNull())
8216     return InvalidOperands(Loc, LHS, RHS);
8217   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
8218       vType->hasFloatingRepresentation())
8219     return InvalidOperands(Loc, LHS, RHS);
8220 
8221   return GetSignedVectorType(LHS.get()->getType());
8222 }
8223 
8224 inline QualType Sema::CheckBitwiseOperands(
8225   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
8226   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
8227 
8228   if (LHS.get()->getType()->isVectorType() ||
8229       RHS.get()->getType()->isVectorType()) {
8230     if (LHS.get()->getType()->hasIntegerRepresentation() &&
8231         RHS.get()->getType()->hasIntegerRepresentation())
8232       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
8233 
8234     return InvalidOperands(Loc, LHS, RHS);
8235   }
8236 
8237   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
8238   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
8239                                                  IsCompAssign);
8240   if (LHSResult.isInvalid() || RHSResult.isInvalid())
8241     return QualType();
8242   LHS = LHSResult.take();
8243   RHS = RHSResult.take();
8244 
8245   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
8246     return compType;
8247   return InvalidOperands(Loc, LHS, RHS);
8248 }
8249 
8250 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
8251   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
8252 
8253   // Check vector operands differently.
8254   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
8255     return CheckVectorLogicalOperands(LHS, RHS, Loc);
8256 
8257   // Diagnose cases where the user write a logical and/or but probably meant a
8258   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
8259   // is a constant.
8260   if (LHS.get()->getType()->isIntegerType() &&
8261       !LHS.get()->getType()->isBooleanType() &&
8262       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
8263       // Don't warn in macros or template instantiations.
8264       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
8265     // If the RHS can be constant folded, and if it constant folds to something
8266     // that isn't 0 or 1 (which indicate a potential logical operation that
8267     // happened to fold to true/false) then warn.
8268     // Parens on the RHS are ignored.
8269     llvm::APSInt Result;
8270     if (RHS.get()->EvaluateAsInt(Result, Context))
8271       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
8272           (Result != 0 && Result != 1)) {
8273         Diag(Loc, diag::warn_logical_instead_of_bitwise)
8274           << RHS.get()->getSourceRange()
8275           << (Opc == BO_LAnd ? "&&" : "||");
8276         // Suggest replacing the logical operator with the bitwise version
8277         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
8278             << (Opc == BO_LAnd ? "&" : "|")
8279             << FixItHint::CreateReplacement(SourceRange(
8280                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
8281                                                 getLangOpts())),
8282                                             Opc == BO_LAnd ? "&" : "|");
8283         if (Opc == BO_LAnd)
8284           // Suggest replacing "Foo() && kNonZero" with "Foo()"
8285           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
8286               << FixItHint::CreateRemoval(
8287                   SourceRange(
8288                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
8289                                                  0, getSourceManager(),
8290                                                  getLangOpts()),
8291                       RHS.get()->getLocEnd()));
8292       }
8293   }
8294 
8295   if (!Context.getLangOpts().CPlusPlus) {
8296     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
8297     // not operate on the built-in scalar and vector float types.
8298     if (Context.getLangOpts().OpenCL &&
8299         Context.getLangOpts().OpenCLVersion < 120) {
8300       if (LHS.get()->getType()->isFloatingType() ||
8301           RHS.get()->getType()->isFloatingType())
8302         return InvalidOperands(Loc, LHS, RHS);
8303     }
8304 
8305     LHS = UsualUnaryConversions(LHS.take());
8306     if (LHS.isInvalid())
8307       return QualType();
8308 
8309     RHS = UsualUnaryConversions(RHS.take());
8310     if (RHS.isInvalid())
8311       return QualType();
8312 
8313     if (!LHS.get()->getType()->isScalarType() ||
8314         !RHS.get()->getType()->isScalarType())
8315       return InvalidOperands(Loc, LHS, RHS);
8316 
8317     return Context.IntTy;
8318   }
8319 
8320   // The following is safe because we only use this method for
8321   // non-overloadable operands.
8322 
8323   // C++ [expr.log.and]p1
8324   // C++ [expr.log.or]p1
8325   // The operands are both contextually converted to type bool.
8326   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
8327   if (LHSRes.isInvalid())
8328     return InvalidOperands(Loc, LHS, RHS);
8329   LHS = LHSRes;
8330 
8331   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
8332   if (RHSRes.isInvalid())
8333     return InvalidOperands(Loc, LHS, RHS);
8334   RHS = RHSRes;
8335 
8336   // C++ [expr.log.and]p2
8337   // C++ [expr.log.or]p2
8338   // The result is a bool.
8339   return Context.BoolTy;
8340 }
8341 
8342 static bool IsReadonlyMessage(Expr *E, Sema &S) {
8343   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
8344   if (!ME) return false;
8345   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
8346   ObjCMessageExpr *Base =
8347     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
8348   if (!Base) return false;
8349   return Base->getMethodDecl() != 0;
8350 }
8351 
8352 /// Is the given expression (which must be 'const') a reference to a
8353 /// variable which was originally non-const, but which has become
8354 /// 'const' due to being captured within a block?
8355 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
8356 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
8357   assert(E->isLValue() && E->getType().isConstQualified());
8358   E = E->IgnoreParens();
8359 
8360   // Must be a reference to a declaration from an enclosing scope.
8361   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
8362   if (!DRE) return NCCK_None;
8363   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
8364 
8365   // The declaration must be a variable which is not declared 'const'.
8366   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
8367   if (!var) return NCCK_None;
8368   if (var->getType().isConstQualified()) return NCCK_None;
8369   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
8370 
8371   // Decide whether the first capture was for a block or a lambda.
8372   DeclContext *DC = S.CurContext, *Prev = 0;
8373   while (DC != var->getDeclContext()) {
8374     Prev = DC;
8375     DC = DC->getParent();
8376   }
8377   // Unless we have an init-capture, we've gone one step too far.
8378   if (!var->isInitCapture())
8379     DC = Prev;
8380   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
8381 }
8382 
8383 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
8384 /// emit an error and return true.  If so, return false.
8385 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
8386   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
8387   SourceLocation OrigLoc = Loc;
8388   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
8389                                                               &Loc);
8390   if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
8391     IsLV = Expr::MLV_InvalidMessageExpression;
8392   if (IsLV == Expr::MLV_Valid)
8393     return false;
8394 
8395   unsigned Diag = 0;
8396   bool NeedType = false;
8397   switch (IsLV) { // C99 6.5.16p2
8398   case Expr::MLV_ConstQualified:
8399     Diag = diag::err_typecheck_assign_const;
8400 
8401     // Use a specialized diagnostic when we're assigning to an object
8402     // from an enclosing function or block.
8403     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
8404       if (NCCK == NCCK_Block)
8405         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
8406       else
8407         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
8408       break;
8409     }
8410 
8411     // In ARC, use some specialized diagnostics for occasions where we
8412     // infer 'const'.  These are always pseudo-strong variables.
8413     if (S.getLangOpts().ObjCAutoRefCount) {
8414       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
8415       if (declRef && isa<VarDecl>(declRef->getDecl())) {
8416         VarDecl *var = cast<VarDecl>(declRef->getDecl());
8417 
8418         // Use the normal diagnostic if it's pseudo-__strong but the
8419         // user actually wrote 'const'.
8420         if (var->isARCPseudoStrong() &&
8421             (!var->getTypeSourceInfo() ||
8422              !var->getTypeSourceInfo()->getType().isConstQualified())) {
8423           // There are two pseudo-strong cases:
8424           //  - self
8425           ObjCMethodDecl *method = S.getCurMethodDecl();
8426           if (method && var == method->getSelfDecl())
8427             Diag = method->isClassMethod()
8428               ? diag::err_typecheck_arc_assign_self_class_method
8429               : diag::err_typecheck_arc_assign_self;
8430 
8431           //  - fast enumeration variables
8432           else
8433             Diag = diag::err_typecheck_arr_assign_enumeration;
8434 
8435           SourceRange Assign;
8436           if (Loc != OrigLoc)
8437             Assign = SourceRange(OrigLoc, OrigLoc);
8438           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8439           // We need to preserve the AST regardless, so migration tool
8440           // can do its job.
8441           return false;
8442         }
8443       }
8444     }
8445 
8446     break;
8447   case Expr::MLV_ArrayType:
8448   case Expr::MLV_ArrayTemporary:
8449     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
8450     NeedType = true;
8451     break;
8452   case Expr::MLV_NotObjectType:
8453     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
8454     NeedType = true;
8455     break;
8456   case Expr::MLV_LValueCast:
8457     Diag = diag::err_typecheck_lvalue_casts_not_supported;
8458     break;
8459   case Expr::MLV_Valid:
8460     llvm_unreachable("did not take early return for MLV_Valid");
8461   case Expr::MLV_InvalidExpression:
8462   case Expr::MLV_MemberFunction:
8463   case Expr::MLV_ClassTemporary:
8464     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
8465     break;
8466   case Expr::MLV_IncompleteType:
8467   case Expr::MLV_IncompleteVoidType:
8468     return S.RequireCompleteType(Loc, E->getType(),
8469              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
8470   case Expr::MLV_DuplicateVectorComponents:
8471     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
8472     break;
8473   case Expr::MLV_NoSetterProperty:
8474     llvm_unreachable("readonly properties should be processed differently");
8475   case Expr::MLV_InvalidMessageExpression:
8476     Diag = diag::error_readonly_message_assignment;
8477     break;
8478   case Expr::MLV_SubObjCPropertySetting:
8479     Diag = diag::error_no_subobject_property_setting;
8480     break;
8481   }
8482 
8483   SourceRange Assign;
8484   if (Loc != OrigLoc)
8485     Assign = SourceRange(OrigLoc, OrigLoc);
8486   if (NeedType)
8487     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
8488   else
8489     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
8490   return true;
8491 }
8492 
8493 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
8494                                          SourceLocation Loc,
8495                                          Sema &Sema) {
8496   // C / C++ fields
8497   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
8498   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
8499   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
8500     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
8501       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
8502   }
8503 
8504   // Objective-C instance variables
8505   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
8506   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
8507   if (OL && OR && OL->getDecl() == OR->getDecl()) {
8508     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
8509     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
8510     if (RL && RR && RL->getDecl() == RR->getDecl())
8511       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
8512   }
8513 }
8514 
8515 // C99 6.5.16.1
8516 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
8517                                        SourceLocation Loc,
8518                                        QualType CompoundType) {
8519   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
8520 
8521   // Verify that LHS is a modifiable lvalue, and emit error if not.
8522   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
8523     return QualType();
8524 
8525   QualType LHSType = LHSExpr->getType();
8526   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
8527                                              CompoundType;
8528   AssignConvertType ConvTy;
8529   if (CompoundType.isNull()) {
8530     Expr *RHSCheck = RHS.get();
8531 
8532     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
8533 
8534     QualType LHSTy(LHSType);
8535     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
8536     if (RHS.isInvalid())
8537       return QualType();
8538     // Special case of NSObject attributes on c-style pointer types.
8539     if (ConvTy == IncompatiblePointer &&
8540         ((Context.isObjCNSObjectType(LHSType) &&
8541           RHSType->isObjCObjectPointerType()) ||
8542          (Context.isObjCNSObjectType(RHSType) &&
8543           LHSType->isObjCObjectPointerType())))
8544       ConvTy = Compatible;
8545 
8546     if (ConvTy == Compatible &&
8547         LHSType->isObjCObjectType())
8548         Diag(Loc, diag::err_objc_object_assignment)
8549           << LHSType;
8550 
8551     // If the RHS is a unary plus or minus, check to see if they = and + are
8552     // right next to each other.  If so, the user may have typo'd "x =+ 4"
8553     // instead of "x += 4".
8554     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
8555       RHSCheck = ICE->getSubExpr();
8556     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
8557       if ((UO->getOpcode() == UO_Plus ||
8558            UO->getOpcode() == UO_Minus) &&
8559           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
8560           // Only if the two operators are exactly adjacent.
8561           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
8562           // And there is a space or other character before the subexpr of the
8563           // unary +/-.  We don't want to warn on "x=-1".
8564           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
8565           UO->getSubExpr()->getLocStart().isFileID()) {
8566         Diag(Loc, diag::warn_not_compound_assign)
8567           << (UO->getOpcode() == UO_Plus ? "+" : "-")
8568           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
8569       }
8570     }
8571 
8572     if (ConvTy == Compatible) {
8573       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
8574         // Warn about retain cycles where a block captures the LHS, but
8575         // not if the LHS is a simple variable into which the block is
8576         // being stored...unless that variable can be captured by reference!
8577         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
8578         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
8579         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
8580           checkRetainCycles(LHSExpr, RHS.get());
8581 
8582         // It is safe to assign a weak reference into a strong variable.
8583         // Although this code can still have problems:
8584         //   id x = self.weakProp;
8585         //   id y = self.weakProp;
8586         // we do not warn to warn spuriously when 'x' and 'y' are on separate
8587         // paths through the function. This should be revisited if
8588         // -Wrepeated-use-of-weak is made flow-sensitive.
8589         DiagnosticsEngine::Level Level =
8590           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
8591                                    RHS.get()->getLocStart());
8592         if (Level != DiagnosticsEngine::Ignored)
8593           getCurFunction()->markSafeWeakUse(RHS.get());
8594 
8595       } else if (getLangOpts().ObjCAutoRefCount) {
8596         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
8597       }
8598     }
8599   } else {
8600     // Compound assignment "x += y"
8601     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
8602   }
8603 
8604   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
8605                                RHS.get(), AA_Assigning))
8606     return QualType();
8607 
8608   CheckForNullPointerDereference(*this, LHSExpr);
8609 
8610   // C99 6.5.16p3: The type of an assignment expression is the type of the
8611   // left operand unless the left operand has qualified type, in which case
8612   // it is the unqualified version of the type of the left operand.
8613   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8614   // is converted to the type of the assignment expression (above).
8615   // C++ 5.17p1: the type of the assignment expression is that of its left
8616   // operand.
8617   return (getLangOpts().CPlusPlus
8618           ? LHSType : LHSType.getUnqualifiedType());
8619 }
8620 
8621 // C99 6.5.17
8622 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8623                                    SourceLocation Loc) {
8624   LHS = S.CheckPlaceholderExpr(LHS.take());
8625   RHS = S.CheckPlaceholderExpr(RHS.take());
8626   if (LHS.isInvalid() || RHS.isInvalid())
8627     return QualType();
8628 
8629   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8630   // operands, but not unary promotions.
8631   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8632 
8633   // So we treat the LHS as a ignored value, and in C++ we allow the
8634   // containing site to determine what should be done with the RHS.
8635   LHS = S.IgnoredValueConversions(LHS.take());
8636   if (LHS.isInvalid())
8637     return QualType();
8638 
8639   S.DiagnoseUnusedExprResult(LHS.get());
8640 
8641   if (!S.getLangOpts().CPlusPlus) {
8642     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8643     if (RHS.isInvalid())
8644       return QualType();
8645     if (!RHS.get()->getType()->isVoidType())
8646       S.RequireCompleteType(Loc, RHS.get()->getType(),
8647                             diag::err_incomplete_type);
8648   }
8649 
8650   return RHS.get()->getType();
8651 }
8652 
8653 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8654 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8655 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8656                                                ExprValueKind &VK,
8657                                                SourceLocation OpLoc,
8658                                                bool IsInc, bool IsPrefix) {
8659   if (Op->isTypeDependent())
8660     return S.Context.DependentTy;
8661 
8662   QualType ResType = Op->getType();
8663   // Atomic types can be used for increment / decrement where the non-atomic
8664   // versions can, so ignore the _Atomic() specifier for the purpose of
8665   // checking.
8666   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8667     ResType = ResAtomicType->getValueType();
8668 
8669   assert(!ResType.isNull() && "no type for increment/decrement expression");
8670 
8671   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8672     // Decrement of bool is not allowed.
8673     if (!IsInc) {
8674       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8675       return QualType();
8676     }
8677     // Increment of bool sets it to true, but is deprecated.
8678     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8679   } else if (S.getLangOpts().CPlusPlus && ResType->isEnumeralType()) {
8680     // Error on enum increments and decrements in C++ mode
8681     S.Diag(OpLoc, diag::err_increment_decrement_enum) << IsInc << ResType;
8682     return QualType();
8683   } else if (ResType->isRealType()) {
8684     // OK!
8685   } else if (ResType->isPointerType()) {
8686     // C99 6.5.2.4p2, 6.5.6p2
8687     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8688       return QualType();
8689   } else if (ResType->isObjCObjectPointerType()) {
8690     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8691     // Otherwise, we just need a complete type.
8692     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8693         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8694       return QualType();
8695   } else if (ResType->isAnyComplexType()) {
8696     // C99 does not support ++/-- on complex types, we allow as an extension.
8697     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8698       << ResType << Op->getSourceRange();
8699   } else if (ResType->isPlaceholderType()) {
8700     ExprResult PR = S.CheckPlaceholderExpr(Op);
8701     if (PR.isInvalid()) return QualType();
8702     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8703                                           IsInc, IsPrefix);
8704   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8705     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8706   } else if(S.getLangOpts().OpenCL && ResType->isVectorType() &&
8707             ResType->getAs<VectorType>()->getElementType()->isIntegerType()) {
8708     // OpenCL V1.2 6.3 says dec/inc ops operate on integer vector types.
8709   } else {
8710     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8711       << ResType << int(IsInc) << Op->getSourceRange();
8712     return QualType();
8713   }
8714   // At this point, we know we have a real, complex or pointer type.
8715   // Now make sure the operand is a modifiable lvalue.
8716   if (CheckForModifiableLvalue(Op, OpLoc, S))
8717     return QualType();
8718   // In C++, a prefix increment is the same type as the operand. Otherwise
8719   // (in C or with postfix), the increment is the unqualified type of the
8720   // operand.
8721   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8722     VK = VK_LValue;
8723     return ResType;
8724   } else {
8725     VK = VK_RValue;
8726     return ResType.getUnqualifiedType();
8727   }
8728 }
8729 
8730 
8731 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8732 /// This routine allows us to typecheck complex/recursive expressions
8733 /// where the declaration is needed for type checking. We only need to
8734 /// handle cases when the expression references a function designator
8735 /// or is an lvalue. Here are some examples:
8736 ///  - &(x) => x
8737 ///  - &*****f => f for f a function designator.
8738 ///  - &s.xx => s
8739 ///  - &s.zz[1].yy -> s, if zz is an array
8740 ///  - *(x + 1) -> x, if x is an array
8741 ///  - &"123"[2] -> 0
8742 ///  - & __real__ x -> x
8743 static ValueDecl *getPrimaryDecl(Expr *E) {
8744   switch (E->getStmtClass()) {
8745   case Stmt::DeclRefExprClass:
8746     return cast<DeclRefExpr>(E)->getDecl();
8747   case Stmt::MemberExprClass:
8748     // If this is an arrow operator, the address is an offset from
8749     // the base's value, so the object the base refers to is
8750     // irrelevant.
8751     if (cast<MemberExpr>(E)->isArrow())
8752       return 0;
8753     // Otherwise, the expression refers to a part of the base
8754     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8755   case Stmt::ArraySubscriptExprClass: {
8756     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8757     // promotion of register arrays earlier.
8758     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8759     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8760       if (ICE->getSubExpr()->getType()->isArrayType())
8761         return getPrimaryDecl(ICE->getSubExpr());
8762     }
8763     return 0;
8764   }
8765   case Stmt::UnaryOperatorClass: {
8766     UnaryOperator *UO = cast<UnaryOperator>(E);
8767 
8768     switch(UO->getOpcode()) {
8769     case UO_Real:
8770     case UO_Imag:
8771     case UO_Extension:
8772       return getPrimaryDecl(UO->getSubExpr());
8773     default:
8774       return 0;
8775     }
8776   }
8777   case Stmt::ParenExprClass:
8778     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8779   case Stmt::ImplicitCastExprClass:
8780     // If the result of an implicit cast is an l-value, we care about
8781     // the sub-expression; otherwise, the result here doesn't matter.
8782     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8783   default:
8784     return 0;
8785   }
8786 }
8787 
8788 namespace {
8789   enum {
8790     AO_Bit_Field = 0,
8791     AO_Vector_Element = 1,
8792     AO_Property_Expansion = 2,
8793     AO_Register_Variable = 3,
8794     AO_No_Error = 4
8795   };
8796 }
8797 /// \brief Diagnose invalid operand for address of operations.
8798 ///
8799 /// \param Type The type of operand which cannot have its address taken.
8800 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8801                                          Expr *E, unsigned Type) {
8802   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8803 }
8804 
8805 /// CheckAddressOfOperand - The operand of & must be either a function
8806 /// designator or an lvalue designating an object. If it is an lvalue, the
8807 /// object cannot be declared with storage class register or be a bit field.
8808 /// Note: The usual conversions are *not* applied to the operand of the &
8809 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8810 /// In C++, the operand might be an overloaded function name, in which case
8811 /// we allow the '&' but retain the overloaded-function type.
8812 QualType Sema::CheckAddressOfOperand(ExprResult &OrigOp, SourceLocation OpLoc) {
8813   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8814     if (PTy->getKind() == BuiltinType::Overload) {
8815       Expr *E = OrigOp.get()->IgnoreParens();
8816       if (!isa<OverloadExpr>(E)) {
8817         assert(cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf);
8818         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8819           << OrigOp.get()->getSourceRange();
8820         return QualType();
8821       }
8822 
8823       OverloadExpr *Ovl = cast<OverloadExpr>(E);
8824       if (isa<UnresolvedMemberExpr>(Ovl))
8825         if (!ResolveSingleFunctionTemplateSpecialization(Ovl)) {
8826           Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8827             << OrigOp.get()->getSourceRange();
8828           return QualType();
8829         }
8830 
8831       return Context.OverloadTy;
8832     }
8833 
8834     if (PTy->getKind() == BuiltinType::UnknownAny)
8835       return Context.UnknownAnyTy;
8836 
8837     if (PTy->getKind() == BuiltinType::BoundMember) {
8838       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8839         << OrigOp.get()->getSourceRange();
8840       return QualType();
8841     }
8842 
8843     OrigOp = CheckPlaceholderExpr(OrigOp.take());
8844     if (OrigOp.isInvalid()) return QualType();
8845   }
8846 
8847   if (OrigOp.get()->isTypeDependent())
8848     return Context.DependentTy;
8849 
8850   assert(!OrigOp.get()->getType()->isPlaceholderType());
8851 
8852   // Make sure to ignore parentheses in subsequent checks
8853   Expr *op = OrigOp.get()->IgnoreParens();
8854 
8855   // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
8856   if (LangOpts.OpenCL && op->getType()->isFunctionType()) {
8857     Diag(op->getExprLoc(), diag::err_opencl_taking_function_address);
8858     return QualType();
8859   }
8860 
8861   if (getLangOpts().C99) {
8862     // Implement C99-only parts of addressof rules.
8863     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8864       if (uOp->getOpcode() == UO_Deref)
8865         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8866         // (assuming the deref expression is valid).
8867         return uOp->getSubExpr()->getType();
8868     }
8869     // Technically, there should be a check for array subscript
8870     // expressions here, but the result of one is always an lvalue anyway.
8871   }
8872   ValueDecl *dcl = getPrimaryDecl(op);
8873   Expr::LValueClassification lval = op->ClassifyLValue(Context);
8874   unsigned AddressOfError = AO_No_Error;
8875 
8876   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) {
8877     bool sfinae = (bool)isSFINAEContext();
8878     Diag(OpLoc, isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8879                                   : diag::ext_typecheck_addrof_temporary)
8880       << op->getType() << op->getSourceRange();
8881     if (sfinae)
8882       return QualType();
8883     // Materialize the temporary as an lvalue so that we can take its address.
8884     OrigOp = op = new (Context)
8885         MaterializeTemporaryExpr(op->getType(), OrigOp.take(), true, 0);
8886   } else if (isa<ObjCSelectorExpr>(op)) {
8887     return Context.getPointerType(op->getType());
8888   } else if (lval == Expr::LV_MemberFunction) {
8889     // If it's an instance method, make a member pointer.
8890     // The expression must have exactly the form &A::foo.
8891 
8892     // If the underlying expression isn't a decl ref, give up.
8893     if (!isa<DeclRefExpr>(op)) {
8894       Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8895         << OrigOp.get()->getSourceRange();
8896       return QualType();
8897     }
8898     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8899     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8900 
8901     // The id-expression was parenthesized.
8902     if (OrigOp.get() != DRE) {
8903       Diag(OpLoc, diag::err_parens_pointer_member_function)
8904         << OrigOp.get()->getSourceRange();
8905 
8906     // The method was named without a qualifier.
8907     } else if (!DRE->getQualifier()) {
8908       if (MD->getParent()->getName().empty())
8909         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8910           << op->getSourceRange();
8911       else {
8912         SmallString<32> Str;
8913         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8914         Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8915           << op->getSourceRange()
8916           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8917       }
8918     }
8919 
8920     // Taking the address of a dtor is illegal per C++ [class.dtor]p2.
8921     if (isa<CXXDestructorDecl>(MD))
8922       Diag(OpLoc, diag::err_typecheck_addrof_dtor) << op->getSourceRange();
8923 
8924     QualType MPTy = Context.getMemberPointerType(
8925         op->getType(), Context.getTypeDeclType(MD->getParent()).getTypePtr());
8926     if (Context.getTargetInfo().getCXXABI().isMicrosoft())
8927       RequireCompleteType(OpLoc, MPTy, 0);
8928     return MPTy;
8929   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8930     // C99 6.5.3.2p1
8931     // The operand must be either an l-value or a function designator
8932     if (!op->getType()->isFunctionType()) {
8933       // Use a special diagnostic for loads from property references.
8934       if (isa<PseudoObjectExpr>(op)) {
8935         AddressOfError = AO_Property_Expansion;
8936       } else {
8937         Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8938           << op->getType() << op->getSourceRange();
8939         return QualType();
8940       }
8941     }
8942   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8943     // The operand cannot be a bit-field
8944     AddressOfError = AO_Bit_Field;
8945   } else if (op->getObjectKind() == OK_VectorComponent) {
8946     // The operand cannot be an element of a vector
8947     AddressOfError = AO_Vector_Element;
8948   } else if (dcl) { // C99 6.5.3.2p1
8949     // We have an lvalue with a decl. Make sure the decl is not declared
8950     // with the register storage-class specifier.
8951     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8952       // in C++ it is not error to take address of a register
8953       // variable (c++03 7.1.1P3)
8954       if (vd->getStorageClass() == SC_Register &&
8955           !getLangOpts().CPlusPlus) {
8956         AddressOfError = AO_Register_Variable;
8957       }
8958     } else if (isa<FunctionTemplateDecl>(dcl)) {
8959       return Context.OverloadTy;
8960     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8961       // Okay: we can take the address of a field.
8962       // Could be a pointer to member, though, if there is an explicit
8963       // scope qualifier for the class.
8964       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8965         DeclContext *Ctx = dcl->getDeclContext();
8966         if (Ctx && Ctx->isRecord()) {
8967           if (dcl->getType()->isReferenceType()) {
8968             Diag(OpLoc,
8969                  diag::err_cannot_form_pointer_to_member_of_reference_type)
8970               << dcl->getDeclName() << dcl->getType();
8971             return QualType();
8972           }
8973 
8974           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8975             Ctx = Ctx->getParent();
8976 
8977           QualType MPTy = Context.getMemberPointerType(
8978               op->getType(),
8979               Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8980           if (Context.getTargetInfo().getCXXABI().isMicrosoft())
8981             RequireCompleteType(OpLoc, MPTy, 0);
8982           return MPTy;
8983         }
8984       }
8985     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8986       llvm_unreachable("Unknown/unexpected decl type");
8987   }
8988 
8989   if (AddressOfError != AO_No_Error) {
8990     diagnoseAddressOfInvalidType(*this, OpLoc, op, AddressOfError);
8991     return QualType();
8992   }
8993 
8994   if (lval == Expr::LV_IncompleteVoidType) {
8995     // Taking the address of a void variable is technically illegal, but we
8996     // allow it in cases which are otherwise valid.
8997     // Example: "extern void x; void* y = &x;".
8998     Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8999   }
9000 
9001   // If the operand has type "type", the result has type "pointer to type".
9002   if (op->getType()->isObjCObjectType())
9003     return Context.getObjCObjectPointerType(op->getType());
9004   return Context.getPointerType(op->getType());
9005 }
9006 
9007 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
9008 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
9009                                         SourceLocation OpLoc) {
9010   if (Op->isTypeDependent())
9011     return S.Context.DependentTy;
9012 
9013   ExprResult ConvResult = S.UsualUnaryConversions(Op);
9014   if (ConvResult.isInvalid())
9015     return QualType();
9016   Op = ConvResult.take();
9017   QualType OpTy = Op->getType();
9018   QualType Result;
9019 
9020   if (isa<CXXReinterpretCastExpr>(Op)) {
9021     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
9022     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
9023                                      Op->getSourceRange());
9024   }
9025 
9026   // Note that per both C89 and C99, indirection is always legal, even if OpTy
9027   // is an incomplete type or void.  It would be possible to warn about
9028   // dereferencing a void pointer, but it's completely well-defined, and such a
9029   // warning is unlikely to catch any mistakes.
9030   if (const PointerType *PT = OpTy->getAs<PointerType>())
9031     Result = PT->getPointeeType();
9032   else if (const ObjCObjectPointerType *OPT =
9033              OpTy->getAs<ObjCObjectPointerType>())
9034     Result = OPT->getPointeeType();
9035   else {
9036     ExprResult PR = S.CheckPlaceholderExpr(Op);
9037     if (PR.isInvalid()) return QualType();
9038     if (PR.take() != Op)
9039       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
9040   }
9041 
9042   if (Result.isNull()) {
9043     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
9044       << OpTy << Op->getSourceRange();
9045     return QualType();
9046   }
9047 
9048   // Dereferences are usually l-values...
9049   VK = VK_LValue;
9050 
9051   // ...except that certain expressions are never l-values in C.
9052   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
9053     VK = VK_RValue;
9054 
9055   return Result;
9056 }
9057 
9058 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
9059   tok::TokenKind Kind) {
9060   BinaryOperatorKind Opc;
9061   switch (Kind) {
9062   default: llvm_unreachable("Unknown binop!");
9063   case tok::periodstar:           Opc = BO_PtrMemD; break;
9064   case tok::arrowstar:            Opc = BO_PtrMemI; break;
9065   case tok::star:                 Opc = BO_Mul; break;
9066   case tok::slash:                Opc = BO_Div; break;
9067   case tok::percent:              Opc = BO_Rem; break;
9068   case tok::plus:                 Opc = BO_Add; break;
9069   case tok::minus:                Opc = BO_Sub; break;
9070   case tok::lessless:             Opc = BO_Shl; break;
9071   case tok::greatergreater:       Opc = BO_Shr; break;
9072   case tok::lessequal:            Opc = BO_LE; break;
9073   case tok::less:                 Opc = BO_LT; break;
9074   case tok::greaterequal:         Opc = BO_GE; break;
9075   case tok::greater:              Opc = BO_GT; break;
9076   case tok::exclaimequal:         Opc = BO_NE; break;
9077   case tok::equalequal:           Opc = BO_EQ; break;
9078   case tok::amp:                  Opc = BO_And; break;
9079   case tok::caret:                Opc = BO_Xor; break;
9080   case tok::pipe:                 Opc = BO_Or; break;
9081   case tok::ampamp:               Opc = BO_LAnd; break;
9082   case tok::pipepipe:             Opc = BO_LOr; break;
9083   case tok::equal:                Opc = BO_Assign; break;
9084   case tok::starequal:            Opc = BO_MulAssign; break;
9085   case tok::slashequal:           Opc = BO_DivAssign; break;
9086   case tok::percentequal:         Opc = BO_RemAssign; break;
9087   case tok::plusequal:            Opc = BO_AddAssign; break;
9088   case tok::minusequal:           Opc = BO_SubAssign; break;
9089   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
9090   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
9091   case tok::ampequal:             Opc = BO_AndAssign; break;
9092   case tok::caretequal:           Opc = BO_XorAssign; break;
9093   case tok::pipeequal:            Opc = BO_OrAssign; break;
9094   case tok::comma:                Opc = BO_Comma; break;
9095   }
9096   return Opc;
9097 }
9098 
9099 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
9100   tok::TokenKind Kind) {
9101   UnaryOperatorKind Opc;
9102   switch (Kind) {
9103   default: llvm_unreachable("Unknown unary op!");
9104   case tok::plusplus:     Opc = UO_PreInc; break;
9105   case tok::minusminus:   Opc = UO_PreDec; break;
9106   case tok::amp:          Opc = UO_AddrOf; break;
9107   case tok::star:         Opc = UO_Deref; break;
9108   case tok::plus:         Opc = UO_Plus; break;
9109   case tok::minus:        Opc = UO_Minus; break;
9110   case tok::tilde:        Opc = UO_Not; break;
9111   case tok::exclaim:      Opc = UO_LNot; break;
9112   case tok::kw___real:    Opc = UO_Real; break;
9113   case tok::kw___imag:    Opc = UO_Imag; break;
9114   case tok::kw___extension__: Opc = UO_Extension; break;
9115   }
9116   return Opc;
9117 }
9118 
9119 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
9120 /// This warning is only emitted for builtin assignment operations. It is also
9121 /// suppressed in the event of macro expansions.
9122 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
9123                                    SourceLocation OpLoc) {
9124   if (!S.ActiveTemplateInstantiations.empty())
9125     return;
9126   if (OpLoc.isInvalid() || OpLoc.isMacroID())
9127     return;
9128   LHSExpr = LHSExpr->IgnoreParenImpCasts();
9129   RHSExpr = RHSExpr->IgnoreParenImpCasts();
9130   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
9131   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
9132   if (!LHSDeclRef || !RHSDeclRef ||
9133       LHSDeclRef->getLocation().isMacroID() ||
9134       RHSDeclRef->getLocation().isMacroID())
9135     return;
9136   const ValueDecl *LHSDecl =
9137     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
9138   const ValueDecl *RHSDecl =
9139     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
9140   if (LHSDecl != RHSDecl)
9141     return;
9142   if (LHSDecl->getType().isVolatileQualified())
9143     return;
9144   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
9145     if (RefTy->getPointeeType().isVolatileQualified())
9146       return;
9147 
9148   S.Diag(OpLoc, diag::warn_self_assignment)
9149       << LHSDeclRef->getType()
9150       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
9151 }
9152 
9153 /// Check if a bitwise-& is performed on an Objective-C pointer.  This
9154 /// is usually indicative of introspection within the Objective-C pointer.
9155 static void checkObjCPointerIntrospection(Sema &S, ExprResult &L, ExprResult &R,
9156                                           SourceLocation OpLoc) {
9157   if (!S.getLangOpts().ObjC1)
9158     return;
9159 
9160   const Expr *ObjCPointerExpr = 0, *OtherExpr = 0;
9161   const Expr *LHS = L.get();
9162   const Expr *RHS = R.get();
9163 
9164   if (LHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9165     ObjCPointerExpr = LHS;
9166     OtherExpr = RHS;
9167   }
9168   else if (RHS->IgnoreParenCasts()->getType()->isObjCObjectPointerType()) {
9169     ObjCPointerExpr = RHS;
9170     OtherExpr = LHS;
9171   }
9172 
9173   // This warning is deliberately made very specific to reduce false
9174   // positives with logic that uses '&' for hashing.  This logic mainly
9175   // looks for code trying to introspect into tagged pointers, which
9176   // code should generally never do.
9177   if (ObjCPointerExpr && isa<IntegerLiteral>(OtherExpr->IgnoreParenCasts())) {
9178     unsigned Diag = diag::warn_objc_pointer_masking;
9179     // Determine if we are introspecting the result of performSelectorXXX.
9180     const Expr *Ex = ObjCPointerExpr->IgnoreParenCasts();
9181     // Special case messages to -performSelector and friends, which
9182     // can return non-pointer values boxed in a pointer value.
9183     // Some clients may wish to silence warnings in this subcase.
9184     if (const ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(Ex)) {
9185       Selector S = ME->getSelector();
9186       StringRef SelArg0 = S.getNameForSlot(0);
9187       if (SelArg0.startswith("performSelector"))
9188         Diag = diag::warn_objc_pointer_masking_performSelector;
9189     }
9190 
9191     S.Diag(OpLoc, Diag)
9192       << ObjCPointerExpr->getSourceRange();
9193   }
9194 }
9195 
9196 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
9197 /// operator @p Opc at location @c TokLoc. This routine only supports
9198 /// built-in operations; ActOnBinOp handles overloaded operators.
9199 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
9200                                     BinaryOperatorKind Opc,
9201                                     Expr *LHSExpr, Expr *RHSExpr) {
9202   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
9203     // The syntax only allows initializer lists on the RHS of assignment,
9204     // so we don't need to worry about accepting invalid code for
9205     // non-assignment operators.
9206     // C++11 5.17p9:
9207     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
9208     //   of x = {} is x = T().
9209     InitializationKind Kind =
9210         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
9211     InitializedEntity Entity =
9212         InitializedEntity::InitializeTemporary(LHSExpr->getType());
9213     InitializationSequence InitSeq(*this, Entity, Kind, RHSExpr);
9214     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
9215     if (Init.isInvalid())
9216       return Init;
9217     RHSExpr = Init.take();
9218   }
9219 
9220   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
9221   QualType ResultTy;     // Result type of the binary operator.
9222   // The following two variables are used for compound assignment operators
9223   QualType CompLHSTy;    // Type of LHS after promotions for computation
9224   QualType CompResultTy; // Type of computation result
9225   ExprValueKind VK = VK_RValue;
9226   ExprObjectKind OK = OK_Ordinary;
9227 
9228   switch (Opc) {
9229   case BO_Assign:
9230     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
9231     if (getLangOpts().CPlusPlus &&
9232         LHS.get()->getObjectKind() != OK_ObjCProperty) {
9233       VK = LHS.get()->getValueKind();
9234       OK = LHS.get()->getObjectKind();
9235     }
9236     if (!ResultTy.isNull())
9237       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
9238     break;
9239   case BO_PtrMemD:
9240   case BO_PtrMemI:
9241     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
9242                                             Opc == BO_PtrMemI);
9243     break;
9244   case BO_Mul:
9245   case BO_Div:
9246     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
9247                                            Opc == BO_Div);
9248     break;
9249   case BO_Rem:
9250     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
9251     break;
9252   case BO_Add:
9253     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
9254     break;
9255   case BO_Sub:
9256     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
9257     break;
9258   case BO_Shl:
9259   case BO_Shr:
9260     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
9261     break;
9262   case BO_LE:
9263   case BO_LT:
9264   case BO_GE:
9265   case BO_GT:
9266     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
9267     break;
9268   case BO_EQ:
9269   case BO_NE:
9270     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
9271     break;
9272   case BO_And:
9273     checkObjCPointerIntrospection(*this, LHS, RHS, OpLoc);
9274   case BO_Xor:
9275   case BO_Or:
9276     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
9277     break;
9278   case BO_LAnd:
9279   case BO_LOr:
9280     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
9281     break;
9282   case BO_MulAssign:
9283   case BO_DivAssign:
9284     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
9285                                                Opc == BO_DivAssign);
9286     CompLHSTy = CompResultTy;
9287     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9288       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9289     break;
9290   case BO_RemAssign:
9291     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
9292     CompLHSTy = CompResultTy;
9293     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9294       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9295     break;
9296   case BO_AddAssign:
9297     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
9298     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9299       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9300     break;
9301   case BO_SubAssign:
9302     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
9303     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9304       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9305     break;
9306   case BO_ShlAssign:
9307   case BO_ShrAssign:
9308     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, 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_AndAssign:
9314   case BO_XorAssign:
9315   case BO_OrAssign:
9316     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
9317     CompLHSTy = CompResultTy;
9318     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
9319       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
9320     break;
9321   case BO_Comma:
9322     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
9323     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
9324       VK = RHS.get()->getValueKind();
9325       OK = RHS.get()->getObjectKind();
9326     }
9327     break;
9328   }
9329   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
9330     return ExprError();
9331 
9332   // Check for array bounds violations for both sides of the BinaryOperator
9333   CheckArrayAccess(LHS.get());
9334   CheckArrayAccess(RHS.get());
9335 
9336   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
9337     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
9338                                                  &Context.Idents.get("object_setClass"),
9339                                                  SourceLocation(), LookupOrdinaryName);
9340     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
9341       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
9342       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
9343       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
9344       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
9345       FixItHint::CreateInsertion(RHSLocEnd, ")");
9346     }
9347     else
9348       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
9349   }
9350   else if (const ObjCIvarRefExpr *OIRE =
9351            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
9352     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
9353 
9354   if (CompResultTy.isNull())
9355     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
9356                                               ResultTy, VK, OK, OpLoc,
9357                                               FPFeatures.fp_contract));
9358   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
9359       OK_ObjCProperty) {
9360     VK = VK_LValue;
9361     OK = LHS.get()->getObjectKind();
9362   }
9363   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
9364                                                     ResultTy, VK, OK, CompLHSTy,
9365                                                     CompResultTy, OpLoc,
9366                                                     FPFeatures.fp_contract));
9367 }
9368 
9369 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
9370 /// operators are mixed in a way that suggests that the programmer forgot that
9371 /// comparison operators have higher precedence. The most typical example of
9372 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
9373 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
9374                                       SourceLocation OpLoc, Expr *LHSExpr,
9375                                       Expr *RHSExpr) {
9376   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
9377   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
9378 
9379   // Check that one of the sides is a comparison operator.
9380   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
9381   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
9382   if (!isLeftComp && !isRightComp)
9383     return;
9384 
9385   // Bitwise operations are sometimes used as eager logical ops.
9386   // Don't diagnose this.
9387   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
9388   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
9389   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
9390     return;
9391 
9392   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
9393                                                    OpLoc)
9394                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
9395   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
9396   SourceRange ParensRange = isLeftComp ?
9397       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
9398     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
9399 
9400   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
9401     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
9402   SuggestParentheses(Self, OpLoc,
9403     Self.PDiag(diag::note_precedence_silence) << OpStr,
9404     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
9405   SuggestParentheses(Self, OpLoc,
9406     Self.PDiag(diag::note_precedence_bitwise_first)
9407       << BinaryOperator::getOpcodeStr(Opc),
9408     ParensRange);
9409 }
9410 
9411 /// \brief It accepts a '&' expr that is inside a '|' one.
9412 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
9413 /// in parentheses.
9414 static void
9415 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
9416                                        BinaryOperator *Bop) {
9417   assert(Bop->getOpcode() == BO_And);
9418   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
9419       << Bop->getSourceRange() << OpLoc;
9420   SuggestParentheses(Self, Bop->getOperatorLoc(),
9421     Self.PDiag(diag::note_precedence_silence)
9422       << Bop->getOpcodeStr(),
9423     Bop->getSourceRange());
9424 }
9425 
9426 /// \brief It accepts a '&&' expr that is inside a '||' one.
9427 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
9428 /// in parentheses.
9429 static void
9430 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
9431                                        BinaryOperator *Bop) {
9432   assert(Bop->getOpcode() == BO_LAnd);
9433   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
9434       << Bop->getSourceRange() << OpLoc;
9435   SuggestParentheses(Self, Bop->getOperatorLoc(),
9436     Self.PDiag(diag::note_precedence_silence)
9437       << Bop->getOpcodeStr(),
9438     Bop->getSourceRange());
9439 }
9440 
9441 /// \brief Returns true if the given expression can be evaluated as a constant
9442 /// 'true'.
9443 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
9444   bool Res;
9445   return !E->isValueDependent() &&
9446          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
9447 }
9448 
9449 /// \brief Returns true if the given expression can be evaluated as a constant
9450 /// 'false'.
9451 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
9452   bool Res;
9453   return !E->isValueDependent() &&
9454          E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
9455 }
9456 
9457 /// \brief Look for '&&' in the left hand of a '||' expr.
9458 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
9459                                              Expr *LHSExpr, Expr *RHSExpr) {
9460   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
9461     if (Bop->getOpcode() == BO_LAnd) {
9462       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
9463       if (EvaluatesAsFalse(S, RHSExpr))
9464         return;
9465       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
9466       if (!EvaluatesAsTrue(S, Bop->getLHS()))
9467         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9468     } else if (Bop->getOpcode() == BO_LOr) {
9469       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
9470         // If it's "a || b && 1 || c" we didn't warn earlier for
9471         // "a || b && 1", but warn now.
9472         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
9473           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
9474       }
9475     }
9476   }
9477 }
9478 
9479 /// \brief Look for '&&' in the right hand of a '||' expr.
9480 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
9481                                              Expr *LHSExpr, Expr *RHSExpr) {
9482   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
9483     if (Bop->getOpcode() == BO_LAnd) {
9484       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
9485       if (EvaluatesAsFalse(S, LHSExpr))
9486         return;
9487       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
9488       if (!EvaluatesAsTrue(S, Bop->getRHS()))
9489         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
9490     }
9491   }
9492 }
9493 
9494 /// \brief Look for '&' in the left or right hand of a '|' expr.
9495 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
9496                                              Expr *OrArg) {
9497   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
9498     if (Bop->getOpcode() == BO_And)
9499       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
9500   }
9501 }
9502 
9503 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
9504                                     Expr *SubExpr, StringRef Shift) {
9505   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
9506     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
9507       StringRef Op = Bop->getOpcodeStr();
9508       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
9509           << Bop->getSourceRange() << OpLoc << Shift << Op;
9510       SuggestParentheses(S, Bop->getOperatorLoc(),
9511           S.PDiag(diag::note_precedence_silence) << Op,
9512           Bop->getSourceRange());
9513     }
9514   }
9515 }
9516 
9517 static void DiagnoseShiftCompare(Sema &S, SourceLocation OpLoc,
9518                                  Expr *LHSExpr, Expr *RHSExpr) {
9519   CXXOperatorCallExpr *OCE = dyn_cast<CXXOperatorCallExpr>(LHSExpr);
9520   if (!OCE)
9521     return;
9522 
9523   FunctionDecl *FD = OCE->getDirectCallee();
9524   if (!FD || !FD->isOverloadedOperator())
9525     return;
9526 
9527   OverloadedOperatorKind Kind = FD->getOverloadedOperator();
9528   if (Kind != OO_LessLess && Kind != OO_GreaterGreater)
9529     return;
9530 
9531   S.Diag(OpLoc, diag::warn_overloaded_shift_in_comparison)
9532       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange()
9533       << (Kind == OO_LessLess);
9534   SuggestParentheses(S, OCE->getOperatorLoc(),
9535                      S.PDiag(diag::note_precedence_silence)
9536                          << (Kind == OO_LessLess ? "<<" : ">>"),
9537                      OCE->getSourceRange());
9538   SuggestParentheses(S, OpLoc,
9539                      S.PDiag(diag::note_evaluate_comparison_first),
9540                      SourceRange(OCE->getArg(1)->getLocStart(),
9541                                  RHSExpr->getLocEnd()));
9542 }
9543 
9544 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
9545 /// precedence.
9546 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
9547                                     SourceLocation OpLoc, Expr *LHSExpr,
9548                                     Expr *RHSExpr){
9549   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
9550   if (BinaryOperator::isBitwiseOp(Opc))
9551     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
9552 
9553   // Diagnose "arg1 & arg2 | arg3"
9554   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9555     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
9556     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
9557   }
9558 
9559   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
9560   // We don't warn for 'assert(a || b && "bad")' since this is safe.
9561   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
9562     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
9563     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
9564   }
9565 
9566   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
9567       || Opc == BO_Shr) {
9568     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
9569     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
9570     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
9571   }
9572 
9573   // Warn on overloaded shift operators and comparisons, such as:
9574   // cout << 5 == 4;
9575   if (BinaryOperator::isComparisonOp(Opc))
9576     DiagnoseShiftCompare(Self, OpLoc, LHSExpr, RHSExpr);
9577 }
9578 
9579 // Binary Operators.  'Tok' is the token for the operator.
9580 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
9581                             tok::TokenKind Kind,
9582                             Expr *LHSExpr, Expr *RHSExpr) {
9583   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
9584   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
9585   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
9586 
9587   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
9588   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
9589 
9590   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
9591 }
9592 
9593 /// Build an overloaded binary operator expression in the given scope.
9594 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
9595                                        BinaryOperatorKind Opc,
9596                                        Expr *LHS, Expr *RHS) {
9597   // Find all of the overloaded operators visible from this
9598   // point. We perform both an operator-name lookup from the local
9599   // scope and an argument-dependent lookup based on the types of
9600   // the arguments.
9601   UnresolvedSet<16> Functions;
9602   OverloadedOperatorKind OverOp
9603     = BinaryOperator::getOverloadedOperator(Opc);
9604   if (Sc && OverOp != OO_None)
9605     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
9606                                    RHS->getType(), Functions);
9607 
9608   // Build the (potentially-overloaded, potentially-dependent)
9609   // binary operation.
9610   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
9611 }
9612 
9613 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
9614                             BinaryOperatorKind Opc,
9615                             Expr *LHSExpr, Expr *RHSExpr) {
9616   // We want to end up calling one of checkPseudoObjectAssignment
9617   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
9618   // both expressions are overloadable or either is type-dependent),
9619   // or CreateBuiltinBinOp (in any other case).  We also want to get
9620   // any placeholder types out of the way.
9621 
9622   // Handle pseudo-objects in the LHS.
9623   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
9624     // Assignments with a pseudo-object l-value need special analysis.
9625     if (pty->getKind() == BuiltinType::PseudoObject &&
9626         BinaryOperator::isAssignmentOp(Opc))
9627       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
9628 
9629     // Don't resolve overloads if the other type is overloadable.
9630     if (pty->getKind() == BuiltinType::Overload) {
9631       // We can't actually test that if we still have a placeholder,
9632       // though.  Fortunately, none of the exceptions we see in that
9633       // code below are valid when the LHS is an overload set.  Note
9634       // that an overload set can be dependently-typed, but it never
9635       // instantiates to having an overloadable type.
9636       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9637       if (resolvedRHS.isInvalid()) return ExprError();
9638       RHSExpr = resolvedRHS.take();
9639 
9640       if (RHSExpr->isTypeDependent() ||
9641           RHSExpr->getType()->isOverloadableType())
9642         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9643     }
9644 
9645     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
9646     if (LHS.isInvalid()) return ExprError();
9647     LHSExpr = LHS.take();
9648   }
9649 
9650   // Handle pseudo-objects in the RHS.
9651   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
9652     // An overload in the RHS can potentially be resolved by the type
9653     // being assigned to.
9654     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
9655       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9656         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9657 
9658       if (LHSExpr->getType()->isOverloadableType())
9659         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9660 
9661       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9662     }
9663 
9664     // Don't resolve overloads if the other type is overloadable.
9665     if (pty->getKind() == BuiltinType::Overload &&
9666         LHSExpr->getType()->isOverloadableType())
9667       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9668 
9669     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
9670     if (!resolvedRHS.isUsable()) return ExprError();
9671     RHSExpr = resolvedRHS.take();
9672   }
9673 
9674   if (getLangOpts().CPlusPlus) {
9675     // If either expression is type-dependent, always build an
9676     // overloaded op.
9677     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
9678       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9679 
9680     // Otherwise, build an overloaded op if either expression has an
9681     // overloadable type.
9682     if (LHSExpr->getType()->isOverloadableType() ||
9683         RHSExpr->getType()->isOverloadableType())
9684       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
9685   }
9686 
9687   // Build a built-in binary operation.
9688   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
9689 }
9690 
9691 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
9692                                       UnaryOperatorKind Opc,
9693                                       Expr *InputExpr) {
9694   ExprResult Input = Owned(InputExpr);
9695   ExprValueKind VK = VK_RValue;
9696   ExprObjectKind OK = OK_Ordinary;
9697   QualType resultType;
9698   switch (Opc) {
9699   case UO_PreInc:
9700   case UO_PreDec:
9701   case UO_PostInc:
9702   case UO_PostDec:
9703     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
9704                                                 Opc == UO_PreInc ||
9705                                                 Opc == UO_PostInc,
9706                                                 Opc == UO_PreInc ||
9707                                                 Opc == UO_PreDec);
9708     break;
9709   case UO_AddrOf:
9710     resultType = CheckAddressOfOperand(Input, OpLoc);
9711     break;
9712   case UO_Deref: {
9713     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9714     if (Input.isInvalid()) return ExprError();
9715     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
9716     break;
9717   }
9718   case UO_Plus:
9719   case UO_Minus:
9720     Input = UsualUnaryConversions(Input.take());
9721     if (Input.isInvalid()) return ExprError();
9722     resultType = Input.get()->getType();
9723     if (resultType->isDependentType())
9724       break;
9725     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
9726         resultType->isVectorType())
9727       break;
9728     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9729              Opc == UO_Plus &&
9730              resultType->isPointerType())
9731       break;
9732 
9733     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9734       << resultType << Input.get()->getSourceRange());
9735 
9736   case UO_Not: // bitwise complement
9737     Input = UsualUnaryConversions(Input.take());
9738     if (Input.isInvalid())
9739       return ExprError();
9740     resultType = Input.get()->getType();
9741     if (resultType->isDependentType())
9742       break;
9743     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9744     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9745       // C99 does not support '~' for complex conjugation.
9746       Diag(OpLoc, diag::ext_integer_complement_complex)
9747           << resultType << Input.get()->getSourceRange();
9748     else if (resultType->hasIntegerRepresentation())
9749       break;
9750     else if (resultType->isExtVectorType()) {
9751       if (Context.getLangOpts().OpenCL) {
9752         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9753         // on vector float types.
9754         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9755         if (!T->isIntegerType())
9756           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9757                            << resultType << Input.get()->getSourceRange());
9758       }
9759       break;
9760     } else {
9761       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9762                        << resultType << Input.get()->getSourceRange());
9763     }
9764     break;
9765 
9766   case UO_LNot: // logical negation
9767     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9768     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9769     if (Input.isInvalid()) return ExprError();
9770     resultType = Input.get()->getType();
9771 
9772     // Though we still have to promote half FP to float...
9773     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9774       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9775       resultType = Context.FloatTy;
9776     }
9777 
9778     if (resultType->isDependentType())
9779       break;
9780     if (resultType->isScalarType() && !isScopedEnumerationType(resultType)) {
9781       // C99 6.5.3.3p1: ok, fallthrough;
9782       if (Context.getLangOpts().CPlusPlus) {
9783         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9784         // operand contextually converted to bool.
9785         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9786                                   ScalarTypeToBooleanCastKind(resultType));
9787       } else if (Context.getLangOpts().OpenCL &&
9788                  Context.getLangOpts().OpenCLVersion < 120) {
9789         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9790         // operate on scalar float types.
9791         if (!resultType->isIntegerType())
9792           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9793                            << resultType << Input.get()->getSourceRange());
9794       }
9795     } else if (resultType->isExtVectorType()) {
9796       if (Context.getLangOpts().OpenCL &&
9797           Context.getLangOpts().OpenCLVersion < 120) {
9798         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9799         // operate on vector float types.
9800         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9801         if (!T->isIntegerType())
9802           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9803                            << resultType << Input.get()->getSourceRange());
9804       }
9805       // Vector logical not returns the signed variant of the operand type.
9806       resultType = GetSignedVectorType(resultType);
9807       break;
9808     } else {
9809       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9810         << resultType << Input.get()->getSourceRange());
9811     }
9812 
9813     // LNot always has type int. C99 6.5.3.3p5.
9814     // In C++, it's bool. C++ 5.3.1p8
9815     resultType = Context.getLogicalOperationType();
9816     break;
9817   case UO_Real:
9818   case UO_Imag:
9819     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9820     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9821     // complex l-values to ordinary l-values and all other values to r-values.
9822     if (Input.isInvalid()) return ExprError();
9823     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9824       if (Input.get()->getValueKind() != VK_RValue &&
9825           Input.get()->getObjectKind() == OK_Ordinary)
9826         VK = Input.get()->getValueKind();
9827     } else if (!getLangOpts().CPlusPlus) {
9828       // In C, a volatile scalar is read by __imag. In C++, it is not.
9829       Input = DefaultLvalueConversion(Input.take());
9830     }
9831     break;
9832   case UO_Extension:
9833     resultType = Input.get()->getType();
9834     VK = Input.get()->getValueKind();
9835     OK = Input.get()->getObjectKind();
9836     break;
9837   }
9838   if (resultType.isNull() || Input.isInvalid())
9839     return ExprError();
9840 
9841   // Check for array bounds violations in the operand of the UnaryOperator,
9842   // except for the '*' and '&' operators that have to be handled specially
9843   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9844   // that are explicitly defined as valid by the standard).
9845   if (Opc != UO_AddrOf && Opc != UO_Deref)
9846     CheckArrayAccess(Input.get());
9847 
9848   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9849                                            VK, OK, OpLoc));
9850 }
9851 
9852 /// \brief Determine whether the given expression is a qualified member
9853 /// access expression, of a form that could be turned into a pointer to member
9854 /// with the address-of operator.
9855 static bool isQualifiedMemberAccess(Expr *E) {
9856   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9857     if (!DRE->getQualifier())
9858       return false;
9859 
9860     ValueDecl *VD = DRE->getDecl();
9861     if (!VD->isCXXClassMember())
9862       return false;
9863 
9864     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9865       return true;
9866     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9867       return Method->isInstance();
9868 
9869     return false;
9870   }
9871 
9872   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9873     if (!ULE->getQualifier())
9874       return false;
9875 
9876     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9877                                            DEnd = ULE->decls_end();
9878          D != DEnd; ++D) {
9879       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9880         if (Method->isInstance())
9881           return true;
9882       } else {
9883         // Overload set does not contain methods.
9884         break;
9885       }
9886     }
9887 
9888     return false;
9889   }
9890 
9891   return false;
9892 }
9893 
9894 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9895                               UnaryOperatorKind Opc, Expr *Input) {
9896   // First things first: handle placeholders so that the
9897   // overloaded-operator check considers the right type.
9898   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9899     // Increment and decrement of pseudo-object references.
9900     if (pty->getKind() == BuiltinType::PseudoObject &&
9901         UnaryOperator::isIncrementDecrementOp(Opc))
9902       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9903 
9904     // extension is always a builtin operator.
9905     if (Opc == UO_Extension)
9906       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9907 
9908     // & gets special logic for several kinds of placeholder.
9909     // The builtin code knows what to do.
9910     if (Opc == UO_AddrOf &&
9911         (pty->getKind() == BuiltinType::Overload ||
9912          pty->getKind() == BuiltinType::UnknownAny ||
9913          pty->getKind() == BuiltinType::BoundMember))
9914       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9915 
9916     // Anything else needs to be handled now.
9917     ExprResult Result = CheckPlaceholderExpr(Input);
9918     if (Result.isInvalid()) return ExprError();
9919     Input = Result.take();
9920   }
9921 
9922   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9923       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9924       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9925     // Find all of the overloaded operators visible from this
9926     // point. We perform both an operator-name lookup from the local
9927     // scope and an argument-dependent lookup based on the types of
9928     // the arguments.
9929     UnresolvedSet<16> Functions;
9930     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9931     if (S && OverOp != OO_None)
9932       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9933                                    Functions);
9934 
9935     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9936   }
9937 
9938   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9939 }
9940 
9941 // Unary Operators.  'Tok' is the token for the operator.
9942 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9943                               tok::TokenKind Op, Expr *Input) {
9944   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9945 }
9946 
9947 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9948 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9949                                 LabelDecl *TheDecl) {
9950   TheDecl->markUsed(Context);
9951   // Create the AST node.  The address of a label always has type 'void*'.
9952   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9953                                        Context.getPointerType(Context.VoidTy)));
9954 }
9955 
9956 /// Given the last statement in a statement-expression, check whether
9957 /// the result is a producing expression (like a call to an
9958 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9959 /// release out of the full-expression.  Otherwise, return null.
9960 /// Cannot fail.
9961 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9962   // Should always be wrapped with one of these.
9963   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9964   if (!cleanups) return 0;
9965 
9966   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9967   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9968     return 0;
9969 
9970   // Splice out the cast.  This shouldn't modify any interesting
9971   // features of the statement.
9972   Expr *producer = cast->getSubExpr();
9973   assert(producer->getType() == cast->getType());
9974   assert(producer->getValueKind() == cast->getValueKind());
9975   cleanups->setSubExpr(producer);
9976   return cleanups;
9977 }
9978 
9979 void Sema::ActOnStartStmtExpr() {
9980   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9981 }
9982 
9983 void Sema::ActOnStmtExprError() {
9984   // Note that function is also called by TreeTransform when leaving a
9985   // StmtExpr scope without rebuilding anything.
9986 
9987   DiscardCleanupsInEvaluationContext();
9988   PopExpressionEvaluationContext();
9989 }
9990 
9991 ExprResult
9992 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9993                     SourceLocation RPLoc) { // "({..})"
9994   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9995   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9996 
9997   if (hasAnyUnrecoverableErrorsInThisFunction())
9998     DiscardCleanupsInEvaluationContext();
9999   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
10000   PopExpressionEvaluationContext();
10001 
10002   bool isFileScope
10003     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
10004   if (isFileScope)
10005     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
10006 
10007   // FIXME: there are a variety of strange constraints to enforce here, for
10008   // example, it is not possible to goto into a stmt expression apparently.
10009   // More semantic analysis is needed.
10010 
10011   // If there are sub-stmts in the compound stmt, take the type of the last one
10012   // as the type of the stmtexpr.
10013   QualType Ty = Context.VoidTy;
10014   bool StmtExprMayBindToTemp = false;
10015   if (!Compound->body_empty()) {
10016     Stmt *LastStmt = Compound->body_back();
10017     LabelStmt *LastLabelStmt = 0;
10018     // If LastStmt is a label, skip down through into the body.
10019     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
10020       LastLabelStmt = Label;
10021       LastStmt = Label->getSubStmt();
10022     }
10023 
10024     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
10025       // Do function/array conversion on the last expression, but not
10026       // lvalue-to-rvalue.  However, initialize an unqualified type.
10027       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
10028       if (LastExpr.isInvalid())
10029         return ExprError();
10030       Ty = LastExpr.get()->getType().getUnqualifiedType();
10031 
10032       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
10033         // In ARC, if the final expression ends in a consume, splice
10034         // the consume out and bind it later.  In the alternate case
10035         // (when dealing with a retainable type), the result
10036         // initialization will create a produce.  In both cases the
10037         // result will be +1, and we'll need to balance that out with
10038         // a bind.
10039         if (Expr *rebuiltLastStmt
10040               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
10041           LastExpr = rebuiltLastStmt;
10042         } else {
10043           LastExpr = PerformCopyInitialization(
10044                             InitializedEntity::InitializeResult(LPLoc,
10045                                                                 Ty,
10046                                                                 false),
10047                                                    SourceLocation(),
10048                                                LastExpr);
10049         }
10050 
10051         if (LastExpr.isInvalid())
10052           return ExprError();
10053         if (LastExpr.get() != 0) {
10054           if (!LastLabelStmt)
10055             Compound->setLastStmt(LastExpr.take());
10056           else
10057             LastLabelStmt->setSubStmt(LastExpr.take());
10058           StmtExprMayBindToTemp = true;
10059         }
10060       }
10061     }
10062   }
10063 
10064   // FIXME: Check that expression type is complete/non-abstract; statement
10065   // expressions are not lvalues.
10066   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
10067   if (StmtExprMayBindToTemp)
10068     return MaybeBindToTemporary(ResStmtExpr);
10069   return Owned(ResStmtExpr);
10070 }
10071 
10072 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
10073                                       TypeSourceInfo *TInfo,
10074                                       OffsetOfComponent *CompPtr,
10075                                       unsigned NumComponents,
10076                                       SourceLocation RParenLoc) {
10077   QualType ArgTy = TInfo->getType();
10078   bool Dependent = ArgTy->isDependentType();
10079   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
10080 
10081   // We must have at least one component that refers to the type, and the first
10082   // one is known to be a field designator.  Verify that the ArgTy represents
10083   // a struct/union/class.
10084   if (!Dependent && !ArgTy->isRecordType())
10085     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
10086                        << ArgTy << TypeRange);
10087 
10088   // Type must be complete per C99 7.17p3 because a declaring a variable
10089   // with an incomplete type would be ill-formed.
10090   if (!Dependent
10091       && RequireCompleteType(BuiltinLoc, ArgTy,
10092                              diag::err_offsetof_incomplete_type, TypeRange))
10093     return ExprError();
10094 
10095   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
10096   // GCC extension, diagnose them.
10097   // FIXME: This diagnostic isn't actually visible because the location is in
10098   // a system header!
10099   if (NumComponents != 1)
10100     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
10101       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
10102 
10103   bool DidWarnAboutNonPOD = false;
10104   QualType CurrentType = ArgTy;
10105   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
10106   SmallVector<OffsetOfNode, 4> Comps;
10107   SmallVector<Expr*, 4> Exprs;
10108   for (unsigned i = 0; i != NumComponents; ++i) {
10109     const OffsetOfComponent &OC = CompPtr[i];
10110     if (OC.isBrackets) {
10111       // Offset of an array sub-field.  TODO: Should we allow vector elements?
10112       if (!CurrentType->isDependentType()) {
10113         const ArrayType *AT = Context.getAsArrayType(CurrentType);
10114         if(!AT)
10115           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
10116                            << CurrentType);
10117         CurrentType = AT->getElementType();
10118       } else
10119         CurrentType = Context.DependentTy;
10120 
10121       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
10122       if (IdxRval.isInvalid())
10123         return ExprError();
10124       Expr *Idx = IdxRval.take();
10125 
10126       // The expression must be an integral expression.
10127       // FIXME: An integral constant expression?
10128       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
10129           !Idx->getType()->isIntegerType())
10130         return ExprError(Diag(Idx->getLocStart(),
10131                               diag::err_typecheck_subscript_not_integer)
10132                          << Idx->getSourceRange());
10133 
10134       // Record this array index.
10135       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
10136       Exprs.push_back(Idx);
10137       continue;
10138     }
10139 
10140     // Offset of a field.
10141     if (CurrentType->isDependentType()) {
10142       // We have the offset of a field, but we can't look into the dependent
10143       // type. Just record the identifier of the field.
10144       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
10145       CurrentType = Context.DependentTy;
10146       continue;
10147     }
10148 
10149     // We need to have a complete type to look into.
10150     if (RequireCompleteType(OC.LocStart, CurrentType,
10151                             diag::err_offsetof_incomplete_type))
10152       return ExprError();
10153 
10154     // Look for the designated field.
10155     const RecordType *RC = CurrentType->getAs<RecordType>();
10156     if (!RC)
10157       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
10158                        << CurrentType);
10159     RecordDecl *RD = RC->getDecl();
10160 
10161     // C++ [lib.support.types]p5:
10162     //   The macro offsetof accepts a restricted set of type arguments in this
10163     //   International Standard. type shall be a POD structure or a POD union
10164     //   (clause 9).
10165     // C++11 [support.types]p4:
10166     //   If type is not a standard-layout class (Clause 9), the results are
10167     //   undefined.
10168     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10169       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
10170       unsigned DiagID =
10171         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
10172                             : diag::warn_offsetof_non_pod_type;
10173 
10174       if (!IsSafe && !DidWarnAboutNonPOD &&
10175           DiagRuntimeBehavior(BuiltinLoc, 0,
10176                               PDiag(DiagID)
10177                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
10178                               << CurrentType))
10179         DidWarnAboutNonPOD = true;
10180     }
10181 
10182     // Look for the field.
10183     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
10184     LookupQualifiedName(R, RD);
10185     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
10186     IndirectFieldDecl *IndirectMemberDecl = 0;
10187     if (!MemberDecl) {
10188       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
10189         MemberDecl = IndirectMemberDecl->getAnonField();
10190     }
10191 
10192     if (!MemberDecl)
10193       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
10194                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
10195                                                               OC.LocEnd));
10196 
10197     // C99 7.17p3:
10198     //   (If the specified member is a bit-field, the behavior is undefined.)
10199     //
10200     // We diagnose this as an error.
10201     if (MemberDecl->isBitField()) {
10202       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
10203         << MemberDecl->getDeclName()
10204         << SourceRange(BuiltinLoc, RParenLoc);
10205       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
10206       return ExprError();
10207     }
10208 
10209     RecordDecl *Parent = MemberDecl->getParent();
10210     if (IndirectMemberDecl)
10211       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
10212 
10213     // If the member was found in a base class, introduce OffsetOfNodes for
10214     // the base class indirections.
10215     CXXBasePaths Paths;
10216     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
10217       if (Paths.getDetectedVirtual()) {
10218         Diag(OC.LocEnd, diag::err_offsetof_field_of_virtual_base)
10219           << MemberDecl->getDeclName()
10220           << SourceRange(BuiltinLoc, RParenLoc);
10221         return ExprError();
10222       }
10223 
10224       CXXBasePath &Path = Paths.front();
10225       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
10226            B != BEnd; ++B)
10227         Comps.push_back(OffsetOfNode(B->Base));
10228     }
10229 
10230     if (IndirectMemberDecl) {
10231       for (auto *FI : IndirectMemberDecl->chain()) {
10232         assert(isa<FieldDecl>(FI));
10233         Comps.push_back(OffsetOfNode(OC.LocStart,
10234                                      cast<FieldDecl>(FI), OC.LocEnd));
10235       }
10236     } else
10237       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
10238 
10239     CurrentType = MemberDecl->getType().getNonReferenceType();
10240   }
10241 
10242   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
10243                                     TInfo, Comps, Exprs, RParenLoc));
10244 }
10245 
10246 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
10247                                       SourceLocation BuiltinLoc,
10248                                       SourceLocation TypeLoc,
10249                                       ParsedType ParsedArgTy,
10250                                       OffsetOfComponent *CompPtr,
10251                                       unsigned NumComponents,
10252                                       SourceLocation RParenLoc) {
10253 
10254   TypeSourceInfo *ArgTInfo;
10255   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
10256   if (ArgTy.isNull())
10257     return ExprError();
10258 
10259   if (!ArgTInfo)
10260     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
10261 
10262   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
10263                               RParenLoc);
10264 }
10265 
10266 
10267 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
10268                                  Expr *CondExpr,
10269                                  Expr *LHSExpr, Expr *RHSExpr,
10270                                  SourceLocation RPLoc) {
10271   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
10272 
10273   ExprValueKind VK = VK_RValue;
10274   ExprObjectKind OK = OK_Ordinary;
10275   QualType resType;
10276   bool ValueDependent = false;
10277   bool CondIsTrue = false;
10278   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
10279     resType = Context.DependentTy;
10280     ValueDependent = true;
10281   } else {
10282     // The conditional expression is required to be a constant expression.
10283     llvm::APSInt condEval(32);
10284     ExprResult CondICE
10285       = VerifyIntegerConstantExpression(CondExpr, &condEval,
10286           diag::err_typecheck_choose_expr_requires_constant, false);
10287     if (CondICE.isInvalid())
10288       return ExprError();
10289     CondExpr = CondICE.take();
10290     CondIsTrue = condEval.getZExtValue();
10291 
10292     // If the condition is > zero, then the AST type is the same as the LSHExpr.
10293     Expr *ActiveExpr = CondIsTrue ? LHSExpr : RHSExpr;
10294 
10295     resType = ActiveExpr->getType();
10296     ValueDependent = ActiveExpr->isValueDependent();
10297     VK = ActiveExpr->getValueKind();
10298     OK = ActiveExpr->getObjectKind();
10299   }
10300 
10301   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
10302                                         resType, VK, OK, RPLoc, CondIsTrue,
10303                                         resType->isDependentType(),
10304                                         ValueDependent));
10305 }
10306 
10307 //===----------------------------------------------------------------------===//
10308 // Clang Extensions.
10309 //===----------------------------------------------------------------------===//
10310 
10311 /// ActOnBlockStart - This callback is invoked when a block literal is started.
10312 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
10313   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
10314 
10315   if (LangOpts.CPlusPlus) {
10316     Decl *ManglingContextDecl;
10317     if (MangleNumberingContext *MCtx =
10318             getCurrentMangleNumberContext(Block->getDeclContext(),
10319                                           ManglingContextDecl)) {
10320       unsigned ManglingNumber = MCtx->getManglingNumber(Block);
10321       Block->setBlockMangling(ManglingNumber, ManglingContextDecl);
10322     }
10323   }
10324 
10325   PushBlockScope(CurScope, Block);
10326   CurContext->addDecl(Block);
10327   if (CurScope)
10328     PushDeclContext(CurScope, Block);
10329   else
10330     CurContext = Block;
10331 
10332   getCurBlock()->HasImplicitReturnType = true;
10333 
10334   // Enter a new evaluation context to insulate the block from any
10335   // cleanups from the enclosing full-expression.
10336   PushExpressionEvaluationContext(PotentiallyEvaluated);
10337 }
10338 
10339 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
10340                                Scope *CurScope) {
10341   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
10342   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
10343   BlockScopeInfo *CurBlock = getCurBlock();
10344 
10345   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
10346   QualType T = Sig->getType();
10347 
10348   // FIXME: We should allow unexpanded parameter packs here, but that would,
10349   // in turn, make the block expression contain unexpanded parameter packs.
10350   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
10351     // Drop the parameters.
10352     FunctionProtoType::ExtProtoInfo EPI;
10353     EPI.HasTrailingReturn = false;
10354     EPI.TypeQuals |= DeclSpec::TQ_const;
10355     T = Context.getFunctionType(Context.DependentTy, None, EPI);
10356     Sig = Context.getTrivialTypeSourceInfo(T);
10357   }
10358 
10359   // GetTypeForDeclarator always produces a function type for a block
10360   // literal signature.  Furthermore, it is always a FunctionProtoType
10361   // unless the function was written with a typedef.
10362   assert(T->isFunctionType() &&
10363          "GetTypeForDeclarator made a non-function block signature");
10364 
10365   // Look for an explicit signature in that function type.
10366   FunctionProtoTypeLoc ExplicitSignature;
10367 
10368   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
10369   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
10370 
10371     // Check whether that explicit signature was synthesized by
10372     // GetTypeForDeclarator.  If so, don't save that as part of the
10373     // written signature.
10374     if (ExplicitSignature.getLocalRangeBegin() ==
10375         ExplicitSignature.getLocalRangeEnd()) {
10376       // This would be much cheaper if we stored TypeLocs instead of
10377       // TypeSourceInfos.
10378       TypeLoc Result = ExplicitSignature.getReturnLoc();
10379       unsigned Size = Result.getFullDataSize();
10380       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
10381       Sig->getTypeLoc().initializeFullCopy(Result, Size);
10382 
10383       ExplicitSignature = FunctionProtoTypeLoc();
10384     }
10385   }
10386 
10387   CurBlock->TheDecl->setSignatureAsWritten(Sig);
10388   CurBlock->FunctionType = T;
10389 
10390   const FunctionType *Fn = T->getAs<FunctionType>();
10391   QualType RetTy = Fn->getReturnType();
10392   bool isVariadic =
10393     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
10394 
10395   CurBlock->TheDecl->setIsVariadic(isVariadic);
10396 
10397   // Context.DependentTy is used as a placeholder for a missing block
10398   // return type.  TODO:  what should we do with declarators like:
10399   //   ^ * { ... }
10400   // If the answer is "apply template argument deduction"....
10401   if (RetTy != Context.DependentTy) {
10402     CurBlock->ReturnType = RetTy;
10403     CurBlock->TheDecl->setBlockMissingReturnType(false);
10404     CurBlock->HasImplicitReturnType = false;
10405   }
10406 
10407   // Push block parameters from the declarator if we had them.
10408   SmallVector<ParmVarDecl*, 8> Params;
10409   if (ExplicitSignature) {
10410     for (unsigned I = 0, E = ExplicitSignature.getNumParams(); I != E; ++I) {
10411       ParmVarDecl *Param = ExplicitSignature.getParam(I);
10412       if (Param->getIdentifier() == 0 &&
10413           !Param->isImplicit() &&
10414           !Param->isInvalidDecl() &&
10415           !getLangOpts().CPlusPlus)
10416         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10417       Params.push_back(Param);
10418     }
10419 
10420   // Fake up parameter variables if we have a typedef, like
10421   //   ^ fntype { ... }
10422   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
10423     for (const auto &I : Fn->param_types()) {
10424       ParmVarDecl *Param = BuildParmVarDeclForTypedef(
10425           CurBlock->TheDecl, ParamInfo.getLocStart(), I);
10426       Params.push_back(Param);
10427     }
10428   }
10429 
10430   // Set the parameters on the block decl.
10431   if (!Params.empty()) {
10432     CurBlock->TheDecl->setParams(Params);
10433     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
10434                              CurBlock->TheDecl->param_end(),
10435                              /*CheckParameterNames=*/false);
10436   }
10437 
10438   // Finally we can process decl attributes.
10439   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
10440 
10441   // Put the parameter variables in scope.
10442   for (auto AI : CurBlock->TheDecl->params()) {
10443     AI->setOwningFunction(CurBlock->TheDecl);
10444 
10445     // If this has an identifier, add it to the scope stack.
10446     if (AI->getIdentifier()) {
10447       CheckShadow(CurBlock->TheScope, AI);
10448 
10449       PushOnScopeChains(AI, CurBlock->TheScope);
10450     }
10451   }
10452 }
10453 
10454 /// ActOnBlockError - If there is an error parsing a block, this callback
10455 /// is invoked to pop the information about the block from the action impl.
10456 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
10457   // Leave the expression-evaluation context.
10458   DiscardCleanupsInEvaluationContext();
10459   PopExpressionEvaluationContext();
10460 
10461   // Pop off CurBlock, handle nested blocks.
10462   PopDeclContext();
10463   PopFunctionScopeInfo();
10464 }
10465 
10466 /// ActOnBlockStmtExpr - This is called when the body of a block statement
10467 /// literal was successfully completed.  ^(int x){...}
10468 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
10469                                     Stmt *Body, Scope *CurScope) {
10470   // If blocks are disabled, emit an error.
10471   if (!LangOpts.Blocks)
10472     Diag(CaretLoc, diag::err_blocks_disable);
10473 
10474   // Leave the expression-evaluation context.
10475   if (hasAnyUnrecoverableErrorsInThisFunction())
10476     DiscardCleanupsInEvaluationContext();
10477   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
10478   PopExpressionEvaluationContext();
10479 
10480   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
10481 
10482   if (BSI->HasImplicitReturnType)
10483     deduceClosureReturnType(*BSI);
10484 
10485   PopDeclContext();
10486 
10487   QualType RetTy = Context.VoidTy;
10488   if (!BSI->ReturnType.isNull())
10489     RetTy = BSI->ReturnType;
10490 
10491   bool NoReturn = BSI->TheDecl->hasAttr<NoReturnAttr>();
10492   QualType BlockTy;
10493 
10494   // Set the captured variables on the block.
10495   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
10496   SmallVector<BlockDecl::Capture, 4> Captures;
10497   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
10498     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
10499     if (Cap.isThisCapture())
10500       continue;
10501     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
10502                               Cap.isNested(), Cap.getInitExpr());
10503     Captures.push_back(NewCap);
10504   }
10505   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
10506                             BSI->CXXThisCaptureIndex != 0);
10507 
10508   // If the user wrote a function type in some form, try to use that.
10509   if (!BSI->FunctionType.isNull()) {
10510     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
10511 
10512     FunctionType::ExtInfo Ext = FTy->getExtInfo();
10513     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
10514 
10515     // Turn protoless block types into nullary block types.
10516     if (isa<FunctionNoProtoType>(FTy)) {
10517       FunctionProtoType::ExtProtoInfo EPI;
10518       EPI.ExtInfo = Ext;
10519       BlockTy = Context.getFunctionType(RetTy, None, EPI);
10520 
10521     // Otherwise, if we don't need to change anything about the function type,
10522     // preserve its sugar structure.
10523     } else if (FTy->getReturnType() == RetTy &&
10524                (!NoReturn || FTy->getNoReturnAttr())) {
10525       BlockTy = BSI->FunctionType;
10526 
10527     // Otherwise, make the minimal modifications to the function type.
10528     } else {
10529       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
10530       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10531       EPI.TypeQuals = 0; // FIXME: silently?
10532       EPI.ExtInfo = Ext;
10533       BlockTy = Context.getFunctionType(RetTy, FPT->getParamTypes(), EPI);
10534     }
10535 
10536   // If we don't have a function type, just build one from nothing.
10537   } else {
10538     FunctionProtoType::ExtProtoInfo EPI;
10539     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
10540     BlockTy = Context.getFunctionType(RetTy, None, EPI);
10541   }
10542 
10543   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
10544                            BSI->TheDecl->param_end());
10545   BlockTy = Context.getBlockPointerType(BlockTy);
10546 
10547   // If needed, diagnose invalid gotos and switches in the block.
10548   if (getCurFunction()->NeedsScopeChecking() &&
10549       !hasAnyUnrecoverableErrorsInThisFunction() &&
10550       !PP.isCodeCompletionEnabled())
10551     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
10552 
10553   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
10554 
10555   // Try to apply the named return value optimization. We have to check again
10556   // if we can do this, though, because blocks keep return statements around
10557   // to deduce an implicit return type.
10558   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
10559       !BSI->TheDecl->isDependentContext())
10560     computeNRVO(Body, getCurBlock());
10561 
10562   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
10563   AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10564   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
10565 
10566   // If the block isn't obviously global, i.e. it captures anything at
10567   // all, then we need to do a few things in the surrounding context:
10568   if (Result->getBlockDecl()->hasCaptures()) {
10569     // First, this expression has a new cleanup object.
10570     ExprCleanupObjects.push_back(Result->getBlockDecl());
10571     ExprNeedsCleanups = true;
10572 
10573     // It also gets a branch-protected scope if any of the captured
10574     // variables needs destruction.
10575     for (const auto &CI : Result->getBlockDecl()->captures()) {
10576       const VarDecl *var = CI.getVariable();
10577       if (var->getType().isDestructedType() != QualType::DK_none) {
10578         getCurFunction()->setHasBranchProtectedScope();
10579         break;
10580       }
10581     }
10582   }
10583 
10584   return Owned(Result);
10585 }
10586 
10587 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
10588                                         Expr *E, ParsedType Ty,
10589                                         SourceLocation RPLoc) {
10590   TypeSourceInfo *TInfo;
10591   GetTypeFromParser(Ty, &TInfo);
10592   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
10593 }
10594 
10595 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
10596                                 Expr *E, TypeSourceInfo *TInfo,
10597                                 SourceLocation RPLoc) {
10598   Expr *OrigExpr = E;
10599 
10600   // Get the va_list type
10601   QualType VaListType = Context.getBuiltinVaListType();
10602   if (VaListType->isArrayType()) {
10603     // Deal with implicit array decay; for example, on x86-64,
10604     // va_list is an array, but it's supposed to decay to
10605     // a pointer for va_arg.
10606     VaListType = Context.getArrayDecayedType(VaListType);
10607     // Make sure the input expression also decays appropriately.
10608     ExprResult Result = UsualUnaryConversions(E);
10609     if (Result.isInvalid())
10610       return ExprError();
10611     E = Result.take();
10612   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
10613     // If va_list is a record type and we are compiling in C++ mode,
10614     // check the argument using reference binding.
10615     InitializedEntity Entity
10616       = InitializedEntity::InitializeParameter(Context,
10617           Context.getLValueReferenceType(VaListType), false);
10618     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
10619     if (Init.isInvalid())
10620       return ExprError();
10621     E = Init.takeAs<Expr>();
10622   } else {
10623     // Otherwise, the va_list argument must be an l-value because
10624     // it is modified by va_arg.
10625     if (!E->isTypeDependent() &&
10626         CheckForModifiableLvalue(E, BuiltinLoc, *this))
10627       return ExprError();
10628   }
10629 
10630   if (!E->isTypeDependent() &&
10631       !Context.hasSameType(VaListType, E->getType())) {
10632     return ExprError(Diag(E->getLocStart(),
10633                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
10634       << OrigExpr->getType() << E->getSourceRange());
10635   }
10636 
10637   if (!TInfo->getType()->isDependentType()) {
10638     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
10639                             diag::err_second_parameter_to_va_arg_incomplete,
10640                             TInfo->getTypeLoc()))
10641       return ExprError();
10642 
10643     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
10644                                TInfo->getType(),
10645                                diag::err_second_parameter_to_va_arg_abstract,
10646                                TInfo->getTypeLoc()))
10647       return ExprError();
10648 
10649     if (!TInfo->getType().isPODType(Context)) {
10650       Diag(TInfo->getTypeLoc().getBeginLoc(),
10651            TInfo->getType()->isObjCLifetimeType()
10652              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
10653              : diag::warn_second_parameter_to_va_arg_not_pod)
10654         << TInfo->getType()
10655         << TInfo->getTypeLoc().getSourceRange();
10656     }
10657 
10658     // Check for va_arg where arguments of the given type will be promoted
10659     // (i.e. this va_arg is guaranteed to have undefined behavior).
10660     QualType PromoteType;
10661     if (TInfo->getType()->isPromotableIntegerType()) {
10662       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
10663       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
10664         PromoteType = QualType();
10665     }
10666     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
10667       PromoteType = Context.DoubleTy;
10668     if (!PromoteType.isNull())
10669       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
10670                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
10671                           << TInfo->getType()
10672                           << PromoteType
10673                           << TInfo->getTypeLoc().getSourceRange());
10674   }
10675 
10676   QualType T = TInfo->getType().getNonLValueExprType(Context);
10677   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
10678 }
10679 
10680 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
10681   // The type of __null will be int or long, depending on the size of
10682   // pointers on the target.
10683   QualType Ty;
10684   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
10685   if (pw == Context.getTargetInfo().getIntWidth())
10686     Ty = Context.IntTy;
10687   else if (pw == Context.getTargetInfo().getLongWidth())
10688     Ty = Context.LongTy;
10689   else if (pw == Context.getTargetInfo().getLongLongWidth())
10690     Ty = Context.LongLongTy;
10691   else {
10692     llvm_unreachable("I don't know size of pointer!");
10693   }
10694 
10695   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
10696 }
10697 
10698 bool
10699 Sema::ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&Exp) {
10700   if (!getLangOpts().ObjC1)
10701     return false;
10702 
10703   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
10704   if (!PT)
10705     return false;
10706 
10707   if (!PT->isObjCIdType()) {
10708     // Check if the destination is the 'NSString' interface.
10709     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
10710     if (!ID || !ID->getIdentifier()->isStr("NSString"))
10711       return false;
10712   }
10713 
10714   // Ignore any parens, implicit casts (should only be
10715   // array-to-pointer decays), and not-so-opaque values.  The last is
10716   // important for making this trigger for property assignments.
10717   Expr *SrcExpr = Exp->IgnoreParenImpCasts();
10718   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10719     if (OV->getSourceExpr())
10720       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10721 
10722   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10723   if (!SL || !SL->isAscii())
10724     return false;
10725   Diag(SL->getLocStart(), diag::err_missing_atsign_prefix)
10726     << FixItHint::CreateInsertion(SL->getLocStart(), "@");
10727   Exp = BuildObjCStringLiteral(SL->getLocStart(), SL).take();
10728   return true;
10729 }
10730 
10731 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10732                                     SourceLocation Loc,
10733                                     QualType DstType, QualType SrcType,
10734                                     Expr *SrcExpr, AssignmentAction Action,
10735                                     bool *Complained) {
10736   if (Complained)
10737     *Complained = false;
10738 
10739   // Decode the result (notice that AST's are still created for extensions).
10740   bool CheckInferredResultType = false;
10741   bool isInvalid = false;
10742   unsigned DiagKind = 0;
10743   FixItHint Hint;
10744   ConversionFixItGenerator ConvHints;
10745   bool MayHaveConvFixit = false;
10746   bool MayHaveFunctionDiff = false;
10747 
10748   switch (ConvTy) {
10749   case Compatible:
10750       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10751       return false;
10752 
10753   case PointerToInt:
10754     DiagKind = diag::ext_typecheck_convert_pointer_int;
10755     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10756     MayHaveConvFixit = true;
10757     break;
10758   case IntToPointer:
10759     DiagKind = diag::ext_typecheck_convert_int_pointer;
10760     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10761     MayHaveConvFixit = true;
10762     break;
10763   case IncompatiblePointer:
10764       DiagKind =
10765         (Action == AA_Passing_CFAudited ?
10766           diag::err_arc_typecheck_convert_incompatible_pointer :
10767           diag::ext_typecheck_convert_incompatible_pointer);
10768     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10769       SrcType->isObjCObjectPointerType();
10770     if (Hint.isNull() && !CheckInferredResultType) {
10771       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10772     }
10773     else if (CheckInferredResultType) {
10774       SrcType = SrcType.getUnqualifiedType();
10775       DstType = DstType.getUnqualifiedType();
10776     }
10777     MayHaveConvFixit = true;
10778     break;
10779   case IncompatiblePointerSign:
10780     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10781     break;
10782   case FunctionVoidPointer:
10783     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10784     break;
10785   case IncompatiblePointerDiscardsQualifiers: {
10786     // Perform array-to-pointer decay if necessary.
10787     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10788 
10789     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10790     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10791     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10792       DiagKind = diag::err_typecheck_incompatible_address_space;
10793       break;
10794 
10795 
10796     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10797       DiagKind = diag::err_typecheck_incompatible_ownership;
10798       break;
10799     }
10800 
10801     llvm_unreachable("unknown error case for discarding qualifiers!");
10802     // fallthrough
10803   }
10804   case CompatiblePointerDiscardsQualifiers:
10805     // If the qualifiers lost were because we were applying the
10806     // (deprecated) C++ conversion from a string literal to a char*
10807     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10808     // Ideally, this check would be performed in
10809     // checkPointerTypesForAssignment. However, that would require a
10810     // bit of refactoring (so that the second argument is an
10811     // expression, rather than a type), which should be done as part
10812     // of a larger effort to fix checkPointerTypesForAssignment for
10813     // C++ semantics.
10814     if (getLangOpts().CPlusPlus &&
10815         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10816       return false;
10817     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10818     break;
10819   case IncompatibleNestedPointerQualifiers:
10820     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10821     break;
10822   case IntToBlockPointer:
10823     DiagKind = diag::err_int_to_block_pointer;
10824     break;
10825   case IncompatibleBlockPointer:
10826     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10827     break;
10828   case IncompatibleObjCQualifiedId:
10829     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10830     // it can give a more specific diagnostic.
10831     DiagKind = diag::warn_incompatible_qualified_id;
10832     break;
10833   case IncompatibleVectors:
10834     DiagKind = diag::warn_incompatible_vectors;
10835     break;
10836   case IncompatibleObjCWeakRef:
10837     DiagKind = diag::err_arc_weak_unavailable_assign;
10838     break;
10839   case Incompatible:
10840     DiagKind = diag::err_typecheck_convert_incompatible;
10841     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10842     MayHaveConvFixit = true;
10843     isInvalid = true;
10844     MayHaveFunctionDiff = true;
10845     break;
10846   }
10847 
10848   QualType FirstType, SecondType;
10849   switch (Action) {
10850   case AA_Assigning:
10851   case AA_Initializing:
10852     // The destination type comes first.
10853     FirstType = DstType;
10854     SecondType = SrcType;
10855     break;
10856 
10857   case AA_Returning:
10858   case AA_Passing:
10859   case AA_Passing_CFAudited:
10860   case AA_Converting:
10861   case AA_Sending:
10862   case AA_Casting:
10863     // The source type comes first.
10864     FirstType = SrcType;
10865     SecondType = DstType;
10866     break;
10867   }
10868 
10869   PartialDiagnostic FDiag = PDiag(DiagKind);
10870   if (Action == AA_Passing_CFAudited)
10871     FDiag << FirstType << SecondType << SrcExpr->getSourceRange();
10872   else
10873     FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10874 
10875   // If we can fix the conversion, suggest the FixIts.
10876   assert(ConvHints.isNull() || Hint.isNull());
10877   if (!ConvHints.isNull()) {
10878     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10879          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10880       FDiag << *HI;
10881   } else {
10882     FDiag << Hint;
10883   }
10884   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10885 
10886   if (MayHaveFunctionDiff)
10887     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10888 
10889   Diag(Loc, FDiag);
10890 
10891   if (SecondType == Context.OverloadTy)
10892     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10893                               FirstType);
10894 
10895   if (CheckInferredResultType)
10896     EmitRelatedResultTypeNote(SrcExpr);
10897 
10898   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10899     EmitRelatedResultTypeNoteForReturn(DstType);
10900 
10901   if (Complained)
10902     *Complained = true;
10903   return isInvalid;
10904 }
10905 
10906 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10907                                                  llvm::APSInt *Result) {
10908   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10909   public:
10910     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
10911       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10912     }
10913   } Diagnoser;
10914 
10915   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10916 }
10917 
10918 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10919                                                  llvm::APSInt *Result,
10920                                                  unsigned DiagID,
10921                                                  bool AllowFold) {
10922   class IDDiagnoser : public VerifyICEDiagnoser {
10923     unsigned DiagID;
10924 
10925   public:
10926     IDDiagnoser(unsigned DiagID)
10927       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10928 
10929     void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
10930       S.Diag(Loc, DiagID) << SR;
10931     }
10932   } Diagnoser(DiagID);
10933 
10934   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10935 }
10936 
10937 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10938                                             SourceRange SR) {
10939   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10940 }
10941 
10942 ExprResult
10943 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10944                                       VerifyICEDiagnoser &Diagnoser,
10945                                       bool AllowFold) {
10946   SourceLocation DiagLoc = E->getLocStart();
10947 
10948   if (getLangOpts().CPlusPlus11) {
10949     // C++11 [expr.const]p5:
10950     //   If an expression of literal class type is used in a context where an
10951     //   integral constant expression is required, then that class type shall
10952     //   have a single non-explicit conversion function to an integral or
10953     //   unscoped enumeration type
10954     ExprResult Converted;
10955     class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10956     public:
10957       CXX11ConvertDiagnoser(bool Silent)
10958           : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false,
10959                                 Silent, true) {}
10960 
10961       SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10962                                            QualType T) override {
10963         return S.Diag(Loc, diag::err_ice_not_integral) << T;
10964       }
10965 
10966       SemaDiagnosticBuilder diagnoseIncomplete(
10967           Sema &S, SourceLocation Loc, QualType T) override {
10968         return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10969       }
10970 
10971       SemaDiagnosticBuilder diagnoseExplicitConv(
10972           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
10973         return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10974       }
10975 
10976       SemaDiagnosticBuilder noteExplicitConv(
10977           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
10978         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10979                  << ConvTy->isEnumeralType() << ConvTy;
10980       }
10981 
10982       SemaDiagnosticBuilder diagnoseAmbiguous(
10983           Sema &S, SourceLocation Loc, QualType T) override {
10984         return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10985       }
10986 
10987       SemaDiagnosticBuilder noteAmbiguous(
10988           Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
10989         return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10990                  << ConvTy->isEnumeralType() << ConvTy;
10991       }
10992 
10993       SemaDiagnosticBuilder diagnoseConversion(
10994           Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
10995         llvm_unreachable("conversion functions are permitted");
10996       }
10997     } ConvertDiagnoser(Diagnoser.Suppress);
10998 
10999     Converted = PerformContextualImplicitConversion(DiagLoc, E,
11000                                                     ConvertDiagnoser);
11001     if (Converted.isInvalid())
11002       return Converted;
11003     E = Converted.take();
11004     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
11005       return ExprError();
11006   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11007     // An ICE must be of integral or unscoped enumeration type.
11008     if (!Diagnoser.Suppress)
11009       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11010     return ExprError();
11011   }
11012 
11013   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
11014   // in the non-ICE case.
11015   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
11016     if (Result)
11017       *Result = E->EvaluateKnownConstInt(Context);
11018     return Owned(E);
11019   }
11020 
11021   Expr::EvalResult EvalResult;
11022   SmallVector<PartialDiagnosticAt, 8> Notes;
11023   EvalResult.Diag = &Notes;
11024 
11025   // Try to evaluate the expression, and produce diagnostics explaining why it's
11026   // not a constant expression as a side-effect.
11027   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
11028                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
11029 
11030   // In C++11, we can rely on diagnostics being produced for any expression
11031   // which is not a constant expression. If no diagnostics were produced, then
11032   // this is a constant expression.
11033   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
11034     if (Result)
11035       *Result = EvalResult.Val.getInt();
11036     return Owned(E);
11037   }
11038 
11039   // If our only note is the usual "invalid subexpression" note, just point
11040   // the caret at its location rather than producing an essentially
11041   // redundant note.
11042   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11043         diag::note_invalid_subexpr_in_const_expr) {
11044     DiagLoc = Notes[0].first;
11045     Notes.clear();
11046   }
11047 
11048   if (!Folded || !AllowFold) {
11049     if (!Diagnoser.Suppress) {
11050       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
11051       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11052         Diag(Notes[I].first, Notes[I].second);
11053     }
11054 
11055     return ExprError();
11056   }
11057 
11058   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
11059   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11060     Diag(Notes[I].first, Notes[I].second);
11061 
11062   if (Result)
11063     *Result = EvalResult.Val.getInt();
11064   return Owned(E);
11065 }
11066 
11067 namespace {
11068   // Handle the case where we conclude a expression which we speculatively
11069   // considered to be unevaluated is actually evaluated.
11070   class TransformToPE : public TreeTransform<TransformToPE> {
11071     typedef TreeTransform<TransformToPE> BaseTransform;
11072 
11073   public:
11074     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
11075 
11076     // Make sure we redo semantic analysis
11077     bool AlwaysRebuild() { return true; }
11078 
11079     // Make sure we handle LabelStmts correctly.
11080     // FIXME: This does the right thing, but maybe we need a more general
11081     // fix to TreeTransform?
11082     StmtResult TransformLabelStmt(LabelStmt *S) {
11083       S->getDecl()->setStmt(0);
11084       return BaseTransform::TransformLabelStmt(S);
11085     }
11086 
11087     // We need to special-case DeclRefExprs referring to FieldDecls which
11088     // are not part of a member pointer formation; normal TreeTransforming
11089     // doesn't catch this case because of the way we represent them in the AST.
11090     // FIXME: This is a bit ugly; is it really the best way to handle this
11091     // case?
11092     //
11093     // Error on DeclRefExprs referring to FieldDecls.
11094     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
11095       if (isa<FieldDecl>(E->getDecl()) &&
11096           !SemaRef.isUnevaluatedContext())
11097         return SemaRef.Diag(E->getLocation(),
11098                             diag::err_invalid_non_static_member_use)
11099             << E->getDecl() << E->getSourceRange();
11100 
11101       return BaseTransform::TransformDeclRefExpr(E);
11102     }
11103 
11104     // Exception: filter out member pointer formation
11105     ExprResult TransformUnaryOperator(UnaryOperator *E) {
11106       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
11107         return E;
11108 
11109       return BaseTransform::TransformUnaryOperator(E);
11110     }
11111 
11112     ExprResult TransformLambdaExpr(LambdaExpr *E) {
11113       // Lambdas never need to be transformed.
11114       return E;
11115     }
11116   };
11117 }
11118 
11119 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
11120   assert(isUnevaluatedContext() &&
11121          "Should only transform unevaluated expressions");
11122   ExprEvalContexts.back().Context =
11123       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
11124   if (isUnevaluatedContext())
11125     return E;
11126   return TransformToPE(*this).TransformExpr(E);
11127 }
11128 
11129 void
11130 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11131                                       Decl *LambdaContextDecl,
11132                                       bool IsDecltype) {
11133   ExprEvalContexts.push_back(
11134              ExpressionEvaluationContextRecord(NewContext,
11135                                                ExprCleanupObjects.size(),
11136                                                ExprNeedsCleanups,
11137                                                LambdaContextDecl,
11138                                                IsDecltype));
11139   ExprNeedsCleanups = false;
11140   if (!MaybeODRUseExprs.empty())
11141     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
11142 }
11143 
11144 void
11145 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
11146                                       ReuseLambdaContextDecl_t,
11147                                       bool IsDecltype) {
11148   Decl *ClosureContextDecl = ExprEvalContexts.back().ManglingContextDecl;
11149   PushExpressionEvaluationContext(NewContext, ClosureContextDecl, IsDecltype);
11150 }
11151 
11152 void Sema::PopExpressionEvaluationContext() {
11153   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
11154 
11155   if (!Rec.Lambdas.empty()) {
11156     if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11157       unsigned D;
11158       if (Rec.isUnevaluated()) {
11159         // C++11 [expr.prim.lambda]p2:
11160         //   A lambda-expression shall not appear in an unevaluated operand
11161         //   (Clause 5).
11162         D = diag::err_lambda_unevaluated_operand;
11163       } else {
11164         // C++1y [expr.const]p2:
11165         //   A conditional-expression e is a core constant expression unless the
11166         //   evaluation of e, following the rules of the abstract machine, would
11167         //   evaluate [...] a lambda-expression.
11168         D = diag::err_lambda_in_constant_expression;
11169       }
11170       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
11171         Diag(Rec.Lambdas[I]->getLocStart(), D);
11172     } else {
11173       // Mark the capture expressions odr-used. This was deferred
11174       // during lambda expression creation.
11175       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
11176         LambdaExpr *Lambda = Rec.Lambdas[I];
11177         for (LambdaExpr::capture_init_iterator
11178                   C = Lambda->capture_init_begin(),
11179                CEnd = Lambda->capture_init_end();
11180              C != CEnd; ++C) {
11181           MarkDeclarationsReferencedInExpr(*C);
11182         }
11183       }
11184     }
11185   }
11186 
11187   // When are coming out of an unevaluated context, clear out any
11188   // temporaries that we may have created as part of the evaluation of
11189   // the expression in that context: they aren't relevant because they
11190   // will never be constructed.
11191   if (Rec.isUnevaluated() || Rec.Context == ConstantEvaluated) {
11192     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
11193                              ExprCleanupObjects.end());
11194     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
11195     CleanupVarDeclMarking();
11196     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
11197   // Otherwise, merge the contexts together.
11198   } else {
11199     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
11200     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
11201                             Rec.SavedMaybeODRUseExprs.end());
11202   }
11203 
11204   // Pop the current expression evaluation context off the stack.
11205   ExprEvalContexts.pop_back();
11206 }
11207 
11208 void Sema::DiscardCleanupsInEvaluationContext() {
11209   ExprCleanupObjects.erase(
11210          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
11211          ExprCleanupObjects.end());
11212   ExprNeedsCleanups = false;
11213   MaybeODRUseExprs.clear();
11214 }
11215 
11216 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
11217   if (!E->getType()->isVariablyModifiedType())
11218     return E;
11219   return TransformToPotentiallyEvaluated(E);
11220 }
11221 
11222 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
11223   // Do not mark anything as "used" within a dependent context; wait for
11224   // an instantiation.
11225   if (SemaRef.CurContext->isDependentContext())
11226     return false;
11227 
11228   switch (SemaRef.ExprEvalContexts.back().Context) {
11229     case Sema::Unevaluated:
11230     case Sema::UnevaluatedAbstract:
11231       // We are in an expression that is not potentially evaluated; do nothing.
11232       // (Depending on how you read the standard, we actually do need to do
11233       // something here for null pointer constants, but the standard's
11234       // definition of a null pointer constant is completely crazy.)
11235       return false;
11236 
11237     case Sema::ConstantEvaluated:
11238     case Sema::PotentiallyEvaluated:
11239       // We are in a potentially evaluated expression (or a constant-expression
11240       // in C++03); we need to do implicit template instantiation, implicitly
11241       // define class members, and mark most declarations as used.
11242       return true;
11243 
11244     case Sema::PotentiallyEvaluatedIfUsed:
11245       // Referenced declarations will only be used if the construct in the
11246       // containing expression is used.
11247       return false;
11248   }
11249   llvm_unreachable("Invalid context");
11250 }
11251 
11252 /// \brief Mark a function referenced, and check whether it is odr-used
11253 /// (C++ [basic.def.odr]p2, C99 6.9p3)
11254 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
11255   assert(Func && "No function?");
11256 
11257   Func->setReferenced();
11258 
11259   // C++11 [basic.def.odr]p3:
11260   //   A function whose name appears as a potentially-evaluated expression is
11261   //   odr-used if it is the unique lookup result or the selected member of a
11262   //   set of overloaded functions [...].
11263   //
11264   // We (incorrectly) mark overload resolution as an unevaluated context, so we
11265   // can just check that here. Skip the rest of this function if we've already
11266   // marked the function as used.
11267   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
11268     // C++11 [temp.inst]p3:
11269     //   Unless a function template specialization has been explicitly
11270     //   instantiated or explicitly specialized, the function template
11271     //   specialization is implicitly instantiated when the specialization is
11272     //   referenced in a context that requires a function definition to exist.
11273     //
11274     // We consider constexpr function templates to be referenced in a context
11275     // that requires a definition to exist whenever they are referenced.
11276     //
11277     // FIXME: This instantiates constexpr functions too frequently. If this is
11278     // really an unevaluated context (and we're not just in the definition of a
11279     // function template or overload resolution or other cases which we
11280     // incorrectly consider to be unevaluated contexts), and we're not in a
11281     // subexpression which we actually need to evaluate (for instance, a
11282     // template argument, array bound or an expression in a braced-init-list),
11283     // we are not permitted to instantiate this constexpr function definition.
11284     //
11285     // FIXME: This also implicitly defines special members too frequently. They
11286     // are only supposed to be implicitly defined if they are odr-used, but they
11287     // are not odr-used from constant expressions in unevaluated contexts.
11288     // However, they cannot be referenced if they are deleted, and they are
11289     // deleted whenever the implicit definition of the special member would
11290     // fail.
11291     if (!Func->isConstexpr() || Func->getBody())
11292       return;
11293     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
11294     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
11295       return;
11296   }
11297 
11298   // Note that this declaration has been used.
11299   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
11300     Constructor = cast<CXXConstructorDecl>(Constructor->getFirstDecl());
11301     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
11302       if (Constructor->isDefaultConstructor()) {
11303         if (Constructor->isTrivial())
11304           return;
11305         DefineImplicitDefaultConstructor(Loc, Constructor);
11306       } else if (Constructor->isCopyConstructor()) {
11307         DefineImplicitCopyConstructor(Loc, Constructor);
11308       } else if (Constructor->isMoveConstructor()) {
11309         DefineImplicitMoveConstructor(Loc, Constructor);
11310       }
11311     } else if (Constructor->getInheritedConstructor()) {
11312       DefineInheritingConstructor(Loc, Constructor);
11313     }
11314 
11315     MarkVTableUsed(Loc, Constructor->getParent());
11316   } else if (CXXDestructorDecl *Destructor =
11317                  dyn_cast<CXXDestructorDecl>(Func)) {
11318     Destructor = cast<CXXDestructorDecl>(Destructor->getFirstDecl());
11319     if (Destructor->isDefaulted() && !Destructor->isDeleted())
11320       DefineImplicitDestructor(Loc, Destructor);
11321     if (Destructor->isVirtual())
11322       MarkVTableUsed(Loc, Destructor->getParent());
11323   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
11324     if (MethodDecl->isOverloadedOperator() &&
11325         MethodDecl->getOverloadedOperator() == OO_Equal) {
11326       MethodDecl = cast<CXXMethodDecl>(MethodDecl->getFirstDecl());
11327       if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted()) {
11328         if (MethodDecl->isCopyAssignmentOperator())
11329           DefineImplicitCopyAssignment(Loc, MethodDecl);
11330         else
11331           DefineImplicitMoveAssignment(Loc, MethodDecl);
11332       }
11333     } else if (isa<CXXConversionDecl>(MethodDecl) &&
11334                MethodDecl->getParent()->isLambda()) {
11335       CXXConversionDecl *Conversion =
11336           cast<CXXConversionDecl>(MethodDecl->getFirstDecl());
11337       if (Conversion->isLambdaToBlockPointerConversion())
11338         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
11339       else
11340         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
11341     } else if (MethodDecl->isVirtual())
11342       MarkVTableUsed(Loc, MethodDecl->getParent());
11343   }
11344 
11345   // Recursive functions should be marked when used from another function.
11346   // FIXME: Is this really right?
11347   if (CurContext == Func) return;
11348 
11349   // Resolve the exception specification for any function which is
11350   // used: CodeGen will need it.
11351   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
11352   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
11353     ResolveExceptionSpec(Loc, FPT);
11354 
11355   // Implicit instantiation of function templates and member functions of
11356   // class templates.
11357   if (Func->isImplicitlyInstantiable()) {
11358     bool AlreadyInstantiated = false;
11359     SourceLocation PointOfInstantiation = Loc;
11360     if (FunctionTemplateSpecializationInfo *SpecInfo
11361                               = Func->getTemplateSpecializationInfo()) {
11362       if (SpecInfo->getPointOfInstantiation().isInvalid())
11363         SpecInfo->setPointOfInstantiation(Loc);
11364       else if (SpecInfo->getTemplateSpecializationKind()
11365                  == TSK_ImplicitInstantiation) {
11366         AlreadyInstantiated = true;
11367         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
11368       }
11369     } else if (MemberSpecializationInfo *MSInfo
11370                                 = Func->getMemberSpecializationInfo()) {
11371       if (MSInfo->getPointOfInstantiation().isInvalid())
11372         MSInfo->setPointOfInstantiation(Loc);
11373       else if (MSInfo->getTemplateSpecializationKind()
11374                  == TSK_ImplicitInstantiation) {
11375         AlreadyInstantiated = true;
11376         PointOfInstantiation = MSInfo->getPointOfInstantiation();
11377       }
11378     }
11379 
11380     if (!AlreadyInstantiated || Func->isConstexpr()) {
11381       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
11382           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass() &&
11383           ActiveTemplateInstantiations.size())
11384         PendingLocalImplicitInstantiations.push_back(
11385             std::make_pair(Func, PointOfInstantiation));
11386       else if (Func->isConstexpr())
11387         // Do not defer instantiations of constexpr functions, to avoid the
11388         // expression evaluator needing to call back into Sema if it sees a
11389         // call to such a function.
11390         InstantiateFunctionDefinition(PointOfInstantiation, Func);
11391       else {
11392         PendingInstantiations.push_back(std::make_pair(Func,
11393                                                        PointOfInstantiation));
11394         // Notify the consumer that a function was implicitly instantiated.
11395         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
11396       }
11397     }
11398   } else {
11399     // Walk redefinitions, as some of them may be instantiable.
11400     for (auto i : Func->redecls()) {
11401       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
11402         MarkFunctionReferenced(Loc, i);
11403     }
11404   }
11405 
11406   // Keep track of used but undefined functions.
11407   if (!Func->isDefined()) {
11408     if (mightHaveNonExternalLinkage(Func))
11409       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11410     else if (Func->getMostRecentDecl()->isInlined() &&
11411              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
11412              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
11413       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
11414   }
11415 
11416   // Normally the most current decl is marked used while processing the use and
11417   // any subsequent decls are marked used by decl merging. This fails with
11418   // template instantiation since marking can happen at the end of the file
11419   // and, because of the two phase lookup, this function is called with at
11420   // decl in the middle of a decl chain. We loop to maintain the invariant
11421   // that once a decl is used, all decls after it are also used.
11422   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
11423     F->markUsed(Context);
11424     if (F == Func)
11425       break;
11426   }
11427 }
11428 
11429 static void
11430 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
11431                                    VarDecl *var, DeclContext *DC) {
11432   DeclContext *VarDC = var->getDeclContext();
11433 
11434   //  If the parameter still belongs to the translation unit, then
11435   //  we're actually just using one parameter in the declaration of
11436   //  the next.
11437   if (isa<ParmVarDecl>(var) &&
11438       isa<TranslationUnitDecl>(VarDC))
11439     return;
11440 
11441   // For C code, don't diagnose about capture if we're not actually in code
11442   // right now; it's impossible to write a non-constant expression outside of
11443   // function context, so we'll get other (more useful) diagnostics later.
11444   //
11445   // For C++, things get a bit more nasty... it would be nice to suppress this
11446   // diagnostic for certain cases like using a local variable in an array bound
11447   // for a member of a local class, but the correct predicate is not obvious.
11448   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
11449     return;
11450 
11451   if (isa<CXXMethodDecl>(VarDC) &&
11452       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
11453     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
11454       << var->getIdentifier();
11455   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
11456     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
11457       << var->getIdentifier() << fn->getDeclName();
11458   } else if (isa<BlockDecl>(VarDC)) {
11459     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
11460       << var->getIdentifier();
11461   } else {
11462     // FIXME: Is there any other context where a local variable can be
11463     // declared?
11464     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
11465       << var->getIdentifier();
11466   }
11467 
11468   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
11469     << var->getIdentifier();
11470 
11471   // FIXME: Add additional diagnostic info about class etc. which prevents
11472   // capture.
11473 }
11474 
11475 
11476 static bool isVariableAlreadyCapturedInScopeInfo(CapturingScopeInfo *CSI, VarDecl *Var,
11477                                       bool &SubCapturesAreNested,
11478                                       QualType &CaptureType,
11479                                       QualType &DeclRefType) {
11480    // Check whether we've already captured it.
11481   if (CSI->CaptureMap.count(Var)) {
11482     // If we found a capture, any subcaptures are nested.
11483     SubCapturesAreNested = true;
11484 
11485     // Retrieve the capture type for this variable.
11486     CaptureType = CSI->getCapture(Var).getCaptureType();
11487 
11488     // Compute the type of an expression that refers to this variable.
11489     DeclRefType = CaptureType.getNonReferenceType();
11490 
11491     const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
11492     if (Cap.isCopyCapture() &&
11493         !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
11494       DeclRefType.addConst();
11495     return true;
11496   }
11497   return false;
11498 }
11499 
11500 // Only block literals, captured statements, and lambda expressions can
11501 // capture; other scopes don't work.
11502 static DeclContext *getParentOfCapturingContextOrNull(DeclContext *DC, VarDecl *Var,
11503                                  SourceLocation Loc,
11504                                  const bool Diagnose, Sema &S) {
11505   if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC) || isLambdaCallOperator(DC))
11506     return getLambdaAwareParentOfDeclContext(DC);
11507   else {
11508     if (Diagnose)
11509        diagnoseUncapturableValueReference(S, Loc, Var, DC);
11510   }
11511   return 0;
11512 }
11513 
11514 // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
11515 // certain types of variables (unnamed, variably modified types etc.)
11516 // so check for eligibility.
11517 static bool isVariableCapturable(CapturingScopeInfo *CSI, VarDecl *Var,
11518                                  SourceLocation Loc,
11519                                  const bool Diagnose, Sema &S) {
11520 
11521   bool IsBlock = isa<BlockScopeInfo>(CSI);
11522   bool IsLambda = isa<LambdaScopeInfo>(CSI);
11523 
11524   // Lambdas are not allowed to capture unnamed variables
11525   // (e.g. anonymous unions).
11526   // FIXME: The C++11 rule don't actually state this explicitly, but I'm
11527   // assuming that's the intent.
11528   if (IsLambda && !Var->getDeclName()) {
11529     if (Diagnose) {
11530       S.Diag(Loc, diag::err_lambda_capture_anonymous_var);
11531       S.Diag(Var->getLocation(), diag::note_declared_at);
11532     }
11533     return false;
11534   }
11535 
11536   // Prohibit variably-modified types; they're difficult to deal with.
11537   if (Var->getType()->isVariablyModifiedType()) {
11538     if (Diagnose) {
11539       if (IsBlock)
11540         S.Diag(Loc, diag::err_ref_vm_type);
11541       else
11542         S.Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
11543       S.Diag(Var->getLocation(), diag::note_previous_decl)
11544         << Var->getDeclName();
11545     }
11546     return false;
11547   }
11548   // Prohibit structs with flexible array members too.
11549   // We cannot capture what is in the tail end of the struct.
11550   if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11551     if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11552       if (Diagnose) {
11553         if (IsBlock)
11554           S.Diag(Loc, diag::err_ref_flexarray_type);
11555         else
11556           S.Diag(Loc, diag::err_lambda_capture_flexarray_type)
11557             << Var->getDeclName();
11558         S.Diag(Var->getLocation(), diag::note_previous_decl)
11559           << Var->getDeclName();
11560       }
11561       return false;
11562     }
11563   }
11564   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11565   // Lambdas and captured statements are not allowed to capture __block
11566   // variables; they don't support the expected semantics.
11567   if (HasBlocksAttr && (IsLambda || isa<CapturedRegionScopeInfo>(CSI))) {
11568     if (Diagnose) {
11569       S.Diag(Loc, diag::err_capture_block_variable)
11570         << Var->getDeclName() << !IsLambda;
11571       S.Diag(Var->getLocation(), diag::note_previous_decl)
11572         << Var->getDeclName();
11573     }
11574     return false;
11575   }
11576 
11577   return true;
11578 }
11579 
11580 // Returns true if the capture by block was successful.
11581 static bool captureInBlock(BlockScopeInfo *BSI, VarDecl *Var,
11582                                  SourceLocation Loc,
11583                                  const bool BuildAndDiagnose,
11584                                  QualType &CaptureType,
11585                                  QualType &DeclRefType,
11586                                  const bool Nested,
11587                                  Sema &S) {
11588   Expr *CopyExpr = 0;
11589   bool ByRef = false;
11590 
11591   // Blocks are not allowed to capture arrays.
11592   if (CaptureType->isArrayType()) {
11593     if (BuildAndDiagnose) {
11594       S.Diag(Loc, diag::err_ref_array_type);
11595       S.Diag(Var->getLocation(), diag::note_previous_decl)
11596       << Var->getDeclName();
11597     }
11598     return false;
11599   }
11600 
11601   // Forbid the block-capture of autoreleasing variables.
11602   if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11603     if (BuildAndDiagnose) {
11604       S.Diag(Loc, diag::err_arc_autoreleasing_capture)
11605         << /*block*/ 0;
11606       S.Diag(Var->getLocation(), diag::note_previous_decl)
11607         << Var->getDeclName();
11608     }
11609     return false;
11610   }
11611   const bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
11612   if (HasBlocksAttr || CaptureType->isReferenceType()) {
11613     // Block capture by reference does not change the capture or
11614     // declaration reference types.
11615     ByRef = true;
11616   } else {
11617     // Block capture by copy introduces 'const'.
11618     CaptureType = CaptureType.getNonReferenceType().withConst();
11619     DeclRefType = CaptureType;
11620 
11621     if (S.getLangOpts().CPlusPlus && BuildAndDiagnose) {
11622       if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11623         // The capture logic needs the destructor, so make sure we mark it.
11624         // Usually this is unnecessary because most local variables have
11625         // their destructors marked at declaration time, but parameters are
11626         // an exception because it's technically only the call site that
11627         // actually requires the destructor.
11628         if (isa<ParmVarDecl>(Var))
11629           S.FinalizeVarWithDestructor(Var, Record);
11630 
11631         // Enter a new evaluation context to insulate the copy
11632         // full-expression.
11633         EnterExpressionEvaluationContext scope(S, S.PotentiallyEvaluated);
11634 
11635         // According to the blocks spec, the capture of a variable from
11636         // the stack requires a const copy constructor.  This is not true
11637         // of the copy/move done to move a __block variable to the heap.
11638         Expr *DeclRef = new (S.Context) DeclRefExpr(Var, Nested,
11639                                                   DeclRefType.withConst(),
11640                                                   VK_LValue, Loc);
11641 
11642         ExprResult Result
11643           = S.PerformCopyInitialization(
11644               InitializedEntity::InitializeBlock(Var->getLocation(),
11645                                                   CaptureType, false),
11646               Loc, S.Owned(DeclRef));
11647 
11648         // Build a full-expression copy expression if initialization
11649         // succeeded and used a non-trivial constructor.  Recover from
11650         // errors by pretending that the copy isn't necessary.
11651         if (!Result.isInvalid() &&
11652             !cast<CXXConstructExpr>(Result.get())->getConstructor()
11653                 ->isTrivial()) {
11654           Result = S.MaybeCreateExprWithCleanups(Result);
11655           CopyExpr = Result.take();
11656         }
11657       }
11658     }
11659   }
11660 
11661   // Actually capture the variable.
11662   if (BuildAndDiagnose)
11663     BSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
11664                     SourceLocation(), CaptureType, CopyExpr);
11665 
11666   return true;
11667 
11668 }
11669 
11670 
11671 /// \brief Capture the given variable in the captured region.
11672 static bool captureInCapturedRegion(CapturedRegionScopeInfo *RSI,
11673                                     VarDecl *Var,
11674                                     SourceLocation Loc,
11675                                     const bool BuildAndDiagnose,
11676                                     QualType &CaptureType,
11677                                     QualType &DeclRefType,
11678                                     const bool RefersToEnclosingLocal,
11679                                     Sema &S) {
11680 
11681   // By default, capture variables by reference.
11682   bool ByRef = true;
11683   // Using an LValue reference type is consistent with Lambdas (see below).
11684   CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11685   Expr *CopyExpr = 0;
11686   if (BuildAndDiagnose) {
11687     // The current implementation assumes that all variables are captured
11688     // by references. Since there is no capture by copy, no expression evaluation
11689     // will be needed.
11690     //
11691     RecordDecl *RD = RSI->TheRecordDecl;
11692 
11693     FieldDecl *Field
11694       = FieldDecl::Create(S.Context, RD, Loc, Loc, 0, CaptureType,
11695                           S.Context.getTrivialTypeSourceInfo(CaptureType, Loc),
11696                           0, false, ICIS_NoInit);
11697     Field->setImplicit(true);
11698     Field->setAccess(AS_private);
11699     RD->addDecl(Field);
11700 
11701     CopyExpr = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11702                                             DeclRefType, VK_LValue, Loc);
11703     Var->setReferenced(true);
11704     Var->markUsed(S.Context);
11705   }
11706 
11707   // Actually capture the variable.
11708   if (BuildAndDiagnose)
11709     RSI->addCapture(Var, /*isBlock*/false, ByRef, RefersToEnclosingLocal, Loc,
11710                     SourceLocation(), CaptureType, CopyExpr);
11711 
11712 
11713   return true;
11714 }
11715 
11716 /// \brief Create a field within the lambda class for the variable
11717 ///  being captured.  Handle Array captures.
11718 static ExprResult addAsFieldToClosureType(Sema &S,
11719                                  LambdaScopeInfo *LSI,
11720                                   VarDecl *Var, QualType FieldType,
11721                                   QualType DeclRefType,
11722                                   SourceLocation Loc,
11723                                   bool RefersToEnclosingLocal) {
11724   CXXRecordDecl *Lambda = LSI->Lambda;
11725 
11726   // Build the non-static data member.
11727   FieldDecl *Field
11728     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
11729                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
11730                         0, false, ICIS_NoInit);
11731   Field->setImplicit(true);
11732   Field->setAccess(AS_private);
11733   Lambda->addDecl(Field);
11734 
11735   // C++11 [expr.prim.lambda]p21:
11736   //   When the lambda-expression is evaluated, the entities that
11737   //   are captured by copy are used to direct-initialize each
11738   //   corresponding non-static data member of the resulting closure
11739   //   object. (For array members, the array elements are
11740   //   direct-initialized in increasing subscript order.) These
11741   //   initializations are performed in the (unspecified) order in
11742   //   which the non-static data members are declared.
11743 
11744   // Introduce a new evaluation context for the initialization, so
11745   // that temporaries introduced as part of the capture are retained
11746   // to be re-"exported" from the lambda expression itself.
11747   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
11748 
11749   // C++ [expr.prim.labda]p12:
11750   //   An entity captured by a lambda-expression is odr-used (3.2) in
11751   //   the scope containing the lambda-expression.
11752   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
11753                                           DeclRefType, VK_LValue, Loc);
11754   Var->setReferenced(true);
11755   Var->markUsed(S.Context);
11756 
11757   // When the field has array type, create index variables for each
11758   // dimension of the array. We use these index variables to subscript
11759   // the source array, and other clients (e.g., CodeGen) will perform
11760   // the necessary iteration with these index variables.
11761   SmallVector<VarDecl *, 4> IndexVariables;
11762   QualType BaseType = FieldType;
11763   QualType SizeType = S.Context.getSizeType();
11764   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
11765   while (const ConstantArrayType *Array
11766                         = S.Context.getAsConstantArrayType(BaseType)) {
11767     // Create the iteration variable for this array index.
11768     IdentifierInfo *IterationVarName = 0;
11769     {
11770       SmallString<8> Str;
11771       llvm::raw_svector_ostream OS(Str);
11772       OS << "__i" << IndexVariables.size();
11773       IterationVarName = &S.Context.Idents.get(OS.str());
11774     }
11775     VarDecl *IterationVar
11776       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11777                         IterationVarName, SizeType,
11778                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11779                         SC_None);
11780     IndexVariables.push_back(IterationVar);
11781     LSI->ArrayIndexVars.push_back(IterationVar);
11782 
11783     // Create a reference to the iteration variable.
11784     ExprResult IterationVarRef
11785       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
11786     assert(!IterationVarRef.isInvalid() &&
11787            "Reference to invented variable cannot fail!");
11788     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
11789     assert(!IterationVarRef.isInvalid() &&
11790            "Conversion of invented variable cannot fail!");
11791 
11792     // Subscript the array with this iteration variable.
11793     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
11794                              Ref, Loc, IterationVarRef.take(), Loc);
11795     if (Subscript.isInvalid()) {
11796       S.CleanupVarDeclMarking();
11797       S.DiscardCleanupsInEvaluationContext();
11798       return ExprError();
11799     }
11800 
11801     Ref = Subscript.take();
11802     BaseType = Array->getElementType();
11803   }
11804 
11805   // Construct the entity that we will be initializing. For an array, this
11806   // will be first element in the array, which may require several levels
11807   // of array-subscript entities.
11808   SmallVector<InitializedEntity, 4> Entities;
11809   Entities.reserve(1 + IndexVariables.size());
11810   Entities.push_back(
11811     InitializedEntity::InitializeLambdaCapture(Var->getIdentifier(),
11812         Field->getType(), Loc));
11813   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
11814     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
11815                                                             0,
11816                                                             Entities.back()));
11817 
11818   InitializationKind InitKind
11819     = InitializationKind::CreateDirect(Loc, Loc, Loc);
11820   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
11821   ExprResult Result(true);
11822   if (!Init.Diagnose(S, Entities.back(), InitKind, Ref))
11823     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
11824 
11825   // If this initialization requires any cleanups (e.g., due to a
11826   // default argument to a copy constructor), note that for the
11827   // lambda.
11828   if (S.ExprNeedsCleanups)
11829     LSI->ExprNeedsCleanups = true;
11830 
11831   // Exit the expression evaluation context used for the capture.
11832   S.CleanupVarDeclMarking();
11833   S.DiscardCleanupsInEvaluationContext();
11834   return Result;
11835 }
11836 
11837 
11838 
11839 /// \brief Capture the given variable in the lambda.
11840 static bool captureInLambda(LambdaScopeInfo *LSI,
11841                             VarDecl *Var,
11842                             SourceLocation Loc,
11843                             const bool BuildAndDiagnose,
11844                             QualType &CaptureType,
11845                             QualType &DeclRefType,
11846                             const bool RefersToEnclosingLocal,
11847                             const Sema::TryCaptureKind Kind,
11848                             SourceLocation EllipsisLoc,
11849                             const bool IsTopScope,
11850                             Sema &S) {
11851 
11852   // Determine whether we are capturing by reference or by value.
11853   bool ByRef = false;
11854   if (IsTopScope && Kind != Sema::TryCapture_Implicit) {
11855     ByRef = (Kind == Sema::TryCapture_ExplicitByRef);
11856   } else {
11857     ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11858   }
11859 
11860   // Compute the type of the field that will capture this variable.
11861   if (ByRef) {
11862     // C++11 [expr.prim.lambda]p15:
11863     //   An entity is captured by reference if it is implicitly or
11864     //   explicitly captured but not captured by copy. It is
11865     //   unspecified whether additional unnamed non-static data
11866     //   members are declared in the closure type for entities
11867     //   captured by reference.
11868     //
11869     // FIXME: It is not clear whether we want to build an lvalue reference
11870     // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11871     // to do the former, while EDG does the latter. Core issue 1249 will
11872     // clarify, but for now we follow GCC because it's a more permissive and
11873     // easily defensible position.
11874     CaptureType = S.Context.getLValueReferenceType(DeclRefType);
11875   } else {
11876     // C++11 [expr.prim.lambda]p14:
11877     //   For each entity captured by copy, an unnamed non-static
11878     //   data member is declared in the closure type. The
11879     //   declaration order of these members is unspecified. The type
11880     //   of such a data member is the type of the corresponding
11881     //   captured entity if the entity is not a reference to an
11882     //   object, or the referenced type otherwise. [Note: If the
11883     //   captured entity is a reference to a function, the
11884     //   corresponding data member is also a reference to a
11885     //   function. - end note ]
11886     if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11887       if (!RefType->getPointeeType()->isFunctionType())
11888         CaptureType = RefType->getPointeeType();
11889     }
11890 
11891     // Forbid the lambda copy-capture of autoreleasing variables.
11892     if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11893       if (BuildAndDiagnose) {
11894         S.Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11895         S.Diag(Var->getLocation(), diag::note_previous_decl)
11896           << Var->getDeclName();
11897       }
11898       return false;
11899     }
11900 
11901     // Make sure that by-copy captures are of a complete and non-abstract type.
11902     if (BuildAndDiagnose) {
11903       if (!CaptureType->isDependentType() &&
11904           S.RequireCompleteType(Loc, CaptureType,
11905                                 diag::err_capture_of_incomplete_type,
11906                                 Var->getDeclName()))
11907         return false;
11908 
11909       if (S.RequireNonAbstractType(Loc, CaptureType,
11910                                    diag::err_capture_of_abstract_type))
11911         return false;
11912     }
11913   }
11914 
11915   // Capture this variable in the lambda.
11916   Expr *CopyExpr = 0;
11917   if (BuildAndDiagnose) {
11918     ExprResult Result = addAsFieldToClosureType(S, LSI, Var,
11919                                         CaptureType, DeclRefType, Loc,
11920                                         RefersToEnclosingLocal);
11921     if (!Result.isInvalid())
11922       CopyExpr = Result.take();
11923   }
11924 
11925   // Compute the type of a reference to this captured variable.
11926   if (ByRef)
11927     DeclRefType = CaptureType.getNonReferenceType();
11928   else {
11929     // C++ [expr.prim.lambda]p5:
11930     //   The closure type for a lambda-expression has a public inline
11931     //   function call operator [...]. This function call operator is
11932     //   declared const (9.3.1) if and only if the lambda-expression’s
11933     //   parameter-declaration-clause is not followed by mutable.
11934     DeclRefType = CaptureType.getNonReferenceType();
11935     if (!LSI->Mutable && !CaptureType->isReferenceType())
11936       DeclRefType.addConst();
11937   }
11938 
11939   // Add the capture.
11940   if (BuildAndDiagnose)
11941     LSI->addCapture(Var, /*IsBlock=*/false, ByRef, RefersToEnclosingLocal,
11942                     Loc, EllipsisLoc, CaptureType, CopyExpr);
11943 
11944   return true;
11945 }
11946 
11947 
11948 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation ExprLoc,
11949                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
11950                               bool BuildAndDiagnose,
11951                               QualType &CaptureType,
11952                               QualType &DeclRefType,
11953 						                const unsigned *const FunctionScopeIndexToStopAt) {
11954   bool Nested = false;
11955 
11956   DeclContext *DC = CurContext;
11957   const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
11958       ? *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
11959   // We need to sync up the Declaration Context with the
11960   // FunctionScopeIndexToStopAt
11961   if (FunctionScopeIndexToStopAt) {
11962     unsigned FSIndex = FunctionScopes.size() - 1;
11963     while (FSIndex != MaxFunctionScopesIndex) {
11964       DC = getLambdaAwareParentOfDeclContext(DC);
11965       --FSIndex;
11966     }
11967   }
11968 
11969 
11970   // If the variable is declared in the current context (and is not an
11971   // init-capture), there is no need to capture it.
11972   if (!Var->isInitCapture() && Var->getDeclContext() == DC) return true;
11973   if (!Var->hasLocalStorage()) return true;
11974 
11975   // Walk up the stack to determine whether we can capture the variable,
11976   // performing the "simple" checks that don't depend on type. We stop when
11977   // we've either hit the declared scope of the variable or find an existing
11978   // capture of that variable.  We start from the innermost capturing-entity
11979   // (the DC) and ensure that all intervening capturing-entities
11980   // (blocks/lambdas etc.) between the innermost capturer and the variable`s
11981   // declcontext can either capture the variable or have already captured
11982   // the variable.
11983   CaptureType = Var->getType();
11984   DeclRefType = CaptureType.getNonReferenceType();
11985   bool Explicit = (Kind != TryCapture_Implicit);
11986   unsigned FunctionScopesIndex = MaxFunctionScopesIndex;
11987   do {
11988     // Only block literals, captured statements, and lambda expressions can
11989     // capture; other scopes don't work.
11990     DeclContext *ParentDC = getParentOfCapturingContextOrNull(DC, Var,
11991                                                               ExprLoc,
11992                                                               BuildAndDiagnose,
11993                                                               *this);
11994     if (!ParentDC) return true;
11995 
11996     FunctionScopeInfo  *FSI = FunctionScopes[FunctionScopesIndex];
11997     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FSI);
11998 
11999 
12000     // Check whether we've already captured it.
12001     if (isVariableAlreadyCapturedInScopeInfo(CSI, Var, Nested, CaptureType,
12002                                              DeclRefType))
12003       break;
12004     // If we are instantiating a generic lambda call operator body,
12005     // we do not want to capture new variables.  What was captured
12006     // during either a lambdas transformation or initial parsing
12007     // should be used.
12008     if (isGenericLambdaCallOperatorSpecialization(DC)) {
12009       if (BuildAndDiagnose) {
12010         LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12011         if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None) {
12012           Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12013           Diag(Var->getLocation(), diag::note_previous_decl)
12014              << Var->getDeclName();
12015           Diag(LSI->Lambda->getLocStart(), diag::note_lambda_decl);
12016         } else
12017           diagnoseUncapturableValueReference(*this, ExprLoc, Var, DC);
12018       }
12019       return true;
12020     }
12021     // Certain capturing entities (lambdas, blocks etc.) are not allowed to capture
12022     // certain types of variables (unnamed, variably modified types etc.)
12023     // so check for eligibility.
12024     if (!isVariableCapturable(CSI, Var, ExprLoc, BuildAndDiagnose, *this))
12025        return true;
12026 
12027     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
12028       // No capture-default, and this is not an explicit capture
12029       // so cannot capture this variable.
12030       if (BuildAndDiagnose) {
12031         Diag(ExprLoc, diag::err_lambda_impcap) << Var->getDeclName();
12032         Diag(Var->getLocation(), diag::note_previous_decl)
12033           << Var->getDeclName();
12034         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
12035              diag::note_lambda_decl);
12036         // FIXME: If we error out because an outer lambda can not implicitly
12037         // capture a variable that an inner lambda explicitly captures, we
12038         // should have the inner lambda do the explicit capture - because
12039         // it makes for cleaner diagnostics later.  This would purely be done
12040         // so that the diagnostic does not misleadingly claim that a variable
12041         // can not be captured by a lambda implicitly even though it is captured
12042         // explicitly.  Suggestion:
12043         //  - create const bool VariableCaptureWasInitiallyExplicit = Explicit
12044         //    at the function head
12045         //  - cache the StartingDeclContext - this must be a lambda
12046         //  - captureInLambda in the innermost lambda the variable.
12047       }
12048       return true;
12049     }
12050 
12051     FunctionScopesIndex--;
12052     DC = ParentDC;
12053     Explicit = false;
12054   } while (!Var->getDeclContext()->Equals(DC));
12055 
12056   // Walk back down the scope stack, (e.g. from outer lambda to inner lambda)
12057   // computing the type of the capture at each step, checking type-specific
12058   // requirements, and adding captures if requested.
12059   // If the variable had already been captured previously, we start capturing
12060   // at the lambda nested within that one.
12061   for (unsigned I = ++FunctionScopesIndex, N = MaxFunctionScopesIndex + 1; I != N;
12062        ++I) {
12063     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
12064 
12065     if (BlockScopeInfo *BSI = dyn_cast<BlockScopeInfo>(CSI)) {
12066       if (!captureInBlock(BSI, Var, ExprLoc,
12067                           BuildAndDiagnose, CaptureType,
12068                           DeclRefType, Nested, *this))
12069         return true;
12070       Nested = true;
12071     } else if (CapturedRegionScopeInfo *RSI = dyn_cast<CapturedRegionScopeInfo>(CSI)) {
12072       if (!captureInCapturedRegion(RSI, Var, ExprLoc,
12073                                    BuildAndDiagnose, CaptureType,
12074                                    DeclRefType, Nested, *this))
12075         return true;
12076       Nested = true;
12077     } else {
12078       LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
12079       if (!captureInLambda(LSI, Var, ExprLoc,
12080                            BuildAndDiagnose, CaptureType,
12081                            DeclRefType, Nested, Kind, EllipsisLoc,
12082                             /*IsTopScope*/I == N - 1, *this))
12083         return true;
12084       Nested = true;
12085     }
12086   }
12087   return false;
12088 }
12089 
12090 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
12091                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {
12092   QualType CaptureType;
12093   QualType DeclRefType;
12094   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
12095                             /*BuildAndDiagnose=*/true, CaptureType,
12096                             DeclRefType, 0);
12097 }
12098 
12099 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
12100   QualType CaptureType;
12101   QualType DeclRefType;
12102 
12103   // Determine whether we can capture this variable.
12104   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
12105                          /*BuildAndDiagnose=*/false, CaptureType,
12106                          DeclRefType, 0))
12107     return QualType();
12108 
12109   return DeclRefType;
12110 }
12111 
12112 
12113 
12114 // If either the type of the variable or the initializer is dependent,
12115 // return false. Otherwise, determine whether the variable is a constant
12116 // expression. Use this if you need to know if a variable that might or
12117 // might not be dependent is truly a constant expression.
12118 static inline bool IsVariableNonDependentAndAConstantExpression(VarDecl *Var,
12119     ASTContext &Context) {
12120 
12121   if (Var->getType()->isDependentType())
12122     return false;
12123   const VarDecl *DefVD = 0;
12124   Var->getAnyInitializer(DefVD);
12125   if (!DefVD)
12126     return false;
12127   EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
12128   Expr *Init = cast<Expr>(Eval->Value);
12129   if (Init->isValueDependent())
12130     return false;
12131   return IsVariableAConstantExpression(Var, Context);
12132 }
12133 
12134 
12135 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
12136   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
12137   // an object that satisfies the requirements for appearing in a
12138   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
12139   // is immediately applied."  This function handles the lvalue-to-rvalue
12140   // conversion part.
12141   MaybeODRUseExprs.erase(E->IgnoreParens());
12142 
12143   // If we are in a lambda, check if this DeclRefExpr or MemberExpr refers
12144   // to a variable that is a constant expression, and if so, identify it as
12145   // a reference to a variable that does not involve an odr-use of that
12146   // variable.
12147   if (LambdaScopeInfo *LSI = getCurLambda()) {
12148     Expr *SansParensExpr = E->IgnoreParens();
12149     VarDecl *Var = 0;
12150     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(SansParensExpr))
12151       Var = dyn_cast<VarDecl>(DRE->getFoundDecl());
12152     else if (MemberExpr *ME = dyn_cast<MemberExpr>(SansParensExpr))
12153       Var = dyn_cast<VarDecl>(ME->getMemberDecl());
12154 
12155     if (Var && IsVariableNonDependentAndAConstantExpression(Var, Context))
12156       LSI->markVariableExprAsNonODRUsed(SansParensExpr);
12157   }
12158 }
12159 
12160 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
12161   if (!Res.isUsable())
12162     return Res;
12163 
12164   // If a constant-expression is a reference to a variable where we delay
12165   // deciding whether it is an odr-use, just assume we will apply the
12166   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
12167   // (a non-type template argument), we have special handling anyway.
12168   UpdateMarkingForLValueToRValue(Res.get());
12169   return Res;
12170 }
12171 
12172 void Sema::CleanupVarDeclMarking() {
12173   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
12174                                         e = MaybeODRUseExprs.end();
12175        i != e; ++i) {
12176     VarDecl *Var;
12177     SourceLocation Loc;
12178     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
12179       Var = cast<VarDecl>(DRE->getDecl());
12180       Loc = DRE->getLocation();
12181     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
12182       Var = cast<VarDecl>(ME->getMemberDecl());
12183       Loc = ME->getMemberLoc();
12184     } else {
12185       llvm_unreachable("Unexpcted expression");
12186     }
12187 
12188     MarkVarDeclODRUsed(Var, Loc, *this, /*MaxFunctionScopeIndex Pointer*/ 0);
12189   }
12190 
12191   MaybeODRUseExprs.clear();
12192 }
12193 
12194 
12195 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
12196                                     VarDecl *Var, Expr *E) {
12197   assert((!E || isa<DeclRefExpr>(E) || isa<MemberExpr>(E)) &&
12198          "Invalid Expr argument to DoMarkVarDeclReferenced");
12199   Var->setReferenced();
12200 
12201   // If the context is not potentially evaluated, this is not an odr-use and
12202   // does not trigger instantiation.
12203   if (!IsPotentiallyEvaluatedContext(SemaRef)) {
12204     if (SemaRef.isUnevaluatedContext())
12205       return;
12206 
12207     // If we don't yet know whether this context is going to end up being an
12208     // evaluated context, and we're referencing a variable from an enclosing
12209     // scope, add a potential capture.
12210     //
12211     // FIXME: Is this necessary? These contexts are only used for default
12212     // arguments, where local variables can't be used.
12213     const bool RefersToEnclosingScope =
12214         (SemaRef.CurContext != Var->getDeclContext() &&
12215          Var->getDeclContext()->isFunctionOrMethod() &&
12216          Var->hasLocalStorage());
12217     if (!RefersToEnclosingScope)
12218       return;
12219 
12220     if (LambdaScopeInfo *const LSI = SemaRef.getCurLambda()) {
12221       // If a variable could potentially be odr-used, defer marking it so
12222       // until we finish analyzing the full expression for any lvalue-to-rvalue
12223       // or discarded value conversions that would obviate odr-use.
12224       // Add it to the list of potential captures that will be analyzed
12225       // later (ActOnFinishFullExpr) for eventual capture and odr-use marking
12226       // unless the variable is a reference that was initialized by a constant
12227       // expression (this will never need to be captured or odr-used).
12228       assert(E && "Capture variable should be used in an expression.");
12229       if (!Var->getType()->isReferenceType() ||
12230           !IsVariableNonDependentAndAConstantExpression(Var, SemaRef.Context))
12231         LSI->addPotentialCapture(E->IgnoreParens());
12232     }
12233     return;
12234   }
12235 
12236   VarTemplateSpecializationDecl *VarSpec =
12237       dyn_cast<VarTemplateSpecializationDecl>(Var);
12238   assert(!isa<VarTemplatePartialSpecializationDecl>(Var) &&
12239          "Can't instantiate a partial template specialization.");
12240 
12241   // Perform implicit instantiation of static data members, static data member
12242   // templates of class templates, and variable template specializations. Delay
12243   // instantiations of variable templates, except for those that could be used
12244   // in a constant expression.
12245   TemplateSpecializationKind TSK = Var->getTemplateSpecializationKind();
12246   if (isTemplateInstantiation(TSK)) {
12247     bool TryInstantiating = TSK == TSK_ImplicitInstantiation;
12248 
12249     if (TryInstantiating && !isa<VarTemplateSpecializationDecl>(Var)) {
12250       if (Var->getPointOfInstantiation().isInvalid()) {
12251         // This is a modification of an existing AST node. Notify listeners.
12252         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
12253           L->StaticDataMemberInstantiated(Var);
12254       } else if (!Var->isUsableInConstantExpressions(SemaRef.Context))
12255         // Don't bother trying to instantiate it again, unless we might need
12256         // its initializer before we get to the end of the TU.
12257         TryInstantiating = false;
12258     }
12259 
12260     if (Var->getPointOfInstantiation().isInvalid())
12261       Var->setTemplateSpecializationKind(TSK, Loc);
12262 
12263     if (TryInstantiating) {
12264       SourceLocation PointOfInstantiation = Var->getPointOfInstantiation();
12265       bool InstantiationDependent = false;
12266       bool IsNonDependent =
12267           VarSpec ? !TemplateSpecializationType::anyDependentTemplateArguments(
12268                         VarSpec->getTemplateArgsInfo(), InstantiationDependent)
12269                   : true;
12270 
12271       // Do not instantiate specializations that are still type-dependent.
12272       if (IsNonDependent) {
12273         if (Var->isUsableInConstantExpressions(SemaRef.Context)) {
12274           // Do not defer instantiations of variables which could be used in a
12275           // constant expression.
12276           SemaRef.InstantiateVariableDefinition(PointOfInstantiation, Var);
12277         } else {
12278           SemaRef.PendingInstantiations
12279               .push_back(std::make_pair(Var, PointOfInstantiation));
12280         }
12281       }
12282     }
12283   }
12284 
12285   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
12286   // the requirements for appearing in a constant expression (5.19) and, if
12287   // it is an object, the lvalue-to-rvalue conversion (4.1)
12288   // is immediately applied."  We check the first part here, and
12289   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
12290   // Note that we use the C++11 definition everywhere because nothing in
12291   // C++03 depends on whether we get the C++03 version correct. The second
12292   // part does not apply to references, since they are not objects.
12293   if (E && IsVariableAConstantExpression(Var, SemaRef.Context)) {
12294     // A reference initialized by a constant expression can never be
12295     // odr-used, so simply ignore it.
12296     if (!Var->getType()->isReferenceType())
12297       SemaRef.MaybeODRUseExprs.insert(E);
12298   } else
12299     MarkVarDeclODRUsed(Var, Loc, SemaRef, /*MaxFunctionScopeIndex ptr*/0);
12300 }
12301 
12302 /// \brief Mark a variable referenced, and check whether it is odr-used
12303 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
12304 /// used directly for normal expressions referring to VarDecl.
12305 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
12306   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
12307 }
12308 
12309 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
12310                                Decl *D, Expr *E, bool OdrUse) {
12311   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
12312     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
12313     return;
12314   }
12315 
12316   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
12317 
12318   // If this is a call to a method via a cast, also mark the method in the
12319   // derived class used in case codegen can devirtualize the call.
12320   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
12321   if (!ME)
12322     return;
12323   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
12324   if (!MD)
12325     return;
12326   const Expr *Base = ME->getBase();
12327   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
12328   if (!MostDerivedClassDecl)
12329     return;
12330   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
12331   if (!DM || DM->isPure())
12332     return;
12333   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
12334 }
12335 
12336 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
12337 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
12338   // TODO: update this with DR# once a defect report is filed.
12339   // C++11 defect. The address of a pure member should not be an ODR use, even
12340   // if it's a qualified reference.
12341   bool OdrUse = true;
12342   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
12343     if (Method->isVirtual())
12344       OdrUse = false;
12345   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
12346 }
12347 
12348 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
12349 void Sema::MarkMemberReferenced(MemberExpr *E) {
12350   // C++11 [basic.def.odr]p2:
12351   //   A non-overloaded function whose name appears as a potentially-evaluated
12352   //   expression or a member of a set of candidate functions, if selected by
12353   //   overload resolution when referred to from a potentially-evaluated
12354   //   expression, is odr-used, unless it is a pure virtual function and its
12355   //   name is not explicitly qualified.
12356   bool OdrUse = true;
12357   if (!E->hasQualifier()) {
12358     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
12359       if (Method->isPure())
12360         OdrUse = false;
12361   }
12362   SourceLocation Loc = E->getMemberLoc().isValid() ?
12363                             E->getMemberLoc() : E->getLocStart();
12364   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
12365 }
12366 
12367 /// \brief Perform marking for a reference to an arbitrary declaration.  It
12368 /// marks the declaration referenced, and performs odr-use checking for functions
12369 /// and variables. This method should not be used when building an normal
12370 /// expression which refers to a variable.
12371 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
12372   if (OdrUse) {
12373     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12374       MarkVariableReferenced(Loc, VD);
12375       return;
12376     }
12377     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12378       MarkFunctionReferenced(Loc, FD);
12379       return;
12380     }
12381   }
12382   D->setReferenced();
12383 }
12384 
12385 namespace {
12386   // Mark all of the declarations referenced
12387   // FIXME: Not fully implemented yet! We need to have a better understanding
12388   // of when we're entering
12389   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
12390     Sema &S;
12391     SourceLocation Loc;
12392 
12393   public:
12394     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
12395 
12396     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
12397 
12398     bool TraverseTemplateArgument(const TemplateArgument &Arg);
12399     bool TraverseRecordType(RecordType *T);
12400   };
12401 }
12402 
12403 bool MarkReferencedDecls::TraverseTemplateArgument(
12404   const TemplateArgument &Arg) {
12405   if (Arg.getKind() == TemplateArgument::Declaration) {
12406     if (Decl *D = Arg.getAsDecl())
12407       S.MarkAnyDeclReferenced(Loc, D, true);
12408   }
12409 
12410   return Inherited::TraverseTemplateArgument(Arg);
12411 }
12412 
12413 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
12414   if (ClassTemplateSpecializationDecl *Spec
12415                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
12416     const TemplateArgumentList &Args = Spec->getTemplateArgs();
12417     return TraverseTemplateArguments(Args.data(), Args.size());
12418   }
12419 
12420   return true;
12421 }
12422 
12423 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
12424   MarkReferencedDecls Marker(*this, Loc);
12425   Marker.TraverseType(Context.getCanonicalType(T));
12426 }
12427 
12428 namespace {
12429   /// \brief Helper class that marks all of the declarations referenced by
12430   /// potentially-evaluated subexpressions as "referenced".
12431   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
12432     Sema &S;
12433     bool SkipLocalVariables;
12434 
12435   public:
12436     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
12437 
12438     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
12439       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
12440 
12441     void VisitDeclRefExpr(DeclRefExpr *E) {
12442       // If we were asked not to visit local variables, don't.
12443       if (SkipLocalVariables) {
12444         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
12445           if (VD->hasLocalStorage())
12446             return;
12447       }
12448 
12449       S.MarkDeclRefReferenced(E);
12450     }
12451 
12452     void VisitMemberExpr(MemberExpr *E) {
12453       S.MarkMemberReferenced(E);
12454       Inherited::VisitMemberExpr(E);
12455     }
12456 
12457     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
12458       S.MarkFunctionReferenced(E->getLocStart(),
12459             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
12460       Visit(E->getSubExpr());
12461     }
12462 
12463     void VisitCXXNewExpr(CXXNewExpr *E) {
12464       if (E->getOperatorNew())
12465         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
12466       if (E->getOperatorDelete())
12467         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12468       Inherited::VisitCXXNewExpr(E);
12469     }
12470 
12471     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
12472       if (E->getOperatorDelete())
12473         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
12474       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
12475       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12476         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12477         S.MarkFunctionReferenced(E->getLocStart(),
12478                                     S.LookupDestructor(Record));
12479       }
12480 
12481       Inherited::VisitCXXDeleteExpr(E);
12482     }
12483 
12484     void VisitCXXConstructExpr(CXXConstructExpr *E) {
12485       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
12486       Inherited::VisitCXXConstructExpr(E);
12487     }
12488 
12489     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12490       Visit(E->getExpr());
12491     }
12492 
12493     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
12494       Inherited::VisitImplicitCastExpr(E);
12495 
12496       if (E->getCastKind() == CK_LValueToRValue)
12497         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
12498     }
12499   };
12500 }
12501 
12502 /// \brief Mark any declarations that appear within this expression or any
12503 /// potentially-evaluated subexpressions as "referenced".
12504 ///
12505 /// \param SkipLocalVariables If true, don't mark local variables as
12506 /// 'referenced'.
12507 void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
12508                                             bool SkipLocalVariables) {
12509   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
12510 }
12511 
12512 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
12513 /// of the program being compiled.
12514 ///
12515 /// This routine emits the given diagnostic when the code currently being
12516 /// type-checked is "potentially evaluated", meaning that there is a
12517 /// possibility that the code will actually be executable. Code in sizeof()
12518 /// expressions, code used only during overload resolution, etc., are not
12519 /// potentially evaluated. This routine will suppress such diagnostics or,
12520 /// in the absolutely nutty case of potentially potentially evaluated
12521 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
12522 /// later.
12523 ///
12524 /// This routine should be used for all diagnostics that describe the run-time
12525 /// behavior of a program, such as passing a non-POD value through an ellipsis.
12526 /// Failure to do so will likely result in spurious diagnostics or failures
12527 /// during overload resolution or within sizeof/alignof/typeof/typeid.
12528 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
12529                                const PartialDiagnostic &PD) {
12530   switch (ExprEvalContexts.back().Context) {
12531   case Unevaluated:
12532   case UnevaluatedAbstract:
12533     // The argument will never be evaluated, so don't complain.
12534     break;
12535 
12536   case ConstantEvaluated:
12537     // Relevant diagnostics should be produced by constant evaluation.
12538     break;
12539 
12540   case PotentiallyEvaluated:
12541   case PotentiallyEvaluatedIfUsed:
12542     if (Statement && getCurFunctionOrMethodDecl()) {
12543       FunctionScopes.back()->PossiblyUnreachableDiags.
12544         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
12545     }
12546     else
12547       Diag(Loc, PD);
12548 
12549     return true;
12550   }
12551 
12552   return false;
12553 }
12554 
12555 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
12556                                CallExpr *CE, FunctionDecl *FD) {
12557   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
12558     return false;
12559 
12560   // If we're inside a decltype's expression, don't check for a valid return
12561   // type or construct temporaries until we know whether this is the last call.
12562   if (ExprEvalContexts.back().IsDecltype) {
12563     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
12564     return false;
12565   }
12566 
12567   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
12568     FunctionDecl *FD;
12569     CallExpr *CE;
12570 
12571   public:
12572     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
12573       : FD(FD), CE(CE) { }
12574 
12575     void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
12576       if (!FD) {
12577         S.Diag(Loc, diag::err_call_incomplete_return)
12578           << T << CE->getSourceRange();
12579         return;
12580       }
12581 
12582       S.Diag(Loc, diag::err_call_function_incomplete_return)
12583         << CE->getSourceRange() << FD->getDeclName() << T;
12584       S.Diag(FD->getLocation(),
12585              diag::note_function_with_incomplete_return_type_declared_here)
12586         << FD->getDeclName();
12587     }
12588   } Diagnoser(FD, CE);
12589 
12590   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
12591     return true;
12592 
12593   return false;
12594 }
12595 
12596 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
12597 // will prevent this condition from triggering, which is what we want.
12598 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
12599   SourceLocation Loc;
12600 
12601   unsigned diagnostic = diag::warn_condition_is_assignment;
12602   bool IsOrAssign = false;
12603 
12604   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
12605     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
12606       return;
12607 
12608     IsOrAssign = Op->getOpcode() == BO_OrAssign;
12609 
12610     // Greylist some idioms by putting them into a warning subcategory.
12611     if (ObjCMessageExpr *ME
12612           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
12613       Selector Sel = ME->getSelector();
12614 
12615       // self = [<foo> init...]
12616       if (isSelfExpr(Op->getLHS()) && ME->getMethodFamily() == OMF_init)
12617         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12618 
12619       // <foo> = [<bar> nextObject]
12620       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
12621         diagnostic = diag::warn_condition_is_idiomatic_assignment;
12622     }
12623 
12624     Loc = Op->getOperatorLoc();
12625   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
12626     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
12627       return;
12628 
12629     IsOrAssign = Op->getOperator() == OO_PipeEqual;
12630     Loc = Op->getOperatorLoc();
12631   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
12632     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
12633   else {
12634     // Not an assignment.
12635     return;
12636   }
12637 
12638   Diag(Loc, diagnostic) << E->getSourceRange();
12639 
12640   SourceLocation Open = E->getLocStart();
12641   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
12642   Diag(Loc, diag::note_condition_assign_silence)
12643         << FixItHint::CreateInsertion(Open, "(")
12644         << FixItHint::CreateInsertion(Close, ")");
12645 
12646   if (IsOrAssign)
12647     Diag(Loc, diag::note_condition_or_assign_to_comparison)
12648       << FixItHint::CreateReplacement(Loc, "!=");
12649   else
12650     Diag(Loc, diag::note_condition_assign_to_comparison)
12651       << FixItHint::CreateReplacement(Loc, "==");
12652 }
12653 
12654 /// \brief Redundant parentheses over an equality comparison can indicate
12655 /// that the user intended an assignment used as condition.
12656 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
12657   // Don't warn if the parens came from a macro.
12658   SourceLocation parenLoc = ParenE->getLocStart();
12659   if (parenLoc.isInvalid() || parenLoc.isMacroID())
12660     return;
12661   // Don't warn for dependent expressions.
12662   if (ParenE->isTypeDependent())
12663     return;
12664 
12665   Expr *E = ParenE->IgnoreParens();
12666 
12667   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
12668     if (opE->getOpcode() == BO_EQ &&
12669         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
12670                                                            == Expr::MLV_Valid) {
12671       SourceLocation Loc = opE->getOperatorLoc();
12672 
12673       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
12674       SourceRange ParenERange = ParenE->getSourceRange();
12675       Diag(Loc, diag::note_equality_comparison_silence)
12676         << FixItHint::CreateRemoval(ParenERange.getBegin())
12677         << FixItHint::CreateRemoval(ParenERange.getEnd());
12678       Diag(Loc, diag::note_equality_comparison_to_assign)
12679         << FixItHint::CreateReplacement(Loc, "=");
12680     }
12681 }
12682 
12683 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
12684   DiagnoseAssignmentAsCondition(E);
12685   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
12686     DiagnoseEqualityWithExtraParens(parenE);
12687 
12688   ExprResult result = CheckPlaceholderExpr(E);
12689   if (result.isInvalid()) return ExprError();
12690   E = result.take();
12691 
12692   if (!E->isTypeDependent()) {
12693     if (getLangOpts().CPlusPlus)
12694       return CheckCXXBooleanCondition(E); // C++ 6.4p4
12695 
12696     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
12697     if (ERes.isInvalid())
12698       return ExprError();
12699     E = ERes.take();
12700 
12701     QualType T = E->getType();
12702     if (!T->isScalarType()) { // C99 6.8.4.1p1
12703       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
12704         << T << E->getSourceRange();
12705       return ExprError();
12706     }
12707   }
12708 
12709   return Owned(E);
12710 }
12711 
12712 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
12713                                        Expr *SubExpr) {
12714   if (!SubExpr)
12715     return ExprError();
12716 
12717   return CheckBooleanCondition(SubExpr, Loc);
12718 }
12719 
12720 namespace {
12721   /// A visitor for rebuilding a call to an __unknown_any expression
12722   /// to have an appropriate type.
12723   struct RebuildUnknownAnyFunction
12724     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
12725 
12726     Sema &S;
12727 
12728     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
12729 
12730     ExprResult VisitStmt(Stmt *S) {
12731       llvm_unreachable("unexpected statement!");
12732     }
12733 
12734     ExprResult VisitExpr(Expr *E) {
12735       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
12736         << E->getSourceRange();
12737       return ExprError();
12738     }
12739 
12740     /// Rebuild an expression which simply semantically wraps another
12741     /// expression which it shares the type and value kind of.
12742     template <class T> ExprResult rebuildSugarExpr(T *E) {
12743       ExprResult SubResult = Visit(E->getSubExpr());
12744       if (SubResult.isInvalid()) return ExprError();
12745 
12746       Expr *SubExpr = SubResult.take();
12747       E->setSubExpr(SubExpr);
12748       E->setType(SubExpr->getType());
12749       E->setValueKind(SubExpr->getValueKind());
12750       assert(E->getObjectKind() == OK_Ordinary);
12751       return E;
12752     }
12753 
12754     ExprResult VisitParenExpr(ParenExpr *E) {
12755       return rebuildSugarExpr(E);
12756     }
12757 
12758     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12759       return rebuildSugarExpr(E);
12760     }
12761 
12762     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12763       ExprResult SubResult = Visit(E->getSubExpr());
12764       if (SubResult.isInvalid()) return ExprError();
12765 
12766       Expr *SubExpr = SubResult.take();
12767       E->setSubExpr(SubExpr);
12768       E->setType(S.Context.getPointerType(SubExpr->getType()));
12769       assert(E->getValueKind() == VK_RValue);
12770       assert(E->getObjectKind() == OK_Ordinary);
12771       return E;
12772     }
12773 
12774     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
12775       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
12776 
12777       E->setType(VD->getType());
12778 
12779       assert(E->getValueKind() == VK_RValue);
12780       if (S.getLangOpts().CPlusPlus &&
12781           !(isa<CXXMethodDecl>(VD) &&
12782             cast<CXXMethodDecl>(VD)->isInstance()))
12783         E->setValueKind(VK_LValue);
12784 
12785       return E;
12786     }
12787 
12788     ExprResult VisitMemberExpr(MemberExpr *E) {
12789       return resolveDecl(E, E->getMemberDecl());
12790     }
12791 
12792     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12793       return resolveDecl(E, E->getDecl());
12794     }
12795   };
12796 }
12797 
12798 /// Given a function expression of unknown-any type, try to rebuild it
12799 /// to have a function type.
12800 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
12801   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
12802   if (Result.isInvalid()) return ExprError();
12803   return S.DefaultFunctionArrayConversion(Result.take());
12804 }
12805 
12806 namespace {
12807   /// A visitor for rebuilding an expression of type __unknown_anytype
12808   /// into one which resolves the type directly on the referring
12809   /// expression.  Strict preservation of the original source
12810   /// structure is not a goal.
12811   struct RebuildUnknownAnyExpr
12812     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
12813 
12814     Sema &S;
12815 
12816     /// The current destination type.
12817     QualType DestType;
12818 
12819     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
12820       : S(S), DestType(CastType) {}
12821 
12822     ExprResult VisitStmt(Stmt *S) {
12823       llvm_unreachable("unexpected statement!");
12824     }
12825 
12826     ExprResult VisitExpr(Expr *E) {
12827       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12828         << E->getSourceRange();
12829       return ExprError();
12830     }
12831 
12832     ExprResult VisitCallExpr(CallExpr *E);
12833     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
12834 
12835     /// Rebuild an expression which simply semantically wraps another
12836     /// expression which it shares the type and value kind of.
12837     template <class T> ExprResult rebuildSugarExpr(T *E) {
12838       ExprResult SubResult = Visit(E->getSubExpr());
12839       if (SubResult.isInvalid()) return ExprError();
12840       Expr *SubExpr = SubResult.take();
12841       E->setSubExpr(SubExpr);
12842       E->setType(SubExpr->getType());
12843       E->setValueKind(SubExpr->getValueKind());
12844       assert(E->getObjectKind() == OK_Ordinary);
12845       return E;
12846     }
12847 
12848     ExprResult VisitParenExpr(ParenExpr *E) {
12849       return rebuildSugarExpr(E);
12850     }
12851 
12852     ExprResult VisitUnaryExtension(UnaryOperator *E) {
12853       return rebuildSugarExpr(E);
12854     }
12855 
12856     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
12857       const PointerType *Ptr = DestType->getAs<PointerType>();
12858       if (!Ptr) {
12859         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
12860           << E->getSourceRange();
12861         return ExprError();
12862       }
12863       assert(E->getValueKind() == VK_RValue);
12864       assert(E->getObjectKind() == OK_Ordinary);
12865       E->setType(DestType);
12866 
12867       // Build the sub-expression as if it were an object of the pointee type.
12868       DestType = Ptr->getPointeeType();
12869       ExprResult SubResult = Visit(E->getSubExpr());
12870       if (SubResult.isInvalid()) return ExprError();
12871       E->setSubExpr(SubResult.take());
12872       return E;
12873     }
12874 
12875     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
12876 
12877     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
12878 
12879     ExprResult VisitMemberExpr(MemberExpr *E) {
12880       return resolveDecl(E, E->getMemberDecl());
12881     }
12882 
12883     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
12884       return resolveDecl(E, E->getDecl());
12885     }
12886   };
12887 }
12888 
12889 /// Rebuilds a call expression which yielded __unknown_anytype.
12890 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
12891   Expr *CalleeExpr = E->getCallee();
12892 
12893   enum FnKind {
12894     FK_MemberFunction,
12895     FK_FunctionPointer,
12896     FK_BlockPointer
12897   };
12898 
12899   FnKind Kind;
12900   QualType CalleeType = CalleeExpr->getType();
12901   if (CalleeType == S.Context.BoundMemberTy) {
12902     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
12903     Kind = FK_MemberFunction;
12904     CalleeType = Expr::findBoundMemberType(CalleeExpr);
12905   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
12906     CalleeType = Ptr->getPointeeType();
12907     Kind = FK_FunctionPointer;
12908   } else {
12909     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
12910     Kind = FK_BlockPointer;
12911   }
12912   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
12913 
12914   // Verify that this is a legal result type of a function.
12915   if (DestType->isArrayType() || DestType->isFunctionType()) {
12916     unsigned diagID = diag::err_func_returning_array_function;
12917     if (Kind == FK_BlockPointer)
12918       diagID = diag::err_block_returning_array_function;
12919 
12920     S.Diag(E->getExprLoc(), diagID)
12921       << DestType->isFunctionType() << DestType;
12922     return ExprError();
12923   }
12924 
12925   // Otherwise, go ahead and set DestType as the call's result.
12926   E->setType(DestType.getNonLValueExprType(S.Context));
12927   E->setValueKind(Expr::getValueKindForType(DestType));
12928   assert(E->getObjectKind() == OK_Ordinary);
12929 
12930   // Rebuild the function type, replacing the result type with DestType.
12931   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType);
12932   if (Proto) {
12933     // __unknown_anytype(...) is a special case used by the debugger when
12934     // it has no idea what a function's signature is.
12935     //
12936     // We want to build this call essentially under the K&R
12937     // unprototyped rules, but making a FunctionNoProtoType in C++
12938     // would foul up all sorts of assumptions.  However, we cannot
12939     // simply pass all arguments as variadic arguments, nor can we
12940     // portably just call the function under a non-variadic type; see
12941     // the comment on IR-gen's TargetInfo::isNoProtoCallVariadic.
12942     // However, it turns out that in practice it is generally safe to
12943     // call a function declared as "A foo(B,C,D);" under the prototype
12944     // "A foo(B,C,D,...);".  The only known exception is with the
12945     // Windows ABI, where any variadic function is implicitly cdecl
12946     // regardless of its normal CC.  Therefore we change the parameter
12947     // types to match the types of the arguments.
12948     //
12949     // This is a hack, but it is far superior to moving the
12950     // corresponding target-specific code from IR-gen to Sema/AST.
12951 
12952     ArrayRef<QualType> ParamTypes = Proto->getParamTypes();
12953     SmallVector<QualType, 8> ArgTypes;
12954     if (ParamTypes.empty() && Proto->isVariadic()) { // the special case
12955       ArgTypes.reserve(E->getNumArgs());
12956       for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
12957         Expr *Arg = E->getArg(i);
12958         QualType ArgType = Arg->getType();
12959         if (E->isLValue()) {
12960           ArgType = S.Context.getLValueReferenceType(ArgType);
12961         } else if (E->isXValue()) {
12962           ArgType = S.Context.getRValueReferenceType(ArgType);
12963         }
12964         ArgTypes.push_back(ArgType);
12965       }
12966       ParamTypes = ArgTypes;
12967     }
12968     DestType = S.Context.getFunctionType(DestType, ParamTypes,
12969                                          Proto->getExtProtoInfo());
12970   } else {
12971     DestType = S.Context.getFunctionNoProtoType(DestType,
12972                                                 FnType->getExtInfo());
12973   }
12974 
12975   // Rebuild the appropriate pointer-to-function type.
12976   switch (Kind) {
12977   case FK_MemberFunction:
12978     // Nothing to do.
12979     break;
12980 
12981   case FK_FunctionPointer:
12982     DestType = S.Context.getPointerType(DestType);
12983     break;
12984 
12985   case FK_BlockPointer:
12986     DestType = S.Context.getBlockPointerType(DestType);
12987     break;
12988   }
12989 
12990   // Finally, we can recurse.
12991   ExprResult CalleeResult = Visit(CalleeExpr);
12992   if (!CalleeResult.isUsable()) return ExprError();
12993   E->setCallee(CalleeResult.take());
12994 
12995   // Bind a temporary if necessary.
12996   return S.MaybeBindToTemporary(E);
12997 }
12998 
12999 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
13000   // Verify that this is a legal result type of a call.
13001   if (DestType->isArrayType() || DestType->isFunctionType()) {
13002     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
13003       << DestType->isFunctionType() << DestType;
13004     return ExprError();
13005   }
13006 
13007   // Rewrite the method result type if available.
13008   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
13009     assert(Method->getReturnType() == S.Context.UnknownAnyTy);
13010     Method->setReturnType(DestType);
13011   }
13012 
13013   // Change the type of the message.
13014   E->setType(DestType.getNonReferenceType());
13015   E->setValueKind(Expr::getValueKindForType(DestType));
13016 
13017   return S.MaybeBindToTemporary(E);
13018 }
13019 
13020 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
13021   // The only case we should ever see here is a function-to-pointer decay.
13022   if (E->getCastKind() == CK_FunctionToPointerDecay) {
13023     assert(E->getValueKind() == VK_RValue);
13024     assert(E->getObjectKind() == OK_Ordinary);
13025 
13026     E->setType(DestType);
13027 
13028     // Rebuild the sub-expression as the pointee (function) type.
13029     DestType = DestType->castAs<PointerType>()->getPointeeType();
13030 
13031     ExprResult Result = Visit(E->getSubExpr());
13032     if (!Result.isUsable()) return ExprError();
13033 
13034     E->setSubExpr(Result.take());
13035     return S.Owned(E);
13036   } else if (E->getCastKind() == CK_LValueToRValue) {
13037     assert(E->getValueKind() == VK_RValue);
13038     assert(E->getObjectKind() == OK_Ordinary);
13039 
13040     assert(isa<BlockPointerType>(E->getType()));
13041 
13042     E->setType(DestType);
13043 
13044     // The sub-expression has to be a lvalue reference, so rebuild it as such.
13045     DestType = S.Context.getLValueReferenceType(DestType);
13046 
13047     ExprResult Result = Visit(E->getSubExpr());
13048     if (!Result.isUsable()) return ExprError();
13049 
13050     E->setSubExpr(Result.take());
13051     return S.Owned(E);
13052   } else {
13053     llvm_unreachable("Unhandled cast type!");
13054   }
13055 }
13056 
13057 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
13058   ExprValueKind ValueKind = VK_LValue;
13059   QualType Type = DestType;
13060 
13061   // We know how to make this work for certain kinds of decls:
13062 
13063   //  - functions
13064   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
13065     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
13066       DestType = Ptr->getPointeeType();
13067       ExprResult Result = resolveDecl(E, VD);
13068       if (Result.isInvalid()) return ExprError();
13069       return S.ImpCastExprToType(Result.take(), Type,
13070                                  CK_FunctionToPointerDecay, VK_RValue);
13071     }
13072 
13073     if (!Type->isFunctionType()) {
13074       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
13075         << VD << E->getSourceRange();
13076       return ExprError();
13077     }
13078 
13079     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
13080       if (MD->isInstance()) {
13081         ValueKind = VK_RValue;
13082         Type = S.Context.BoundMemberTy;
13083       }
13084 
13085     // Function references aren't l-values in C.
13086     if (!S.getLangOpts().CPlusPlus)
13087       ValueKind = VK_RValue;
13088 
13089   //  - variables
13090   } else if (isa<VarDecl>(VD)) {
13091     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
13092       Type = RefTy->getPointeeType();
13093     } else if (Type->isFunctionType()) {
13094       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
13095         << VD << E->getSourceRange();
13096       return ExprError();
13097     }
13098 
13099   //  - nothing else
13100   } else {
13101     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
13102       << VD << E->getSourceRange();
13103     return ExprError();
13104   }
13105 
13106   // Modifying the declaration like this is friendly to IR-gen but
13107   // also really dangerous.
13108   VD->setType(DestType);
13109   E->setType(Type);
13110   E->setValueKind(ValueKind);
13111   return S.Owned(E);
13112 }
13113 
13114 /// Check a cast of an unknown-any type.  We intentionally only
13115 /// trigger this for C-style casts.
13116 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
13117                                      Expr *CastExpr, CastKind &CastKind,
13118                                      ExprValueKind &VK, CXXCastPath &Path) {
13119   // Rewrite the casted expression from scratch.
13120   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
13121   if (!result.isUsable()) return ExprError();
13122 
13123   CastExpr = result.take();
13124   VK = CastExpr->getValueKind();
13125   CastKind = CK_NoOp;
13126 
13127   return CastExpr;
13128 }
13129 
13130 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
13131   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
13132 }
13133 
13134 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
13135                                     Expr *arg, QualType &paramType) {
13136   // If the syntactic form of the argument is not an explicit cast of
13137   // any sort, just do default argument promotion.
13138   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
13139   if (!castArg) {
13140     ExprResult result = DefaultArgumentPromotion(arg);
13141     if (result.isInvalid()) return ExprError();
13142     paramType = result.get()->getType();
13143     return result;
13144   }
13145 
13146   // Otherwise, use the type that was written in the explicit cast.
13147   assert(!arg->hasPlaceholderType());
13148   paramType = castArg->getTypeAsWritten();
13149 
13150   // Copy-initialize a parameter of that type.
13151   InitializedEntity entity =
13152     InitializedEntity::InitializeParameter(Context, paramType,
13153                                            /*consumed*/ false);
13154   return PerformCopyInitialization(entity, callLoc, Owned(arg));
13155 }
13156 
13157 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
13158   Expr *orig = E;
13159   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
13160   while (true) {
13161     E = E->IgnoreParenImpCasts();
13162     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
13163       E = call->getCallee();
13164       diagID = diag::err_uncasted_call_of_unknown_any;
13165     } else {
13166       break;
13167     }
13168   }
13169 
13170   SourceLocation loc;
13171   NamedDecl *d;
13172   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
13173     loc = ref->getLocation();
13174     d = ref->getDecl();
13175   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
13176     loc = mem->getMemberLoc();
13177     d = mem->getMemberDecl();
13178   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
13179     diagID = diag::err_uncasted_call_of_unknown_any;
13180     loc = msg->getSelectorStartLoc();
13181     d = msg->getMethodDecl();
13182     if (!d) {
13183       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
13184         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
13185         << orig->getSourceRange();
13186       return ExprError();
13187     }
13188   } else {
13189     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
13190       << E->getSourceRange();
13191     return ExprError();
13192   }
13193 
13194   S.Diag(loc, diagID) << d << orig->getSourceRange();
13195 
13196   // Never recoverable.
13197   return ExprError();
13198 }
13199 
13200 /// Check for operands with placeholder types and complain if found.
13201 /// Returns true if there was an error and no recovery was possible.
13202 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
13203   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
13204   if (!placeholderType) return Owned(E);
13205 
13206   switch (placeholderType->getKind()) {
13207 
13208   // Overloaded expressions.
13209   case BuiltinType::Overload: {
13210     // Try to resolve a single function template specialization.
13211     // This is obligatory.
13212     ExprResult result = Owned(E);
13213     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
13214       return result;
13215 
13216     // If that failed, try to recover with a call.
13217     } else {
13218       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
13219                            /*complain*/ true);
13220       return result;
13221     }
13222   }
13223 
13224   // Bound member functions.
13225   case BuiltinType::BoundMember: {
13226     ExprResult result = Owned(E);
13227     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
13228                          /*complain*/ true);
13229     return result;
13230   }
13231 
13232   // ARC unbridged casts.
13233   case BuiltinType::ARCUnbridgedCast: {
13234     Expr *realCast = stripARCUnbridgedCast(E);
13235     diagnoseARCUnbridgedCast(realCast);
13236     return Owned(realCast);
13237   }
13238 
13239   // Expressions of unknown type.
13240   case BuiltinType::UnknownAny:
13241     return diagnoseUnknownAnyExpr(*this, E);
13242 
13243   // Pseudo-objects.
13244   case BuiltinType::PseudoObject:
13245     return checkPseudoObjectRValue(E);
13246 
13247   case BuiltinType::BuiltinFn:
13248     Diag(E->getLocStart(), diag::err_builtin_fn_use);
13249     return ExprError();
13250 
13251   // Everything else should be impossible.
13252 #define BUILTIN_TYPE(Id, SingletonId) \
13253   case BuiltinType::Id:
13254 #define PLACEHOLDER_TYPE(Id, SingletonId)
13255 #include "clang/AST/BuiltinTypes.def"
13256     break;
13257   }
13258 
13259   llvm_unreachable("invalid placeholder type!");
13260 }
13261 
13262 bool Sema::CheckCaseExpression(Expr *E) {
13263   if (E->isTypeDependent())
13264     return true;
13265   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
13266     return E->getType()->isIntegralOrEnumerationType();
13267   return false;
13268 }
13269 
13270 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
13271 ExprResult
13272 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
13273   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
13274          "Unknown Objective-C Boolean value!");
13275   QualType BoolT = Context.ObjCBuiltinBoolTy;
13276   if (!Context.getBOOLDecl()) {
13277     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
13278                         Sema::LookupOrdinaryName);
13279     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
13280       NamedDecl *ND = Result.getFoundDecl();
13281       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND))
13282         Context.setBOOLDecl(TD);
13283     }
13284   }
13285   if (Context.getBOOLDecl())
13286     BoolT = Context.getBOOLType();
13287   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
13288                                         BoolT, OpLoc));
13289 }
13290