]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
Merge sendmail 8.14.7 to HEAD
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaExpr.cpp
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/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/EvaluatedExprVisitor.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/ExprObjC.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/LiteralSupport.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "clang/Sema/AnalysisBasedWarnings.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/DelayedDiagnostic.h"
36 #include "clang/Sema/Designator.h"
37 #include "clang/Sema/Initialization.h"
38 #include "clang/Sema/Lookup.h"
39 #include "clang/Sema/ParsedTemplate.h"
40 #include "clang/Sema/Scope.h"
41 #include "clang/Sema/ScopeInfo.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 using namespace clang;
45 using namespace sema;
46
47 /// \brief Determine whether the use of this declaration is valid, without
48 /// emitting diagnostics.
49 bool Sema::CanUseDecl(NamedDecl *D) {
50   // See if this is an auto-typed variable whose initializer we are parsing.
51   if (ParsingInitForAutoVars.count(D))
52     return false;
53
54   // See if this is a deleted function.
55   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
56     if (FD->isDeleted())
57       return false;
58   }
59
60   // See if this function is unavailable.
61   if (D->getAvailability() == AR_Unavailable &&
62       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
63     return false;
64
65   return true;
66 }
67
68 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
69   // Warn if this is used but marked unused.
70   if (D->hasAttr<UnusedAttr>()) {
71     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
72     if (!DC->hasAttr<UnusedAttr>())
73       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
74   }
75 }
76
77 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
78                               NamedDecl *D, SourceLocation Loc,
79                               const ObjCInterfaceDecl *UnknownObjCClass) {
80   // See if this declaration is unavailable or deprecated.
81   std::string Message;
82   AvailabilityResult Result = D->getAvailability(&Message);
83   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
84     if (Result == AR_Available) {
85       const DeclContext *DC = ECD->getDeclContext();
86       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
87         Result = TheEnumDecl->getAvailability(&Message);
88     }
89
90   const ObjCPropertyDecl *ObjCPDecl = 0;
91   if (Result == AR_Deprecated || Result == AR_Unavailable) {
92     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
93       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
94         AvailabilityResult PDeclResult = PD->getAvailability(0);
95         if (PDeclResult == Result)
96           ObjCPDecl = PD;
97       }
98     }
99   }
100   
101   switch (Result) {
102     case AR_Available:
103     case AR_NotYetIntroduced:
104       break;
105             
106     case AR_Deprecated:
107       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
108       break;
109             
110     case AR_Unavailable:
111       if (S.getCurContextAvailability() != AR_Unavailable) {
112         if (Message.empty()) {
113           if (!UnknownObjCClass) {
114             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
115             if (ObjCPDecl)
116               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
117                 << ObjCPDecl->getDeclName() << 1;
118           }
119           else
120             S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 
121               << D->getDeclName();
122         }
123         else
124           S.Diag(Loc, diag::err_unavailable_message) 
125             << D->getDeclName() << Message;
126         S.Diag(D->getLocation(), diag::note_unavailable_here)
127                   << isa<FunctionDecl>(D) << false;
128         if (ObjCPDecl)
129           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
130           << ObjCPDecl->getDeclName() << 1;
131       }
132       break;
133     }
134     return Result;
135 }
136
137 /// \brief Emit a note explaining that this function is deleted or unavailable.
138 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
139   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
140
141   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
142     // If the method was explicitly defaulted, point at that declaration.
143     if (!Method->isImplicit())
144       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
145
146     // Try to diagnose why this special member function was implicitly
147     // deleted. This might fail, if that reason no longer applies.
148     CXXSpecialMember CSM = getSpecialMember(Method);
149     if (CSM != CXXInvalid)
150       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
151
152     return;
153   }
154
155   Diag(Decl->getLocation(), diag::note_unavailable_here)
156     << 1 << Decl->isDeleted();
157 }
158
159 /// \brief Determine whether a FunctionDecl was ever declared with an
160 /// explicit storage class.
161 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
162   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
163                                      E = D->redecls_end();
164        I != E; ++I) {
165     if (I->getStorageClass() != SC_None)
166       return true;
167   }
168   return false;
169 }
170
171 /// \brief Check whether we're in an extern inline function and referring to a
172 /// variable or function with internal linkage (C11 6.7.4p3).
173 ///
174 /// This is only a warning because we used to silently accept this code, but
175 /// in many cases it will not behave correctly. This is not enabled in C++ mode
176 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
177 /// and so while there may still be user mistakes, most of the time we can't
178 /// prove that there are errors.
179 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
180                                                       const NamedDecl *D,
181                                                       SourceLocation Loc) {
182   // This is disabled under C++; there are too many ways for this to fire in
183   // contexts where the warning is a false positive, or where it is technically
184   // correct but benign.
185   if (S.getLangOpts().CPlusPlus)
186     return;
187
188   // Check if this is an inlined function or method.
189   FunctionDecl *Current = S.getCurFunctionDecl();
190   if (!Current)
191     return;
192   if (!Current->isInlined())
193     return;
194   if (Current->getLinkage() != ExternalLinkage)
195     return;
196   
197   // Check if the decl has internal linkage.
198   if (D->getLinkage() != InternalLinkage)
199     return;
200
201   // Downgrade from ExtWarn to Extension if
202   //  (1) the supposedly external inline function is in the main file,
203   //      and probably won't be included anywhere else.
204   //  (2) the thing we're referencing is a pure function.
205   //  (3) the thing we're referencing is another inline function.
206   // This last can give us false negatives, but it's better than warning on
207   // wrappers for simple C library functions.
208   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
209   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
210   if (!DowngradeWarning && UsedFn)
211     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
212
213   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
214                                : diag::warn_internal_in_extern_inline)
215     << /*IsVar=*/!UsedFn << D;
216
217   S.MaybeSuggestAddingStaticToDecl(Current);
218
219   S.Diag(D->getCanonicalDecl()->getLocation(),
220          diag::note_internal_decl_declared_here)
221     << D;
222 }
223
224 void Sema::MaybeSuggestAddingStaticToDecl(const FunctionDecl *Cur) {
225   const FunctionDecl *First = Cur->getFirstDeclaration();
226
227   // Suggest "static" on the function, if possible.
228   if (!hasAnyExplicitStorageClass(First)) {
229     SourceLocation DeclBegin = First->getSourceRange().getBegin();
230     Diag(DeclBegin, diag::note_convert_inline_to_static)
231       << Cur << FixItHint::CreateInsertion(DeclBegin, "static ");
232   }
233 }
234
235 /// \brief Determine whether the use of this declaration is valid, and
236 /// emit any corresponding diagnostics.
237 ///
238 /// This routine diagnoses various problems with referencing
239 /// declarations that can occur when using a declaration. For example,
240 /// it might warn if a deprecated or unavailable declaration is being
241 /// used, or produce an error (and return true) if a C++0x deleted
242 /// function is being used.
243 ///
244 /// \returns true if there was an error (this declaration cannot be
245 /// referenced), false otherwise.
246 ///
247 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
248                              const ObjCInterfaceDecl *UnknownObjCClass) {
249   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
250     // If there were any diagnostics suppressed by template argument deduction,
251     // emit them now.
252     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
253       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
254     if (Pos != SuppressedDiagnostics.end()) {
255       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
256       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
257         Diag(Suppressed[I].first, Suppressed[I].second);
258       
259       // Clear out the list of suppressed diagnostics, so that we don't emit
260       // them again for this specialization. However, we don't obsolete this
261       // entry from the table, because we want to avoid ever emitting these
262       // diagnostics again.
263       Suppressed.clear();
264     }
265   }
266
267   // See if this is an auto-typed variable whose initializer we are parsing.
268   if (ParsingInitForAutoVars.count(D)) {
269     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
270       << D->getDeclName();
271     return true;
272   }
273
274   // See if this is a deleted function.
275   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
276     if (FD->isDeleted()) {
277       Diag(Loc, diag::err_deleted_function_use);
278       NoteDeletedFunction(FD);
279       return true;
280     }
281   }
282   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
283
284   DiagnoseUnusedOfDecl(*this, D, Loc);
285
286   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
287
288   return false;
289 }
290
291 /// \brief Retrieve the message suffix that should be added to a
292 /// diagnostic complaining about the given function being deleted or
293 /// unavailable.
294 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
295   std::string Message;
296   if (FD->getAvailability(&Message))
297     return ": " + Message;
298
299   return std::string();
300 }
301
302 /// DiagnoseSentinelCalls - This routine checks whether a call or
303 /// message-send is to a declaration with the sentinel attribute, and
304 /// if so, it checks that the requirements of the sentinel are
305 /// satisfied.
306 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
307                                  Expr **args, unsigned numArgs) {
308   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
309   if (!attr)
310     return;
311
312   // The number of formal parameters of the declaration.
313   unsigned numFormalParams;
314
315   // The kind of declaration.  This is also an index into a %select in
316   // the diagnostic.
317   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
318
319   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
320     numFormalParams = MD->param_size();
321     calleeType = CT_Method;
322   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
323     numFormalParams = FD->param_size();
324     calleeType = CT_Function;
325   } else if (isa<VarDecl>(D)) {
326     QualType type = cast<ValueDecl>(D)->getType();
327     const FunctionType *fn = 0;
328     if (const PointerType *ptr = type->getAs<PointerType>()) {
329       fn = ptr->getPointeeType()->getAs<FunctionType>();
330       if (!fn) return;
331       calleeType = CT_Function;
332     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
333       fn = ptr->getPointeeType()->castAs<FunctionType>();
334       calleeType = CT_Block;
335     } else {
336       return;
337     }
338
339     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
340       numFormalParams = proto->getNumArgs();
341     } else {
342       numFormalParams = 0;
343     }
344   } else {
345     return;
346   }
347
348   // "nullPos" is the number of formal parameters at the end which
349   // effectively count as part of the variadic arguments.  This is
350   // useful if you would prefer to not have *any* formal parameters,
351   // but the language forces you to have at least one.
352   unsigned nullPos = attr->getNullPos();
353   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
354   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
355
356   // The number of arguments which should follow the sentinel.
357   unsigned numArgsAfterSentinel = attr->getSentinel();
358
359   // If there aren't enough arguments for all the formal parameters,
360   // the sentinel, and the args after the sentinel, complain.
361   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
362     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
363     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
364     return;
365   }
366
367   // Otherwise, find the sentinel expression.
368   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
369   if (!sentinelExpr) return;
370   if (sentinelExpr->isValueDependent()) return;
371   if (Context.isSentinelNullExpr(sentinelExpr)) return;
372
373   // Pick a reasonable string to insert.  Optimistically use 'nil' or
374   // 'NULL' if those are actually defined in the context.  Only use
375   // 'nil' for ObjC methods, where it's much more likely that the
376   // variadic arguments form a list of object pointers.
377   SourceLocation MissingNilLoc
378     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
379   std::string NullValue;
380   if (calleeType == CT_Method &&
381       PP.getIdentifierInfo("nil")->hasMacroDefinition())
382     NullValue = "nil";
383   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
384     NullValue = "NULL";
385   else
386     NullValue = "(void*) 0";
387
388   if (MissingNilLoc.isInvalid())
389     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
390   else
391     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
392       << calleeType
393       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
394   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
395 }
396
397 SourceRange Sema::getExprRange(Expr *E) const {
398   return E ? E->getSourceRange() : SourceRange();
399 }
400
401 //===----------------------------------------------------------------------===//
402 //  Standard Promotions and Conversions
403 //===----------------------------------------------------------------------===//
404
405 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
406 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
407   // Handle any placeholder expressions which made it here.
408   if (E->getType()->isPlaceholderType()) {
409     ExprResult result = CheckPlaceholderExpr(E);
410     if (result.isInvalid()) return ExprError();
411     E = result.take();
412   }
413   
414   QualType Ty = E->getType();
415   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
416
417   if (Ty->isFunctionType())
418     E = ImpCastExprToType(E, Context.getPointerType(Ty),
419                           CK_FunctionToPointerDecay).take();
420   else if (Ty->isArrayType()) {
421     // In C90 mode, arrays only promote to pointers if the array expression is
422     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
423     // type 'array of type' is converted to an expression that has type 'pointer
424     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
425     // that has type 'array of type' ...".  The relevant change is "an lvalue"
426     // (C90) to "an expression" (C99).
427     //
428     // C++ 4.2p1:
429     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
430     // T" can be converted to an rvalue of type "pointer to T".
431     //
432     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
433       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
434                             CK_ArrayToPointerDecay).take();
435   }
436   return Owned(E);
437 }
438
439 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
440   // Check to see if we are dereferencing a null pointer.  If so,
441   // and if not volatile-qualified, this is undefined behavior that the
442   // optimizer will delete, so warn about it.  People sometimes try to use this
443   // to get a deterministic trap and are surprised by clang's behavior.  This
444   // only handles the pattern "*null", which is a very syntactic check.
445   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
446     if (UO->getOpcode() == UO_Deref &&
447         UO->getSubExpr()->IgnoreParenCasts()->
448           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
449         !UO->getType().isVolatileQualified()) {
450     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
451                           S.PDiag(diag::warn_indirection_through_null)
452                             << UO->getSubExpr()->getSourceRange());
453     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
454                         S.PDiag(diag::note_indirection_through_null));
455   }
456 }
457
458 static void DiagnoseDirectIsaAccess(Sema &S, const ObjCIvarRefExpr *OIRE,
459                                     SourceLocation AssignLoc,
460                                     const Expr* RHS) {
461   const ObjCIvarDecl *IV = OIRE->getDecl();
462   if (!IV)
463     return;
464   
465   DeclarationName MemberName = IV->getDeclName();
466   IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
467   if (!Member || !Member->isStr("isa"))
468     return;
469   
470   const Expr *Base = OIRE->getBase();
471   QualType BaseType = Base->getType();
472   if (OIRE->isArrow())
473     BaseType = BaseType->getPointeeType();
474   if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>())
475     if (ObjCInterfaceDecl *IDecl = OTy->getInterface()) {
476       ObjCInterfaceDecl *ClassDeclared = 0;
477       ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
478       if (!ClassDeclared->getSuperClass()
479           && (*ClassDeclared->ivar_begin()) == IV) {
480         if (RHS) {
481           NamedDecl *ObjectSetClass =
482             S.LookupSingleName(S.TUScope,
483                                &S.Context.Idents.get("object_setClass"),
484                                SourceLocation(), S.LookupOrdinaryName);
485           if (ObjectSetClass) {
486             SourceLocation RHSLocEnd = S.PP.getLocForEndOfToken(RHS->getLocEnd());
487             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_assign) <<
488             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_setClass(") <<
489             FixItHint::CreateReplacement(SourceRange(OIRE->getOpLoc(),
490                                                      AssignLoc), ",") <<
491             FixItHint::CreateInsertion(RHSLocEnd, ")");
492           }
493           else
494             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_assign);
495         } else {
496           NamedDecl *ObjectGetClass =
497             S.LookupSingleName(S.TUScope,
498                                &S.Context.Idents.get("object_getClass"),
499                                SourceLocation(), S.LookupOrdinaryName);
500           if (ObjectGetClass)
501             S.Diag(OIRE->getExprLoc(), diag::warn_objc_isa_use) <<
502             FixItHint::CreateInsertion(OIRE->getLocStart(), "object_getClass(") <<
503             FixItHint::CreateReplacement(
504                                          SourceRange(OIRE->getOpLoc(),
505                                                      OIRE->getLocEnd()), ")");
506           else
507             S.Diag(OIRE->getLocation(), diag::warn_objc_isa_use);
508         }
509         S.Diag(IV->getLocation(), diag::note_ivar_decl);
510       }
511     }
512 }
513
514 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
515   // Handle any placeholder expressions which made it here.
516   if (E->getType()->isPlaceholderType()) {
517     ExprResult result = CheckPlaceholderExpr(E);
518     if (result.isInvalid()) return ExprError();
519     E = result.take();
520   }
521   
522   // C++ [conv.lval]p1:
523   //   A glvalue of a non-function, non-array type T can be
524   //   converted to a prvalue.
525   if (!E->isGLValue()) return Owned(E);
526
527   QualType T = E->getType();
528   assert(!T.isNull() && "r-value conversion on typeless expression?");
529
530   // We don't want to throw lvalue-to-rvalue casts on top of
531   // expressions of certain types in C++.
532   if (getLangOpts().CPlusPlus &&
533       (E->getType() == Context.OverloadTy ||
534        T->isDependentType() ||
535        T->isRecordType()))
536     return Owned(E);
537
538   // The C standard is actually really unclear on this point, and
539   // DR106 tells us what the result should be but not why.  It's
540   // generally best to say that void types just doesn't undergo
541   // lvalue-to-rvalue at all.  Note that expressions of unqualified
542   // 'void' type are never l-values, but qualified void can be.
543   if (T->isVoidType())
544     return Owned(E);
545
546   // OpenCL usually rejects direct accesses to values of 'half' type.
547   if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp16 &&
548       T->isHalfType()) {
549     Diag(E->getExprLoc(), diag::err_opencl_half_load_store)
550       << 0 << T;
551     return ExprError();
552   }
553
554   CheckForNullPointerDereference(*this, E);
555   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(E->IgnoreParenCasts())) {
556     NamedDecl *ObjectGetClass = LookupSingleName(TUScope,
557                                      &Context.Idents.get("object_getClass"),
558                                      SourceLocation(), LookupOrdinaryName);
559     if (ObjectGetClass)
560       Diag(E->getExprLoc(), diag::warn_objc_isa_use) <<
561         FixItHint::CreateInsertion(OISA->getLocStart(), "object_getClass(") <<
562         FixItHint::CreateReplacement(
563                     SourceRange(OISA->getOpLoc(), OISA->getIsaMemberLoc()), ")");
564     else
565       Diag(E->getExprLoc(), diag::warn_objc_isa_use);
566   }
567   else if (const ObjCIvarRefExpr *OIRE =
568             dyn_cast<ObjCIvarRefExpr>(E->IgnoreParenCasts()))
569     DiagnoseDirectIsaAccess(*this, OIRE, SourceLocation(), /* Expr*/0);
570   
571   // C++ [conv.lval]p1:
572   //   [...] If T is a non-class type, the type of the prvalue is the
573   //   cv-unqualified version of T. Otherwise, the type of the
574   //   rvalue is T.
575   //
576   // C99 6.3.2.1p2:
577   //   If the lvalue has qualified type, the value has the unqualified
578   //   version of the type of the lvalue; otherwise, the value has the
579   //   type of the lvalue.
580   if (T.hasQualifiers())
581     T = T.getUnqualifiedType();
582
583   UpdateMarkingForLValueToRValue(E);
584   
585   // Loading a __weak object implicitly retains the value, so we need a cleanup to 
586   // balance that.
587   if (getLangOpts().ObjCAutoRefCount &&
588       E->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
589     ExprNeedsCleanups = true;
590
591   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
592                                                   E, 0, VK_RValue));
593
594   // C11 6.3.2.1p2:
595   //   ... if the lvalue has atomic type, the value has the non-atomic version 
596   //   of the type of the lvalue ...
597   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
598     T = Atomic->getValueType().getUnqualifiedType();
599     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
600                                          Res.get(), 0, VK_RValue));
601   }
602   
603   return Res;
604 }
605
606 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
607   ExprResult Res = DefaultFunctionArrayConversion(E);
608   if (Res.isInvalid())
609     return ExprError();
610   Res = DefaultLvalueConversion(Res.take());
611   if (Res.isInvalid())
612     return ExprError();
613   return Res;
614 }
615
616
617 /// UsualUnaryConversions - Performs various conversions that are common to most
618 /// operators (C99 6.3). The conversions of array and function types are
619 /// sometimes suppressed. For example, the array->pointer conversion doesn't
620 /// apply if the array is an argument to the sizeof or address (&) operators.
621 /// In these instances, this routine should *not* be called.
622 ExprResult Sema::UsualUnaryConversions(Expr *E) {
623   // First, convert to an r-value.
624   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
625   if (Res.isInvalid())
626     return ExprError();
627   E = Res.take();
628
629   QualType Ty = E->getType();
630   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
631
632   // Half FP have to be promoted to float unless it is natively supported
633   if (Ty->isHalfType() && !getLangOpts().NativeHalfType)
634     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
635
636   // Try to perform integral promotions if the object has a theoretically
637   // promotable type.
638   if (Ty->isIntegralOrUnscopedEnumerationType()) {
639     // C99 6.3.1.1p2:
640     //
641     //   The following may be used in an expression wherever an int or
642     //   unsigned int may be used:
643     //     - an object or expression with an integer type whose integer
644     //       conversion rank is less than or equal to the rank of int
645     //       and unsigned int.
646     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
647     //
648     //   If an int can represent all values of the original type, the
649     //   value is converted to an int; otherwise, it is converted to an
650     //   unsigned int. These are called the integer promotions. All
651     //   other types are unchanged by the integer promotions.
652
653     QualType PTy = Context.isPromotableBitField(E);
654     if (!PTy.isNull()) {
655       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
656       return Owned(E);
657     }
658     if (Ty->isPromotableIntegerType()) {
659       QualType PT = Context.getPromotedIntegerType(Ty);
660       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
661       return Owned(E);
662     }
663   }
664   return Owned(E);
665 }
666
667 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
668 /// do not have a prototype. Arguments that have type float or __fp16
669 /// are promoted to double. All other argument types are converted by
670 /// UsualUnaryConversions().
671 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
672   QualType Ty = E->getType();
673   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
674
675   ExprResult Res = UsualUnaryConversions(E);
676   if (Res.isInvalid())
677     return ExprError();
678   E = Res.take();
679
680   // If this is a 'float' or '__fp16' (CVR qualified or typedef) promote to
681   // double.
682   const BuiltinType *BTy = Ty->getAs<BuiltinType>();
683   if (BTy && (BTy->getKind() == BuiltinType::Half ||
684               BTy->getKind() == BuiltinType::Float))
685     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
686
687   // C++ performs lvalue-to-rvalue conversion as a default argument
688   // promotion, even on class types, but note:
689   //   C++11 [conv.lval]p2:
690   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
691   //     operand or a subexpression thereof the value contained in the
692   //     referenced object is not accessed. Otherwise, if the glvalue
693   //     has a class type, the conversion copy-initializes a temporary
694   //     of type T from the glvalue and the result of the conversion
695   //     is a prvalue for the temporary.
696   // FIXME: add some way to gate this entire thing for correctness in
697   // potentially potentially evaluated contexts.
698   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
699     ExprResult Temp = PerformCopyInitialization(
700                        InitializedEntity::InitializeTemporary(E->getType()),
701                                                 E->getExprLoc(),
702                                                 Owned(E));
703     if (Temp.isInvalid())
704       return ExprError();
705     E = Temp.get();
706   }
707
708   return Owned(E);
709 }
710
711 /// Determine the degree of POD-ness for an expression.
712 /// Incomplete types are considered POD, since this check can be performed
713 /// when we're in an unevaluated context.
714 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
715   if (Ty->isIncompleteType()) {
716     if (Ty->isObjCObjectType())
717       return VAK_Invalid;
718     return VAK_Valid;
719   }
720
721   if (Ty.isCXX98PODType(Context))
722     return VAK_Valid;
723
724   // C++11 [expr.call]p7:
725   //   Passing a potentially-evaluated argument of class type (Clause 9)
726   //   having a non-trivial copy constructor, a non-trivial move constructor,
727   //   or a non-trivial destructor, with no corresponding parameter,
728   //   is conditionally-supported with implementation-defined semantics.
729   if (getLangOpts().CPlusPlus11 && !Ty->isDependentType())
730     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
731       if (!Record->hasNonTrivialCopyConstructor() &&
732           !Record->hasNonTrivialMoveConstructor() &&
733           !Record->hasNonTrivialDestructor())
734         return VAK_ValidInCXX11;
735
736   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
737     return VAK_Valid;
738   return VAK_Invalid;
739 }
740
741 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
742   // Don't allow one to pass an Objective-C interface to a vararg.
743   const QualType & Ty = E->getType();
744
745   // Complain about passing non-POD types through varargs.
746   switch (isValidVarArgType(Ty)) {
747   case VAK_Valid:
748     break;
749   case VAK_ValidInCXX11:
750     DiagRuntimeBehavior(E->getLocStart(), 0,
751         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
752         << E->getType() << CT);
753     break;
754   case VAK_Invalid: {
755     if (Ty->isObjCObjectType())
756       return DiagRuntimeBehavior(E->getLocStart(), 0,
757                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
758                             << Ty << CT);
759
760     return DiagRuntimeBehavior(E->getLocStart(), 0,
761                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
762                    << getLangOpts().CPlusPlus11 << Ty << CT);
763   }
764   }
765   // c++ rules are enforced elsewhere.
766   return false;
767 }
768
769 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
770 /// will create a trap if the resulting type is not a POD type.
771 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
772                                                   FunctionDecl *FDecl) {
773   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
774     // Strip the unbridged-cast placeholder expression off, if applicable.
775     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
776         (CT == VariadicMethod ||
777          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
778       E = stripARCUnbridgedCast(E);
779
780     // Otherwise, do normal placeholder checking.
781     } else {
782       ExprResult ExprRes = CheckPlaceholderExpr(E);
783       if (ExprRes.isInvalid())
784         return ExprError();
785       E = ExprRes.take();
786     }
787   }
788   
789   ExprResult ExprRes = DefaultArgumentPromotion(E);
790   if (ExprRes.isInvalid())
791     return ExprError();
792   E = ExprRes.take();
793
794   // Diagnostics regarding non-POD argument types are
795   // emitted along with format string checking in Sema::CheckFunctionCall().
796   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
797     // Turn this into a trap.
798     CXXScopeSpec SS;
799     SourceLocation TemplateKWLoc;
800     UnqualifiedId Name;
801     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
802                        E->getLocStart());
803     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
804                                           Name, true, false);
805     if (TrapFn.isInvalid())
806       return ExprError();
807
808     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
809                                     E->getLocStart(), MultiExprArg(),
810                                     E->getLocEnd());
811     if (Call.isInvalid())
812       return ExprError();
813
814     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
815                                   Call.get(), E);
816     if (Comma.isInvalid())
817       return ExprError();
818     return Comma.get();
819   }
820
821   if (!getLangOpts().CPlusPlus &&
822       RequireCompleteType(E->getExprLoc(), E->getType(),
823                           diag::err_call_incomplete_argument))
824     return ExprError();
825
826   return Owned(E);
827 }
828
829 /// \brief Converts an integer to complex float type.  Helper function of
830 /// UsualArithmeticConversions()
831 ///
832 /// \return false if the integer expression is an integer type and is
833 /// successfully converted to the complex type.
834 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
835                                                   ExprResult &ComplexExpr,
836                                                   QualType IntTy,
837                                                   QualType ComplexTy,
838                                                   bool SkipCast) {
839   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
840   if (SkipCast) return false;
841   if (IntTy->isIntegerType()) {
842     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
843     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
844     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
845                                   CK_FloatingRealToComplex);
846   } else {
847     assert(IntTy->isComplexIntegerType());
848     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
849                                   CK_IntegralComplexToFloatingComplex);
850   }
851   return false;
852 }
853
854 /// \brief Takes two complex float types and converts them to the same type.
855 /// Helper function of UsualArithmeticConversions()
856 static QualType
857 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
858                                             ExprResult &RHS, QualType LHSType,
859                                             QualType RHSType,
860                                             bool IsCompAssign) {
861   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
862
863   if (order < 0) {
864     // _Complex float -> _Complex double
865     if (!IsCompAssign)
866       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
867     return RHSType;
868   }
869   if (order > 0)
870     // _Complex float -> _Complex double
871     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
872   return LHSType;
873 }
874
875 /// \brief Converts otherExpr to complex float and promotes complexExpr if
876 /// necessary.  Helper function of UsualArithmeticConversions()
877 static QualType handleOtherComplexFloatConversion(Sema &S,
878                                                   ExprResult &ComplexExpr,
879                                                   ExprResult &OtherExpr,
880                                                   QualType ComplexTy,
881                                                   QualType OtherTy,
882                                                   bool ConvertComplexExpr,
883                                                   bool ConvertOtherExpr) {
884   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
885
886   // If just the complexExpr is complex, the otherExpr needs to be converted,
887   // and the complexExpr might need to be promoted.
888   if (order > 0) { // complexExpr is wider
889     // float -> _Complex double
890     if (ConvertOtherExpr) {
891       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
892       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
893       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
894                                       CK_FloatingRealToComplex);
895     }
896     return ComplexTy;
897   }
898
899   // otherTy is at least as wide.  Find its corresponding complex type.
900   QualType result = (order == 0 ? ComplexTy :
901                                   S.Context.getComplexType(OtherTy));
902
903   // double -> _Complex double
904   if (ConvertOtherExpr)
905     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
906                                     CK_FloatingRealToComplex);
907
908   // _Complex float -> _Complex double
909   if (ConvertComplexExpr && order < 0)
910     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
911                                       CK_FloatingComplexCast);
912
913   return result;
914 }
915
916 /// \brief Handle arithmetic conversion with complex types.  Helper function of
917 /// UsualArithmeticConversions()
918 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
919                                              ExprResult &RHS, QualType LHSType,
920                                              QualType RHSType,
921                                              bool IsCompAssign) {
922   // if we have an integer operand, the result is the complex type.
923   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
924                                              /*skipCast*/false))
925     return LHSType;
926   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
927                                              /*skipCast*/IsCompAssign))
928     return RHSType;
929
930   // This handles complex/complex, complex/float, or float/complex.
931   // When both operands are complex, the shorter operand is converted to the
932   // type of the longer, and that is the type of the result. This corresponds
933   // to what is done when combining two real floating-point operands.
934   // The fun begins when size promotion occur across type domains.
935   // From H&S 6.3.4: When one operand is complex and the other is a real
936   // floating-point type, the less precise type is converted, within it's
937   // real or complex domain, to the precision of the other type. For example,
938   // when combining a "long double" with a "double _Complex", the
939   // "double _Complex" is promoted to "long double _Complex".
940
941   bool LHSComplexFloat = LHSType->isComplexType();
942   bool RHSComplexFloat = RHSType->isComplexType();
943
944   // If both are complex, just cast to the more precise type.
945   if (LHSComplexFloat && RHSComplexFloat)
946     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
947                                                        LHSType, RHSType,
948                                                        IsCompAssign);
949
950   // If only one operand is complex, promote it if necessary and convert the
951   // other operand to complex.
952   if (LHSComplexFloat)
953     return handleOtherComplexFloatConversion(
954         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
955         /*convertOtherExpr*/ true);
956
957   assert(RHSComplexFloat);
958   return handleOtherComplexFloatConversion(
959       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
960       /*convertOtherExpr*/ !IsCompAssign);
961 }
962
963 /// \brief Hande arithmetic conversion from integer to float.  Helper function
964 /// of UsualArithmeticConversions()
965 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
966                                            ExprResult &IntExpr,
967                                            QualType FloatTy, QualType IntTy,
968                                            bool ConvertFloat, bool ConvertInt) {
969   if (IntTy->isIntegerType()) {
970     if (ConvertInt)
971       // Convert intExpr to the lhs floating point type.
972       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
973                                     CK_IntegralToFloating);
974     return FloatTy;
975   }
976      
977   // Convert both sides to the appropriate complex float.
978   assert(IntTy->isComplexIntegerType());
979   QualType result = S.Context.getComplexType(FloatTy);
980
981   // _Complex int -> _Complex float
982   if (ConvertInt)
983     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
984                                   CK_IntegralComplexToFloatingComplex);
985
986   // float -> _Complex float
987   if (ConvertFloat)
988     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
989                                     CK_FloatingRealToComplex);
990
991   return result;
992 }
993
994 /// \brief Handle arithmethic conversion with floating point types.  Helper
995 /// function of UsualArithmeticConversions()
996 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
997                                       ExprResult &RHS, QualType LHSType,
998                                       QualType RHSType, bool IsCompAssign) {
999   bool LHSFloat = LHSType->isRealFloatingType();
1000   bool RHSFloat = RHSType->isRealFloatingType();
1001
1002   // If we have two real floating types, convert the smaller operand
1003   // to the bigger result.
1004   if (LHSFloat && RHSFloat) {
1005     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
1006     if (order > 0) {
1007       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
1008       return LHSType;
1009     }
1010
1011     assert(order < 0 && "illegal float comparison");
1012     if (!IsCompAssign)
1013       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
1014     return RHSType;
1015   }
1016
1017   if (LHSFloat)
1018     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
1019                                       /*convertFloat=*/!IsCompAssign,
1020                                       /*convertInt=*/ true);
1021   assert(RHSFloat);
1022   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
1023                                     /*convertInt=*/ true,
1024                                     /*convertFloat=*/!IsCompAssign);
1025 }
1026
1027 typedef ExprResult PerformCastFn(Sema &S, Expr *operand, QualType toType);
1028
1029 namespace {
1030 /// These helper callbacks are placed in an anonymous namespace to
1031 /// permit their use as function template parameters.
1032 ExprResult doIntegralCast(Sema &S, Expr *op, QualType toType) {
1033   return S.ImpCastExprToType(op, toType, CK_IntegralCast);
1034 }
1035
1036 ExprResult doComplexIntegralCast(Sema &S, Expr *op, QualType toType) {
1037   return S.ImpCastExprToType(op, S.Context.getComplexType(toType),
1038                              CK_IntegralComplexCast);
1039 }
1040 }
1041
1042 /// \brief Handle integer arithmetic conversions.  Helper function of
1043 /// UsualArithmeticConversions()
1044 template <PerformCastFn doLHSCast, PerformCastFn doRHSCast>
1045 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
1046                                         ExprResult &RHS, QualType LHSType,
1047                                         QualType RHSType, bool IsCompAssign) {
1048   // The rules for this case are in C99 6.3.1.8
1049   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
1050   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
1051   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
1052   if (LHSSigned == RHSSigned) {
1053     // Same signedness; use the higher-ranked type
1054     if (order >= 0) {
1055       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1056       return LHSType;
1057     } else if (!IsCompAssign)
1058       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1059     return RHSType;
1060   } else if (order != (LHSSigned ? 1 : -1)) {
1061     // The unsigned type has greater than or equal rank to the
1062     // signed type, so use the unsigned type
1063     if (RHSSigned) {
1064       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1065       return LHSType;
1066     } else if (!IsCompAssign)
1067       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1068     return RHSType;
1069   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1070     // The two types are different widths; if we are here, that
1071     // means the signed type is larger than the unsigned type, so
1072     // use the signed type.
1073     if (LHSSigned) {
1074       RHS = (*doRHSCast)(S, RHS.take(), LHSType);
1075       return LHSType;
1076     } else if (!IsCompAssign)
1077       LHS = (*doLHSCast)(S, LHS.take(), RHSType);
1078     return RHSType;
1079   } else {
1080     // The signed type is higher-ranked than the unsigned type,
1081     // but isn't actually any bigger (like unsigned int and long
1082     // on most 32-bit systems).  Use the unsigned type corresponding
1083     // to the signed type.
1084     QualType result =
1085       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1086     RHS = (*doRHSCast)(S, RHS.take(), result);
1087     if (!IsCompAssign)
1088       LHS = (*doLHSCast)(S, LHS.take(), result);
1089     return result;
1090   }
1091 }
1092
1093 /// \brief Handle conversions with GCC complex int extension.  Helper function
1094 /// of UsualArithmeticConversions()
1095 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
1096                                            ExprResult &RHS, QualType LHSType,
1097                                            QualType RHSType,
1098                                            bool IsCompAssign) {
1099   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
1100   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
1101
1102   if (LHSComplexInt && RHSComplexInt) {
1103     QualType LHSEltType = LHSComplexInt->getElementType();
1104     QualType RHSEltType = RHSComplexInt->getElementType();
1105     QualType ScalarType =
1106       handleIntegerConversion<doComplexIntegralCast, doComplexIntegralCast>
1107         (S, LHS, RHS, LHSEltType, RHSEltType, IsCompAssign);
1108
1109     return S.Context.getComplexType(ScalarType);
1110   }
1111
1112   if (LHSComplexInt) {
1113     QualType LHSEltType = LHSComplexInt->getElementType();
1114     QualType ScalarType =
1115       handleIntegerConversion<doComplexIntegralCast, doIntegralCast>
1116         (S, LHS, RHS, LHSEltType, RHSType, IsCompAssign);
1117     QualType ComplexType = S.Context.getComplexType(ScalarType);
1118     RHS = S.ImpCastExprToType(RHS.take(), ComplexType,
1119                               CK_IntegralRealToComplex);
1120  
1121     return ComplexType;
1122   }
1123
1124   assert(RHSComplexInt);
1125
1126   QualType RHSEltType = RHSComplexInt->getElementType();
1127   QualType ScalarType =
1128     handleIntegerConversion<doIntegralCast, doComplexIntegralCast>
1129       (S, LHS, RHS, LHSType, RHSEltType, IsCompAssign);
1130   QualType ComplexType = S.Context.getComplexType(ScalarType);
1131   
1132   if (!IsCompAssign)
1133     LHS = S.ImpCastExprToType(LHS.take(), ComplexType,
1134                               CK_IntegralRealToComplex);
1135   return ComplexType;
1136 }
1137
1138 /// UsualArithmeticConversions - Performs various conversions that are common to
1139 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1140 /// routine returns the first non-arithmetic type found. The client is
1141 /// responsible for emitting appropriate error diagnostics.
1142 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1143                                           bool IsCompAssign) {
1144   if (!IsCompAssign) {
1145     LHS = UsualUnaryConversions(LHS.take());
1146     if (LHS.isInvalid())
1147       return QualType();
1148   }
1149
1150   RHS = UsualUnaryConversions(RHS.take());
1151   if (RHS.isInvalid())
1152     return QualType();
1153
1154   // For conversion purposes, we ignore any qualifiers.
1155   // For example, "const float" and "float" are equivalent.
1156   QualType LHSType =
1157     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1158   QualType RHSType =
1159     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1160
1161   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1162   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1163     LHSType = AtomicLHS->getValueType();
1164
1165   // If both types are identical, no conversion is needed.
1166   if (LHSType == RHSType)
1167     return LHSType;
1168
1169   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1170   // The caller can deal with this (e.g. pointer + int).
1171   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1172     return QualType();
1173
1174   // Apply unary and bitfield promotions to the LHS's type.
1175   QualType LHSUnpromotedType = LHSType;
1176   if (LHSType->isPromotableIntegerType())
1177     LHSType = Context.getPromotedIntegerType(LHSType);
1178   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1179   if (!LHSBitfieldPromoteTy.isNull())
1180     LHSType = LHSBitfieldPromoteTy;
1181   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1182     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1183
1184   // If both types are identical, no conversion is needed.
1185   if (LHSType == RHSType)
1186     return LHSType;
1187
1188   // At this point, we have two different arithmetic types.
1189
1190   // Handle complex types first (C99 6.3.1.8p1).
1191   if (LHSType->isComplexType() || RHSType->isComplexType())
1192     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1193                                         IsCompAssign);
1194
1195   // Now handle "real" floating types (i.e. float, double, long double).
1196   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1197     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1198                                  IsCompAssign);
1199
1200   // Handle GCC complex int extension.
1201   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1202     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1203                                       IsCompAssign);
1204
1205   // Finally, we have two differing integer types.
1206   return handleIntegerConversion<doIntegralCast, doIntegralCast>
1207            (*this, LHS, RHS, LHSType, RHSType, IsCompAssign);
1208 }
1209
1210
1211 //===----------------------------------------------------------------------===//
1212 //  Semantic Analysis for various Expression Types
1213 //===----------------------------------------------------------------------===//
1214
1215
1216 ExprResult
1217 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1218                                 SourceLocation DefaultLoc,
1219                                 SourceLocation RParenLoc,
1220                                 Expr *ControllingExpr,
1221                                 MultiTypeArg ArgTypes,
1222                                 MultiExprArg ArgExprs) {
1223   unsigned NumAssocs = ArgTypes.size();
1224   assert(NumAssocs == ArgExprs.size());
1225
1226   ParsedType *ParsedTypes = ArgTypes.data();
1227   Expr **Exprs = ArgExprs.data();
1228
1229   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1230   for (unsigned i = 0; i < NumAssocs; ++i) {
1231     if (ParsedTypes[i])
1232       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1233     else
1234       Types[i] = 0;
1235   }
1236
1237   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1238                                              ControllingExpr, Types, Exprs,
1239                                              NumAssocs);
1240   delete [] Types;
1241   return ER;
1242 }
1243
1244 ExprResult
1245 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1246                                  SourceLocation DefaultLoc,
1247                                  SourceLocation RParenLoc,
1248                                  Expr *ControllingExpr,
1249                                  TypeSourceInfo **Types,
1250                                  Expr **Exprs,
1251                                  unsigned NumAssocs) {
1252   if (ControllingExpr->getType()->isPlaceholderType()) {
1253     ExprResult result = CheckPlaceholderExpr(ControllingExpr);
1254     if (result.isInvalid()) return ExprError();
1255     ControllingExpr = result.take();
1256   }
1257
1258   bool TypeErrorFound = false,
1259        IsResultDependent = ControllingExpr->isTypeDependent(),
1260        ContainsUnexpandedParameterPack
1261          = ControllingExpr->containsUnexpandedParameterPack();
1262
1263   for (unsigned i = 0; i < NumAssocs; ++i) {
1264     if (Exprs[i]->containsUnexpandedParameterPack())
1265       ContainsUnexpandedParameterPack = true;
1266
1267     if (Types[i]) {
1268       if (Types[i]->getType()->containsUnexpandedParameterPack())
1269         ContainsUnexpandedParameterPack = true;
1270
1271       if (Types[i]->getType()->isDependentType()) {
1272         IsResultDependent = true;
1273       } else {
1274         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1275         // complete object type other than a variably modified type."
1276         unsigned D = 0;
1277         if (Types[i]->getType()->isIncompleteType())
1278           D = diag::err_assoc_type_incomplete;
1279         else if (!Types[i]->getType()->isObjectType())
1280           D = diag::err_assoc_type_nonobject;
1281         else if (Types[i]->getType()->isVariablyModifiedType())
1282           D = diag::err_assoc_type_variably_modified;
1283
1284         if (D != 0) {
1285           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1286             << Types[i]->getTypeLoc().getSourceRange()
1287             << Types[i]->getType();
1288           TypeErrorFound = true;
1289         }
1290
1291         // C11 6.5.1.1p2 "No two generic associations in the same generic
1292         // selection shall specify compatible types."
1293         for (unsigned j = i+1; j < NumAssocs; ++j)
1294           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1295               Context.typesAreCompatible(Types[i]->getType(),
1296                                          Types[j]->getType())) {
1297             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1298                  diag::err_assoc_compatible_types)
1299               << Types[j]->getTypeLoc().getSourceRange()
1300               << Types[j]->getType()
1301               << Types[i]->getType();
1302             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1303                  diag::note_compat_assoc)
1304               << Types[i]->getTypeLoc().getSourceRange()
1305               << Types[i]->getType();
1306             TypeErrorFound = true;
1307           }
1308       }
1309     }
1310   }
1311   if (TypeErrorFound)
1312     return ExprError();
1313
1314   // If we determined that the generic selection is result-dependent, don't
1315   // try to compute the result expression.
1316   if (IsResultDependent)
1317     return Owned(new (Context) GenericSelectionExpr(
1318                    Context, KeyLoc, ControllingExpr,
1319                    llvm::makeArrayRef(Types, NumAssocs),
1320                    llvm::makeArrayRef(Exprs, NumAssocs),
1321                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1322
1323   SmallVector<unsigned, 1> CompatIndices;
1324   unsigned DefaultIndex = -1U;
1325   for (unsigned i = 0; i < NumAssocs; ++i) {
1326     if (!Types[i])
1327       DefaultIndex = i;
1328     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1329                                         Types[i]->getType()))
1330       CompatIndices.push_back(i);
1331   }
1332
1333   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1334   // type compatible with at most one of the types named in its generic
1335   // association list."
1336   if (CompatIndices.size() > 1) {
1337     // We strip parens here because the controlling expression is typically
1338     // parenthesized in macro definitions.
1339     ControllingExpr = ControllingExpr->IgnoreParens();
1340     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1341       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1342       << (unsigned) CompatIndices.size();
1343     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1344          E = CompatIndices.end(); I != E; ++I) {
1345       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1346            diag::note_compat_assoc)
1347         << Types[*I]->getTypeLoc().getSourceRange()
1348         << Types[*I]->getType();
1349     }
1350     return ExprError();
1351   }
1352
1353   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1354   // its controlling expression shall have type compatible with exactly one of
1355   // the types named in its generic association list."
1356   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1357     // We strip parens here because the controlling expression is typically
1358     // parenthesized in macro definitions.
1359     ControllingExpr = ControllingExpr->IgnoreParens();
1360     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1361       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1362     return ExprError();
1363   }
1364
1365   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1366   // type name that is compatible with the type of the controlling expression,
1367   // then the result expression of the generic selection is the expression
1368   // in that generic association. Otherwise, the result expression of the
1369   // generic selection is the expression in the default generic association."
1370   unsigned ResultIndex =
1371     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1372
1373   return Owned(new (Context) GenericSelectionExpr(
1374                  Context, KeyLoc, ControllingExpr,
1375                  llvm::makeArrayRef(Types, NumAssocs),
1376                  llvm::makeArrayRef(Exprs, NumAssocs),
1377                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1378                  ResultIndex));
1379 }
1380
1381 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1382 /// location of the token and the offset of the ud-suffix within it.
1383 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1384                                      unsigned Offset) {
1385   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1386                                         S.getLangOpts());
1387 }
1388
1389 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1390 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1391 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1392                                                  IdentifierInfo *UDSuffix,
1393                                                  SourceLocation UDSuffixLoc,
1394                                                  ArrayRef<Expr*> Args,
1395                                                  SourceLocation LitEndLoc) {
1396   assert(Args.size() <= 2 && "too many arguments for literal operator");
1397
1398   QualType ArgTy[2];
1399   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1400     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1401     if (ArgTy[ArgIdx]->isArrayType())
1402       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1403   }
1404
1405   DeclarationName OpName =
1406     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1407   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1408   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1409
1410   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1411   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1412                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1413     return ExprError();
1414
1415   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1416 }
1417
1418 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1419 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1420 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1421 /// multiple tokens.  However, the common case is that StringToks points to one
1422 /// string.
1423 ///
1424 ExprResult
1425 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1426                          Scope *UDLScope) {
1427   assert(NumStringToks && "Must have at least one string!");
1428
1429   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1430   if (Literal.hadError)
1431     return ExprError();
1432
1433   SmallVector<SourceLocation, 4> StringTokLocs;
1434   for (unsigned i = 0; i != NumStringToks; ++i)
1435     StringTokLocs.push_back(StringToks[i].getLocation());
1436
1437   QualType StrTy = Context.CharTy;
1438   if (Literal.isWide())
1439     StrTy = Context.getWCharType();
1440   else if (Literal.isUTF16())
1441     StrTy = Context.Char16Ty;
1442   else if (Literal.isUTF32())
1443     StrTy = Context.Char32Ty;
1444   else if (Literal.isPascal())
1445     StrTy = Context.UnsignedCharTy;
1446
1447   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1448   if (Literal.isWide())
1449     Kind = StringLiteral::Wide;
1450   else if (Literal.isUTF8())
1451     Kind = StringLiteral::UTF8;
1452   else if (Literal.isUTF16())
1453     Kind = StringLiteral::UTF16;
1454   else if (Literal.isUTF32())
1455     Kind = StringLiteral::UTF32;
1456
1457   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1458   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1459     StrTy.addConst();
1460
1461   // Get an array type for the string, according to C99 6.4.5.  This includes
1462   // the nul terminator character as well as the string length for pascal
1463   // strings.
1464   StrTy = Context.getConstantArrayType(StrTy,
1465                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1466                                        ArrayType::Normal, 0);
1467
1468   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1469   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1470                                              Kind, Literal.Pascal, StrTy,
1471                                              &StringTokLocs[0],
1472                                              StringTokLocs.size());
1473   if (Literal.getUDSuffix().empty())
1474     return Owned(Lit);
1475
1476   // We're building a user-defined literal.
1477   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1478   SourceLocation UDSuffixLoc =
1479     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1480                    Literal.getUDSuffixOffset());
1481
1482   // Make sure we're allowed user-defined literals here.
1483   if (!UDLScope)
1484     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1485
1486   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1487   //   operator "" X (str, len)
1488   QualType SizeType = Context.getSizeType();
1489   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1490   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1491                                                   StringTokLocs[0]);
1492   Expr *Args[] = { Lit, LenArg };
1493   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1494                                         Args, StringTokLocs.back());
1495 }
1496
1497 ExprResult
1498 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1499                        SourceLocation Loc,
1500                        const CXXScopeSpec *SS) {
1501   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1502   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1503 }
1504
1505 /// BuildDeclRefExpr - Build an expression that references a
1506 /// declaration that does not require a closure capture.
1507 ExprResult
1508 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1509                        const DeclarationNameInfo &NameInfo,
1510                        const CXXScopeSpec *SS, NamedDecl *FoundD) {
1511   if (getLangOpts().CUDA)
1512     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1513       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1514         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1515                            CalleeTarget = IdentifyCUDATarget(Callee);
1516         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1517           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1518             << CalleeTarget << D->getIdentifier() << CallerTarget;
1519           Diag(D->getLocation(), diag::note_previous_decl)
1520             << D->getIdentifier();
1521           return ExprError();
1522         }
1523       }
1524
1525   bool refersToEnclosingScope =
1526     (CurContext != D->getDeclContext() &&
1527      D->getDeclContext()->isFunctionOrMethod());
1528
1529   DeclRefExpr *E = DeclRefExpr::Create(Context,
1530                                        SS ? SS->getWithLocInContext(Context)
1531                                               : NestedNameSpecifierLoc(),
1532                                        SourceLocation(),
1533                                        D, refersToEnclosingScope,
1534                                        NameInfo, Ty, VK, FoundD);
1535
1536   MarkDeclRefReferenced(E);
1537
1538   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1539       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1540     DiagnosticsEngine::Level Level =
1541       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1542                                E->getLocStart());
1543     if (Level != DiagnosticsEngine::Ignored)
1544       getCurFunction()->recordUseOfWeak(E);
1545   }
1546
1547   // Just in case we're building an illegal pointer-to-member.
1548   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1549   if (FD && FD->isBitField())
1550     E->setObjectKind(OK_BitField);
1551
1552   return Owned(E);
1553 }
1554
1555 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1556 /// possibly a list of template arguments.
1557 ///
1558 /// If this produces template arguments, it is permitted to call
1559 /// DecomposeTemplateName.
1560 ///
1561 /// This actually loses a lot of source location information for
1562 /// non-standard name kinds; we should consider preserving that in
1563 /// some way.
1564 void
1565 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1566                              TemplateArgumentListInfo &Buffer,
1567                              DeclarationNameInfo &NameInfo,
1568                              const TemplateArgumentListInfo *&TemplateArgs) {
1569   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1570     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1571     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1572
1573     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1574                                        Id.TemplateId->NumArgs);
1575     translateTemplateArguments(TemplateArgsPtr, Buffer);
1576
1577     TemplateName TName = Id.TemplateId->Template.get();
1578     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1579     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1580     TemplateArgs = &Buffer;
1581   } else {
1582     NameInfo = GetNameFromUnqualifiedId(Id);
1583     TemplateArgs = 0;
1584   }
1585 }
1586
1587 /// Diagnose an empty lookup.
1588 ///
1589 /// \return false if new lookup candidates were found
1590 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1591                                CorrectionCandidateCallback &CCC,
1592                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1593                                llvm::ArrayRef<Expr *> Args) {
1594   DeclarationName Name = R.getLookupName();
1595
1596   unsigned diagnostic = diag::err_undeclared_var_use;
1597   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1598   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1599       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1600       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1601     diagnostic = diag::err_undeclared_use;
1602     diagnostic_suggest = diag::err_undeclared_use_suggest;
1603   }
1604
1605   // If the original lookup was an unqualified lookup, fake an
1606   // unqualified lookup.  This is useful when (for example) the
1607   // original lookup would not have found something because it was a
1608   // dependent name.
1609   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1610     ? CurContext : 0;
1611   while (DC) {
1612     if (isa<CXXRecordDecl>(DC)) {
1613       LookupQualifiedName(R, DC);
1614
1615       if (!R.empty()) {
1616         // Don't give errors about ambiguities in this lookup.
1617         R.suppressDiagnostics();
1618
1619         // During a default argument instantiation the CurContext points
1620         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1621         // function parameter list, hence add an explicit check.
1622         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1623                               ActiveTemplateInstantiations.back().Kind ==
1624             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1625         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1626         bool isInstance = CurMethod &&
1627                           CurMethod->isInstance() &&
1628                           DC == CurMethod->getParent() && !isDefaultArgument;
1629                           
1630
1631         // Give a code modification hint to insert 'this->'.
1632         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1633         // Actually quite difficult!
1634         if (getLangOpts().MicrosoftMode)
1635           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1636         if (isInstance) {
1637           Diag(R.getNameLoc(), diagnostic) << Name
1638             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1639           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1640               CallsUndergoingInstantiation.back()->getCallee());
1641
1642           CXXMethodDecl *DepMethod;
1643           if (CurMethod->isDependentContext())
1644             DepMethod = CurMethod;
1645           else if (CurMethod->getTemplatedKind() ==
1646               FunctionDecl::TK_FunctionTemplateSpecialization)
1647             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1648                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1649           else
1650             DepMethod = cast<CXXMethodDecl>(
1651                 CurMethod->getInstantiatedFromMemberFunction());
1652           assert(DepMethod && "No template pattern found");
1653
1654           QualType DepThisType = DepMethod->getThisType(Context);
1655           CheckCXXThisCapture(R.getNameLoc());
1656           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1657                                      R.getNameLoc(), DepThisType, false);
1658           TemplateArgumentListInfo TList;
1659           if (ULE->hasExplicitTemplateArgs())
1660             ULE->copyTemplateArgumentsInto(TList);
1661           
1662           CXXScopeSpec SS;
1663           SS.Adopt(ULE->getQualifierLoc());
1664           CXXDependentScopeMemberExpr *DepExpr =
1665               CXXDependentScopeMemberExpr::Create(
1666                   Context, DepThis, DepThisType, true, SourceLocation(),
1667                   SS.getWithLocInContext(Context),
1668                   ULE->getTemplateKeywordLoc(), 0,
1669                   R.getLookupNameInfo(),
1670                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1671           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1672         } else {
1673           Diag(R.getNameLoc(), diagnostic) << Name;
1674         }
1675
1676         // Do we really want to note all of these?
1677         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1678           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1679
1680         // Return true if we are inside a default argument instantiation
1681         // and the found name refers to an instance member function, otherwise
1682         // the function calling DiagnoseEmptyLookup will try to create an
1683         // implicit member call and this is wrong for default argument.
1684         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1685           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1686           return true;
1687         }
1688
1689         // Tell the callee to try to recover.
1690         return false;
1691       }
1692
1693       R.clear();
1694     }
1695
1696     // In Microsoft mode, if we are performing lookup from within a friend
1697     // function definition declared at class scope then we must set
1698     // DC to the lexical parent to be able to search into the parent
1699     // class.
1700     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1701         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1702         DC->getLexicalParent()->isRecord())
1703       DC = DC->getLexicalParent();
1704     else
1705       DC = DC->getParent();
1706   }
1707
1708   // We didn't find anything, so try to correct for a typo.
1709   TypoCorrection Corrected;
1710   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1711                                     S, &SS, CCC))) {
1712     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1713     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1714     R.setLookupName(Corrected.getCorrection());
1715
1716     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1717       if (Corrected.isOverloaded()) {
1718         OverloadCandidateSet OCS(R.getNameLoc());
1719         OverloadCandidateSet::iterator Best;
1720         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1721                                         CDEnd = Corrected.end();
1722              CD != CDEnd; ++CD) {
1723           if (FunctionTemplateDecl *FTD =
1724                    dyn_cast<FunctionTemplateDecl>(*CD))
1725             AddTemplateOverloadCandidate(
1726                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1727                 Args, OCS);
1728           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1729             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1730               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1731                                    Args, OCS);
1732         }
1733         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1734           case OR_Success:
1735             ND = Best->Function;
1736             break;
1737           default:
1738             break;
1739         }
1740       }
1741       R.addDecl(ND);
1742       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1743         if (SS.isEmpty())
1744           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1745             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1746         else
1747           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1748             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1749             << SS.getRange()
1750             << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1751                                             CorrectedStr);
1752
1753         unsigned diag = isa<ImplicitParamDecl>(ND)
1754           ? diag::note_implicit_param_decl
1755           : diag::note_previous_decl;
1756
1757         Diag(ND->getLocation(), diag)
1758           << CorrectedQuotedStr;
1759
1760         // Tell the callee to try to recover.
1761         return false;
1762       }
1763
1764       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1765         // FIXME: If we ended up with a typo for a type name or
1766         // Objective-C class name, we're in trouble because the parser
1767         // is in the wrong place to recover. Suggest the typo
1768         // correction, but don't make it a fix-it since we're not going
1769         // to recover well anyway.
1770         if (SS.isEmpty())
1771           Diag(R.getNameLoc(), diagnostic_suggest)
1772             << Name << CorrectedQuotedStr;
1773         else
1774           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1775             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1776             << SS.getRange();
1777
1778         // Don't try to recover; it won't work.
1779         return true;
1780       }
1781     } else {
1782       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1783       // because we aren't able to recover.
1784       if (SS.isEmpty())
1785         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1786       else
1787         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1788         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1789         << SS.getRange();
1790       return true;
1791     }
1792   }
1793   R.clear();
1794
1795   // Emit a special diagnostic for failed member lookups.
1796   // FIXME: computing the declaration context might fail here (?)
1797   if (!SS.isEmpty()) {
1798     Diag(R.getNameLoc(), diag::err_no_member)
1799       << Name << computeDeclContext(SS, false)
1800       << SS.getRange();
1801     return true;
1802   }
1803
1804   // Give up, we can't recover.
1805   Diag(R.getNameLoc(), diagnostic) << Name;
1806   return true;
1807 }
1808
1809 ExprResult Sema::ActOnIdExpression(Scope *S,
1810                                    CXXScopeSpec &SS,
1811                                    SourceLocation TemplateKWLoc,
1812                                    UnqualifiedId &Id,
1813                                    bool HasTrailingLParen,
1814                                    bool IsAddressOfOperand,
1815                                    CorrectionCandidateCallback *CCC) {
1816   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1817          "cannot be direct & operand and have a trailing lparen");
1818
1819   if (SS.isInvalid())
1820     return ExprError();
1821
1822   TemplateArgumentListInfo TemplateArgsBuffer;
1823
1824   // Decompose the UnqualifiedId into the following data.
1825   DeclarationNameInfo NameInfo;
1826   const TemplateArgumentListInfo *TemplateArgs;
1827   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1828
1829   DeclarationName Name = NameInfo.getName();
1830   IdentifierInfo *II = Name.getAsIdentifierInfo();
1831   SourceLocation NameLoc = NameInfo.getLoc();
1832
1833   // C++ [temp.dep.expr]p3:
1834   //   An id-expression is type-dependent if it contains:
1835   //     -- an identifier that was declared with a dependent type,
1836   //        (note: handled after lookup)
1837   //     -- a template-id that is dependent,
1838   //        (note: handled in BuildTemplateIdExpr)
1839   //     -- a conversion-function-id that specifies a dependent type,
1840   //     -- a nested-name-specifier that contains a class-name that
1841   //        names a dependent type.
1842   // Determine whether this is a member of an unknown specialization;
1843   // we need to handle these differently.
1844   bool DependentID = false;
1845   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1846       Name.getCXXNameType()->isDependentType()) {
1847     DependentID = true;
1848   } else if (SS.isSet()) {
1849     if (DeclContext *DC = computeDeclContext(SS, false)) {
1850       if (RequireCompleteDeclContext(SS, DC))
1851         return ExprError();
1852     } else {
1853       DependentID = true;
1854     }
1855   }
1856
1857   if (DependentID)
1858     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1859                                       IsAddressOfOperand, TemplateArgs);
1860
1861   // Perform the required lookup.
1862   LookupResult R(*this, NameInfo, 
1863                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
1864                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1865   if (TemplateArgs) {
1866     // Lookup the template name again to correctly establish the context in
1867     // which it was found. This is really unfortunate as we already did the
1868     // lookup to determine that it was a template name in the first place. If
1869     // this becomes a performance hit, we can work harder to preserve those
1870     // results until we get here but it's likely not worth it.
1871     bool MemberOfUnknownSpecialization;
1872     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1873                        MemberOfUnknownSpecialization);
1874     
1875     if (MemberOfUnknownSpecialization ||
1876         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1877       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1878                                         IsAddressOfOperand, TemplateArgs);
1879   } else {
1880     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1881     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1882
1883     // If the result might be in a dependent base class, this is a dependent 
1884     // id-expression.
1885     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1886       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1887                                         IsAddressOfOperand, TemplateArgs);
1888
1889     // If this reference is in an Objective-C method, then we need to do
1890     // some special Objective-C lookup, too.
1891     if (IvarLookupFollowUp) {
1892       ExprResult E(LookupInObjCMethod(R, S, II, true));
1893       if (E.isInvalid())
1894         return ExprError();
1895
1896       if (Expr *Ex = E.takeAs<Expr>())
1897         return Owned(Ex);
1898     }
1899   }
1900
1901   if (R.isAmbiguous())
1902     return ExprError();
1903
1904   // Determine whether this name might be a candidate for
1905   // argument-dependent lookup.
1906   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1907
1908   if (R.empty() && !ADL) {
1909     // Otherwise, this could be an implicitly declared function reference (legal
1910     // in C90, extension in C99, forbidden in C++).
1911     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1912       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1913       if (D) R.addDecl(D);
1914     }
1915
1916     // If this name wasn't predeclared and if this is not a function
1917     // call, diagnose the problem.
1918     if (R.empty()) {
1919
1920       // In Microsoft mode, if we are inside a template class member function
1921       // and we can't resolve an identifier then assume the identifier is type
1922       // dependent. The goal is to postpone name lookup to instantiation time 
1923       // to be able to search into type dependent base classes.
1924       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1925           isa<CXXMethodDecl>(CurContext))
1926         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1927                                           IsAddressOfOperand, TemplateArgs);
1928
1929       CorrectionCandidateCallback DefaultValidator;
1930       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1931         return ExprError();
1932
1933       assert(!R.empty() &&
1934              "DiagnoseEmptyLookup returned false but added no results");
1935
1936       // If we found an Objective-C instance variable, let
1937       // LookupInObjCMethod build the appropriate expression to
1938       // reference the ivar.
1939       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1940         R.clear();
1941         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1942         // In a hopelessly buggy code, Objective-C instance variable
1943         // lookup fails and no expression will be built to reference it.
1944         if (!E.isInvalid() && !E.get())
1945           return ExprError();
1946         return E;
1947       }
1948     }
1949   }
1950
1951   // This is guaranteed from this point on.
1952   assert(!R.empty() || ADL);
1953
1954   // Check whether this might be a C++ implicit instance member access.
1955   // C++ [class.mfct.non-static]p3:
1956   //   When an id-expression that is not part of a class member access
1957   //   syntax and not used to form a pointer to member is used in the
1958   //   body of a non-static member function of class X, if name lookup
1959   //   resolves the name in the id-expression to a non-static non-type
1960   //   member of some class C, the id-expression is transformed into a
1961   //   class member access expression using (*this) as the
1962   //   postfix-expression to the left of the . operator.
1963   //
1964   // But we don't actually need to do this for '&' operands if R
1965   // resolved to a function or overloaded function set, because the
1966   // expression is ill-formed if it actually works out to be a
1967   // non-static member function:
1968   //
1969   // C++ [expr.ref]p4:
1970   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1971   //   [t]he expression can be used only as the left-hand operand of a
1972   //   member function call.
1973   //
1974   // There are other safeguards against such uses, but it's important
1975   // to get this right here so that we don't end up making a
1976   // spuriously dependent expression if we're inside a dependent
1977   // instance method.
1978   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1979     bool MightBeImplicitMember;
1980     if (!IsAddressOfOperand)
1981       MightBeImplicitMember = true;
1982     else if (!SS.isEmpty())
1983       MightBeImplicitMember = false;
1984     else if (R.isOverloadedResult())
1985       MightBeImplicitMember = false;
1986     else if (R.isUnresolvableResult())
1987       MightBeImplicitMember = true;
1988     else
1989       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1990                               isa<IndirectFieldDecl>(R.getFoundDecl());
1991
1992     if (MightBeImplicitMember)
1993       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1994                                              R, TemplateArgs);
1995   }
1996
1997   if (TemplateArgs || TemplateKWLoc.isValid())
1998     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1999
2000   return BuildDeclarationNameExpr(SS, R, ADL);
2001 }
2002
2003 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
2004 /// declaration name, generally during template instantiation.
2005 /// There's a large number of things which don't need to be done along
2006 /// this path.
2007 ExprResult
2008 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
2009                                         const DeclarationNameInfo &NameInfo,
2010                                         bool IsAddressOfOperand) {
2011   DeclContext *DC = computeDeclContext(SS, false);
2012   if (!DC)
2013     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2014                                      NameInfo, /*TemplateArgs=*/0);
2015
2016   if (RequireCompleteDeclContext(SS, DC))
2017     return ExprError();
2018
2019   LookupResult R(*this, NameInfo, LookupOrdinaryName);
2020   LookupQualifiedName(R, DC);
2021
2022   if (R.isAmbiguous())
2023     return ExprError();
2024
2025   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
2026     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
2027                                      NameInfo, /*TemplateArgs=*/0);
2028
2029   if (R.empty()) {
2030     Diag(NameInfo.getLoc(), diag::err_no_member)
2031       << NameInfo.getName() << DC << SS.getRange();
2032     return ExprError();
2033   }
2034
2035   // Defend against this resolving to an implicit member access. We usually
2036   // won't get here if this might be a legitimate a class member (we end up in
2037   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
2038   // a pointer-to-member or in an unevaluated context in C++11.
2039   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
2040     return BuildPossibleImplicitMemberExpr(SS,
2041                                            /*TemplateKWLoc=*/SourceLocation(),
2042                                            R, /*TemplateArgs=*/0);
2043
2044   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
2045 }
2046
2047 /// LookupInObjCMethod - The parser has read a name in, and Sema has
2048 /// detected that we're currently inside an ObjC method.  Perform some
2049 /// additional lookup.
2050 ///
2051 /// Ideally, most of this would be done by lookup, but there's
2052 /// actually quite a lot of extra work involved.
2053 ///
2054 /// Returns a null sentinel to indicate trivial success.
2055 ExprResult
2056 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
2057                          IdentifierInfo *II, bool AllowBuiltinCreation) {
2058   SourceLocation Loc = Lookup.getNameLoc();
2059   ObjCMethodDecl *CurMethod = getCurMethodDecl();
2060   
2061   // Check for error condition which is already reported.
2062   if (!CurMethod)
2063     return ExprError();
2064
2065   // There are two cases to handle here.  1) scoped lookup could have failed,
2066   // in which case we should look for an ivar.  2) scoped lookup could have
2067   // found a decl, but that decl is outside the current instance method (i.e.
2068   // a global variable).  In these two cases, we do a lookup for an ivar with
2069   // this name, if the lookup sucedes, we replace it our current decl.
2070
2071   // If we're in a class method, we don't normally want to look for
2072   // ivars.  But if we don't find anything else, and there's an
2073   // ivar, that's an error.
2074   bool IsClassMethod = CurMethod->isClassMethod();
2075
2076   bool LookForIvars;
2077   if (Lookup.empty())
2078     LookForIvars = true;
2079   else if (IsClassMethod)
2080     LookForIvars = false;
2081   else
2082     LookForIvars = (Lookup.isSingleResult() &&
2083                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
2084   ObjCInterfaceDecl *IFace = 0;
2085   if (LookForIvars) {
2086     IFace = CurMethod->getClassInterface();
2087     ObjCInterfaceDecl *ClassDeclared;
2088     ObjCIvarDecl *IV = 0;
2089     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
2090       // Diagnose using an ivar in a class method.
2091       if (IsClassMethod)
2092         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2093                          << IV->getDeclName());
2094
2095       // If we're referencing an invalid decl, just return this as a silent
2096       // error node.  The error diagnostic was already emitted on the decl.
2097       if (IV->isInvalidDecl())
2098         return ExprError();
2099
2100       // Check if referencing a field with __attribute__((deprecated)).
2101       if (DiagnoseUseOfDecl(IV, Loc))
2102         return ExprError();
2103
2104       // Diagnose the use of an ivar outside of the declaring class.
2105       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
2106           !declaresSameEntity(ClassDeclared, IFace) &&
2107           !getLangOpts().DebuggerSupport)
2108         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
2109
2110       // FIXME: This should use a new expr for a direct reference, don't
2111       // turn this into Self->ivar, just return a BareIVarExpr or something.
2112       IdentifierInfo &II = Context.Idents.get("self");
2113       UnqualifiedId SelfName;
2114       SelfName.setIdentifier(&II, SourceLocation());
2115       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2116       CXXScopeSpec SelfScopeSpec;
2117       SourceLocation TemplateKWLoc;
2118       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2119                                               SelfName, false, false);
2120       if (SelfExpr.isInvalid())
2121         return ExprError();
2122
2123       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2124       if (SelfExpr.isInvalid())
2125         return ExprError();
2126
2127       MarkAnyDeclReferenced(Loc, IV, true);
2128       
2129       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2130       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize &&
2131           !IvarBacksCurrentMethodAccessor(IFace, CurMethod, IV))
2132         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2133
2134       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2135                                                               Loc, IV->getLocation(),
2136                                                               SelfExpr.take(),
2137                                                               true, true);
2138
2139       if (getLangOpts().ObjCAutoRefCount) {
2140         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2141           DiagnosticsEngine::Level Level =
2142             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2143           if (Level != DiagnosticsEngine::Ignored)
2144             getCurFunction()->recordUseOfWeak(Result);
2145         }
2146         if (CurContext->isClosure())
2147           Diag(Loc, diag::warn_implicitly_retains_self)
2148             << FixItHint::CreateInsertion(Loc, "self->");
2149       }
2150       
2151       return Owned(Result);
2152     }
2153   } else if (CurMethod->isInstanceMethod()) {
2154     // We should warn if a local variable hides an ivar.
2155     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2156       ObjCInterfaceDecl *ClassDeclared;
2157       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2158         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2159             declaresSameEntity(IFace, ClassDeclared))
2160           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2161       }
2162     }
2163   } else if (Lookup.isSingleResult() &&
2164              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2165     // If accessing a stand-alone ivar in a class method, this is an error.
2166     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2167       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2168                        << IV->getDeclName());
2169   }
2170
2171   if (Lookup.empty() && II && AllowBuiltinCreation) {
2172     // FIXME. Consolidate this with similar code in LookupName.
2173     if (unsigned BuiltinID = II->getBuiltinID()) {
2174       if (!(getLangOpts().CPlusPlus &&
2175             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2176         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2177                                            S, Lookup.isForRedeclaration(),
2178                                            Lookup.getNameLoc());
2179         if (D) Lookup.addDecl(D);
2180       }
2181     }
2182   }
2183   // Sentinel value saying that we didn't do anything special.
2184   return Owned((Expr*) 0);
2185 }
2186
2187 /// \brief Cast a base object to a member's actual type.
2188 ///
2189 /// Logically this happens in three phases:
2190 ///
2191 /// * First we cast from the base type to the naming class.
2192 ///   The naming class is the class into which we were looking
2193 ///   when we found the member;  it's the qualifier type if a
2194 ///   qualifier was provided, and otherwise it's the base type.
2195 ///
2196 /// * Next we cast from the naming class to the declaring class.
2197 ///   If the member we found was brought into a class's scope by
2198 ///   a using declaration, this is that class;  otherwise it's
2199 ///   the class declaring the member.
2200 ///
2201 /// * Finally we cast from the declaring class to the "true"
2202 ///   declaring class of the member.  This conversion does not
2203 ///   obey access control.
2204 ExprResult
2205 Sema::PerformObjectMemberConversion(Expr *From,
2206                                     NestedNameSpecifier *Qualifier,
2207                                     NamedDecl *FoundDecl,
2208                                     NamedDecl *Member) {
2209   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2210   if (!RD)
2211     return Owned(From);
2212
2213   QualType DestRecordType;
2214   QualType DestType;
2215   QualType FromRecordType;
2216   QualType FromType = From->getType();
2217   bool PointerConversions = false;
2218   if (isa<FieldDecl>(Member)) {
2219     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2220
2221     if (FromType->getAs<PointerType>()) {
2222       DestType = Context.getPointerType(DestRecordType);
2223       FromRecordType = FromType->getPointeeType();
2224       PointerConversions = true;
2225     } else {
2226       DestType = DestRecordType;
2227       FromRecordType = FromType;
2228     }
2229   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2230     if (Method->isStatic())
2231       return Owned(From);
2232
2233     DestType = Method->getThisType(Context);
2234     DestRecordType = DestType->getPointeeType();
2235
2236     if (FromType->getAs<PointerType>()) {
2237       FromRecordType = FromType->getPointeeType();
2238       PointerConversions = true;
2239     } else {
2240       FromRecordType = FromType;
2241       DestType = DestRecordType;
2242     }
2243   } else {
2244     // No conversion necessary.
2245     return Owned(From);
2246   }
2247
2248   if (DestType->isDependentType() || FromType->isDependentType())
2249     return Owned(From);
2250
2251   // If the unqualified types are the same, no conversion is necessary.
2252   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2253     return Owned(From);
2254
2255   SourceRange FromRange = From->getSourceRange();
2256   SourceLocation FromLoc = FromRange.getBegin();
2257
2258   ExprValueKind VK = From->getValueKind();
2259
2260   // C++ [class.member.lookup]p8:
2261   //   [...] Ambiguities can often be resolved by qualifying a name with its
2262   //   class name.
2263   //
2264   // If the member was a qualified name and the qualified referred to a
2265   // specific base subobject type, we'll cast to that intermediate type
2266   // first and then to the object in which the member is declared. That allows
2267   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2268   //
2269   //   class Base { public: int x; };
2270   //   class Derived1 : public Base { };
2271   //   class Derived2 : public Base { };
2272   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2273   //
2274   //   void VeryDerived::f() {
2275   //     x = 17; // error: ambiguous base subobjects
2276   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2277   //   }
2278   if (Qualifier) {
2279     QualType QType = QualType(Qualifier->getAsType(), 0);
2280     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2281     assert(QType->isRecordType() && "lookup done with non-record type");
2282
2283     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2284
2285     // In C++98, the qualifier type doesn't actually have to be a base
2286     // type of the object type, in which case we just ignore it.
2287     // Otherwise build the appropriate casts.
2288     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2289       CXXCastPath BasePath;
2290       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2291                                        FromLoc, FromRange, &BasePath))
2292         return ExprError();
2293
2294       if (PointerConversions)
2295         QType = Context.getPointerType(QType);
2296       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2297                                VK, &BasePath).take();
2298
2299       FromType = QType;
2300       FromRecordType = QRecordType;
2301
2302       // If the qualifier type was the same as the destination type,
2303       // we're done.
2304       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2305         return Owned(From);
2306     }
2307   }
2308
2309   bool IgnoreAccess = false;
2310
2311   // If we actually found the member through a using declaration, cast
2312   // down to the using declaration's type.
2313   //
2314   // Pointer equality is fine here because only one declaration of a
2315   // class ever has member declarations.
2316   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2317     assert(isa<UsingShadowDecl>(FoundDecl));
2318     QualType URecordType = Context.getTypeDeclType(
2319                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2320
2321     // We only need to do this if the naming-class to declaring-class
2322     // conversion is non-trivial.
2323     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2324       assert(IsDerivedFrom(FromRecordType, URecordType));
2325       CXXCastPath BasePath;
2326       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2327                                        FromLoc, FromRange, &BasePath))
2328         return ExprError();
2329
2330       QualType UType = URecordType;
2331       if (PointerConversions)
2332         UType = Context.getPointerType(UType);
2333       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2334                                VK, &BasePath).take();
2335       FromType = UType;
2336       FromRecordType = URecordType;
2337     }
2338
2339     // We don't do access control for the conversion from the
2340     // declaring class to the true declaring class.
2341     IgnoreAccess = true;
2342   }
2343
2344   CXXCastPath BasePath;
2345   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2346                                    FromLoc, FromRange, &BasePath,
2347                                    IgnoreAccess))
2348     return ExprError();
2349
2350   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2351                            VK, &BasePath);
2352 }
2353
2354 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2355                                       const LookupResult &R,
2356                                       bool HasTrailingLParen) {
2357   // Only when used directly as the postfix-expression of a call.
2358   if (!HasTrailingLParen)
2359     return false;
2360
2361   // Never if a scope specifier was provided.
2362   if (SS.isSet())
2363     return false;
2364
2365   // Only in C++ or ObjC++.
2366   if (!getLangOpts().CPlusPlus)
2367     return false;
2368
2369   // Turn off ADL when we find certain kinds of declarations during
2370   // normal lookup:
2371   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2372     NamedDecl *D = *I;
2373
2374     // C++0x [basic.lookup.argdep]p3:
2375     //     -- a declaration of a class member
2376     // Since using decls preserve this property, we check this on the
2377     // original decl.
2378     if (D->isCXXClassMember())
2379       return false;
2380
2381     // C++0x [basic.lookup.argdep]p3:
2382     //     -- a block-scope function declaration that is not a
2383     //        using-declaration
2384     // NOTE: we also trigger this for function templates (in fact, we
2385     // don't check the decl type at all, since all other decl types
2386     // turn off ADL anyway).
2387     if (isa<UsingShadowDecl>(D))
2388       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2389     else if (D->getDeclContext()->isFunctionOrMethod())
2390       return false;
2391
2392     // C++0x [basic.lookup.argdep]p3:
2393     //     -- a declaration that is neither a function or a function
2394     //        template
2395     // And also for builtin functions.
2396     if (isa<FunctionDecl>(D)) {
2397       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2398
2399       // But also builtin functions.
2400       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2401         return false;
2402     } else if (!isa<FunctionTemplateDecl>(D))
2403       return false;
2404   }
2405
2406   return true;
2407 }
2408
2409
2410 /// Diagnoses obvious problems with the use of the given declaration
2411 /// as an expression.  This is only actually called for lookups that
2412 /// were not overloaded, and it doesn't promise that the declaration
2413 /// will in fact be used.
2414 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2415   if (isa<TypedefNameDecl>(D)) {
2416     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2417     return true;
2418   }
2419
2420   if (isa<ObjCInterfaceDecl>(D)) {
2421     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2422     return true;
2423   }
2424
2425   if (isa<NamespaceDecl>(D)) {
2426     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2427     return true;
2428   }
2429
2430   return false;
2431 }
2432
2433 ExprResult
2434 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2435                                LookupResult &R,
2436                                bool NeedsADL) {
2437   // If this is a single, fully-resolved result and we don't need ADL,
2438   // just build an ordinary singleton decl ref.
2439   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2440     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
2441                                     R.getRepresentativeDecl());
2442
2443   // We only need to check the declaration if there's exactly one
2444   // result, because in the overloaded case the results can only be
2445   // functions and function templates.
2446   if (R.isSingleResult() &&
2447       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2448     return ExprError();
2449
2450   // Otherwise, just build an unresolved lookup expression.  Suppress
2451   // any lookup-related diagnostics; we'll hash these out later, when
2452   // we've picked a target.
2453   R.suppressDiagnostics();
2454
2455   UnresolvedLookupExpr *ULE
2456     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2457                                    SS.getWithLocInContext(Context),
2458                                    R.getLookupNameInfo(),
2459                                    NeedsADL, R.isOverloadedResult(),
2460                                    R.begin(), R.end());
2461
2462   return Owned(ULE);
2463 }
2464
2465 /// \brief Complete semantic analysis for a reference to the given declaration.
2466 ExprResult
2467 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2468                                const DeclarationNameInfo &NameInfo,
2469                                NamedDecl *D, NamedDecl *FoundD) {
2470   assert(D && "Cannot refer to a NULL declaration");
2471   assert(!isa<FunctionTemplateDecl>(D) &&
2472          "Cannot refer unambiguously to a function template");
2473
2474   SourceLocation Loc = NameInfo.getLoc();
2475   if (CheckDeclInExpr(*this, Loc, D))
2476     return ExprError();
2477
2478   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2479     // Specifically diagnose references to class templates that are missing
2480     // a template argument list.
2481     Diag(Loc, diag::err_template_decl_ref)
2482       << Template << SS.getRange();
2483     Diag(Template->getLocation(), diag::note_template_decl_here);
2484     return ExprError();
2485   }
2486
2487   // Make sure that we're referring to a value.
2488   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2489   if (!VD) {
2490     Diag(Loc, diag::err_ref_non_value)
2491       << D << SS.getRange();
2492     Diag(D->getLocation(), diag::note_declared_at);
2493     return ExprError();
2494   }
2495
2496   // Check whether this declaration can be used. Note that we suppress
2497   // this check when we're going to perform argument-dependent lookup
2498   // on this function name, because this might not be the function
2499   // that overload resolution actually selects.
2500   if (DiagnoseUseOfDecl(VD, Loc))
2501     return ExprError();
2502
2503   // Only create DeclRefExpr's for valid Decl's.
2504   if (VD->isInvalidDecl())
2505     return ExprError();
2506
2507   // Handle members of anonymous structs and unions.  If we got here,
2508   // and the reference is to a class member indirect field, then this
2509   // must be the subject of a pointer-to-member expression.
2510   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2511     if (!indirectField->isCXXClassMember())
2512       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2513                                                       indirectField);
2514
2515   {
2516     QualType type = VD->getType();
2517     ExprValueKind valueKind = VK_RValue;
2518
2519     switch (D->getKind()) {
2520     // Ignore all the non-ValueDecl kinds.
2521 #define ABSTRACT_DECL(kind)
2522 #define VALUE(type, base)
2523 #define DECL(type, base) \
2524     case Decl::type:
2525 #include "clang/AST/DeclNodes.inc"
2526       llvm_unreachable("invalid value decl kind");
2527
2528     // These shouldn't make it here.
2529     case Decl::ObjCAtDefsField:
2530     case Decl::ObjCIvar:
2531       llvm_unreachable("forming non-member reference to ivar?");
2532
2533     // Enum constants are always r-values and never references.
2534     // Unresolved using declarations are dependent.
2535     case Decl::EnumConstant:
2536     case Decl::UnresolvedUsingValue:
2537       valueKind = VK_RValue;
2538       break;
2539
2540     // Fields and indirect fields that got here must be for
2541     // pointer-to-member expressions; we just call them l-values for
2542     // internal consistency, because this subexpression doesn't really
2543     // exist in the high-level semantics.
2544     case Decl::Field:
2545     case Decl::IndirectField:
2546       assert(getLangOpts().CPlusPlus &&
2547              "building reference to field in C?");
2548
2549       // These can't have reference type in well-formed programs, but
2550       // for internal consistency we do this anyway.
2551       type = type.getNonReferenceType();
2552       valueKind = VK_LValue;
2553       break;
2554
2555     // Non-type template parameters are either l-values or r-values
2556     // depending on the type.
2557     case Decl::NonTypeTemplateParm: {
2558       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2559         type = reftype->getPointeeType();
2560         valueKind = VK_LValue; // even if the parameter is an r-value reference
2561         break;
2562       }
2563
2564       // For non-references, we need to strip qualifiers just in case
2565       // the template parameter was declared as 'const int' or whatever.
2566       valueKind = VK_RValue;
2567       type = type.getUnqualifiedType();
2568       break;
2569     }
2570
2571     case Decl::Var:
2572       // In C, "extern void blah;" is valid and is an r-value.
2573       if (!getLangOpts().CPlusPlus &&
2574           !type.hasQualifiers() &&
2575           type->isVoidType()) {
2576         valueKind = VK_RValue;
2577         break;
2578       }
2579       // fallthrough
2580
2581     case Decl::ImplicitParam:
2582     case Decl::ParmVar: {
2583       // These are always l-values.
2584       valueKind = VK_LValue;
2585       type = type.getNonReferenceType();
2586
2587       // FIXME: Does the addition of const really only apply in
2588       // potentially-evaluated contexts? Since the variable isn't actually
2589       // captured in an unevaluated context, it seems that the answer is no.
2590       if (!isUnevaluatedContext()) {
2591         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2592         if (!CapturedType.isNull())
2593           type = CapturedType;
2594       }
2595       
2596       break;
2597     }
2598         
2599     case Decl::Function: {
2600       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2601         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2602           type = Context.BuiltinFnTy;
2603           valueKind = VK_RValue;
2604           break;
2605         }
2606       }
2607
2608       const FunctionType *fty = type->castAs<FunctionType>();
2609
2610       // If we're referring to a function with an __unknown_anytype
2611       // result type, make the entire expression __unknown_anytype.
2612       if (fty->getResultType() == Context.UnknownAnyTy) {
2613         type = Context.UnknownAnyTy;
2614         valueKind = VK_RValue;
2615         break;
2616       }
2617
2618       // Functions are l-values in C++.
2619       if (getLangOpts().CPlusPlus) {
2620         valueKind = VK_LValue;
2621         break;
2622       }
2623       
2624       // C99 DR 316 says that, if a function type comes from a
2625       // function definition (without a prototype), that type is only
2626       // used for checking compatibility. Therefore, when referencing
2627       // the function, we pretend that we don't have the full function
2628       // type.
2629       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2630           isa<FunctionProtoType>(fty))
2631         type = Context.getFunctionNoProtoType(fty->getResultType(),
2632                                               fty->getExtInfo());
2633
2634       // Functions are r-values in C.
2635       valueKind = VK_RValue;
2636       break;
2637     }
2638
2639     case Decl::CXXMethod:
2640       // If we're referring to a method with an __unknown_anytype
2641       // result type, make the entire expression __unknown_anytype.
2642       // This should only be possible with a type written directly.
2643       if (const FunctionProtoType *proto
2644             = dyn_cast<FunctionProtoType>(VD->getType()))
2645         if (proto->getResultType() == Context.UnknownAnyTy) {
2646           type = Context.UnknownAnyTy;
2647           valueKind = VK_RValue;
2648           break;
2649         }
2650
2651       // C++ methods are l-values if static, r-values if non-static.
2652       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2653         valueKind = VK_LValue;
2654         break;
2655       }
2656       // fallthrough
2657
2658     case Decl::CXXConversion:
2659     case Decl::CXXDestructor:
2660     case Decl::CXXConstructor:
2661       valueKind = VK_RValue;
2662       break;
2663     }
2664
2665     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS, FoundD);
2666   }
2667 }
2668
2669 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2670   PredefinedExpr::IdentType IT;
2671
2672   switch (Kind) {
2673   default: llvm_unreachable("Unknown simple primary expr!");
2674   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2675   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2676   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2677   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2678   }
2679
2680   // Pre-defined identifiers are of type char[x], where x is the length of the
2681   // string.
2682
2683   Decl *currentDecl = getCurFunctionOrMethodDecl();
2684   // Blocks and lambdas can occur at global scope. Don't emit a warning.
2685   if (!currentDecl) {
2686     if (const BlockScopeInfo *BSI = getCurBlock())
2687       currentDecl = BSI->TheDecl;
2688     else if (const LambdaScopeInfo *LSI = getCurLambda())
2689       currentDecl = LSI->CallOperator;
2690   }
2691
2692   if (!currentDecl) {
2693     Diag(Loc, diag::ext_predef_outside_function);
2694     currentDecl = Context.getTranslationUnitDecl();
2695   }
2696
2697   QualType ResTy;
2698   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2699     ResTy = Context.DependentTy;
2700   } else {
2701     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2702
2703     llvm::APInt LengthI(32, Length + 1);
2704     if (IT == PredefinedExpr::LFunction)
2705       ResTy = Context.WCharTy.withConst();
2706     else
2707       ResTy = Context.CharTy.withConst();
2708     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2709   }
2710   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2711 }
2712
2713 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2714   SmallString<16> CharBuffer;
2715   bool Invalid = false;
2716   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2717   if (Invalid)
2718     return ExprError();
2719
2720   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2721                             PP, Tok.getKind());
2722   if (Literal.hadError())
2723     return ExprError();
2724
2725   QualType Ty;
2726   if (Literal.isWide())
2727     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2728   else if (Literal.isUTF16())
2729     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2730   else if (Literal.isUTF32())
2731     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2732   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2733     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2734   else
2735     Ty = Context.CharTy;  // 'x' -> char in C++
2736
2737   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2738   if (Literal.isWide())
2739     Kind = CharacterLiteral::Wide;
2740   else if (Literal.isUTF16())
2741     Kind = CharacterLiteral::UTF16;
2742   else if (Literal.isUTF32())
2743     Kind = CharacterLiteral::UTF32;
2744
2745   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2746                                              Tok.getLocation());
2747
2748   if (Literal.getUDSuffix().empty())
2749     return Owned(Lit);
2750
2751   // We're building a user-defined literal.
2752   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2753   SourceLocation UDSuffixLoc =
2754     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2755
2756   // Make sure we're allowed user-defined literals here.
2757   if (!UDLScope)
2758     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2759
2760   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2761   //   operator "" X (ch)
2762   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2763                                         llvm::makeArrayRef(&Lit, 1),
2764                                         Tok.getLocation());
2765 }
2766
2767 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2768   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2769   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2770                                       Context.IntTy, Loc));
2771 }
2772
2773 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2774                                   QualType Ty, SourceLocation Loc) {
2775   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2776
2777   using llvm::APFloat;
2778   APFloat Val(Format);
2779
2780   APFloat::opStatus result = Literal.GetFloatValue(Val);
2781
2782   // Overflow is always an error, but underflow is only an error if
2783   // we underflowed to zero (APFloat reports denormals as underflow).
2784   if ((result & APFloat::opOverflow) ||
2785       ((result & APFloat::opUnderflow) && Val.isZero())) {
2786     unsigned diagnostic;
2787     SmallString<20> buffer;
2788     if (result & APFloat::opOverflow) {
2789       diagnostic = diag::warn_float_overflow;
2790       APFloat::getLargest(Format).toString(buffer);
2791     } else {
2792       diagnostic = diag::warn_float_underflow;
2793       APFloat::getSmallest(Format).toString(buffer);
2794     }
2795
2796     S.Diag(Loc, diagnostic)
2797       << Ty
2798       << StringRef(buffer.data(), buffer.size());
2799   }
2800
2801   bool isExact = (result == APFloat::opOK);
2802   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2803 }
2804
2805 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2806   // Fast path for a single digit (which is quite common).  A single digit
2807   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2808   if (Tok.getLength() == 1) {
2809     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2810     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2811   }
2812
2813   SmallString<128> SpellingBuffer;
2814   // NumericLiteralParser wants to overread by one character.  Add padding to
2815   // the buffer in case the token is copied to the buffer.  If getSpelling()
2816   // returns a StringRef to the memory buffer, it should have a null char at
2817   // the EOF, so it is also safe.
2818   SpellingBuffer.resize(Tok.getLength() + 1);
2819
2820   // Get the spelling of the token, which eliminates trigraphs, etc.
2821   bool Invalid = false;
2822   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2823   if (Invalid)
2824     return ExprError();
2825
2826   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2827   if (Literal.hadError)
2828     return ExprError();
2829
2830   if (Literal.hasUDSuffix()) {
2831     // We're building a user-defined literal.
2832     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2833     SourceLocation UDSuffixLoc =
2834       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2835
2836     // Make sure we're allowed user-defined literals here.
2837     if (!UDLScope)
2838       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2839
2840     QualType CookedTy;
2841     if (Literal.isFloatingLiteral()) {
2842       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2843       // long double, the literal is treated as a call of the form
2844       //   operator "" X (f L)
2845       CookedTy = Context.LongDoubleTy;
2846     } else {
2847       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2848       // unsigned long long, the literal is treated as a call of the form
2849       //   operator "" X (n ULL)
2850       CookedTy = Context.UnsignedLongLongTy;
2851     }
2852
2853     DeclarationName OpName =
2854       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2855     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2856     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2857
2858     // Perform literal operator lookup to determine if we're building a raw
2859     // literal or a cooked one.
2860     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2861     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2862                                   /*AllowRawAndTemplate*/true)) {
2863     case LOLR_Error:
2864       return ExprError();
2865
2866     case LOLR_Cooked: {
2867       Expr *Lit;
2868       if (Literal.isFloatingLiteral()) {
2869         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2870       } else {
2871         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2872         if (Literal.GetIntegerValue(ResultVal))
2873           Diag(Tok.getLocation(), diag::warn_integer_too_large);
2874         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2875                                      Tok.getLocation());
2876       }
2877       return BuildLiteralOperatorCall(R, OpNameInfo,
2878                                       llvm::makeArrayRef(&Lit, 1),
2879                                       Tok.getLocation());
2880     }
2881
2882     case LOLR_Raw: {
2883       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2884       // literal is treated as a call of the form
2885       //   operator "" X ("n")
2886       SourceLocation TokLoc = Tok.getLocation();
2887       unsigned Length = Literal.getUDSuffixOffset();
2888       QualType StrTy = Context.getConstantArrayType(
2889           Context.CharTy.withConst(), llvm::APInt(32, Length + 1),
2890           ArrayType::Normal, 0);
2891       Expr *Lit = StringLiteral::Create(
2892           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2893           /*Pascal*/false, StrTy, &TokLoc, 1);
2894       return BuildLiteralOperatorCall(R, OpNameInfo,
2895                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
2896     }
2897
2898     case LOLR_Template:
2899       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2900       // template), L is treated as a call fo the form
2901       //   operator "" X <'c1', 'c2', ... 'ck'>()
2902       // where n is the source character sequence c1 c2 ... ck.
2903       TemplateArgumentListInfo ExplicitArgs;
2904       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2905       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2906       llvm::APSInt Value(CharBits, CharIsUnsigned);
2907       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2908         Value = TokSpelling[I];
2909         TemplateArgument Arg(Context, Value, Context.CharTy);
2910         TemplateArgumentLocInfo ArgInfo;
2911         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2912       }
2913       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2914                                       Tok.getLocation(), &ExplicitArgs);
2915     }
2916
2917     llvm_unreachable("unexpected literal operator lookup result");
2918   }
2919
2920   Expr *Res;
2921
2922   if (Literal.isFloatingLiteral()) {
2923     QualType Ty;
2924     if (Literal.isFloat)
2925       Ty = Context.FloatTy;
2926     else if (!Literal.isLong)
2927       Ty = Context.DoubleTy;
2928     else
2929       Ty = Context.LongDoubleTy;
2930
2931     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2932
2933     if (Ty == Context.DoubleTy) {
2934       if (getLangOpts().SinglePrecisionConstants) {
2935         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2936       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2937         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2938         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2939       }
2940     }
2941   } else if (!Literal.isIntegerLiteral()) {
2942     return ExprError();
2943   } else {
2944     QualType Ty;
2945
2946     // 'long long' is a C99 or C++11 feature.
2947     if (!getLangOpts().C99 && Literal.isLongLong) {
2948       if (getLangOpts().CPlusPlus)
2949         Diag(Tok.getLocation(),
2950              getLangOpts().CPlusPlus11 ?
2951              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2952       else
2953         Diag(Tok.getLocation(), diag::ext_c99_longlong);
2954     }
2955
2956     // Get the value in the widest-possible width.
2957     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2958     // The microsoft literal suffix extensions support 128-bit literals, which
2959     // may be wider than [u]intmax_t.
2960     // FIXME: Actually, they don't. We seem to have accidentally invented the
2961     //        i128 suffix.
2962     if (Literal.isMicrosoftInteger && MaxWidth < 128 &&
2963         PP.getTargetInfo().hasInt128Type())
2964       MaxWidth = 128;
2965     llvm::APInt ResultVal(MaxWidth, 0);
2966
2967     if (Literal.GetIntegerValue(ResultVal)) {
2968       // If this value didn't fit into uintmax_t, warn and force to ull.
2969       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2970       Ty = Context.UnsignedLongLongTy;
2971       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2972              "long long is not intmax_t?");
2973     } else {
2974       // If this value fits into a ULL, try to figure out what else it fits into
2975       // according to the rules of C99 6.4.4.1p5.
2976
2977       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2978       // be an unsigned int.
2979       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2980
2981       // Check from smallest to largest, picking the smallest type we can.
2982       unsigned Width = 0;
2983       if (!Literal.isLong && !Literal.isLongLong) {
2984         // Are int/unsigned possibilities?
2985         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2986
2987         // Does it fit in a unsigned int?
2988         if (ResultVal.isIntN(IntSize)) {
2989           // Does it fit in a signed int?
2990           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2991             Ty = Context.IntTy;
2992           else if (AllowUnsigned)
2993             Ty = Context.UnsignedIntTy;
2994           Width = IntSize;
2995         }
2996       }
2997
2998       // Are long/unsigned long possibilities?
2999       if (Ty.isNull() && !Literal.isLongLong) {
3000         unsigned LongSize = Context.getTargetInfo().getLongWidth();
3001
3002         // Does it fit in a unsigned long?
3003         if (ResultVal.isIntN(LongSize)) {
3004           // Does it fit in a signed long?
3005           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
3006             Ty = Context.LongTy;
3007           else if (AllowUnsigned)
3008             Ty = Context.UnsignedLongTy;
3009           Width = LongSize;
3010         }
3011       }
3012
3013       // Check long long if needed.
3014       if (Ty.isNull()) {
3015         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
3016
3017         // Does it fit in a unsigned long long?
3018         if (ResultVal.isIntN(LongLongSize)) {
3019           // Does it fit in a signed long long?
3020           // To be compatible with MSVC, hex integer literals ending with the
3021           // LL or i64 suffix are always signed in Microsoft mode.
3022           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
3023               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
3024             Ty = Context.LongLongTy;
3025           else if (AllowUnsigned)
3026             Ty = Context.UnsignedLongLongTy;
3027           Width = LongLongSize;
3028         }
3029       }
3030         
3031       // If it doesn't fit in unsigned long long, and we're using Microsoft
3032       // extensions, then its a 128-bit integer literal.
3033       if (Ty.isNull() && Literal.isMicrosoftInteger &&
3034           PP.getTargetInfo().hasInt128Type()) {
3035         if (Literal.isUnsigned)
3036           Ty = Context.UnsignedInt128Ty;
3037         else
3038           Ty = Context.Int128Ty;
3039         Width = 128;
3040       }
3041
3042       // If we still couldn't decide a type, we probably have something that
3043       // does not fit in a signed long long, but has no U suffix.
3044       if (Ty.isNull()) {
3045         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
3046         Ty = Context.UnsignedLongLongTy;
3047         Width = Context.getTargetInfo().getLongLongWidth();
3048       }
3049
3050       if (ResultVal.getBitWidth() != Width)
3051         ResultVal = ResultVal.trunc(Width);
3052     }
3053     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
3054   }
3055
3056   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
3057   if (Literal.isImaginary)
3058     Res = new (Context) ImaginaryLiteral(Res,
3059                                         Context.getComplexType(Res->getType()));
3060
3061   return Owned(Res);
3062 }
3063
3064 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
3065   assert((E != 0) && "ActOnParenExpr() missing expr");
3066   return Owned(new (Context) ParenExpr(L, R, E));
3067 }
3068
3069 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
3070                                          SourceLocation Loc,
3071                                          SourceRange ArgRange) {
3072   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
3073   // scalar or vector data type argument..."
3074   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
3075   // type (C99 6.2.5p18) or void.
3076   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
3077     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
3078       << T << ArgRange;
3079     return true;
3080   }
3081
3082   assert((T->isVoidType() || !T->isIncompleteType()) &&
3083          "Scalar types should always be complete");
3084   return false;
3085 }
3086
3087 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
3088                                            SourceLocation Loc,
3089                                            SourceRange ArgRange,
3090                                            UnaryExprOrTypeTrait TraitKind) {
3091   // C99 6.5.3.4p1:
3092   if (T->isFunctionType() &&
3093       (TraitKind == UETT_SizeOf || TraitKind == UETT_AlignOf)) {
3094     // sizeof(function)/alignof(function) is allowed as an extension.
3095     S.Diag(Loc, diag::ext_sizeof_alignof_function_type)
3096       << TraitKind << ArgRange;
3097     return false;
3098   }
3099
3100   // Allow sizeof(void)/alignof(void) as an extension.
3101   if (T->isVoidType()) {
3102     S.Diag(Loc, diag::ext_sizeof_alignof_void_type) << TraitKind << ArgRange;
3103     return false;
3104   }
3105
3106   return true;
3107 }
3108
3109 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
3110                                              SourceLocation Loc,
3111                                              SourceRange ArgRange,
3112                                              UnaryExprOrTypeTrait TraitKind) {
3113   // Reject sizeof(interface) and sizeof(interface<proto>) if the
3114   // runtime doesn't allow it.
3115   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
3116     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
3117       << T << (TraitKind == UETT_SizeOf)
3118       << ArgRange;
3119     return true;
3120   }
3121
3122   return false;
3123 }
3124
3125 /// \brief Check whether E is a pointer from a decayed array type (the decayed
3126 /// pointer type is equal to T) and emit a warning if it is.
3127 static void warnOnSizeofOnArrayDecay(Sema &S, SourceLocation Loc, QualType T,
3128                                      Expr *E) {
3129   // Don't warn if the operation changed the type.
3130   if (T != E->getType())
3131     return;
3132
3133   // Now look for array decays.
3134   ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E);
3135   if (!ICE || ICE->getCastKind() != CK_ArrayToPointerDecay)
3136     return;
3137
3138   S.Diag(Loc, diag::warn_sizeof_array_decay) << ICE->getSourceRange()
3139                                              << ICE->getType()
3140                                              << ICE->getSubExpr()->getType();
3141 }
3142
3143 /// \brief Check the constrains on expression operands to unary type expression
3144 /// and type traits.
3145 ///
3146 /// Completes any types necessary and validates the constraints on the operand
3147 /// expression. The logic mostly mirrors the type-based overload, but may modify
3148 /// the expression as it completes the type for that expression through template
3149 /// instantiation, etc.
3150 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3151                                             UnaryExprOrTypeTrait ExprKind) {
3152   QualType ExprTy = E->getType();
3153
3154   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3155   //   the result is the size of the referenced type."
3156   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3157   //   result shall be the alignment of the referenced type."
3158   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3159     ExprTy = Ref->getPointeeType();
3160
3161   if (ExprKind == UETT_VecStep)
3162     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3163                                         E->getSourceRange());
3164
3165   // Whitelist some types as extensions
3166   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3167                                       E->getSourceRange(), ExprKind))
3168     return false;
3169
3170   if (RequireCompleteExprType(E,
3171                               diag::err_sizeof_alignof_incomplete_type,
3172                               ExprKind, E->getSourceRange()))
3173     return true;
3174
3175   // Completeing the expression's type may have changed it.
3176   ExprTy = E->getType();
3177   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3178     ExprTy = Ref->getPointeeType();
3179
3180   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3181                                        E->getSourceRange(), ExprKind))
3182     return true;
3183
3184   if (ExprKind == UETT_SizeOf) {
3185     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3186       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3187         QualType OType = PVD->getOriginalType();
3188         QualType Type = PVD->getType();
3189         if (Type->isPointerType() && OType->isArrayType()) {
3190           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3191             << Type << OType;
3192           Diag(PVD->getLocation(), diag::note_declared_at);
3193         }
3194       }
3195     }
3196
3197     // Warn on "sizeof(array op x)" and "sizeof(x op array)", where the array
3198     // decays into a pointer and returns an unintended result. This is most
3199     // likely a typo for "sizeof(array) op x".
3200     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E->IgnoreParens())) {
3201       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3202                                BO->getLHS());
3203       warnOnSizeofOnArrayDecay(*this, BO->getOperatorLoc(), BO->getType(),
3204                                BO->getRHS());
3205     }
3206   }
3207
3208   return false;
3209 }
3210
3211 /// \brief Check the constraints on operands to unary expression and type
3212 /// traits.
3213 ///
3214 /// This will complete any types necessary, and validate the various constraints
3215 /// on those operands.
3216 ///
3217 /// The UsualUnaryConversions() function is *not* called by this routine.
3218 /// C99 6.3.2.1p[2-4] all state:
3219 ///   Except when it is the operand of the sizeof operator ...
3220 ///
3221 /// C++ [expr.sizeof]p4
3222 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3223 ///   standard conversions are not applied to the operand of sizeof.
3224 ///
3225 /// This policy is followed for all of the unary trait expressions.
3226 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3227                                             SourceLocation OpLoc,
3228                                             SourceRange ExprRange,
3229                                             UnaryExprOrTypeTrait ExprKind) {
3230   if (ExprType->isDependentType())
3231     return false;
3232
3233   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3234   //   the result is the size of the referenced type."
3235   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3236   //   result shall be the alignment of the referenced type."
3237   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3238     ExprType = Ref->getPointeeType();
3239
3240   if (ExprKind == UETT_VecStep)
3241     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3242
3243   // Whitelist some types as extensions
3244   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3245                                       ExprKind))
3246     return false;
3247
3248   if (RequireCompleteType(OpLoc, ExprType,
3249                           diag::err_sizeof_alignof_incomplete_type,
3250                           ExprKind, ExprRange))
3251     return true;
3252
3253   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3254                                        ExprKind))
3255     return true;
3256
3257   return false;
3258 }
3259
3260 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3261   E = E->IgnoreParens();
3262
3263   // alignof decl is always ok.
3264   if (isa<DeclRefExpr>(E))
3265     return false;
3266
3267   // Cannot know anything else if the expression is dependent.
3268   if (E->isTypeDependent())
3269     return false;
3270
3271   if (E->getBitField()) {
3272     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3273        << 1 << E->getSourceRange();
3274     return true;
3275   }
3276
3277   // Alignment of a field access is always okay, so long as it isn't a
3278   // bit-field.
3279   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3280     if (isa<FieldDecl>(ME->getMemberDecl()))
3281       return false;
3282
3283   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3284 }
3285
3286 bool Sema::CheckVecStepExpr(Expr *E) {
3287   E = E->IgnoreParens();
3288
3289   // Cannot know anything else if the expression is dependent.
3290   if (E->isTypeDependent())
3291     return false;
3292
3293   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3294 }
3295
3296 /// \brief Build a sizeof or alignof expression given a type operand.
3297 ExprResult
3298 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3299                                      SourceLocation OpLoc,
3300                                      UnaryExprOrTypeTrait ExprKind,
3301                                      SourceRange R) {
3302   if (!TInfo)
3303     return ExprError();
3304
3305   QualType T = TInfo->getType();
3306
3307   if (!T->isDependentType() &&
3308       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3309     return ExprError();
3310
3311   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3312   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3313                                                       Context.getSizeType(),
3314                                                       OpLoc, R.getEnd()));
3315 }
3316
3317 /// \brief Build a sizeof or alignof expression given an expression
3318 /// operand.
3319 ExprResult
3320 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3321                                      UnaryExprOrTypeTrait ExprKind) {
3322   ExprResult PE = CheckPlaceholderExpr(E);
3323   if (PE.isInvalid()) 
3324     return ExprError();
3325
3326   E = PE.get();
3327   
3328   // Verify that the operand is valid.
3329   bool isInvalid = false;
3330   if (E->isTypeDependent()) {
3331     // Delay type-checking for type-dependent expressions.
3332   } else if (ExprKind == UETT_AlignOf) {
3333     isInvalid = CheckAlignOfExpr(*this, E);
3334   } else if (ExprKind == UETT_VecStep) {
3335     isInvalid = CheckVecStepExpr(E);
3336   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3337     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3338     isInvalid = true;
3339   } else {
3340     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3341   }
3342
3343   if (isInvalid)
3344     return ExprError();
3345
3346   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3347     PE = TransformToPotentiallyEvaluated(E);
3348     if (PE.isInvalid()) return ExprError();
3349     E = PE.take();
3350   }
3351
3352   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3353   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3354       ExprKind, E, Context.getSizeType(), OpLoc,
3355       E->getSourceRange().getEnd()));
3356 }
3357
3358 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3359 /// expr and the same for @c alignof and @c __alignof
3360 /// Note that the ArgRange is invalid if isType is false.
3361 ExprResult
3362 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3363                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3364                                     void *TyOrEx, const SourceRange &ArgRange) {
3365   // If error parsing type, ignore.
3366   if (TyOrEx == 0) return ExprError();
3367
3368   if (IsType) {
3369     TypeSourceInfo *TInfo;
3370     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3371     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3372   }
3373
3374   Expr *ArgEx = (Expr *)TyOrEx;
3375   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3376   return Result;
3377 }
3378
3379 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3380                                      bool IsReal) {
3381   if (V.get()->isTypeDependent())
3382     return S.Context.DependentTy;
3383
3384   // _Real and _Imag are only l-values for normal l-values.
3385   if (V.get()->getObjectKind() != OK_Ordinary) {
3386     V = S.DefaultLvalueConversion(V.take());
3387     if (V.isInvalid())
3388       return QualType();
3389   }
3390
3391   // These operators return the element type of a complex type.
3392   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3393     return CT->getElementType();
3394
3395   // Otherwise they pass through real integer and floating point types here.
3396   if (V.get()->getType()->isArithmeticType())
3397     return V.get()->getType();
3398
3399   // Test for placeholders.
3400   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3401   if (PR.isInvalid()) return QualType();
3402   if (PR.get() != V.get()) {
3403     V = PR;
3404     return CheckRealImagOperand(S, V, Loc, IsReal);
3405   }
3406
3407   // Reject anything else.
3408   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3409     << (IsReal ? "__real" : "__imag");
3410   return QualType();
3411 }
3412
3413
3414
3415 ExprResult
3416 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3417                           tok::TokenKind Kind, Expr *Input) {
3418   UnaryOperatorKind Opc;
3419   switch (Kind) {
3420   default: llvm_unreachable("Unknown unary op!");
3421   case tok::plusplus:   Opc = UO_PostInc; break;
3422   case tok::minusminus: Opc = UO_PostDec; break;
3423   }
3424
3425   // Since this might is a postfix expression, get rid of ParenListExprs.
3426   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3427   if (Result.isInvalid()) return ExprError();
3428   Input = Result.take();
3429
3430   return BuildUnaryOp(S, OpLoc, Opc, Input);
3431 }
3432
3433 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3434 ///
3435 /// \return true on error
3436 static bool checkArithmeticOnObjCPointer(Sema &S,
3437                                          SourceLocation opLoc,
3438                                          Expr *op) {
3439   assert(op->getType()->isObjCObjectPointerType());
3440   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3441     return false;
3442
3443   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3444     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3445     << op->getSourceRange();
3446   return true;
3447 }
3448
3449 ExprResult
3450 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *base, SourceLocation lbLoc,
3451                               Expr *idx, SourceLocation rbLoc) {
3452   // Since this might be a postfix expression, get rid of ParenListExprs.
3453   if (isa<ParenListExpr>(base)) {
3454     ExprResult result = MaybeConvertParenListExprToParenExpr(S, base);
3455     if (result.isInvalid()) return ExprError();
3456     base = result.take();
3457   }
3458
3459   // Handle any non-overload placeholder types in the base and index
3460   // expressions.  We can't handle overloads here because the other
3461   // operand might be an overloadable type, in which case the overload
3462   // resolution for the operator overload should get the first crack
3463   // at the overload.
3464   if (base->getType()->isNonOverloadPlaceholderType()) {
3465     ExprResult result = CheckPlaceholderExpr(base);
3466     if (result.isInvalid()) return ExprError();
3467     base = result.take();
3468   }
3469   if (idx->getType()->isNonOverloadPlaceholderType()) {
3470     ExprResult result = CheckPlaceholderExpr(idx);
3471     if (result.isInvalid()) return ExprError();
3472     idx = result.take();
3473   }
3474
3475   // Build an unanalyzed expression if either operand is type-dependent.
3476   if (getLangOpts().CPlusPlus &&
3477       (base->isTypeDependent() || idx->isTypeDependent())) {
3478     return Owned(new (Context) ArraySubscriptExpr(base, idx,
3479                                                   Context.DependentTy,
3480                                                   VK_LValue, OK_Ordinary,
3481                                                   rbLoc));
3482   }
3483
3484   // Use C++ overloaded-operator rules if either operand has record
3485   // type.  The spec says to do this if either type is *overloadable*,
3486   // but enum types can't declare subscript operators or conversion
3487   // operators, so there's nothing interesting for overload resolution
3488   // to do if there aren't any record types involved.
3489   //
3490   // ObjC pointers have their own subscripting logic that is not tied
3491   // to overload resolution and so should not take this path.
3492   if (getLangOpts().CPlusPlus &&
3493       (base->getType()->isRecordType() ||
3494        (!base->getType()->isObjCObjectPointerType() &&
3495         idx->getType()->isRecordType()))) {
3496     return CreateOverloadedArraySubscriptExpr(lbLoc, rbLoc, base, idx);
3497   }
3498
3499   return CreateBuiltinArraySubscriptExpr(base, lbLoc, idx, rbLoc);
3500 }
3501
3502 ExprResult
3503 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3504                                       Expr *Idx, SourceLocation RLoc) {
3505   Expr *LHSExp = Base;
3506   Expr *RHSExp = Idx;
3507
3508   // Perform default conversions.
3509   if (!LHSExp->getType()->getAs<VectorType>()) {
3510     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3511     if (Result.isInvalid())
3512       return ExprError();
3513     LHSExp = Result.take();
3514   }
3515   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3516   if (Result.isInvalid())
3517     return ExprError();
3518   RHSExp = Result.take();
3519
3520   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3521   ExprValueKind VK = VK_LValue;
3522   ExprObjectKind OK = OK_Ordinary;
3523
3524   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3525   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3526   // in the subscript position. As a result, we need to derive the array base
3527   // and index from the expression types.
3528   Expr *BaseExpr, *IndexExpr;
3529   QualType ResultType;
3530   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3531     BaseExpr = LHSExp;
3532     IndexExpr = RHSExp;
3533     ResultType = Context.DependentTy;
3534   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3535     BaseExpr = LHSExp;
3536     IndexExpr = RHSExp;
3537     ResultType = PTy->getPointeeType();
3538   } else if (const ObjCObjectPointerType *PTy =
3539                LHSTy->getAs<ObjCObjectPointerType>()) {
3540     BaseExpr = LHSExp;
3541     IndexExpr = RHSExp;
3542
3543     // Use custom logic if this should be the pseudo-object subscript
3544     // expression.
3545     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3546       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3547
3548     ResultType = PTy->getPointeeType();
3549     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3550       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3551         << ResultType << BaseExpr->getSourceRange();
3552       return ExprError();
3553     }
3554   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3555      // Handle the uncommon case of "123[Ptr]".
3556     BaseExpr = RHSExp;
3557     IndexExpr = LHSExp;
3558     ResultType = PTy->getPointeeType();
3559   } else if (const ObjCObjectPointerType *PTy =
3560                RHSTy->getAs<ObjCObjectPointerType>()) {
3561      // Handle the uncommon case of "123[Ptr]".
3562     BaseExpr = RHSExp;
3563     IndexExpr = LHSExp;
3564     ResultType = PTy->getPointeeType();
3565     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3566       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3567         << ResultType << BaseExpr->getSourceRange();
3568       return ExprError();
3569     }
3570   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3571     BaseExpr = LHSExp;    // vectors: V[123]
3572     IndexExpr = RHSExp;
3573     VK = LHSExp->getValueKind();
3574     if (VK != VK_RValue)
3575       OK = OK_VectorComponent;
3576
3577     // FIXME: need to deal with const...
3578     ResultType = VTy->getElementType();
3579   } else if (LHSTy->isArrayType()) {
3580     // If we see an array that wasn't promoted by
3581     // DefaultFunctionArrayLvalueConversion, it must be an array that
3582     // wasn't promoted because of the C90 rule that doesn't
3583     // allow promoting non-lvalue arrays.  Warn, then
3584     // force the promotion here.
3585     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3586         LHSExp->getSourceRange();
3587     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3588                                CK_ArrayToPointerDecay).take();
3589     LHSTy = LHSExp->getType();
3590
3591     BaseExpr = LHSExp;
3592     IndexExpr = RHSExp;
3593     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3594   } else if (RHSTy->isArrayType()) {
3595     // Same as previous, except for 123[f().a] case
3596     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3597         RHSExp->getSourceRange();
3598     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3599                                CK_ArrayToPointerDecay).take();
3600     RHSTy = RHSExp->getType();
3601
3602     BaseExpr = RHSExp;
3603     IndexExpr = LHSExp;
3604     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3605   } else {
3606     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3607        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3608   }
3609   // C99 6.5.2.1p1
3610   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3611     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3612                      << IndexExpr->getSourceRange());
3613
3614   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3615        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3616          && !IndexExpr->isTypeDependent())
3617     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3618
3619   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3620   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3621   // type. Note that Functions are not objects, and that (in C99 parlance)
3622   // incomplete types are not object types.
3623   if (ResultType->isFunctionType()) {
3624     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3625       << ResultType << BaseExpr->getSourceRange();
3626     return ExprError();
3627   }
3628
3629   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3630     // GNU extension: subscripting on pointer to void
3631     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3632       << BaseExpr->getSourceRange();
3633
3634     // C forbids expressions of unqualified void type from being l-values.
3635     // See IsCForbiddenLValueType.
3636     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3637   } else if (!ResultType->isDependentType() &&
3638       RequireCompleteType(LLoc, ResultType,
3639                           diag::err_subscript_incomplete_type, BaseExpr))
3640     return ExprError();
3641
3642   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3643          !ResultType.isCForbiddenLValueType());
3644
3645   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3646                                                 ResultType, VK, OK, RLoc));
3647 }
3648
3649 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3650                                         FunctionDecl *FD,
3651                                         ParmVarDecl *Param) {
3652   if (Param->hasUnparsedDefaultArg()) {
3653     Diag(CallLoc,
3654          diag::err_use_of_default_argument_to_function_declared_later) <<
3655       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3656     Diag(UnparsedDefaultArgLocs[Param],
3657          diag::note_default_argument_declared_here);
3658     return ExprError();
3659   }
3660   
3661   if (Param->hasUninstantiatedDefaultArg()) {
3662     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3663
3664     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3665                                                  Param);
3666
3667     // Instantiate the expression.
3668     MultiLevelTemplateArgumentList ArgList
3669       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3670
3671     std::pair<const TemplateArgument *, unsigned> Innermost
3672       = ArgList.getInnermost();
3673     InstantiatingTemplate Inst(*this, CallLoc, Param,
3674                                ArrayRef<TemplateArgument>(Innermost.first,
3675                                                           Innermost.second));
3676     if (Inst)
3677       return ExprError();
3678
3679     ExprResult Result;
3680     {
3681       // C++ [dcl.fct.default]p5:
3682       //   The names in the [default argument] expression are bound, and
3683       //   the semantic constraints are checked, at the point where the
3684       //   default argument expression appears.
3685       ContextRAII SavedContext(*this, FD);
3686       LocalInstantiationScope Local(*this);
3687       Result = SubstExpr(UninstExpr, ArgList);
3688     }
3689     if (Result.isInvalid())
3690       return ExprError();
3691
3692     // Check the expression as an initializer for the parameter.
3693     InitializedEntity Entity
3694       = InitializedEntity::InitializeParameter(Context, Param);
3695     InitializationKind Kind
3696       = InitializationKind::CreateCopy(Param->getLocation(),
3697              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3698     Expr *ResultE = Result.takeAs<Expr>();
3699
3700     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3701     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3702     if (Result.isInvalid())
3703       return ExprError();
3704
3705     Expr *Arg = Result.takeAs<Expr>();
3706     CheckCompletedExpr(Arg, Param->getOuterLocStart());
3707     // Build the default argument expression.
3708     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3709   }
3710
3711   // If the default expression creates temporaries, we need to
3712   // push them to the current stack of expression temporaries so they'll
3713   // be properly destroyed.
3714   // FIXME: We should really be rebuilding the default argument with new
3715   // bound temporaries; see the comment in PR5810.
3716   // We don't need to do that with block decls, though, because
3717   // blocks in default argument expression can never capture anything.
3718   if (isa<ExprWithCleanups>(Param->getInit())) {
3719     // Set the "needs cleanups" bit regardless of whether there are
3720     // any explicit objects.
3721     ExprNeedsCleanups = true;
3722
3723     // Append all the objects to the cleanup list.  Right now, this
3724     // should always be a no-op, because blocks in default argument
3725     // expressions should never be able to capture anything.
3726     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3727            "default argument expression has capturing blocks?");
3728   }
3729
3730   // We already type-checked the argument, so we know it works. 
3731   // Just mark all of the declarations in this potentially-evaluated expression
3732   // as being "referenced".
3733   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3734                                    /*SkipLocalVariables=*/true);
3735   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3736 }
3737
3738
3739 Sema::VariadicCallType
3740 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3741                           Expr *Fn) {
3742   if (Proto && Proto->isVariadic()) {
3743     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3744       return VariadicConstructor;
3745     else if (Fn && Fn->getType()->isBlockPointerType())
3746       return VariadicBlock;
3747     else if (FDecl) {
3748       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3749         if (Method->isInstance())
3750           return VariadicMethod;
3751     }
3752     return VariadicFunction;
3753   }
3754   return VariadicDoesNotApply;
3755 }
3756
3757 /// ConvertArgumentsForCall - Converts the arguments specified in
3758 /// Args/NumArgs to the parameter types of the function FDecl with
3759 /// function prototype Proto. Call is the call expression itself, and
3760 /// Fn is the function expression. For a C++ member function, this
3761 /// routine does not attempt to convert the object argument. Returns
3762 /// true if the call is ill-formed.
3763 bool
3764 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3765                               FunctionDecl *FDecl,
3766                               const FunctionProtoType *Proto,
3767                               Expr **Args, unsigned NumArgs,
3768                               SourceLocation RParenLoc,
3769                               bool IsExecConfig) {
3770   // Bail out early if calling a builtin with custom typechecking.
3771   // We don't need to do this in the 
3772   if (FDecl)
3773     if (unsigned ID = FDecl->getBuiltinID())
3774       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3775         return false;
3776
3777   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3778   // assignment, to the types of the corresponding parameter, ...
3779   unsigned NumArgsInProto = Proto->getNumArgs();
3780   bool Invalid = false;
3781   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3782   unsigned FnKind = Fn->getType()->isBlockPointerType()
3783                        ? 1 /* block */
3784                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3785                                        : 0 /* function */);
3786
3787   // If too few arguments are available (and we don't have default
3788   // arguments for the remaining parameters), don't make the call.
3789   if (NumArgs < NumArgsInProto) {
3790     if (NumArgs < MinArgs) {
3791       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3792         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3793                           ? diag::err_typecheck_call_too_few_args_one
3794                           : diag::err_typecheck_call_too_few_args_at_least_one)
3795           << FnKind
3796           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3797       else
3798         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3799                           ? diag::err_typecheck_call_too_few_args
3800                           : diag::err_typecheck_call_too_few_args_at_least)
3801           << FnKind
3802           << MinArgs << NumArgs << Fn->getSourceRange();
3803
3804       // Emit the location of the prototype.
3805       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3806         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3807           << FDecl;
3808
3809       return true;
3810     }
3811     Call->setNumArgs(Context, NumArgsInProto);
3812   }
3813
3814   // If too many are passed and not variadic, error on the extras and drop
3815   // them.
3816   if (NumArgs > NumArgsInProto) {
3817     if (!Proto->isVariadic()) {
3818       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3819         Diag(Args[NumArgsInProto]->getLocStart(),
3820              MinArgs == NumArgsInProto
3821                ? diag::err_typecheck_call_too_many_args_one
3822                : diag::err_typecheck_call_too_many_args_at_most_one)
3823           << FnKind
3824           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3825           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3826                          Args[NumArgs-1]->getLocEnd());
3827       else
3828         Diag(Args[NumArgsInProto]->getLocStart(),
3829              MinArgs == NumArgsInProto
3830                ? diag::err_typecheck_call_too_many_args
3831                : diag::err_typecheck_call_too_many_args_at_most)
3832           << FnKind
3833           << NumArgsInProto << NumArgs << Fn->getSourceRange()
3834           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3835                          Args[NumArgs-1]->getLocEnd());
3836
3837       // Emit the location of the prototype.
3838       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3839         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3840           << FDecl;
3841       
3842       // This deletes the extra arguments.
3843       Call->setNumArgs(Context, NumArgsInProto);
3844       return true;
3845     }
3846   }
3847   SmallVector<Expr *, 8> AllArgs;
3848   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3849   
3850   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3851                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3852   if (Invalid)
3853     return true;
3854   unsigned TotalNumArgs = AllArgs.size();
3855   for (unsigned i = 0; i < TotalNumArgs; ++i)
3856     Call->setArg(i, AllArgs[i]);
3857
3858   return false;
3859 }
3860
3861 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3862                                   FunctionDecl *FDecl,
3863                                   const FunctionProtoType *Proto,
3864                                   unsigned FirstProtoArg,
3865                                   Expr **Args, unsigned NumArgs,
3866                                   SmallVector<Expr *, 8> &AllArgs,
3867                                   VariadicCallType CallType,
3868                                   bool AllowExplicit,
3869                                   bool IsListInitialization) {
3870   unsigned NumArgsInProto = Proto->getNumArgs();
3871   unsigned NumArgsToCheck = NumArgs;
3872   bool Invalid = false;
3873   if (NumArgs != NumArgsInProto)
3874     // Use default arguments for missing arguments
3875     NumArgsToCheck = NumArgsInProto;
3876   unsigned ArgIx = 0;
3877   // Continue to check argument types (even if we have too few/many args).
3878   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3879     QualType ProtoArgType = Proto->getArgType(i);
3880
3881     Expr *Arg;
3882     ParmVarDecl *Param;
3883     if (ArgIx < NumArgs) {
3884       Arg = Args[ArgIx++];
3885
3886       if (RequireCompleteType(Arg->getLocStart(),
3887                               ProtoArgType,
3888                               diag::err_call_incomplete_argument, Arg))
3889         return true;
3890
3891       // Pass the argument
3892       Param = 0;
3893       if (FDecl && i < FDecl->getNumParams())
3894         Param = FDecl->getParamDecl(i);
3895
3896       // Strip the unbridged-cast placeholder expression off, if applicable.
3897       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3898           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3899           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3900         Arg = stripARCUnbridgedCast(Arg);
3901
3902       InitializedEntity Entity = Param ?
3903           InitializedEntity::InitializeParameter(Context, Param, ProtoArgType)
3904         : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3905                                                  Proto->isArgConsumed(i));
3906       ExprResult ArgE = PerformCopyInitialization(Entity,
3907                                                   SourceLocation(),
3908                                                   Owned(Arg),
3909                                                   IsListInitialization,
3910                                                   AllowExplicit);
3911       if (ArgE.isInvalid())
3912         return true;
3913
3914       Arg = ArgE.takeAs<Expr>();
3915     } else {
3916       assert(FDecl && "can't use default arguments without a known callee");
3917       Param = FDecl->getParamDecl(i);
3918
3919       ExprResult ArgExpr =
3920         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3921       if (ArgExpr.isInvalid())
3922         return true;
3923
3924       Arg = ArgExpr.takeAs<Expr>();
3925     }
3926
3927     // Check for array bounds violations for each argument to the call. This
3928     // check only triggers warnings when the argument isn't a more complex Expr
3929     // with its own checking, such as a BinaryOperator.
3930     CheckArrayAccess(Arg);
3931
3932     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3933     CheckStaticArrayArgument(CallLoc, Param, Arg);
3934
3935     AllArgs.push_back(Arg);
3936   }
3937
3938   // If this is a variadic call, handle args passed through "...".
3939   if (CallType != VariadicDoesNotApply) {
3940     // Assume that extern "C" functions with variadic arguments that
3941     // return __unknown_anytype aren't *really* variadic.
3942     if (Proto->getResultType() == Context.UnknownAnyTy &&
3943         FDecl && FDecl->isExternC()) {
3944       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3945         QualType paramType; // ignored
3946         ExprResult arg = checkUnknownAnyArg(CallLoc, Args[i], paramType);
3947         Invalid |= arg.isInvalid();
3948         AllArgs.push_back(arg.take());
3949       }
3950
3951     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3952     } else {
3953       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3954         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3955                                                           FDecl);
3956         Invalid |= Arg.isInvalid();
3957         AllArgs.push_back(Arg.take());
3958       }
3959     }
3960
3961     // Check for array bounds violations.
3962     for (unsigned i = ArgIx; i != NumArgs; ++i)
3963       CheckArrayAccess(Args[i]);
3964   }
3965   return Invalid;
3966 }
3967
3968 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3969   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3970   if (ArrayTypeLoc ATL = TL.getAs<ArrayTypeLoc>())
3971     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3972       << ATL.getLocalSourceRange();
3973 }
3974
3975 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3976 /// array parameter, check that it is non-null, and that if it is formed by
3977 /// array-to-pointer decay, the underlying array is sufficiently large.
3978 ///
3979 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3980 /// array type derivation, then for each call to the function, the value of the
3981 /// corresponding actual argument shall provide access to the first element of
3982 /// an array with at least as many elements as specified by the size expression.
3983 void
3984 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3985                                ParmVarDecl *Param,
3986                                const Expr *ArgExpr) {
3987   // Static array parameters are not supported in C++.
3988   if (!Param || getLangOpts().CPlusPlus)
3989     return;
3990
3991   QualType OrigTy = Param->getOriginalType();
3992
3993   const ArrayType *AT = Context.getAsArrayType(OrigTy);
3994   if (!AT || AT->getSizeModifier() != ArrayType::Static)
3995     return;
3996
3997   if (ArgExpr->isNullPointerConstant(Context,
3998                                      Expr::NPC_NeverValueDependent)) {
3999     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
4000     DiagnoseCalleeStaticArrayParam(*this, Param);
4001     return;
4002   }
4003
4004   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
4005   if (!CAT)
4006     return;
4007
4008   const ConstantArrayType *ArgCAT =
4009     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
4010   if (!ArgCAT)
4011     return;
4012
4013   if (ArgCAT->getSize().ult(CAT->getSize())) {
4014     Diag(CallLoc, diag::warn_static_array_too_small)
4015       << ArgExpr->getSourceRange()
4016       << (unsigned) ArgCAT->getSize().getZExtValue()
4017       << (unsigned) CAT->getSize().getZExtValue();
4018     DiagnoseCalleeStaticArrayParam(*this, Param);
4019   }
4020 }
4021
4022 /// Given a function expression of unknown-any type, try to rebuild it
4023 /// to have a function type.
4024 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
4025
4026 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
4027 /// This provides the location of the left/right parens and a list of comma
4028 /// locations.
4029 ExprResult
4030 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
4031                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
4032                     Expr *ExecConfig, bool IsExecConfig) {
4033   // Since this might be a postfix expression, get rid of ParenListExprs.
4034   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
4035   if (Result.isInvalid()) return ExprError();
4036   Fn = Result.take();
4037
4038   if (getLangOpts().CPlusPlus) {
4039     // If this is a pseudo-destructor expression, build the call immediately.
4040     if (isa<CXXPseudoDestructorExpr>(Fn)) {
4041       if (!ArgExprs.empty()) {
4042         // Pseudo-destructor calls should not have any arguments.
4043         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
4044           << FixItHint::CreateRemoval(
4045                                     SourceRange(ArgExprs[0]->getLocStart(),
4046                                                 ArgExprs.back()->getLocEnd()));
4047       }
4048
4049       return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
4050                                           Context.VoidTy, VK_RValue,
4051                                           RParenLoc));
4052     }
4053
4054     // Determine whether this is a dependent call inside a C++ template,
4055     // in which case we won't do any semantic analysis now.
4056     // FIXME: Will need to cache the results of name lookup (including ADL) in
4057     // Fn.
4058     bool Dependent = false;
4059     if (Fn->isTypeDependent())
4060       Dependent = true;
4061     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
4062       Dependent = true;
4063
4064     if (Dependent) {
4065       if (ExecConfig) {
4066         return Owned(new (Context) CUDAKernelCallExpr(
4067             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
4068             Context.DependentTy, VK_RValue, RParenLoc));
4069       } else {
4070         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
4071                                             Context.DependentTy, VK_RValue,
4072                                             RParenLoc));
4073       }
4074     }
4075
4076     // Determine whether this is a call to an object (C++ [over.call.object]).
4077     if (Fn->getType()->isRecordType())
4078       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
4079                                                 ArgExprs.data(),
4080                                                 ArgExprs.size(), RParenLoc));
4081
4082     if (Fn->getType() == Context.UnknownAnyTy) {
4083       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4084       if (result.isInvalid()) return ExprError();
4085       Fn = result.take();
4086     }
4087
4088     if (Fn->getType() == Context.BoundMemberTy) {
4089       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4090                                        ArgExprs.size(), RParenLoc);
4091     }
4092   }
4093
4094   // Check for overloaded calls.  This can happen even in C due to extensions.
4095   if (Fn->getType() == Context.OverloadTy) {
4096     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
4097
4098     // We aren't supposed to apply this logic for if there's an '&' involved.
4099     if (!find.HasFormOfMemberPointer) {
4100       OverloadExpr *ovl = find.Expression;
4101       if (isa<UnresolvedLookupExpr>(ovl)) {
4102         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
4103         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
4104                                        ArgExprs.size(), RParenLoc, ExecConfig);
4105       } else {
4106         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
4107                                          ArgExprs.size(), RParenLoc);
4108       }
4109     }
4110   }
4111
4112   // If we're directly calling a function, get the appropriate declaration.
4113   if (Fn->getType() == Context.UnknownAnyTy) {
4114     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
4115     if (result.isInvalid()) return ExprError();
4116     Fn = result.take();
4117   }
4118
4119   Expr *NakedFn = Fn->IgnoreParens();
4120
4121   NamedDecl *NDecl = 0;
4122   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
4123     if (UnOp->getOpcode() == UO_AddrOf)
4124       NakedFn = UnOp->getSubExpr()->IgnoreParens();
4125   
4126   if (isa<DeclRefExpr>(NakedFn))
4127     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
4128   else if (isa<MemberExpr>(NakedFn))
4129     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
4130
4131   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
4132                                ArgExprs.size(), RParenLoc, ExecConfig,
4133                                IsExecConfig);
4134 }
4135
4136 ExprResult
4137 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
4138                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
4139   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
4140   if (!ConfigDecl)
4141     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
4142                           << "cudaConfigureCall");
4143   QualType ConfigQTy = ConfigDecl->getType();
4144
4145   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
4146       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
4147   MarkFunctionReferenced(LLLLoc, ConfigDecl);
4148
4149   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
4150                        /*IsExecConfig=*/true);
4151 }
4152
4153 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
4154 ///
4155 /// __builtin_astype( value, dst type )
4156 ///
4157 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
4158                                  SourceLocation BuiltinLoc,
4159                                  SourceLocation RParenLoc) {
4160   ExprValueKind VK = VK_RValue;
4161   ExprObjectKind OK = OK_Ordinary;
4162   QualType DstTy = GetTypeFromParser(ParsedDestTy);
4163   QualType SrcTy = E->getType();
4164   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
4165     return ExprError(Diag(BuiltinLoc,
4166                           diag::err_invalid_astype_of_different_size)
4167                      << DstTy
4168                      << SrcTy
4169                      << E->getSourceRange());
4170   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
4171                RParenLoc));
4172 }
4173
4174 /// BuildResolvedCallExpr - Build a call to a resolved expression,
4175 /// i.e. an expression not of \p OverloadTy.  The expression should
4176 /// unary-convert to an expression of function-pointer or
4177 /// block-pointer type.
4178 ///
4179 /// \param NDecl the declaration being called, if available
4180 ExprResult
4181 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4182                             SourceLocation LParenLoc,
4183                             Expr **Args, unsigned NumArgs,
4184                             SourceLocation RParenLoc,
4185                             Expr *Config, bool IsExecConfig) {
4186   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4187   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4188
4189   // Promote the function operand.
4190   // We special-case function promotion here because we only allow promoting
4191   // builtin functions to function pointers in the callee of a call.
4192   ExprResult Result;
4193   if (BuiltinID &&
4194       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4195     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4196                                CK_BuiltinFnToFnPtr).take();
4197   } else {
4198     Result = UsualUnaryConversions(Fn);
4199   }
4200   if (Result.isInvalid())
4201     return ExprError();
4202   Fn = Result.take();
4203
4204   // Make the call expr early, before semantic checks.  This guarantees cleanup
4205   // of arguments and function on error.
4206   CallExpr *TheCall;
4207   if (Config)
4208     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4209                                                cast<CallExpr>(Config),
4210                                                llvm::makeArrayRef(Args,NumArgs),
4211                                                Context.BoolTy,
4212                                                VK_RValue,
4213                                                RParenLoc);
4214   else
4215     TheCall = new (Context) CallExpr(Context, Fn,
4216                                      llvm::makeArrayRef(Args, NumArgs),
4217                                      Context.BoolTy,
4218                                      VK_RValue,
4219                                      RParenLoc);
4220
4221   // Bail out early if calling a builtin with custom typechecking.
4222   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4223     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4224
4225  retry:
4226   const FunctionType *FuncT;
4227   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4228     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4229     // have type pointer to function".
4230     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4231     if (FuncT == 0)
4232       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4233                          << Fn->getType() << Fn->getSourceRange());
4234   } else if (const BlockPointerType *BPT =
4235                Fn->getType()->getAs<BlockPointerType>()) {
4236     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4237   } else {
4238     // Handle calls to expressions of unknown-any type.
4239     if (Fn->getType() == Context.UnknownAnyTy) {
4240       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4241       if (rewrite.isInvalid()) return ExprError();
4242       Fn = rewrite.take();
4243       TheCall->setCallee(Fn);
4244       goto retry;
4245     }
4246
4247     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4248       << Fn->getType() << Fn->getSourceRange());
4249   }
4250
4251   if (getLangOpts().CUDA) {
4252     if (Config) {
4253       // CUDA: Kernel calls must be to global functions
4254       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4255         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4256             << FDecl->getName() << Fn->getSourceRange());
4257
4258       // CUDA: Kernel function must have 'void' return type
4259       if (!FuncT->getResultType()->isVoidType())
4260         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4261             << Fn->getType() << Fn->getSourceRange());
4262     } else {
4263       // CUDA: Calls to global functions must be configured
4264       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4265         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4266             << FDecl->getName() << Fn->getSourceRange());
4267     }
4268   }
4269
4270   // Check for a valid return type
4271   if (CheckCallReturnType(FuncT->getResultType(),
4272                           Fn->getLocStart(), TheCall,
4273                           FDecl))
4274     return ExprError();
4275
4276   // We know the result type of the call, set it.
4277   TheCall->setType(FuncT->getCallResultType(Context));
4278   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4279
4280   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4281   if (Proto) {
4282     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4283                                 RParenLoc, IsExecConfig))
4284       return ExprError();
4285   } else {
4286     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4287
4288     if (FDecl) {
4289       // Check if we have too few/too many template arguments, based
4290       // on our knowledge of the function definition.
4291       const FunctionDecl *Def = 0;
4292       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4293         Proto = Def->getType()->getAs<FunctionProtoType>();
4294         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4295           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4296             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4297       }
4298       
4299       // If the function we're calling isn't a function prototype, but we have
4300       // a function prototype from a prior declaratiom, use that prototype.
4301       if (!FDecl->hasPrototype())
4302         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4303     }
4304
4305     // Promote the arguments (C99 6.5.2.2p6).
4306     for (unsigned i = 0; i != NumArgs; i++) {
4307       Expr *Arg = Args[i];
4308
4309       if (Proto && i < Proto->getNumArgs()) {
4310         InitializedEntity Entity
4311           = InitializedEntity::InitializeParameter(Context, 
4312                                                    Proto->getArgType(i),
4313                                                    Proto->isArgConsumed(i));
4314         ExprResult ArgE = PerformCopyInitialization(Entity,
4315                                                     SourceLocation(),
4316                                                     Owned(Arg));
4317         if (ArgE.isInvalid())
4318           return true;
4319         
4320         Arg = ArgE.takeAs<Expr>();
4321
4322       } else {
4323         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4324
4325         if (ArgE.isInvalid())
4326           return true;
4327
4328         Arg = ArgE.takeAs<Expr>();
4329       }
4330       
4331       if (RequireCompleteType(Arg->getLocStart(),
4332                               Arg->getType(),
4333                               diag::err_call_incomplete_argument, Arg))
4334         return ExprError();
4335
4336       TheCall->setArg(i, Arg);
4337     }
4338   }
4339
4340   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4341     if (!Method->isStatic())
4342       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4343         << Fn->getSourceRange());
4344
4345   // Check for sentinels
4346   if (NDecl)
4347     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4348
4349   // Do special checking on direct calls to functions.
4350   if (FDecl) {
4351     if (CheckFunctionCall(FDecl, TheCall, Proto))
4352       return ExprError();
4353
4354     if (BuiltinID)
4355       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4356   } else if (NDecl) {
4357     if (CheckBlockCall(NDecl, TheCall, Proto))
4358       return ExprError();
4359   }
4360
4361   return MaybeBindToTemporary(TheCall);
4362 }
4363
4364 ExprResult
4365 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4366                            SourceLocation RParenLoc, Expr *InitExpr) {
4367   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4368   // FIXME: put back this assert when initializers are worked out.
4369   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4370
4371   TypeSourceInfo *TInfo;
4372   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4373   if (!TInfo)
4374     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4375
4376   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4377 }
4378
4379 ExprResult
4380 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4381                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4382   QualType literalType = TInfo->getType();
4383
4384   if (literalType->isArrayType()) {
4385     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4386           diag::err_illegal_decl_array_incomplete_type,
4387           SourceRange(LParenLoc,
4388                       LiteralExpr->getSourceRange().getEnd())))
4389       return ExprError();
4390     if (literalType->isVariableArrayType())
4391       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4392         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4393   } else if (!literalType->isDependentType() &&
4394              RequireCompleteType(LParenLoc, literalType,
4395                diag::err_typecheck_decl_incomplete_type,
4396                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4397     return ExprError();
4398
4399   InitializedEntity Entity
4400     = InitializedEntity::InitializeTemporary(literalType);
4401   InitializationKind Kind
4402     = InitializationKind::CreateCStyleCast(LParenLoc, 
4403                                            SourceRange(LParenLoc, RParenLoc),
4404                                            /*InitList=*/true);
4405   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4406   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4407                                       &literalType);
4408   if (Result.isInvalid())
4409     return ExprError();
4410   LiteralExpr = Result.get();
4411
4412   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4413   if (isFileScope) { // 6.5.2.5p3
4414     if (CheckForConstantInitializer(LiteralExpr, literalType))
4415       return ExprError();
4416   }
4417
4418   // In C, compound literals are l-values for some reason.
4419   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4420
4421   return MaybeBindToTemporary(
4422            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4423                                              VK, LiteralExpr, isFileScope));
4424 }
4425
4426 ExprResult
4427 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4428                     SourceLocation RBraceLoc) {
4429   // Immediately handle non-overload placeholders.  Overloads can be
4430   // resolved contextually, but everything else here can't.
4431   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4432     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4433       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4434
4435       // Ignore failures; dropping the entire initializer list because
4436       // of one failure would be terrible for indexing/etc.
4437       if (result.isInvalid()) continue;
4438
4439       InitArgList[I] = result.take();
4440     }
4441   }
4442
4443   // Semantic analysis for initializers is done by ActOnDeclarator() and
4444   // CheckInitializer() - it requires knowledge of the object being intialized.
4445
4446   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4447                                                RBraceLoc);
4448   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4449   return Owned(E);
4450 }
4451
4452 /// Do an explicit extend of the given block pointer if we're in ARC.
4453 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4454   assert(E.get()->getType()->isBlockPointerType());
4455   assert(E.get()->isRValue());
4456
4457   // Only do this in an r-value context.
4458   if (!S.getLangOpts().ObjCAutoRefCount) return;
4459
4460   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4461                                CK_ARCExtendBlockObject, E.get(),
4462                                /*base path*/ 0, VK_RValue);
4463   S.ExprNeedsCleanups = true;
4464 }
4465
4466 /// Prepare a conversion of the given expression to an ObjC object
4467 /// pointer type.
4468 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4469   QualType type = E.get()->getType();
4470   if (type->isObjCObjectPointerType()) {
4471     return CK_BitCast;
4472   } else if (type->isBlockPointerType()) {
4473     maybeExtendBlockObject(*this, E);
4474     return CK_BlockPointerToObjCPointerCast;
4475   } else {
4476     assert(type->isPointerType());
4477     return CK_CPointerToObjCPointerCast;
4478   }
4479 }
4480
4481 /// Prepares for a scalar cast, performing all the necessary stages
4482 /// except the final cast and returning the kind required.
4483 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4484   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4485   // Also, callers should have filtered out the invalid cases with
4486   // pointers.  Everything else should be possible.
4487
4488   QualType SrcTy = Src.get()->getType();
4489   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4490     return CK_NoOp;
4491
4492   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4493   case Type::STK_MemberPointer:
4494     llvm_unreachable("member pointer type in C");
4495
4496   case Type::STK_CPointer:
4497   case Type::STK_BlockPointer:
4498   case Type::STK_ObjCObjectPointer:
4499     switch (DestTy->getScalarTypeKind()) {
4500     case Type::STK_CPointer:
4501       return CK_BitCast;
4502     case Type::STK_BlockPointer:
4503       return (SrcKind == Type::STK_BlockPointer
4504                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4505     case Type::STK_ObjCObjectPointer:
4506       if (SrcKind == Type::STK_ObjCObjectPointer)
4507         return CK_BitCast;
4508       if (SrcKind == Type::STK_CPointer)
4509         return CK_CPointerToObjCPointerCast;
4510       maybeExtendBlockObject(*this, Src);
4511       return CK_BlockPointerToObjCPointerCast;
4512     case Type::STK_Bool:
4513       return CK_PointerToBoolean;
4514     case Type::STK_Integral:
4515       return CK_PointerToIntegral;
4516     case Type::STK_Floating:
4517     case Type::STK_FloatingComplex:
4518     case Type::STK_IntegralComplex:
4519     case Type::STK_MemberPointer:
4520       llvm_unreachable("illegal cast from pointer");
4521     }
4522     llvm_unreachable("Should have returned before this");
4523
4524   case Type::STK_Bool: // casting from bool is like casting from an integer
4525   case Type::STK_Integral:
4526     switch (DestTy->getScalarTypeKind()) {
4527     case Type::STK_CPointer:
4528     case Type::STK_ObjCObjectPointer:
4529     case Type::STK_BlockPointer:
4530       if (Src.get()->isNullPointerConstant(Context,
4531                                            Expr::NPC_ValueDependentIsNull))
4532         return CK_NullToPointer;
4533       return CK_IntegralToPointer;
4534     case Type::STK_Bool:
4535       return CK_IntegralToBoolean;
4536     case Type::STK_Integral:
4537       return CK_IntegralCast;
4538     case Type::STK_Floating:
4539       return CK_IntegralToFloating;
4540     case Type::STK_IntegralComplex:
4541       Src = ImpCastExprToType(Src.take(),
4542                               DestTy->castAs<ComplexType>()->getElementType(),
4543                               CK_IntegralCast);
4544       return CK_IntegralRealToComplex;
4545     case Type::STK_FloatingComplex:
4546       Src = ImpCastExprToType(Src.take(),
4547                               DestTy->castAs<ComplexType>()->getElementType(),
4548                               CK_IntegralToFloating);
4549       return CK_FloatingRealToComplex;
4550     case Type::STK_MemberPointer:
4551       llvm_unreachable("member pointer type in C");
4552     }
4553     llvm_unreachable("Should have returned before this");
4554
4555   case Type::STK_Floating:
4556     switch (DestTy->getScalarTypeKind()) {
4557     case Type::STK_Floating:
4558       return CK_FloatingCast;
4559     case Type::STK_Bool:
4560       return CK_FloatingToBoolean;
4561     case Type::STK_Integral:
4562       return CK_FloatingToIntegral;
4563     case Type::STK_FloatingComplex:
4564       Src = ImpCastExprToType(Src.take(),
4565                               DestTy->castAs<ComplexType>()->getElementType(),
4566                               CK_FloatingCast);
4567       return CK_FloatingRealToComplex;
4568     case Type::STK_IntegralComplex:
4569       Src = ImpCastExprToType(Src.take(),
4570                               DestTy->castAs<ComplexType>()->getElementType(),
4571                               CK_FloatingToIntegral);
4572       return CK_IntegralRealToComplex;
4573     case Type::STK_CPointer:
4574     case Type::STK_ObjCObjectPointer:
4575     case Type::STK_BlockPointer:
4576       llvm_unreachable("valid float->pointer cast?");
4577     case Type::STK_MemberPointer:
4578       llvm_unreachable("member pointer type in C");
4579     }
4580     llvm_unreachable("Should have returned before this");
4581
4582   case Type::STK_FloatingComplex:
4583     switch (DestTy->getScalarTypeKind()) {
4584     case Type::STK_FloatingComplex:
4585       return CK_FloatingComplexCast;
4586     case Type::STK_IntegralComplex:
4587       return CK_FloatingComplexToIntegralComplex;
4588     case Type::STK_Floating: {
4589       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4590       if (Context.hasSameType(ET, DestTy))
4591         return CK_FloatingComplexToReal;
4592       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4593       return CK_FloatingCast;
4594     }
4595     case Type::STK_Bool:
4596       return CK_FloatingComplexToBoolean;
4597     case Type::STK_Integral:
4598       Src = ImpCastExprToType(Src.take(),
4599                               SrcTy->castAs<ComplexType>()->getElementType(),
4600                               CK_FloatingComplexToReal);
4601       return CK_FloatingToIntegral;
4602     case Type::STK_CPointer:
4603     case Type::STK_ObjCObjectPointer:
4604     case Type::STK_BlockPointer:
4605       llvm_unreachable("valid complex float->pointer cast?");
4606     case Type::STK_MemberPointer:
4607       llvm_unreachable("member pointer type in C");
4608     }
4609     llvm_unreachable("Should have returned before this");
4610
4611   case Type::STK_IntegralComplex:
4612     switch (DestTy->getScalarTypeKind()) {
4613     case Type::STK_FloatingComplex:
4614       return CK_IntegralComplexToFloatingComplex;
4615     case Type::STK_IntegralComplex:
4616       return CK_IntegralComplexCast;
4617     case Type::STK_Integral: {
4618       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4619       if (Context.hasSameType(ET, DestTy))
4620         return CK_IntegralComplexToReal;
4621       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4622       return CK_IntegralCast;
4623     }
4624     case Type::STK_Bool:
4625       return CK_IntegralComplexToBoolean;
4626     case Type::STK_Floating:
4627       Src = ImpCastExprToType(Src.take(),
4628                               SrcTy->castAs<ComplexType>()->getElementType(),
4629                               CK_IntegralComplexToReal);
4630       return CK_IntegralToFloating;
4631     case Type::STK_CPointer:
4632     case Type::STK_ObjCObjectPointer:
4633     case Type::STK_BlockPointer:
4634       llvm_unreachable("valid complex int->pointer cast?");
4635     case Type::STK_MemberPointer:
4636       llvm_unreachable("member pointer type in C");
4637     }
4638     llvm_unreachable("Should have returned before this");
4639   }
4640
4641   llvm_unreachable("Unhandled scalar cast");
4642 }
4643
4644 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4645                            CastKind &Kind) {
4646   assert(VectorTy->isVectorType() && "Not a vector type!");
4647
4648   if (Ty->isVectorType() || Ty->isIntegerType()) {
4649     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4650       return Diag(R.getBegin(),
4651                   Ty->isVectorType() ?
4652                   diag::err_invalid_conversion_between_vectors :
4653                   diag::err_invalid_conversion_between_vector_and_integer)
4654         << VectorTy << Ty << R;
4655   } else
4656     return Diag(R.getBegin(),
4657                 diag::err_invalid_conversion_between_vector_and_scalar)
4658       << VectorTy << Ty << R;
4659
4660   Kind = CK_BitCast;
4661   return false;
4662 }
4663
4664 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4665                                     Expr *CastExpr, CastKind &Kind) {
4666   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4667
4668   QualType SrcTy = CastExpr->getType();
4669
4670   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4671   // an ExtVectorType.
4672   // In OpenCL, casts between vectors of different types are not allowed.
4673   // (See OpenCL 6.2).
4674   if (SrcTy->isVectorType()) {
4675     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4676         || (getLangOpts().OpenCL &&
4677             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4678       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4679         << DestTy << SrcTy << R;
4680       return ExprError();
4681     }
4682     Kind = CK_BitCast;
4683     return Owned(CastExpr);
4684   }
4685
4686   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4687   // conversion will take place first from scalar to elt type, and then
4688   // splat from elt type to vector.
4689   if (SrcTy->isPointerType())
4690     return Diag(R.getBegin(),
4691                 diag::err_invalid_conversion_between_vector_and_scalar)
4692       << DestTy << SrcTy << R;
4693
4694   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4695   ExprResult CastExprRes = Owned(CastExpr);
4696   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4697   if (CastExprRes.isInvalid())
4698     return ExprError();
4699   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4700
4701   Kind = CK_VectorSplat;
4702   return Owned(CastExpr);
4703 }
4704
4705 ExprResult
4706 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4707                     Declarator &D, ParsedType &Ty,
4708                     SourceLocation RParenLoc, Expr *CastExpr) {
4709   assert(!D.isInvalidType() && (CastExpr != 0) &&
4710          "ActOnCastExpr(): missing type or expr");
4711
4712   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4713   if (D.isInvalidType())
4714     return ExprError();
4715
4716   if (getLangOpts().CPlusPlus) {
4717     // Check that there are no default arguments (C++ only).
4718     CheckExtraCXXDefaultArguments(D);
4719   }
4720
4721   checkUnusedDeclAttributes(D);
4722
4723   QualType castType = castTInfo->getType();
4724   Ty = CreateParsedType(castType, castTInfo);
4725
4726   bool isVectorLiteral = false;
4727
4728   // Check for an altivec or OpenCL literal,
4729   // i.e. all the elements are integer constants.
4730   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4731   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4732   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4733        && castType->isVectorType() && (PE || PLE)) {
4734     if (PLE && PLE->getNumExprs() == 0) {
4735       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4736       return ExprError();
4737     }
4738     if (PE || PLE->getNumExprs() == 1) {
4739       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4740       if (!E->getType()->isVectorType())
4741         isVectorLiteral = true;
4742     }
4743     else
4744       isVectorLiteral = true;
4745   }
4746
4747   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4748   // then handle it as such.
4749   if (isVectorLiteral)
4750     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4751
4752   // If the Expr being casted is a ParenListExpr, handle it specially.
4753   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4754   // sequence of BinOp comma operators.
4755   if (isa<ParenListExpr>(CastExpr)) {
4756     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4757     if (Result.isInvalid()) return ExprError();
4758     CastExpr = Result.take();
4759   }
4760
4761   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4762 }
4763
4764 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4765                                     SourceLocation RParenLoc, Expr *E,
4766                                     TypeSourceInfo *TInfo) {
4767   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4768          "Expected paren or paren list expression");
4769
4770   Expr **exprs;
4771   unsigned numExprs;
4772   Expr *subExpr;
4773   SourceLocation LiteralLParenLoc, LiteralRParenLoc;
4774   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4775     LiteralLParenLoc = PE->getLParenLoc();
4776     LiteralRParenLoc = PE->getRParenLoc();
4777     exprs = PE->getExprs();
4778     numExprs = PE->getNumExprs();
4779   } else { // isa<ParenExpr> by assertion at function entrance
4780     LiteralLParenLoc = cast<ParenExpr>(E)->getLParen();
4781     LiteralRParenLoc = cast<ParenExpr>(E)->getRParen();
4782     subExpr = cast<ParenExpr>(E)->getSubExpr();
4783     exprs = &subExpr;
4784     numExprs = 1;
4785   }
4786
4787   QualType Ty = TInfo->getType();
4788   assert(Ty->isVectorType() && "Expected vector type");
4789
4790   SmallVector<Expr *, 8> initExprs;
4791   const VectorType *VTy = Ty->getAs<VectorType>();
4792   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4793   
4794   // '(...)' form of vector initialization in AltiVec: the number of
4795   // initializers must be one or must match the size of the vector.
4796   // If a single value is specified in the initializer then it will be
4797   // replicated to all the components of the vector
4798   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4799     // The number of initializers must be one or must match the size of the
4800     // vector. If a single value is specified in the initializer then it will
4801     // be replicated to all the components of the vector
4802     if (numExprs == 1) {
4803       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4804       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4805       if (Literal.isInvalid())
4806         return ExprError();
4807       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4808                                   PrepareScalarCast(Literal, ElemTy));
4809       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4810     }
4811     else if (numExprs < numElems) {
4812       Diag(E->getExprLoc(),
4813            diag::err_incorrect_number_of_vector_initializers);
4814       return ExprError();
4815     }
4816     else
4817       initExprs.append(exprs, exprs + numExprs);
4818   }
4819   else {
4820     // For OpenCL, when the number of initializers is a single value,
4821     // it will be replicated to all components of the vector.
4822     if (getLangOpts().OpenCL &&
4823         VTy->getVectorKind() == VectorType::GenericVector &&
4824         numExprs == 1) {
4825         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4826         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4827         if (Literal.isInvalid())
4828           return ExprError();
4829         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4830                                     PrepareScalarCast(Literal, ElemTy));
4831         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4832     }
4833     
4834     initExprs.append(exprs, exprs + numExprs);
4835   }
4836   // FIXME: This means that pretty-printing the final AST will produce curly
4837   // braces instead of the original commas.
4838   InitListExpr *initE = new (Context) InitListExpr(Context, LiteralLParenLoc,
4839                                                    initExprs, LiteralRParenLoc);
4840   initE->setType(Ty);
4841   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4842 }
4843
4844 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4845 /// the ParenListExpr into a sequence of comma binary operators.
4846 ExprResult
4847 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4848   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4849   if (!E)
4850     return Owned(OrigExpr);
4851
4852   ExprResult Result(E->getExpr(0));
4853
4854   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4855     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4856                         E->getExpr(i));
4857
4858   if (Result.isInvalid()) return ExprError();
4859
4860   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4861 }
4862
4863 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4864                                     SourceLocation R,
4865                                     MultiExprArg Val) {
4866   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4867   return Owned(expr);
4868 }
4869
4870 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4871 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4872 /// emitted.
4873 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4874                                       SourceLocation QuestionLoc) {
4875   Expr *NullExpr = LHSExpr;
4876   Expr *NonPointerExpr = RHSExpr;
4877   Expr::NullPointerConstantKind NullKind =
4878       NullExpr->isNullPointerConstant(Context,
4879                                       Expr::NPC_ValueDependentIsNotNull);
4880
4881   if (NullKind == Expr::NPCK_NotNull) {
4882     NullExpr = RHSExpr;
4883     NonPointerExpr = LHSExpr;
4884     NullKind =
4885         NullExpr->isNullPointerConstant(Context,
4886                                         Expr::NPC_ValueDependentIsNotNull);
4887   }
4888
4889   if (NullKind == Expr::NPCK_NotNull)
4890     return false;
4891
4892   if (NullKind == Expr::NPCK_ZeroExpression)
4893     return false;
4894
4895   if (NullKind == Expr::NPCK_ZeroLiteral) {
4896     // In this case, check to make sure that we got here from a "NULL"
4897     // string in the source code.
4898     NullExpr = NullExpr->IgnoreParenImpCasts();
4899     SourceLocation loc = NullExpr->getExprLoc();
4900     if (!findMacroSpelling(loc, "NULL"))
4901       return false;
4902   }
4903
4904   int DiagType = (NullKind == Expr::NPCK_CXX11_nullptr);
4905   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4906       << NonPointerExpr->getType() << DiagType
4907       << NonPointerExpr->getSourceRange();
4908   return true;
4909 }
4910
4911 /// \brief Return false if the condition expression is valid, true otherwise.
4912 static bool checkCondition(Sema &S, Expr *Cond) {
4913   QualType CondTy = Cond->getType();
4914
4915   // C99 6.5.15p2
4916   if (CondTy->isScalarType()) return false;
4917
4918   // OpenCL v1.1 s6.3.i says the condition is allowed to be a vector or scalar.
4919   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4920     return false;
4921
4922   // Emit the proper error message.
4923   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4924                               diag::err_typecheck_cond_expect_scalar :
4925                               diag::err_typecheck_cond_expect_scalar_or_vector)
4926     << CondTy;
4927   return true;
4928 }
4929
4930 /// \brief Return false if the two expressions can be converted to a vector,
4931 /// true otherwise
4932 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4933                                                     ExprResult &RHS,
4934                                                     QualType CondTy) {
4935   // Both operands should be of scalar type.
4936   if (!LHS.get()->getType()->isScalarType()) {
4937     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4938       << CondTy;
4939     return true;
4940   }
4941   if (!RHS.get()->getType()->isScalarType()) {
4942     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4943       << CondTy;
4944     return true;
4945   }
4946
4947   // Implicity convert these scalars to the type of the condition.
4948   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4949   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4950   return false;
4951 }
4952
4953 /// \brief Handle when one or both operands are void type.
4954 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4955                                          ExprResult &RHS) {
4956     Expr *LHSExpr = LHS.get();
4957     Expr *RHSExpr = RHS.get();
4958
4959     if (!LHSExpr->getType()->isVoidType())
4960       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4961         << RHSExpr->getSourceRange();
4962     if (!RHSExpr->getType()->isVoidType())
4963       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4964         << LHSExpr->getSourceRange();
4965     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4966     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4967     return S.Context.VoidTy;
4968 }
4969
4970 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4971 /// true otherwise.
4972 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4973                                         QualType PointerTy) {
4974   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4975       !NullExpr.get()->isNullPointerConstant(S.Context,
4976                                             Expr::NPC_ValueDependentIsNull))
4977     return true;
4978
4979   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4980   return false;
4981 }
4982
4983 /// \brief Checks compatibility between two pointers and return the resulting
4984 /// type.
4985 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4986                                                      ExprResult &RHS,
4987                                                      SourceLocation Loc) {
4988   QualType LHSTy = LHS.get()->getType();
4989   QualType RHSTy = RHS.get()->getType();
4990
4991   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4992     // Two identical pointers types are always compatible.
4993     return LHSTy;
4994   }
4995
4996   QualType lhptee, rhptee;
4997
4998   // Get the pointee types.
4999   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
5000     lhptee = LHSBTy->getPointeeType();
5001     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
5002   } else {
5003     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
5004     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
5005   }
5006
5007   // C99 6.5.15p6: If both operands are pointers to compatible types or to
5008   // differently qualified versions of compatible types, the result type is
5009   // a pointer to an appropriately qualified version of the composite
5010   // type.
5011
5012   // Only CVR-qualifiers exist in the standard, and the differently-qualified
5013   // clause doesn't make sense for our extensions. E.g. address space 2 should
5014   // be incompatible with address space 3: they may live on different devices or
5015   // anything.
5016   Qualifiers lhQual = lhptee.getQualifiers();
5017   Qualifiers rhQual = rhptee.getQualifiers();
5018
5019   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
5020   lhQual.removeCVRQualifiers();
5021   rhQual.removeCVRQualifiers();
5022
5023   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
5024   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
5025
5026   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
5027
5028   if (CompositeTy.isNull()) {
5029     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
5030       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5031       << RHS.get()->getSourceRange();
5032     // In this situation, we assume void* type. No especially good
5033     // reason, but this is what gcc does, and we do have to pick
5034     // to get a consistent AST.
5035     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
5036     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5037     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5038     return incompatTy;
5039   }
5040
5041   // The pointer types are compatible.
5042   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
5043   ResultTy = S.Context.getPointerType(ResultTy);
5044
5045   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
5046   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
5047   return ResultTy;
5048 }
5049
5050 /// \brief Return the resulting type when the operands are both block pointers.
5051 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
5052                                                           ExprResult &LHS,
5053                                                           ExprResult &RHS,
5054                                                           SourceLocation Loc) {
5055   QualType LHSTy = LHS.get()->getType();
5056   QualType RHSTy = RHS.get()->getType();
5057
5058   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
5059     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
5060       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
5061       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5062       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5063       return destType;
5064     }
5065     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
5066       << LHSTy << RHSTy << LHS.get()->getSourceRange()
5067       << RHS.get()->getSourceRange();
5068     return QualType();
5069   }
5070
5071   // We have 2 block pointer types.
5072   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5073 }
5074
5075 /// \brief Return the resulting type when the operands are both pointers.
5076 static QualType
5077 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
5078                                             ExprResult &RHS,
5079                                             SourceLocation Loc) {
5080   // get the pointer types
5081   QualType LHSTy = LHS.get()->getType();
5082   QualType RHSTy = RHS.get()->getType();
5083
5084   // get the "pointed to" types
5085   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5086   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5087
5088   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
5089   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
5090     // Figure out necessary qualifiers (C99 6.5.15p6)
5091     QualType destPointee
5092       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5093     QualType destType = S.Context.getPointerType(destPointee);
5094     // Add qualifiers if necessary.
5095     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5096     // Promote to void*.
5097     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5098     return destType;
5099   }
5100   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
5101     QualType destPointee
5102       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5103     QualType destType = S.Context.getPointerType(destPointee);
5104     // Add qualifiers if necessary.
5105     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5106     // Promote to void*.
5107     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5108     return destType;
5109   }
5110
5111   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
5112 }
5113
5114 /// \brief Return false if the first expression is not an integer and the second
5115 /// expression is not a pointer, true otherwise.
5116 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
5117                                         Expr* PointerExpr, SourceLocation Loc,
5118                                         bool IsIntFirstExpr) {
5119   if (!PointerExpr->getType()->isPointerType() ||
5120       !Int.get()->getType()->isIntegerType())
5121     return false;
5122
5123   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
5124   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
5125
5126   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
5127     << Expr1->getType() << Expr2->getType()
5128     << Expr1->getSourceRange() << Expr2->getSourceRange();
5129   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
5130                             CK_IntegralToPointer);
5131   return true;
5132 }
5133
5134 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
5135 /// In that case, LHS = cond.
5136 /// C99 6.5.15
5137 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5138                                         ExprResult &RHS, ExprValueKind &VK,
5139                                         ExprObjectKind &OK,
5140                                         SourceLocation QuestionLoc) {
5141
5142   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
5143   if (!LHSResult.isUsable()) return QualType();
5144   LHS = LHSResult;
5145
5146   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
5147   if (!RHSResult.isUsable()) return QualType();
5148   RHS = RHSResult;
5149
5150   // C++ is sufficiently different to merit its own checker.
5151   if (getLangOpts().CPlusPlus)
5152     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
5153
5154   VK = VK_RValue;
5155   OK = OK_Ordinary;
5156
5157   Cond = UsualUnaryConversions(Cond.take());
5158   if (Cond.isInvalid())
5159     return QualType();
5160   LHS = UsualUnaryConversions(LHS.take());
5161   if (LHS.isInvalid())
5162     return QualType();
5163   RHS = UsualUnaryConversions(RHS.take());
5164   if (RHS.isInvalid())
5165     return QualType();
5166
5167   QualType CondTy = Cond.get()->getType();
5168   QualType LHSTy = LHS.get()->getType();
5169   QualType RHSTy = RHS.get()->getType();
5170
5171   // first, check the condition.
5172   if (checkCondition(*this, Cond.get()))
5173     return QualType();
5174
5175   // Now check the two expressions.
5176   if (LHSTy->isVectorType() || RHSTy->isVectorType())
5177     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
5178
5179   // If the condition is a vector, and both operands are scalar,
5180   // attempt to implicity convert them to the vector type to act like the
5181   // built in select. (OpenCL v1.1 s6.3.i)
5182   if (getLangOpts().OpenCL && CondTy->isVectorType())
5183     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5184       return QualType();
5185   
5186   // If both operands have arithmetic type, do the usual arithmetic conversions
5187   // to find a common type: C99 6.5.15p3,5.
5188   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5189     UsualArithmeticConversions(LHS, RHS);
5190     if (LHS.isInvalid() || RHS.isInvalid())
5191       return QualType();
5192     return LHS.get()->getType();
5193   }
5194
5195   // If both operands are the same structure or union type, the result is that
5196   // type.
5197   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5198     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5199       if (LHSRT->getDecl() == RHSRT->getDecl())
5200         // "If both the operands have structure or union type, the result has
5201         // that type."  This implies that CV qualifiers are dropped.
5202         return LHSTy.getUnqualifiedType();
5203     // FIXME: Type of conditional expression must be complete in C mode.
5204   }
5205
5206   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5207   // The following || allows only one side to be void (a GCC-ism).
5208   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5209     return checkConditionalVoidType(*this, LHS, RHS);
5210   }
5211
5212   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5213   // the type of the other operand."
5214   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5215   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5216
5217   // All objective-c pointer type analysis is done here.
5218   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5219                                                         QuestionLoc);
5220   if (LHS.isInvalid() || RHS.isInvalid())
5221     return QualType();
5222   if (!compositeType.isNull())
5223     return compositeType;
5224
5225
5226   // Handle block pointer types.
5227   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5228     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5229                                                      QuestionLoc);
5230
5231   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5232   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5233     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5234                                                        QuestionLoc);
5235
5236   // GCC compatibility: soften pointer/integer mismatch.  Note that
5237   // null pointers have been filtered out by this point.
5238   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5239       /*isIntFirstExpr=*/true))
5240     return RHSTy;
5241   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5242       /*isIntFirstExpr=*/false))
5243     return LHSTy;
5244
5245   // Emit a better diagnostic if one of the expressions is a null pointer
5246   // constant and the other is not a pointer type. In this case, the user most
5247   // likely forgot to take the address of the other expression.
5248   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5249     return QualType();
5250
5251   // Otherwise, the operands are not compatible.
5252   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5253     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5254     << RHS.get()->getSourceRange();
5255   return QualType();
5256 }
5257
5258 /// FindCompositeObjCPointerType - Helper method to find composite type of
5259 /// two objective-c pointer types of the two input expressions.
5260 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5261                                             SourceLocation QuestionLoc) {
5262   QualType LHSTy = LHS.get()->getType();
5263   QualType RHSTy = RHS.get()->getType();
5264
5265   // Handle things like Class and struct objc_class*.  Here we case the result
5266   // to the pseudo-builtin, because that will be implicitly cast back to the
5267   // redefinition type if an attempt is made to access its fields.
5268   if (LHSTy->isObjCClassType() &&
5269       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5270     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5271     return LHSTy;
5272   }
5273   if (RHSTy->isObjCClassType() &&
5274       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5275     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5276     return RHSTy;
5277   }
5278   // And the same for struct objc_object* / id
5279   if (LHSTy->isObjCIdType() &&
5280       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5281     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5282     return LHSTy;
5283   }
5284   if (RHSTy->isObjCIdType() &&
5285       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5286     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5287     return RHSTy;
5288   }
5289   // And the same for struct objc_selector* / SEL
5290   if (Context.isObjCSelType(LHSTy) &&
5291       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5292     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5293     return LHSTy;
5294   }
5295   if (Context.isObjCSelType(RHSTy) &&
5296       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5297     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5298     return RHSTy;
5299   }
5300   // Check constraints for Objective-C object pointers types.
5301   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5302
5303     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5304       // Two identical object pointer types are always compatible.
5305       return LHSTy;
5306     }
5307     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5308     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5309     QualType compositeType = LHSTy;
5310
5311     // If both operands are interfaces and either operand can be
5312     // assigned to the other, use that type as the composite
5313     // type. This allows
5314     //   xxx ? (A*) a : (B*) b
5315     // where B is a subclass of A.
5316     //
5317     // Additionally, as for assignment, if either type is 'id'
5318     // allow silent coercion. Finally, if the types are
5319     // incompatible then make sure to use 'id' as the composite
5320     // type so the result is acceptable for sending messages to.
5321
5322     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5323     // It could return the composite type.
5324     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5325       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5326     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5327       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5328     } else if ((LHSTy->isObjCQualifiedIdType() ||
5329                 RHSTy->isObjCQualifiedIdType()) &&
5330                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5331       // Need to handle "id<xx>" explicitly.
5332       // GCC allows qualified id and any Objective-C type to devolve to
5333       // id. Currently localizing to here until clear this should be
5334       // part of ObjCQualifiedIdTypesAreCompatible.
5335       compositeType = Context.getObjCIdType();
5336     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5337       compositeType = Context.getObjCIdType();
5338     } else if (!(compositeType =
5339                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5340       ;
5341     else {
5342       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5343       << LHSTy << RHSTy
5344       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5345       QualType incompatTy = Context.getObjCIdType();
5346       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5347       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5348       return incompatTy;
5349     }
5350     // The object pointer types are compatible.
5351     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5352     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5353     return compositeType;
5354   }
5355   // Check Objective-C object pointer types and 'void *'
5356   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5357     if (getLangOpts().ObjCAutoRefCount) {
5358       // ARC forbids the implicit conversion of object pointers to 'void *',
5359       // so these types are not compatible.
5360       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5361           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5362       LHS = RHS = true;
5363       return QualType();
5364     }
5365     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5366     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5367     QualType destPointee
5368     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5369     QualType destType = Context.getPointerType(destPointee);
5370     // Add qualifiers if necessary.
5371     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5372     // Promote to void*.
5373     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5374     return destType;
5375   }
5376   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5377     if (getLangOpts().ObjCAutoRefCount) {
5378       // ARC forbids the implicit conversion of object pointers to 'void *',
5379       // so these types are not compatible.
5380       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5381           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5382       LHS = RHS = true;
5383       return QualType();
5384     }
5385     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5386     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5387     QualType destPointee
5388     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5389     QualType destType = Context.getPointerType(destPointee);
5390     // Add qualifiers if necessary.
5391     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5392     // Promote to void*.
5393     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5394     return destType;
5395   }
5396   return QualType();
5397 }
5398
5399 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5400 /// ParenRange in parentheses.
5401 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5402                                const PartialDiagnostic &Note,
5403                                SourceRange ParenRange) {
5404   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5405   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5406       EndLoc.isValid()) {
5407     Self.Diag(Loc, Note)
5408       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5409       << FixItHint::CreateInsertion(EndLoc, ")");
5410   } else {
5411     // We can't display the parentheses, so just show the bare note.
5412     Self.Diag(Loc, Note) << ParenRange;
5413   }
5414 }
5415
5416 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5417   return Opc >= BO_Mul && Opc <= BO_Shr;
5418 }
5419
5420 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5421 /// expression, either using a built-in or overloaded operator,
5422 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5423 /// expression.
5424 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5425                                    Expr **RHSExprs) {
5426   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5427   E = E->IgnoreImpCasts();
5428   E = E->IgnoreConversionOperator();
5429   E = E->IgnoreImpCasts();
5430
5431   // Built-in binary operator.
5432   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5433     if (IsArithmeticOp(OP->getOpcode())) {
5434       *Opcode = OP->getOpcode();
5435       *RHSExprs = OP->getRHS();
5436       return true;
5437     }
5438   }
5439
5440   // Overloaded operator.
5441   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5442     if (Call->getNumArgs() != 2)
5443       return false;
5444
5445     // Make sure this is really a binary operator that is safe to pass into
5446     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5447     OverloadedOperatorKind OO = Call->getOperator();
5448     if (OO < OO_Plus || OO > OO_Arrow ||
5449         OO == OO_PlusPlus || OO == OO_MinusMinus)
5450       return false;
5451
5452     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5453     if (IsArithmeticOp(OpKind)) {
5454       *Opcode = OpKind;
5455       *RHSExprs = Call->getArg(1);
5456       return true;
5457     }
5458   }
5459
5460   return false;
5461 }
5462
5463 static bool IsLogicOp(BinaryOperatorKind Opc) {
5464   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5465 }
5466
5467 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5468 /// or is a logical expression such as (x==y) which has int type, but is
5469 /// commonly interpreted as boolean.
5470 static bool ExprLooksBoolean(Expr *E) {
5471   E = E->IgnoreParenImpCasts();
5472
5473   if (E->getType()->isBooleanType())
5474     return true;
5475   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5476     return IsLogicOp(OP->getOpcode());
5477   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5478     return OP->getOpcode() == UO_LNot;
5479
5480   return false;
5481 }
5482
5483 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5484 /// and binary operator are mixed in a way that suggests the programmer assumed
5485 /// the conditional operator has higher precedence, for example:
5486 /// "int x = a + someBinaryCondition ? 1 : 2".
5487 static void DiagnoseConditionalPrecedence(Sema &Self,
5488                                           SourceLocation OpLoc,
5489                                           Expr *Condition,
5490                                           Expr *LHSExpr,
5491                                           Expr *RHSExpr) {
5492   BinaryOperatorKind CondOpcode;
5493   Expr *CondRHS;
5494
5495   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5496     return;
5497   if (!ExprLooksBoolean(CondRHS))
5498     return;
5499
5500   // The condition is an arithmetic binary expression, with a right-
5501   // hand side that looks boolean, so warn.
5502
5503   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5504       << Condition->getSourceRange()
5505       << BinaryOperator::getOpcodeStr(CondOpcode);
5506
5507   SuggestParentheses(Self, OpLoc,
5508     Self.PDiag(diag::note_precedence_silence)
5509       << BinaryOperator::getOpcodeStr(CondOpcode),
5510     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5511
5512   SuggestParentheses(Self, OpLoc,
5513     Self.PDiag(diag::note_precedence_conditional_first),
5514     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5515 }
5516
5517 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5518 /// in the case of a the GNU conditional expr extension.
5519 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5520                                     SourceLocation ColonLoc,
5521                                     Expr *CondExpr, Expr *LHSExpr,
5522                                     Expr *RHSExpr) {
5523   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5524   // was the condition.
5525   OpaqueValueExpr *opaqueValue = 0;
5526   Expr *commonExpr = 0;
5527   if (LHSExpr == 0) {
5528     commonExpr = CondExpr;
5529
5530     // We usually want to apply unary conversions *before* saving, except
5531     // in the special case of a C++ l-value conditional.
5532     if (!(getLangOpts().CPlusPlus
5533           && !commonExpr->isTypeDependent()
5534           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5535           && commonExpr->isGLValue()
5536           && commonExpr->isOrdinaryOrBitFieldObject()
5537           && RHSExpr->isOrdinaryOrBitFieldObject()
5538           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5539       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5540       if (commonRes.isInvalid())
5541         return ExprError();
5542       commonExpr = commonRes.take();
5543     }
5544
5545     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5546                                                 commonExpr->getType(),
5547                                                 commonExpr->getValueKind(),
5548                                                 commonExpr->getObjectKind(),
5549                                                 commonExpr);
5550     LHSExpr = CondExpr = opaqueValue;
5551   }
5552
5553   ExprValueKind VK = VK_RValue;
5554   ExprObjectKind OK = OK_Ordinary;
5555   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5556   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
5557                                              VK, OK, QuestionLoc);
5558   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5559       RHS.isInvalid())
5560     return ExprError();
5561
5562   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5563                                 RHS.get());
5564
5565   if (!commonExpr)
5566     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5567                                                    LHS.take(), ColonLoc, 
5568                                                    RHS.take(), result, VK, OK));
5569
5570   return Owned(new (Context)
5571     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5572                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5573                               OK));
5574 }
5575
5576 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5577 // being closely modeled after the C99 spec:-). The odd characteristic of this
5578 // routine is it effectively iqnores the qualifiers on the top level pointee.
5579 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5580 // FIXME: add a couple examples in this comment.
5581 static Sema::AssignConvertType
5582 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5583   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5584   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5585
5586   // get the "pointed to" type (ignoring qualifiers at the top level)
5587   const Type *lhptee, *rhptee;
5588   Qualifiers lhq, rhq;
5589   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5590   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5591
5592   Sema::AssignConvertType ConvTy = Sema::Compatible;
5593
5594   // C99 6.5.16.1p1: This following citation is common to constraints
5595   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5596   // qualifiers of the type *pointed to* by the right;
5597   Qualifiers lq;
5598
5599   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5600   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5601       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5602     // Ignore lifetime for further calculation.
5603     lhq.removeObjCLifetime();
5604     rhq.removeObjCLifetime();
5605   }
5606
5607   if (!lhq.compatiblyIncludes(rhq)) {
5608     // Treat address-space mismatches as fatal.  TODO: address subspaces
5609     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5610       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5611
5612     // It's okay to add or remove GC or lifetime qualifiers when converting to
5613     // and from void*.
5614     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5615                         .compatiblyIncludes(
5616                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5617              && (lhptee->isVoidType() || rhptee->isVoidType()))
5618       ; // keep old
5619
5620     // Treat lifetime mismatches as fatal.
5621     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5622       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5623     
5624     // For GCC compatibility, other qualifier mismatches are treated
5625     // as still compatible in C.
5626     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5627   }
5628
5629   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5630   // incomplete type and the other is a pointer to a qualified or unqualified
5631   // version of void...
5632   if (lhptee->isVoidType()) {
5633     if (rhptee->isIncompleteOrObjectType())
5634       return ConvTy;
5635
5636     // As an extension, we allow cast to/from void* to function pointer.
5637     assert(rhptee->isFunctionType());
5638     return Sema::FunctionVoidPointer;
5639   }
5640
5641   if (rhptee->isVoidType()) {
5642     if (lhptee->isIncompleteOrObjectType())
5643       return ConvTy;
5644
5645     // As an extension, we allow cast to/from void* to function pointer.
5646     assert(lhptee->isFunctionType());
5647     return Sema::FunctionVoidPointer;
5648   }
5649
5650   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5651   // unqualified versions of compatible types, ...
5652   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5653   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5654     // Check if the pointee types are compatible ignoring the sign.
5655     // We explicitly check for char so that we catch "char" vs
5656     // "unsigned char" on systems where "char" is unsigned.
5657     if (lhptee->isCharType())
5658       ltrans = S.Context.UnsignedCharTy;
5659     else if (lhptee->hasSignedIntegerRepresentation())
5660       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5661
5662     if (rhptee->isCharType())
5663       rtrans = S.Context.UnsignedCharTy;
5664     else if (rhptee->hasSignedIntegerRepresentation())
5665       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5666
5667     if (ltrans == rtrans) {
5668       // Types are compatible ignoring the sign. Qualifier incompatibility
5669       // takes priority over sign incompatibility because the sign
5670       // warning can be disabled.
5671       if (ConvTy != Sema::Compatible)
5672         return ConvTy;
5673
5674       return Sema::IncompatiblePointerSign;
5675     }
5676
5677     // If we are a multi-level pointer, it's possible that our issue is simply
5678     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5679     // the eventual target type is the same and the pointers have the same
5680     // level of indirection, this must be the issue.
5681     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5682       do {
5683         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5684         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5685       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5686
5687       if (lhptee == rhptee)
5688         return Sema::IncompatibleNestedPointerQualifiers;
5689     }
5690
5691     // General pointer incompatibility takes priority over qualifiers.
5692     return Sema::IncompatiblePointer;
5693   }
5694   if (!S.getLangOpts().CPlusPlus &&
5695       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5696     return Sema::IncompatiblePointer;
5697   return ConvTy;
5698 }
5699
5700 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5701 /// block pointer types are compatible or whether a block and normal pointer
5702 /// are compatible. It is more restrict than comparing two function pointer
5703 // types.
5704 static Sema::AssignConvertType
5705 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5706                                     QualType RHSType) {
5707   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5708   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5709
5710   QualType lhptee, rhptee;
5711
5712   // get the "pointed to" type (ignoring qualifiers at the top level)
5713   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5714   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5715
5716   // In C++, the types have to match exactly.
5717   if (S.getLangOpts().CPlusPlus)
5718     return Sema::IncompatibleBlockPointer;
5719
5720   Sema::AssignConvertType ConvTy = Sema::Compatible;
5721
5722   // For blocks we enforce that qualifiers are identical.
5723   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5724     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5725
5726   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5727     return Sema::IncompatibleBlockPointer;
5728
5729   return ConvTy;
5730 }
5731
5732 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5733 /// for assignment compatibility.
5734 static Sema::AssignConvertType
5735 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5736                                    QualType RHSType) {
5737   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5738   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5739
5740   if (LHSType->isObjCBuiltinType()) {
5741     // Class is not compatible with ObjC object pointers.
5742     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5743         !RHSType->isObjCQualifiedClassType())
5744       return Sema::IncompatiblePointer;
5745     return Sema::Compatible;
5746   }
5747   if (RHSType->isObjCBuiltinType()) {
5748     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5749         !LHSType->isObjCQualifiedClassType())
5750       return Sema::IncompatiblePointer;
5751     return Sema::Compatible;
5752   }
5753   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5754   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5755
5756   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5757       // make an exception for id<P>
5758       !LHSType->isObjCQualifiedIdType())
5759     return Sema::CompatiblePointerDiscardsQualifiers;
5760
5761   if (S.Context.typesAreCompatible(LHSType, RHSType))
5762     return Sema::Compatible;
5763   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5764     return Sema::IncompatibleObjCQualifiedId;
5765   return Sema::IncompatiblePointer;
5766 }
5767
5768 Sema::AssignConvertType
5769 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5770                                  QualType LHSType, QualType RHSType) {
5771   // Fake up an opaque expression.  We don't actually care about what
5772   // cast operations are required, so if CheckAssignmentConstraints
5773   // adds casts to this they'll be wasted, but fortunately that doesn't
5774   // usually happen on valid code.
5775   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5776   ExprResult RHSPtr = &RHSExpr;
5777   CastKind K = CK_Invalid;
5778
5779   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5780 }
5781
5782 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5783 /// has code to accommodate several GCC extensions when type checking
5784 /// pointers. Here are some objectionable examples that GCC considers warnings:
5785 ///
5786 ///  int a, *pint;
5787 ///  short *pshort;
5788 ///  struct foo *pfoo;
5789 ///
5790 ///  pint = pshort; // warning: assignment from incompatible pointer type
5791 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5792 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5793 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5794 ///
5795 /// As a result, the code for dealing with pointers is more complex than the
5796 /// C99 spec dictates.
5797 ///
5798 /// Sets 'Kind' for any result kind except Incompatible.
5799 Sema::AssignConvertType
5800 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5801                                  CastKind &Kind) {
5802   QualType RHSType = RHS.get()->getType();
5803   QualType OrigLHSType = LHSType;
5804
5805   // Get canonical types.  We're not formatting these types, just comparing
5806   // them.
5807   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5808   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5809
5810   // Common case: no conversion required.
5811   if (LHSType == RHSType) {
5812     Kind = CK_NoOp;
5813     return Compatible;
5814   }
5815
5816   // If we have an atomic type, try a non-atomic assignment, then just add an
5817   // atomic qualification step.
5818   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5819     Sema::AssignConvertType result =
5820       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5821     if (result != Compatible)
5822       return result;
5823     if (Kind != CK_NoOp)
5824       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5825     Kind = CK_NonAtomicToAtomic;
5826     return Compatible;
5827   }
5828
5829   // If the left-hand side is a reference type, then we are in a
5830   // (rare!) case where we've allowed the use of references in C,
5831   // e.g., as a parameter type in a built-in function. In this case,
5832   // just make sure that the type referenced is compatible with the
5833   // right-hand side type. The caller is responsible for adjusting
5834   // LHSType so that the resulting expression does not have reference
5835   // type.
5836   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5837     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5838       Kind = CK_LValueBitCast;
5839       return Compatible;
5840     }
5841     return Incompatible;
5842   }
5843
5844   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5845   // to the same ExtVector type.
5846   if (LHSType->isExtVectorType()) {
5847     if (RHSType->isExtVectorType())
5848       return Incompatible;
5849     if (RHSType->isArithmeticType()) {
5850       // CK_VectorSplat does T -> vector T, so first cast to the
5851       // element type.
5852       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5853       if (elType != RHSType) {
5854         Kind = PrepareScalarCast(RHS, elType);
5855         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5856       }
5857       Kind = CK_VectorSplat;
5858       return Compatible;
5859     }
5860   }
5861
5862   // Conversions to or from vector type.
5863   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5864     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5865       // Allow assignments of an AltiVec vector type to an equivalent GCC
5866       // vector type and vice versa
5867       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5868         Kind = CK_BitCast;
5869         return Compatible;
5870       }
5871
5872       // If we are allowing lax vector conversions, and LHS and RHS are both
5873       // vectors, the total size only needs to be the same. This is a bitcast;
5874       // no bits are changed but the result type is different.
5875       if (getLangOpts().LaxVectorConversions &&
5876           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5877         Kind = CK_BitCast;
5878         return IncompatibleVectors;
5879       }
5880     }
5881     return Incompatible;
5882   }
5883
5884   // Arithmetic conversions.
5885   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5886       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5887     Kind = PrepareScalarCast(RHS, LHSType);
5888     return Compatible;
5889   }
5890
5891   // Conversions to normal pointers.
5892   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5893     // U* -> T*
5894     if (isa<PointerType>(RHSType)) {
5895       Kind = CK_BitCast;
5896       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5897     }
5898
5899     // int -> T*
5900     if (RHSType->isIntegerType()) {
5901       Kind = CK_IntegralToPointer; // FIXME: null?
5902       return IntToPointer;
5903     }
5904
5905     // C pointers are not compatible with ObjC object pointers,
5906     // with two exceptions:
5907     if (isa<ObjCObjectPointerType>(RHSType)) {
5908       //  - conversions to void*
5909       if (LHSPointer->getPointeeType()->isVoidType()) {
5910         Kind = CK_BitCast;
5911         return Compatible;
5912       }
5913
5914       //  - conversions from 'Class' to the redefinition type
5915       if (RHSType->isObjCClassType() &&
5916           Context.hasSameType(LHSType, 
5917                               Context.getObjCClassRedefinitionType())) {
5918         Kind = CK_BitCast;
5919         return Compatible;
5920       }
5921
5922       Kind = CK_BitCast;
5923       return IncompatiblePointer;
5924     }
5925
5926     // U^ -> void*
5927     if (RHSType->getAs<BlockPointerType>()) {
5928       if (LHSPointer->getPointeeType()->isVoidType()) {
5929         Kind = CK_BitCast;
5930         return Compatible;
5931       }
5932     }
5933
5934     return Incompatible;
5935   }
5936
5937   // Conversions to block pointers.
5938   if (isa<BlockPointerType>(LHSType)) {
5939     // U^ -> T^
5940     if (RHSType->isBlockPointerType()) {
5941       Kind = CK_BitCast;
5942       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5943     }
5944
5945     // int or null -> T^
5946     if (RHSType->isIntegerType()) {
5947       Kind = CK_IntegralToPointer; // FIXME: null
5948       return IntToBlockPointer;
5949     }
5950
5951     // id -> T^
5952     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5953       Kind = CK_AnyPointerToBlockPointerCast;
5954       return Compatible;
5955     }
5956
5957     // void* -> T^
5958     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5959       if (RHSPT->getPointeeType()->isVoidType()) {
5960         Kind = CK_AnyPointerToBlockPointerCast;
5961         return Compatible;
5962       }
5963
5964     return Incompatible;
5965   }
5966
5967   // Conversions to Objective-C pointers.
5968   if (isa<ObjCObjectPointerType>(LHSType)) {
5969     // A* -> B*
5970     if (RHSType->isObjCObjectPointerType()) {
5971       Kind = CK_BitCast;
5972       Sema::AssignConvertType result = 
5973         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5974       if (getLangOpts().ObjCAutoRefCount &&
5975           result == Compatible && 
5976           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5977         result = IncompatibleObjCWeakRef;
5978       return result;
5979     }
5980
5981     // int or null -> A*
5982     if (RHSType->isIntegerType()) {
5983       Kind = CK_IntegralToPointer; // FIXME: null
5984       return IntToPointer;
5985     }
5986
5987     // In general, C pointers are not compatible with ObjC object pointers,
5988     // with two exceptions:
5989     if (isa<PointerType>(RHSType)) {
5990       Kind = CK_CPointerToObjCPointerCast;
5991
5992       //  - conversions from 'void*'
5993       if (RHSType->isVoidPointerType()) {
5994         return Compatible;
5995       }
5996
5997       //  - conversions to 'Class' from its redefinition type
5998       if (LHSType->isObjCClassType() &&
5999           Context.hasSameType(RHSType, 
6000                               Context.getObjCClassRedefinitionType())) {
6001         return Compatible;
6002       }
6003
6004       return IncompatiblePointer;
6005     }
6006
6007     // T^ -> A*
6008     if (RHSType->isBlockPointerType()) {
6009       maybeExtendBlockObject(*this, RHS);
6010       Kind = CK_BlockPointerToObjCPointerCast;
6011       return Compatible;
6012     }
6013
6014     return Incompatible;
6015   }
6016
6017   // Conversions from pointers that are not covered by the above.
6018   if (isa<PointerType>(RHSType)) {
6019     // T* -> _Bool
6020     if (LHSType == Context.BoolTy) {
6021       Kind = CK_PointerToBoolean;
6022       return Compatible;
6023     }
6024
6025     // T* -> int
6026     if (LHSType->isIntegerType()) {
6027       Kind = CK_PointerToIntegral;
6028       return PointerToInt;
6029     }
6030
6031     return Incompatible;
6032   }
6033
6034   // Conversions from Objective-C pointers that are not covered by the above.
6035   if (isa<ObjCObjectPointerType>(RHSType)) {
6036     // T* -> _Bool
6037     if (LHSType == Context.BoolTy) {
6038       Kind = CK_PointerToBoolean;
6039       return Compatible;
6040     }
6041
6042     // T* -> int
6043     if (LHSType->isIntegerType()) {
6044       Kind = CK_PointerToIntegral;
6045       return PointerToInt;
6046     }
6047
6048     return Incompatible;
6049   }
6050
6051   // struct A -> struct B
6052   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
6053     if (Context.typesAreCompatible(LHSType, RHSType)) {
6054       Kind = CK_NoOp;
6055       return Compatible;
6056     }
6057   }
6058
6059   return Incompatible;
6060 }
6061
6062 /// \brief Constructs a transparent union from an expression that is
6063 /// used to initialize the transparent union.
6064 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
6065                                       ExprResult &EResult, QualType UnionType,
6066                                       FieldDecl *Field) {
6067   // Build an initializer list that designates the appropriate member
6068   // of the transparent union.
6069   Expr *E = EResult.take();
6070   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
6071                                                    E, SourceLocation());
6072   Initializer->setType(UnionType);
6073   Initializer->setInitializedFieldInUnion(Field);
6074
6075   // Build a compound literal constructing a value of the transparent
6076   // union type from this initializer list.
6077   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
6078   EResult = S.Owned(
6079     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
6080                                 VK_RValue, Initializer, false));
6081 }
6082
6083 Sema::AssignConvertType
6084 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
6085                                                ExprResult &RHS) {
6086   QualType RHSType = RHS.get()->getType();
6087
6088   // If the ArgType is a Union type, we want to handle a potential
6089   // transparent_union GCC extension.
6090   const RecordType *UT = ArgType->getAsUnionType();
6091   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
6092     return Incompatible;
6093
6094   // The field to initialize within the transparent union.
6095   RecordDecl *UD = UT->getDecl();
6096   FieldDecl *InitField = 0;
6097   // It's compatible if the expression matches any of the fields.
6098   for (RecordDecl::field_iterator it = UD->field_begin(),
6099          itend = UD->field_end();
6100        it != itend; ++it) {
6101     if (it->getType()->isPointerType()) {
6102       // If the transparent union contains a pointer type, we allow:
6103       // 1) void pointer
6104       // 2) null pointer constant
6105       if (RHSType->isPointerType())
6106         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
6107           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
6108           InitField = *it;
6109           break;
6110         }
6111
6112       if (RHS.get()->isNullPointerConstant(Context,
6113                                            Expr::NPC_ValueDependentIsNull)) {
6114         RHS = ImpCastExprToType(RHS.take(), it->getType(),
6115                                 CK_NullToPointer);
6116         InitField = *it;
6117         break;
6118       }
6119     }
6120
6121     CastKind Kind = CK_Invalid;
6122     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
6123           == Compatible) {
6124       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
6125       InitField = *it;
6126       break;
6127     }
6128   }
6129
6130   if (!InitField)
6131     return Incompatible;
6132
6133   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
6134   return Compatible;
6135 }
6136
6137 Sema::AssignConvertType
6138 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
6139                                        bool Diagnose) {
6140   if (getLangOpts().CPlusPlus) {
6141     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
6142       // C++ 5.17p3: If the left operand is not of class type, the
6143       // expression is implicitly converted (C++ 4) to the
6144       // cv-unqualified type of the left operand.
6145       ExprResult Res;
6146       if (Diagnose) {
6147         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6148                                         AA_Assigning);
6149       } else {
6150         ImplicitConversionSequence ICS =
6151             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6152                                   /*SuppressUserConversions=*/false,
6153                                   /*AllowExplicit=*/false,
6154                                   /*InOverloadResolution=*/false,
6155                                   /*CStyle=*/false,
6156                                   /*AllowObjCWritebackConversion=*/false);
6157         if (ICS.isFailure())
6158           return Incompatible;
6159         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
6160                                         ICS, AA_Assigning);
6161       }
6162       if (Res.isInvalid())
6163         return Incompatible;
6164       Sema::AssignConvertType result = Compatible;
6165       if (getLangOpts().ObjCAutoRefCount &&
6166           !CheckObjCARCUnavailableWeakConversion(LHSType,
6167                                                  RHS.get()->getType()))
6168         result = IncompatibleObjCWeakRef;
6169       RHS = Res;
6170       return result;
6171     }
6172
6173     // FIXME: Currently, we fall through and treat C++ classes like C
6174     // structures.
6175     // FIXME: We also fall through for atomics; not sure what should
6176     // happen there, though.
6177   }
6178
6179   // C99 6.5.16.1p1: the left operand is a pointer and the right is
6180   // a null pointer constant.
6181   if ((LHSType->isPointerType() ||
6182        LHSType->isObjCObjectPointerType() ||
6183        LHSType->isBlockPointerType())
6184       && RHS.get()->isNullPointerConstant(Context,
6185                                           Expr::NPC_ValueDependentIsNull)) {
6186     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6187     return Compatible;
6188   }
6189
6190   // This check seems unnatural, however it is necessary to ensure the proper
6191   // conversion of functions/arrays. If the conversion were done for all
6192   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6193   // expressions that suppress this implicit conversion (&, sizeof).
6194   //
6195   // Suppress this for references: C++ 8.5.3p5.
6196   if (!LHSType->isReferenceType()) {
6197     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6198     if (RHS.isInvalid())
6199       return Incompatible;
6200   }
6201
6202   CastKind Kind = CK_Invalid;
6203   Sema::AssignConvertType result =
6204     CheckAssignmentConstraints(LHSType, RHS, Kind);
6205
6206   // C99 6.5.16.1p2: The value of the right operand is converted to the
6207   // type of the assignment expression.
6208   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6209   // so that we can use references in built-in functions even in C.
6210   // The getNonReferenceType() call makes sure that the resulting expression
6211   // does not have reference type.
6212   if (result != Incompatible && RHS.get()->getType() != LHSType)
6213     RHS = ImpCastExprToType(RHS.take(),
6214                             LHSType.getNonLValueExprType(Context), Kind);
6215   return result;
6216 }
6217
6218 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6219                                ExprResult &RHS) {
6220   Diag(Loc, diag::err_typecheck_invalid_operands)
6221     << LHS.get()->getType() << RHS.get()->getType()
6222     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6223   return QualType();
6224 }
6225
6226 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6227                                    SourceLocation Loc, bool IsCompAssign) {
6228   if (!IsCompAssign) {
6229     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6230     if (LHS.isInvalid())
6231       return QualType();
6232   }
6233   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6234   if (RHS.isInvalid())
6235     return QualType();
6236
6237   // For conversion purposes, we ignore any qualifiers.
6238   // For example, "const float" and "float" are equivalent.
6239   QualType LHSType =
6240     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6241   QualType RHSType =
6242     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6243
6244   // If the vector types are identical, return.
6245   if (LHSType == RHSType)
6246     return LHSType;
6247
6248   // Handle the case of equivalent AltiVec and GCC vector types
6249   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6250       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6251     if (LHSType->isExtVectorType()) {
6252       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6253       return LHSType;
6254     }
6255
6256     if (!IsCompAssign)
6257       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6258     return RHSType;
6259   }
6260
6261   if (getLangOpts().LaxVectorConversions &&
6262       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6263     // If we are allowing lax vector conversions, and LHS and RHS are both
6264     // vectors, the total size only needs to be the same. This is a
6265     // bitcast; no bits are changed but the result type is different.
6266     // FIXME: Should we really be allowing this?
6267     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6268     return LHSType;
6269   }
6270
6271   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6272   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6273   bool swapped = false;
6274   if (RHSType->isExtVectorType() && !IsCompAssign) {
6275     swapped = true;
6276     std::swap(RHS, LHS);
6277     std::swap(RHSType, LHSType);
6278   }
6279
6280   // Handle the case of an ext vector and scalar.
6281   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6282     QualType EltTy = LV->getElementType();
6283     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6284       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6285       if (order > 0)
6286         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6287       if (order >= 0) {
6288         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6289         if (swapped) std::swap(RHS, LHS);
6290         return LHSType;
6291       }
6292     }
6293     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6294         RHSType->isRealFloatingType()) {
6295       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6296       if (order > 0)
6297         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6298       if (order >= 0) {
6299         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6300         if (swapped) std::swap(RHS, LHS);
6301         return LHSType;
6302       }
6303     }
6304   }
6305
6306   // Vectors of different size or scalar and non-ext-vector are errors.
6307   if (swapped) std::swap(RHS, LHS);
6308   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6309     << LHS.get()->getType() << RHS.get()->getType()
6310     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6311   return QualType();
6312 }
6313
6314 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6315 // expression.  These are mainly cases where the null pointer is used as an
6316 // integer instead of a pointer.
6317 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6318                                 SourceLocation Loc, bool IsCompare) {
6319   // The canonical way to check for a GNU null is with isNullPointerConstant,
6320   // but we use a bit of a hack here for speed; this is a relatively
6321   // hot path, and isNullPointerConstant is slow.
6322   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6323   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6324
6325   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6326
6327   // Avoid analyzing cases where the result will either be invalid (and
6328   // diagnosed as such) or entirely valid and not something to warn about.
6329   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6330       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6331     return;
6332
6333   // Comparison operations would not make sense with a null pointer no matter
6334   // what the other expression is.
6335   if (!IsCompare) {
6336     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6337         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6338         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6339     return;
6340   }
6341
6342   // The rest of the operations only make sense with a null pointer
6343   // if the other expression is a pointer.
6344   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6345       NonNullType->canDecayToPointerType())
6346     return;
6347
6348   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6349       << LHSNull /* LHS is NULL */ << NonNullType
6350       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6351 }
6352
6353 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6354                                            SourceLocation Loc,
6355                                            bool IsCompAssign, bool IsDiv) {
6356   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6357
6358   if (LHS.get()->getType()->isVectorType() ||
6359       RHS.get()->getType()->isVectorType())
6360     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6361
6362   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6363   if (LHS.isInvalid() || RHS.isInvalid())
6364     return QualType();
6365
6366
6367   if (compType.isNull() || !compType->isArithmeticType())
6368     return InvalidOperands(Loc, LHS, RHS);
6369
6370   // Check for division by zero.
6371   if (IsDiv &&
6372       RHS.get()->isNullPointerConstant(Context,
6373                                        Expr::NPC_ValueDependentIsNotNull))
6374     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6375                                           << RHS.get()->getSourceRange());
6376
6377   return compType;
6378 }
6379
6380 QualType Sema::CheckRemainderOperands(
6381   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6382   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6383
6384   if (LHS.get()->getType()->isVectorType() ||
6385       RHS.get()->getType()->isVectorType()) {
6386     if (LHS.get()->getType()->hasIntegerRepresentation() && 
6387         RHS.get()->getType()->hasIntegerRepresentation())
6388       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6389     return InvalidOperands(Loc, LHS, RHS);
6390   }
6391
6392   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6393   if (LHS.isInvalid() || RHS.isInvalid())
6394     return QualType();
6395
6396   if (compType.isNull() || !compType->isIntegerType())
6397     return InvalidOperands(Loc, LHS, RHS);
6398
6399   // Check for remainder by zero.
6400   if (RHS.get()->isNullPointerConstant(Context,
6401                                        Expr::NPC_ValueDependentIsNotNull))
6402     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6403                                  << RHS.get()->getSourceRange());
6404
6405   return compType;
6406 }
6407
6408 /// \brief Diagnose invalid arithmetic on two void pointers.
6409 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6410                                                 Expr *LHSExpr, Expr *RHSExpr) {
6411   S.Diag(Loc, S.getLangOpts().CPlusPlus
6412                 ? diag::err_typecheck_pointer_arith_void_type
6413                 : diag::ext_gnu_void_ptr)
6414     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6415                             << RHSExpr->getSourceRange();
6416 }
6417
6418 /// \brief Diagnose invalid arithmetic on a void pointer.
6419 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6420                                             Expr *Pointer) {
6421   S.Diag(Loc, S.getLangOpts().CPlusPlus
6422                 ? diag::err_typecheck_pointer_arith_void_type
6423                 : diag::ext_gnu_void_ptr)
6424     << 0 /* one pointer */ << Pointer->getSourceRange();
6425 }
6426
6427 /// \brief Diagnose invalid arithmetic on two function pointers.
6428 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6429                                                     Expr *LHS, Expr *RHS) {
6430   assert(LHS->getType()->isAnyPointerType());
6431   assert(RHS->getType()->isAnyPointerType());
6432   S.Diag(Loc, S.getLangOpts().CPlusPlus
6433                 ? diag::err_typecheck_pointer_arith_function_type
6434                 : diag::ext_gnu_ptr_func_arith)
6435     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6436     // We only show the second type if it differs from the first.
6437     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6438                                                    RHS->getType())
6439     << RHS->getType()->getPointeeType()
6440     << LHS->getSourceRange() << RHS->getSourceRange();
6441 }
6442
6443 /// \brief Diagnose invalid arithmetic on a function pointer.
6444 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6445                                                 Expr *Pointer) {
6446   assert(Pointer->getType()->isAnyPointerType());
6447   S.Diag(Loc, S.getLangOpts().CPlusPlus
6448                 ? diag::err_typecheck_pointer_arith_function_type
6449                 : diag::ext_gnu_ptr_func_arith)
6450     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6451     << 0 /* one pointer, so only one type */
6452     << Pointer->getSourceRange();
6453 }
6454
6455 /// \brief Emit error if Operand is incomplete pointer type
6456 ///
6457 /// \returns True if pointer has incomplete type
6458 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6459                                                  Expr *Operand) {
6460   assert(Operand->getType()->isAnyPointerType() &&
6461          !Operand->getType()->isDependentType());
6462   QualType PointeeTy = Operand->getType()->getPointeeType();
6463   return S.RequireCompleteType(Loc, PointeeTy,
6464                                diag::err_typecheck_arithmetic_incomplete_type,
6465                                PointeeTy, Operand->getSourceRange());
6466 }
6467
6468 /// \brief Check the validity of an arithmetic pointer operand.
6469 ///
6470 /// If the operand has pointer type, this code will check for pointer types
6471 /// which are invalid in arithmetic operations. These will be diagnosed
6472 /// appropriately, including whether or not the use is supported as an
6473 /// extension.
6474 ///
6475 /// \returns True when the operand is valid to use (even if as an extension).
6476 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6477                                             Expr *Operand) {
6478   if (!Operand->getType()->isAnyPointerType()) return true;
6479
6480   QualType PointeeTy = Operand->getType()->getPointeeType();
6481   if (PointeeTy->isVoidType()) {
6482     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6483     return !S.getLangOpts().CPlusPlus;
6484   }
6485   if (PointeeTy->isFunctionType()) {
6486     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6487     return !S.getLangOpts().CPlusPlus;
6488   }
6489
6490   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6491
6492   return true;
6493 }
6494
6495 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6496 /// operands.
6497 ///
6498 /// This routine will diagnose any invalid arithmetic on pointer operands much
6499 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6500 /// for emitting a single diagnostic even for operations where both LHS and RHS
6501 /// are (potentially problematic) pointers.
6502 ///
6503 /// \returns True when the operand is valid to use (even if as an extension).
6504 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6505                                                 Expr *LHSExpr, Expr *RHSExpr) {
6506   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6507   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6508   if (!isLHSPointer && !isRHSPointer) return true;
6509
6510   QualType LHSPointeeTy, RHSPointeeTy;
6511   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6512   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6513
6514   // Check for arithmetic on pointers to incomplete types.
6515   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6516   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6517   if (isLHSVoidPtr || isRHSVoidPtr) {
6518     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6519     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6520     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6521
6522     return !S.getLangOpts().CPlusPlus;
6523   }
6524
6525   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6526   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6527   if (isLHSFuncPtr || isRHSFuncPtr) {
6528     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6529     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6530                                                                 RHSExpr);
6531     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6532
6533     return !S.getLangOpts().CPlusPlus;
6534   }
6535
6536   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6537     return false;
6538   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6539     return false;
6540
6541   return true;
6542 }
6543
6544 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6545 /// literal.
6546 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6547                                   Expr *LHSExpr, Expr *RHSExpr) {
6548   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6549   Expr* IndexExpr = RHSExpr;
6550   if (!StrExpr) {
6551     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6552     IndexExpr = LHSExpr;
6553   }
6554
6555   bool IsStringPlusInt = StrExpr &&
6556       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6557   if (!IsStringPlusInt)
6558     return;
6559
6560   llvm::APSInt index;
6561   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6562     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6563     if (index.isNonNegative() &&
6564         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6565                               index.isUnsigned()))
6566       return;
6567   }
6568
6569   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6570   Self.Diag(OpLoc, diag::warn_string_plus_int)
6571       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6572
6573   // Only print a fixit for "str" + int, not for int + "str".
6574   if (IndexExpr == RHSExpr) {
6575     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6576     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6577         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6578         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6579         << FixItHint::CreateInsertion(EndLoc, "]");
6580   } else
6581     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6582 }
6583
6584 /// \brief Emit error when two pointers are incompatible.
6585 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6586                                            Expr *LHSExpr, Expr *RHSExpr) {
6587   assert(LHSExpr->getType()->isAnyPointerType());
6588   assert(RHSExpr->getType()->isAnyPointerType());
6589   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6590     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6591     << RHSExpr->getSourceRange();
6592 }
6593
6594 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6595     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6596     QualType* CompLHSTy) {
6597   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6598
6599   if (LHS.get()->getType()->isVectorType() ||
6600       RHS.get()->getType()->isVectorType()) {
6601     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6602     if (CompLHSTy) *CompLHSTy = compType;
6603     return compType;
6604   }
6605
6606   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6607   if (LHS.isInvalid() || RHS.isInvalid())
6608     return QualType();
6609
6610   // Diagnose "string literal" '+' int.
6611   if (Opc == BO_Add)
6612     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6613
6614   // handle the common case first (both operands are arithmetic).
6615   if (!compType.isNull() && compType->isArithmeticType()) {
6616     if (CompLHSTy) *CompLHSTy = compType;
6617     return compType;
6618   }
6619
6620   // Type-checking.  Ultimately the pointer's going to be in PExp;
6621   // note that we bias towards the LHS being the pointer.
6622   Expr *PExp = LHS.get(), *IExp = RHS.get();
6623
6624   bool isObjCPointer;
6625   if (PExp->getType()->isPointerType()) {
6626     isObjCPointer = false;
6627   } else if (PExp->getType()->isObjCObjectPointerType()) {
6628     isObjCPointer = true;
6629   } else {
6630     std::swap(PExp, IExp);
6631     if (PExp->getType()->isPointerType()) {
6632       isObjCPointer = false;
6633     } else if (PExp->getType()->isObjCObjectPointerType()) {
6634       isObjCPointer = true;
6635     } else {
6636       return InvalidOperands(Loc, LHS, RHS);
6637     }
6638   }
6639   assert(PExp->getType()->isAnyPointerType());
6640
6641   if (!IExp->getType()->isIntegerType())
6642     return InvalidOperands(Loc, LHS, RHS);
6643
6644   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6645     return QualType();
6646
6647   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6648     return QualType();
6649
6650   // Check array bounds for pointer arithemtic
6651   CheckArrayAccess(PExp, IExp);
6652
6653   if (CompLHSTy) {
6654     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6655     if (LHSTy.isNull()) {
6656       LHSTy = LHS.get()->getType();
6657       if (LHSTy->isPromotableIntegerType())
6658         LHSTy = Context.getPromotedIntegerType(LHSTy);
6659     }
6660     *CompLHSTy = LHSTy;
6661   }
6662
6663   return PExp->getType();
6664 }
6665
6666 // C99 6.5.6
6667 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6668                                         SourceLocation Loc,
6669                                         QualType* CompLHSTy) {
6670   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6671
6672   if (LHS.get()->getType()->isVectorType() ||
6673       RHS.get()->getType()->isVectorType()) {
6674     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6675     if (CompLHSTy) *CompLHSTy = compType;
6676     return compType;
6677   }
6678
6679   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6680   if (LHS.isInvalid() || RHS.isInvalid())
6681     return QualType();
6682
6683   // Enforce type constraints: C99 6.5.6p3.
6684
6685   // Handle the common case first (both operands are arithmetic).
6686   if (!compType.isNull() && compType->isArithmeticType()) {
6687     if (CompLHSTy) *CompLHSTy = compType;
6688     return compType;
6689   }
6690
6691   // Either ptr - int   or   ptr - ptr.
6692   if (LHS.get()->getType()->isAnyPointerType()) {
6693     QualType lpointee = LHS.get()->getType()->getPointeeType();
6694
6695     // Diagnose bad cases where we step over interface counts.
6696     if (LHS.get()->getType()->isObjCObjectPointerType() &&
6697         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6698       return QualType();
6699
6700     // The result type of a pointer-int computation is the pointer type.
6701     if (RHS.get()->getType()->isIntegerType()) {
6702       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6703         return QualType();
6704
6705       // Check array bounds for pointer arithemtic
6706       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6707                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6708
6709       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6710       return LHS.get()->getType();
6711     }
6712
6713     // Handle pointer-pointer subtractions.
6714     if (const PointerType *RHSPTy
6715           = RHS.get()->getType()->getAs<PointerType>()) {
6716       QualType rpointee = RHSPTy->getPointeeType();
6717
6718       if (getLangOpts().CPlusPlus) {
6719         // Pointee types must be the same: C++ [expr.add]
6720         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6721           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6722         }
6723       } else {
6724         // Pointee types must be compatible C99 6.5.6p3
6725         if (!Context.typesAreCompatible(
6726                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6727                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6728           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6729           return QualType();
6730         }
6731       }
6732
6733       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6734                                                LHS.get(), RHS.get()))
6735         return QualType();
6736
6737       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6738       return Context.getPointerDiffType();
6739     }
6740   }
6741
6742   return InvalidOperands(Loc, LHS, RHS);
6743 }
6744
6745 static bool isScopedEnumerationType(QualType T) {
6746   if (const EnumType *ET = dyn_cast<EnumType>(T))
6747     return ET->getDecl()->isScoped();
6748   return false;
6749 }
6750
6751 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6752                                    SourceLocation Loc, unsigned Opc,
6753                                    QualType LHSType) {
6754   // OpenCL 6.3j: shift values are effectively % word size of LHS (more defined),
6755   // so skip remaining warnings as we don't want to modify values within Sema.
6756   if (S.getLangOpts().OpenCL)
6757     return;
6758
6759   llvm::APSInt Right;
6760   // Check right/shifter operand
6761   if (RHS.get()->isValueDependent() ||
6762       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6763     return;
6764
6765   if (Right.isNegative()) {
6766     S.DiagRuntimeBehavior(Loc, RHS.get(),
6767                           S.PDiag(diag::warn_shift_negative)
6768                             << RHS.get()->getSourceRange());
6769     return;
6770   }
6771   llvm::APInt LeftBits(Right.getBitWidth(),
6772                        S.Context.getTypeSize(LHS.get()->getType()));
6773   if (Right.uge(LeftBits)) {
6774     S.DiagRuntimeBehavior(Loc, RHS.get(),
6775                           S.PDiag(diag::warn_shift_gt_typewidth)
6776                             << RHS.get()->getSourceRange());
6777     return;
6778   }
6779   if (Opc != BO_Shl)
6780     return;
6781
6782   // When left shifting an ICE which is signed, we can check for overflow which
6783   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6784   // integers have defined behavior modulo one more than the maximum value
6785   // representable in the result type, so never warn for those.
6786   llvm::APSInt Left;
6787   if (LHS.get()->isValueDependent() ||
6788       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6789       LHSType->hasUnsignedIntegerRepresentation())
6790     return;
6791   llvm::APInt ResultBits =
6792       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6793   if (LeftBits.uge(ResultBits))
6794     return;
6795   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6796   Result = Result.shl(Right);
6797
6798   // Print the bit representation of the signed integer as an unsigned
6799   // hexadecimal number.
6800   SmallString<40> HexResult;
6801   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6802
6803   // If we are only missing a sign bit, this is less likely to result in actual
6804   // bugs -- if the result is cast back to an unsigned type, it will have the
6805   // expected value. Thus we place this behind a different warning that can be
6806   // turned off separately if needed.
6807   if (LeftBits == ResultBits - 1) {
6808     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6809         << HexResult.str() << LHSType
6810         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6811     return;
6812   }
6813
6814   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6815     << HexResult.str() << Result.getMinSignedBits() << LHSType
6816     << Left.getBitWidth() << LHS.get()->getSourceRange()
6817     << RHS.get()->getSourceRange();
6818 }
6819
6820 // C99 6.5.7
6821 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6822                                   SourceLocation Loc, unsigned Opc,
6823                                   bool IsCompAssign) {
6824   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6825
6826   // C99 6.5.7p2: Each of the operands shall have integer type.
6827   if (!LHS.get()->getType()->hasIntegerRepresentation() || 
6828       !RHS.get()->getType()->hasIntegerRepresentation())
6829     return InvalidOperands(Loc, LHS, RHS);
6830
6831   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6832   // hasIntegerRepresentation() above instead of this.
6833   if (isScopedEnumerationType(LHS.get()->getType()) ||
6834       isScopedEnumerationType(RHS.get()->getType())) {
6835     return InvalidOperands(Loc, LHS, RHS);
6836   }
6837
6838   // Vector shifts promote their scalar inputs to vector type.
6839   if (LHS.get()->getType()->isVectorType() ||
6840       RHS.get()->getType()->isVectorType())
6841     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6842
6843   // Shifts don't perform usual arithmetic conversions, they just do integer
6844   // promotions on each operand. C99 6.5.7p3
6845
6846   // For the LHS, do usual unary conversions, but then reset them away
6847   // if this is a compound assignment.
6848   ExprResult OldLHS = LHS;
6849   LHS = UsualUnaryConversions(LHS.take());
6850   if (LHS.isInvalid())
6851     return QualType();
6852   QualType LHSType = LHS.get()->getType();
6853   if (IsCompAssign) LHS = OldLHS;
6854
6855   // The RHS is simpler.
6856   RHS = UsualUnaryConversions(RHS.take());
6857   if (RHS.isInvalid())
6858     return QualType();
6859
6860   // Sanity-check shift operands
6861   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6862
6863   // "The type of the result is that of the promoted left operand."
6864   return LHSType;
6865 }
6866
6867 static bool IsWithinTemplateSpecialization(Decl *D) {
6868   if (DeclContext *DC = D->getDeclContext()) {
6869     if (isa<ClassTemplateSpecializationDecl>(DC))
6870       return true;
6871     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6872       return FD->isFunctionTemplateSpecialization();
6873   }
6874   return false;
6875 }
6876
6877 /// If two different enums are compared, raise a warning.
6878 static void checkEnumComparison(Sema &S, SourceLocation Loc, Expr *LHS,
6879                                 Expr *RHS) {
6880   QualType LHSStrippedType = LHS->IgnoreParenImpCasts()->getType();
6881   QualType RHSStrippedType = RHS->IgnoreParenImpCasts()->getType();
6882
6883   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6884   if (!LHSEnumType)
6885     return;
6886   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6887   if (!RHSEnumType)
6888     return;
6889
6890   // Ignore anonymous enums.
6891   if (!LHSEnumType->getDecl()->getIdentifier())
6892     return;
6893   if (!RHSEnumType->getDecl()->getIdentifier())
6894     return;
6895
6896   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6897     return;
6898
6899   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6900       << LHSStrippedType << RHSStrippedType
6901       << LHS->getSourceRange() << RHS->getSourceRange();
6902 }
6903
6904 /// \brief Diagnose bad pointer comparisons.
6905 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6906                                               ExprResult &LHS, ExprResult &RHS,
6907                                               bool IsError) {
6908   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6909                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6910     << LHS.get()->getType() << RHS.get()->getType()
6911     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6912 }
6913
6914 /// \brief Returns false if the pointers are converted to a composite type,
6915 /// true otherwise.
6916 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6917                                            ExprResult &LHS, ExprResult &RHS) {
6918   // C++ [expr.rel]p2:
6919   //   [...] Pointer conversions (4.10) and qualification
6920   //   conversions (4.4) are performed on pointer operands (or on
6921   //   a pointer operand and a null pointer constant) to bring
6922   //   them to their composite pointer type. [...]
6923   //
6924   // C++ [expr.eq]p1 uses the same notion for (in)equality
6925   // comparisons of pointers.
6926
6927   // C++ [expr.eq]p2:
6928   //   In addition, pointers to members can be compared, or a pointer to
6929   //   member and a null pointer constant. Pointer to member conversions
6930   //   (4.11) and qualification conversions (4.4) are performed to bring
6931   //   them to a common type. If one operand is a null pointer constant,
6932   //   the common type is the type of the other operand. Otherwise, the
6933   //   common type is a pointer to member type similar (4.4) to the type
6934   //   of one of the operands, with a cv-qualification signature (4.4)
6935   //   that is the union of the cv-qualification signatures of the operand
6936   //   types.
6937
6938   QualType LHSType = LHS.get()->getType();
6939   QualType RHSType = RHS.get()->getType();
6940   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6941          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6942
6943   bool NonStandardCompositeType = false;
6944   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6945   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6946   if (T.isNull()) {
6947     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6948     return true;
6949   }
6950
6951   if (NonStandardCompositeType)
6952     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6953       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6954       << RHS.get()->getSourceRange();
6955
6956   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6957   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6958   return false;
6959 }
6960
6961 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6962                                                     ExprResult &LHS,
6963                                                     ExprResult &RHS,
6964                                                     bool IsError) {
6965   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6966                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6967     << LHS.get()->getType() << RHS.get()->getType()
6968     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6969 }
6970
6971 static bool isObjCObjectLiteral(ExprResult &E) {
6972   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
6973   case Stmt::ObjCArrayLiteralClass:
6974   case Stmt::ObjCDictionaryLiteralClass:
6975   case Stmt::ObjCStringLiteralClass:
6976   case Stmt::ObjCBoxedExprClass:
6977     return true;
6978   default:
6979     // Note that ObjCBoolLiteral is NOT an object literal!
6980     return false;
6981   }
6982 }
6983
6984 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6985   const ObjCObjectPointerType *Type =
6986     LHS->getType()->getAs<ObjCObjectPointerType>();
6987
6988   // If this is not actually an Objective-C object, bail out.
6989   if (!Type)
6990     return false;
6991
6992   // Get the LHS object's interface type.
6993   QualType InterfaceType = Type->getPointeeType();
6994   if (const ObjCObjectType *iQFaceTy =
6995       InterfaceType->getAsObjCQualifiedInterfaceType())
6996     InterfaceType = iQFaceTy->getBaseType();
6997
6998   // If the RHS isn't an Objective-C object, bail out.
6999   if (!RHS->getType()->isObjCObjectPointerType())
7000     return false;
7001
7002   // Try to find the -isEqual: method.
7003   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
7004   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
7005                                                       InterfaceType,
7006                                                       /*instance=*/true);
7007   if (!Method) {
7008     if (Type->isObjCIdType()) {
7009       // For 'id', just check the global pool.
7010       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
7011                                                   /*receiverId=*/true,
7012                                                   /*warn=*/false);
7013     } else {
7014       // Check protocols.
7015       Method = S.LookupMethodInQualifiedType(IsEqualSel, Type,
7016                                              /*instance=*/true);
7017     }
7018   }
7019
7020   if (!Method)
7021     return false;
7022
7023   QualType T = Method->param_begin()[0]->getType();
7024   if (!T->isObjCObjectPointerType())
7025     return false;
7026   
7027   QualType R = Method->getResultType();
7028   if (!R->isScalarType())
7029     return false;
7030
7031   return true;
7032 }
7033
7034 Sema::ObjCLiteralKind Sema::CheckLiteralKind(Expr *FromE) {
7035   FromE = FromE->IgnoreParenImpCasts();
7036   switch (FromE->getStmtClass()) {
7037     default:
7038       break;
7039     case Stmt::ObjCStringLiteralClass:
7040       // "string literal"
7041       return LK_String;
7042     case Stmt::ObjCArrayLiteralClass:
7043       // "array literal"
7044       return LK_Array;
7045     case Stmt::ObjCDictionaryLiteralClass:
7046       // "dictionary literal"
7047       return LK_Dictionary;
7048     case Stmt::BlockExprClass:
7049       return LK_Block;
7050     case Stmt::ObjCBoxedExprClass: {
7051       Expr *Inner = cast<ObjCBoxedExpr>(FromE)->getSubExpr()->IgnoreParens();
7052       switch (Inner->getStmtClass()) {
7053         case Stmt::IntegerLiteralClass:
7054         case Stmt::FloatingLiteralClass:
7055         case Stmt::CharacterLiteralClass:
7056         case Stmt::ObjCBoolLiteralExprClass:
7057         case Stmt::CXXBoolLiteralExprClass:
7058           // "numeric literal"
7059           return LK_Numeric;
7060         case Stmt::ImplicitCastExprClass: {
7061           CastKind CK = cast<CastExpr>(Inner)->getCastKind();
7062           // Boolean literals can be represented by implicit casts.
7063           if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast)
7064             return LK_Numeric;
7065           break;
7066         }
7067         default:
7068           break;
7069       }
7070       return LK_Boxed;
7071     }
7072   }
7073   return LK_None;
7074 }
7075
7076 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
7077                                           ExprResult &LHS, ExprResult &RHS,
7078                                           BinaryOperator::Opcode Opc){
7079   Expr *Literal;
7080   Expr *Other;
7081   if (isObjCObjectLiteral(LHS)) {
7082     Literal = LHS.get();
7083     Other = RHS.get();
7084   } else {
7085     Literal = RHS.get();
7086     Other = LHS.get();
7087   }
7088
7089   // Don't warn on comparisons against nil.
7090   Other = Other->IgnoreParenCasts();
7091   if (Other->isNullPointerConstant(S.getASTContext(),
7092                                    Expr::NPC_ValueDependentIsNotNull))
7093     return;
7094
7095   // This should be kept in sync with warn_objc_literal_comparison.
7096   // LK_String should always be after the other literals, since it has its own
7097   // warning flag.
7098   Sema::ObjCLiteralKind LiteralKind = S.CheckLiteralKind(Literal);
7099   assert(LiteralKind != Sema::LK_Block);
7100   if (LiteralKind == Sema::LK_None) {
7101     llvm_unreachable("Unknown Objective-C object literal kind");
7102   }
7103
7104   if (LiteralKind == Sema::LK_String)
7105     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
7106       << Literal->getSourceRange();
7107   else
7108     S.Diag(Loc, diag::warn_objc_literal_comparison)
7109       << LiteralKind << Literal->getSourceRange();
7110
7111   if (BinaryOperator::isEqualityOp(Opc) &&
7112       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
7113     SourceLocation Start = LHS.get()->getLocStart();
7114     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
7115     CharSourceRange OpRange =
7116       CharSourceRange::getCharRange(Loc, S.PP.getLocForEndOfToken(Loc));
7117
7118     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
7119       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
7120       << FixItHint::CreateReplacement(OpRange, " isEqual:")
7121       << FixItHint::CreateInsertion(End, "]");
7122   }
7123 }
7124
7125 // C99 6.5.8, C++ [expr.rel]
7126 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
7127                                     SourceLocation Loc, unsigned OpaqueOpc,
7128                                     bool IsRelational) {
7129   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
7130
7131   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
7132
7133   // Handle vector comparisons separately.
7134   if (LHS.get()->getType()->isVectorType() ||
7135       RHS.get()->getType()->isVectorType())
7136     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
7137
7138   QualType LHSType = LHS.get()->getType();
7139   QualType RHSType = RHS.get()->getType();
7140
7141   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
7142   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
7143
7144   checkEnumComparison(*this, Loc, LHS.get(), RHS.get());
7145
7146   if (!LHSType->hasFloatingRepresentation() &&
7147       !(LHSType->isBlockPointerType() && IsRelational) &&
7148       !LHS.get()->getLocStart().isMacroID() &&
7149       !RHS.get()->getLocStart().isMacroID()) {
7150     // For non-floating point types, check for self-comparisons of the form
7151     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7152     // often indicate logic errors in the program.
7153     //
7154     // NOTE: Don't warn about comparison expressions resulting from macro
7155     // expansion. Also don't warn about comparisons which are only self
7156     // comparisons within a template specialization. The warnings should catch
7157     // obvious cases in the definition of the template anyways. The idea is to
7158     // warn when the typed comparison operator will always evaluate to the same
7159     // result.
7160     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
7161       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
7162         if (DRL->getDecl() == DRR->getDecl() &&
7163             !IsWithinTemplateSpecialization(DRL->getDecl())) {
7164           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7165                               << 0 // self-
7166                               << (Opc == BO_EQ
7167                                   || Opc == BO_LE
7168                                   || Opc == BO_GE));
7169         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
7170                    !DRL->getDecl()->getType()->isReferenceType() &&
7171                    !DRR->getDecl()->getType()->isReferenceType()) {
7172             // what is it always going to eval to?
7173             char always_evals_to;
7174             switch(Opc) {
7175             case BO_EQ: // e.g. array1 == array2
7176               always_evals_to = 0; // false
7177               break;
7178             case BO_NE: // e.g. array1 != array2
7179               always_evals_to = 1; // true
7180               break;
7181             default:
7182               // best we can say is 'a constant'
7183               always_evals_to = 2; // e.g. array1 <= array2
7184               break;
7185             }
7186             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7187                                 << 1 // array
7188                                 << always_evals_to);
7189         }
7190       }
7191     }
7192
7193     if (isa<CastExpr>(LHSStripped))
7194       LHSStripped = LHSStripped->IgnoreParenCasts();
7195     if (isa<CastExpr>(RHSStripped))
7196       RHSStripped = RHSStripped->IgnoreParenCasts();
7197
7198     // Warn about comparisons against a string constant (unless the other
7199     // operand is null), the user probably wants strcmp.
7200     Expr *literalString = 0;
7201     Expr *literalStringStripped = 0;
7202     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7203         !RHSStripped->isNullPointerConstant(Context,
7204                                             Expr::NPC_ValueDependentIsNull)) {
7205       literalString = LHS.get();
7206       literalStringStripped = LHSStripped;
7207     } else if ((isa<StringLiteral>(RHSStripped) ||
7208                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7209                !LHSStripped->isNullPointerConstant(Context,
7210                                             Expr::NPC_ValueDependentIsNull)) {
7211       literalString = RHS.get();
7212       literalStringStripped = RHSStripped;
7213     }
7214
7215     if (literalString) {
7216       std::string resultComparison;
7217       switch (Opc) {
7218       case BO_LT: resultComparison = ") < 0"; break;
7219       case BO_GT: resultComparison = ") > 0"; break;
7220       case BO_LE: resultComparison = ") <= 0"; break;
7221       case BO_GE: resultComparison = ") >= 0"; break;
7222       case BO_EQ: resultComparison = ") == 0"; break;
7223       case BO_NE: resultComparison = ") != 0"; break;
7224       default: llvm_unreachable("Invalid comparison operator");
7225       }
7226
7227       DiagRuntimeBehavior(Loc, 0,
7228         PDiag(diag::warn_stringcompare)
7229           << isa<ObjCEncodeExpr>(literalStringStripped)
7230           << literalString->getSourceRange());
7231     }
7232   }
7233
7234   // C99 6.5.8p3 / C99 6.5.9p4
7235   if (LHS.get()->getType()->isArithmeticType() &&
7236       RHS.get()->getType()->isArithmeticType()) {
7237     UsualArithmeticConversions(LHS, RHS);
7238     if (LHS.isInvalid() || RHS.isInvalid())
7239       return QualType();
7240   }
7241   else {
7242     LHS = UsualUnaryConversions(LHS.take());
7243     if (LHS.isInvalid())
7244       return QualType();
7245
7246     RHS = UsualUnaryConversions(RHS.take());
7247     if (RHS.isInvalid())
7248       return QualType();
7249   }
7250
7251   LHSType = LHS.get()->getType();
7252   RHSType = RHS.get()->getType();
7253
7254   // The result of comparisons is 'bool' in C++, 'int' in C.
7255   QualType ResultTy = Context.getLogicalOperationType();
7256
7257   if (IsRelational) {
7258     if (LHSType->isRealType() && RHSType->isRealType())
7259       return ResultTy;
7260   } else {
7261     // Check for comparisons of floating point operands using != and ==.
7262     if (LHSType->hasFloatingRepresentation())
7263       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7264
7265     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7266       return ResultTy;
7267   }
7268
7269   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7270                                               Expr::NPC_ValueDependentIsNull);
7271   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7272                                               Expr::NPC_ValueDependentIsNull);
7273
7274   // All of the following pointer-related warnings are GCC extensions, except
7275   // when handling null pointer constants. 
7276   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7277     QualType LCanPointeeTy =
7278       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7279     QualType RCanPointeeTy =
7280       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7281
7282     if (getLangOpts().CPlusPlus) {
7283       if (LCanPointeeTy == RCanPointeeTy)
7284         return ResultTy;
7285       if (!IsRelational &&
7286           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7287         // Valid unless comparison between non-null pointer and function pointer
7288         // This is a gcc extension compatibility comparison.
7289         // In a SFINAE context, we treat this as a hard error to maintain
7290         // conformance with the C++ standard.
7291         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7292             && !LHSIsNull && !RHSIsNull) {
7293           diagnoseFunctionPointerToVoidComparison(
7294               *this, Loc, LHS, RHS, /*isError*/ (bool)isSFINAEContext());
7295           
7296           if (isSFINAEContext())
7297             return QualType();
7298           
7299           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7300           return ResultTy;
7301         }
7302       }
7303
7304       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7305         return QualType();
7306       else
7307         return ResultTy;
7308     }
7309     // C99 6.5.9p2 and C99 6.5.8p2
7310     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7311                                    RCanPointeeTy.getUnqualifiedType())) {
7312       // Valid unless a relational comparison of function pointers
7313       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7314         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7315           << LHSType << RHSType << LHS.get()->getSourceRange()
7316           << RHS.get()->getSourceRange();
7317       }
7318     } else if (!IsRelational &&
7319                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7320       // Valid unless comparison between non-null pointer and function pointer
7321       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7322           && !LHSIsNull && !RHSIsNull)
7323         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7324                                                 /*isError*/false);
7325     } else {
7326       // Invalid
7327       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7328     }
7329     if (LCanPointeeTy != RCanPointeeTy) {
7330       if (LHSIsNull && !RHSIsNull)
7331         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7332       else
7333         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7334     }
7335     return ResultTy;
7336   }
7337
7338   if (getLangOpts().CPlusPlus) {
7339     // Comparison of nullptr_t with itself.
7340     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7341       return ResultTy;
7342     
7343     // Comparison of pointers with null pointer constants and equality
7344     // comparisons of member pointers to null pointer constants.
7345     if (RHSIsNull &&
7346         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7347          (!IsRelational && 
7348           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7349       RHS = ImpCastExprToType(RHS.take(), LHSType, 
7350                         LHSType->isMemberPointerType()
7351                           ? CK_NullToMemberPointer
7352                           : CK_NullToPointer);
7353       return ResultTy;
7354     }
7355     if (LHSIsNull &&
7356         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7357          (!IsRelational && 
7358           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7359       LHS = ImpCastExprToType(LHS.take(), RHSType, 
7360                         RHSType->isMemberPointerType()
7361                           ? CK_NullToMemberPointer
7362                           : CK_NullToPointer);
7363       return ResultTy;
7364     }
7365
7366     // Comparison of member pointers.
7367     if (!IsRelational &&
7368         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7369       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7370         return QualType();
7371       else
7372         return ResultTy;
7373     }
7374
7375     // Handle scoped enumeration types specifically, since they don't promote
7376     // to integers.
7377     if (LHS.get()->getType()->isEnumeralType() &&
7378         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7379                                        RHS.get()->getType()))
7380       return ResultTy;
7381   }
7382
7383   // Handle block pointer types.
7384   if (!IsRelational && LHSType->isBlockPointerType() &&
7385       RHSType->isBlockPointerType()) {
7386     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7387     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7388
7389     if (!LHSIsNull && !RHSIsNull &&
7390         !Context.typesAreCompatible(lpointee, rpointee)) {
7391       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7392         << LHSType << RHSType << LHS.get()->getSourceRange()
7393         << RHS.get()->getSourceRange();
7394     }
7395     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7396     return ResultTy;
7397   }
7398
7399   // Allow block pointers to be compared with null pointer constants.
7400   if (!IsRelational
7401       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7402           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7403     if (!LHSIsNull && !RHSIsNull) {
7404       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7405              ->getPointeeType()->isVoidType())
7406             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7407                 ->getPointeeType()->isVoidType())))
7408         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7409           << LHSType << RHSType << LHS.get()->getSourceRange()
7410           << RHS.get()->getSourceRange();
7411     }
7412     if (LHSIsNull && !RHSIsNull)
7413       LHS = ImpCastExprToType(LHS.take(), RHSType,
7414                               RHSType->isPointerType() ? CK_BitCast
7415                                 : CK_AnyPointerToBlockPointerCast);
7416     else
7417       RHS = ImpCastExprToType(RHS.take(), LHSType,
7418                               LHSType->isPointerType() ? CK_BitCast
7419                                 : CK_AnyPointerToBlockPointerCast);
7420     return ResultTy;
7421   }
7422
7423   if (LHSType->isObjCObjectPointerType() ||
7424       RHSType->isObjCObjectPointerType()) {
7425     const PointerType *LPT = LHSType->getAs<PointerType>();
7426     const PointerType *RPT = RHSType->getAs<PointerType>();
7427     if (LPT || RPT) {
7428       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7429       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7430
7431       if (!LPtrToVoid && !RPtrToVoid &&
7432           !Context.typesAreCompatible(LHSType, RHSType)) {
7433         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7434                                           /*isError*/false);
7435       }
7436       if (LHSIsNull && !RHSIsNull)
7437         LHS = ImpCastExprToType(LHS.take(), RHSType,
7438                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7439       else
7440         RHS = ImpCastExprToType(RHS.take(), LHSType,
7441                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7442       return ResultTy;
7443     }
7444     if (LHSType->isObjCObjectPointerType() &&
7445         RHSType->isObjCObjectPointerType()) {
7446       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7447         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7448                                           /*isError*/false);
7449       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7450         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7451
7452       if (LHSIsNull && !RHSIsNull)
7453         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7454       else
7455         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7456       return ResultTy;
7457     }
7458   }
7459   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7460       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7461     unsigned DiagID = 0;
7462     bool isError = false;
7463     if (LangOpts.DebuggerSupport) {
7464       // Under a debugger, allow the comparison of pointers to integers,
7465       // since users tend to want to compare addresses.
7466     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7467         (RHSIsNull && RHSType->isIntegerType())) {
7468       if (IsRelational && !getLangOpts().CPlusPlus)
7469         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7470     } else if (IsRelational && !getLangOpts().CPlusPlus)
7471       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7472     else if (getLangOpts().CPlusPlus) {
7473       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7474       isError = true;
7475     } else
7476       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7477
7478     if (DiagID) {
7479       Diag(Loc, DiagID)
7480         << LHSType << RHSType << LHS.get()->getSourceRange()
7481         << RHS.get()->getSourceRange();
7482       if (isError)
7483         return QualType();
7484     }
7485     
7486     if (LHSType->isIntegerType())
7487       LHS = ImpCastExprToType(LHS.take(), RHSType,
7488                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7489     else
7490       RHS = ImpCastExprToType(RHS.take(), LHSType,
7491                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7492     return ResultTy;
7493   }
7494   
7495   // Handle block pointers.
7496   if (!IsRelational && RHSIsNull
7497       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7498     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7499     return ResultTy;
7500   }
7501   if (!IsRelational && LHSIsNull
7502       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7503     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7504     return ResultTy;
7505   }
7506
7507   return InvalidOperands(Loc, LHS, RHS);
7508 }
7509
7510
7511 // Return a signed type that is of identical size and number of elements.
7512 // For floating point vectors, return an integer type of identical size 
7513 // and number of elements.
7514 QualType Sema::GetSignedVectorType(QualType V) {
7515   const VectorType *VTy = V->getAs<VectorType>();
7516   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7517   if (TypeSize == Context.getTypeSize(Context.CharTy))
7518     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7519   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7520     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7521   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7522     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7523   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7524     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7525   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7526          "Unhandled vector element size in vector compare");
7527   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7528 }
7529
7530 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7531 /// operates on extended vector types.  Instead of producing an IntTy result,
7532 /// like a scalar comparison, a vector comparison produces a vector of integer
7533 /// types.
7534 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7535                                           SourceLocation Loc,
7536                                           bool IsRelational) {
7537   // Check to make sure we're operating on vectors of the same type and width,
7538   // Allowing one side to be a scalar of element type.
7539   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7540   if (vType.isNull())
7541     return vType;
7542
7543   QualType LHSType = LHS.get()->getType();
7544
7545   // If AltiVec, the comparison results in a numeric type, i.e.
7546   // bool for C++, int for C
7547   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7548     return Context.getLogicalOperationType();
7549
7550   // For non-floating point types, check for self-comparisons of the form
7551   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7552   // often indicate logic errors in the program.
7553   if (!LHSType->hasFloatingRepresentation()) {
7554     if (DeclRefExpr* DRL
7555           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7556       if (DeclRefExpr* DRR
7557             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7558         if (DRL->getDecl() == DRR->getDecl())
7559           DiagRuntimeBehavior(Loc, 0,
7560                               PDiag(diag::warn_comparison_always)
7561                                 << 0 // self-
7562                                 << 2 // "a constant"
7563                               );
7564   }
7565
7566   // Check for comparisons of floating point operands using != and ==.
7567   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7568     assert (RHS.get()->getType()->hasFloatingRepresentation());
7569     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7570   }
7571   
7572   // Return a signed type for the vector.
7573   return GetSignedVectorType(LHSType);
7574 }
7575
7576 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7577                                           SourceLocation Loc) {
7578   // Ensure that either both operands are of the same vector type, or
7579   // one operand is of a vector type and the other is of its element type.
7580   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7581   if (vType.isNull())
7582     return InvalidOperands(Loc, LHS, RHS);
7583   if (getLangOpts().OpenCL && getLangOpts().OpenCLVersion < 120 &&
7584       vType->hasFloatingRepresentation())
7585     return InvalidOperands(Loc, LHS, RHS);
7586   
7587   return GetSignedVectorType(LHS.get()->getType());
7588 }
7589
7590 inline QualType Sema::CheckBitwiseOperands(
7591   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7592   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7593
7594   if (LHS.get()->getType()->isVectorType() ||
7595       RHS.get()->getType()->isVectorType()) {
7596     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7597         RHS.get()->getType()->hasIntegerRepresentation())
7598       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7599     
7600     return InvalidOperands(Loc, LHS, RHS);
7601   }
7602
7603   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7604   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7605                                                  IsCompAssign);
7606   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7607     return QualType();
7608   LHS = LHSResult.take();
7609   RHS = RHSResult.take();
7610
7611   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7612     return compType;
7613   return InvalidOperands(Loc, LHS, RHS);
7614 }
7615
7616 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7617   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7618   
7619   // Check vector operands differently.
7620   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7621     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7622   
7623   // Diagnose cases where the user write a logical and/or but probably meant a
7624   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7625   // is a constant.
7626   if (LHS.get()->getType()->isIntegerType() &&
7627       !LHS.get()->getType()->isBooleanType() &&
7628       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7629       // Don't warn in macros or template instantiations.
7630       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7631     // If the RHS can be constant folded, and if it constant folds to something
7632     // that isn't 0 or 1 (which indicate a potential logical operation that
7633     // happened to fold to true/false) then warn.
7634     // Parens on the RHS are ignored.
7635     llvm::APSInt Result;
7636     if (RHS.get()->EvaluateAsInt(Result, Context))
7637       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7638           (Result != 0 && Result != 1)) {
7639         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7640           << RHS.get()->getSourceRange()
7641           << (Opc == BO_LAnd ? "&&" : "||");
7642         // Suggest replacing the logical operator with the bitwise version
7643         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7644             << (Opc == BO_LAnd ? "&" : "|")
7645             << FixItHint::CreateReplacement(SourceRange(
7646                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7647                                                 getLangOpts())),
7648                                             Opc == BO_LAnd ? "&" : "|");
7649         if (Opc == BO_LAnd)
7650           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7651           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7652               << FixItHint::CreateRemoval(
7653                   SourceRange(
7654                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7655                                                  0, getSourceManager(),
7656                                                  getLangOpts()),
7657                       RHS.get()->getLocEnd()));
7658       }
7659   }
7660
7661   if (!Context.getLangOpts().CPlusPlus) {
7662     // OpenCL v1.1 s6.3.g: The logical operators and (&&), or (||) do
7663     // not operate on the built-in scalar and vector float types.
7664     if (Context.getLangOpts().OpenCL &&
7665         Context.getLangOpts().OpenCLVersion < 120) {
7666       if (LHS.get()->getType()->isFloatingType() ||
7667           RHS.get()->getType()->isFloatingType())
7668         return InvalidOperands(Loc, LHS, RHS);
7669     }
7670
7671     LHS = UsualUnaryConversions(LHS.take());
7672     if (LHS.isInvalid())
7673       return QualType();
7674
7675     RHS = UsualUnaryConversions(RHS.take());
7676     if (RHS.isInvalid())
7677       return QualType();
7678
7679     if (!LHS.get()->getType()->isScalarType() ||
7680         !RHS.get()->getType()->isScalarType())
7681       return InvalidOperands(Loc, LHS, RHS);
7682
7683     return Context.IntTy;
7684   }
7685
7686   // The following is safe because we only use this method for
7687   // non-overloadable operands.
7688
7689   // C++ [expr.log.and]p1
7690   // C++ [expr.log.or]p1
7691   // The operands are both contextually converted to type bool.
7692   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7693   if (LHSRes.isInvalid())
7694     return InvalidOperands(Loc, LHS, RHS);
7695   LHS = LHSRes;
7696
7697   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7698   if (RHSRes.isInvalid())
7699     return InvalidOperands(Loc, LHS, RHS);
7700   RHS = RHSRes;
7701
7702   // C++ [expr.log.and]p2
7703   // C++ [expr.log.or]p2
7704   // The result is a bool.
7705   return Context.BoolTy;
7706 }
7707
7708 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7709 /// is a read-only property; return true if so. A readonly property expression
7710 /// depends on various declarations and thus must be treated specially.
7711 ///
7712 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7713   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7714   if (!PropExpr) return false;
7715   if (PropExpr->isImplicitProperty()) return false;
7716
7717   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7718   QualType BaseType = PropExpr->isSuperReceiver() ? 
7719                             PropExpr->getSuperReceiverType() :  
7720                             PropExpr->getBase()->getType();
7721       
7722   if (const ObjCObjectPointerType *OPT =
7723       BaseType->getAsObjCInterfacePointerType())
7724     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7725       if (S.isPropertyReadonly(PDecl, IFace))
7726         return true;
7727   return false;
7728 }
7729
7730 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7731   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7732   if (!ME) return false;
7733   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7734   ObjCMessageExpr *Base =
7735     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7736   if (!Base) return false;
7737   return Base->getMethodDecl() != 0;
7738 }
7739
7740 /// Is the given expression (which must be 'const') a reference to a
7741 /// variable which was originally non-const, but which has become
7742 /// 'const' due to being captured within a block?
7743 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7744 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7745   assert(E->isLValue() && E->getType().isConstQualified());
7746   E = E->IgnoreParens();
7747
7748   // Must be a reference to a declaration from an enclosing scope.
7749   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7750   if (!DRE) return NCCK_None;
7751   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7752
7753   // The declaration must be a variable which is not declared 'const'.
7754   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7755   if (!var) return NCCK_None;
7756   if (var->getType().isConstQualified()) return NCCK_None;
7757   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7758
7759   // Decide whether the first capture was for a block or a lambda.
7760   DeclContext *DC = S.CurContext;
7761   while (DC->getParent() != var->getDeclContext())
7762     DC = DC->getParent();
7763   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7764 }
7765
7766 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7767 /// emit an error and return true.  If so, return false.
7768 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7769   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7770   SourceLocation OrigLoc = Loc;
7771   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7772                                                               &Loc);
7773   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7774     IsLV = Expr::MLV_ReadonlyProperty;
7775   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7776     IsLV = Expr::MLV_InvalidMessageExpression;
7777   if (IsLV == Expr::MLV_Valid)
7778     return false;
7779
7780   unsigned Diag = 0;
7781   bool NeedType = false;
7782   switch (IsLV) { // C99 6.5.16p2
7783   case Expr::MLV_ConstQualified:
7784     Diag = diag::err_typecheck_assign_const;
7785
7786     // Use a specialized diagnostic when we're assigning to an object
7787     // from an enclosing function or block.
7788     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7789       if (NCCK == NCCK_Block)
7790         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7791       else
7792         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7793       break;
7794     }
7795
7796     // In ARC, use some specialized diagnostics for occasions where we
7797     // infer 'const'.  These are always pseudo-strong variables.
7798     if (S.getLangOpts().ObjCAutoRefCount) {
7799       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7800       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7801         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7802
7803         // Use the normal diagnostic if it's pseudo-__strong but the
7804         // user actually wrote 'const'.
7805         if (var->isARCPseudoStrong() &&
7806             (!var->getTypeSourceInfo() ||
7807              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7808           // There are two pseudo-strong cases:
7809           //  - self
7810           ObjCMethodDecl *method = S.getCurMethodDecl();
7811           if (method && var == method->getSelfDecl())
7812             Diag = method->isClassMethod()
7813               ? diag::err_typecheck_arc_assign_self_class_method
7814               : diag::err_typecheck_arc_assign_self;
7815
7816           //  - fast enumeration variables
7817           else
7818             Diag = diag::err_typecheck_arr_assign_enumeration;
7819
7820           SourceRange Assign;
7821           if (Loc != OrigLoc)
7822             Assign = SourceRange(OrigLoc, OrigLoc);
7823           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7824           // We need to preserve the AST regardless, so migration tool 
7825           // can do its job.
7826           return false;
7827         }
7828       }
7829     }
7830
7831     break;
7832   case Expr::MLV_ArrayType:
7833   case Expr::MLV_ArrayTemporary:
7834     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7835     NeedType = true;
7836     break;
7837   case Expr::MLV_NotObjectType:
7838     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7839     NeedType = true;
7840     break;
7841   case Expr::MLV_LValueCast:
7842     Diag = diag::err_typecheck_lvalue_casts_not_supported;
7843     break;
7844   case Expr::MLV_Valid:
7845     llvm_unreachable("did not take early return for MLV_Valid");
7846   case Expr::MLV_InvalidExpression:
7847   case Expr::MLV_MemberFunction:
7848   case Expr::MLV_ClassTemporary:
7849     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7850     break;
7851   case Expr::MLV_IncompleteType:
7852   case Expr::MLV_IncompleteVoidType:
7853     return S.RequireCompleteType(Loc, E->getType(),
7854              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7855   case Expr::MLV_DuplicateVectorComponents:
7856     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7857     break;
7858   case Expr::MLV_ReadonlyProperty:
7859   case Expr::MLV_NoSetterProperty:
7860     llvm_unreachable("readonly properties should be processed differently");
7861   case Expr::MLV_InvalidMessageExpression:
7862     Diag = diag::error_readonly_message_assignment;
7863     break;
7864   case Expr::MLV_SubObjCPropertySetting:
7865     Diag = diag::error_no_subobject_property_setting;
7866     break;
7867   }
7868
7869   SourceRange Assign;
7870   if (Loc != OrigLoc)
7871     Assign = SourceRange(OrigLoc, OrigLoc);
7872   if (NeedType)
7873     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7874   else
7875     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7876   return true;
7877 }
7878
7879 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7880                                          SourceLocation Loc,
7881                                          Sema &Sema) {
7882   // C / C++ fields
7883   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7884   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7885   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7886     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7887       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7888   }
7889
7890   // Objective-C instance variables
7891   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7892   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7893   if (OL && OR && OL->getDecl() == OR->getDecl()) {
7894     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7895     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7896     if (RL && RR && RL->getDecl() == RR->getDecl())
7897       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7898   }
7899 }
7900
7901 // C99 6.5.16.1
7902 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7903                                        SourceLocation Loc,
7904                                        QualType CompoundType) {
7905   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7906
7907   // Verify that LHS is a modifiable lvalue, and emit error if not.
7908   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7909     return QualType();
7910
7911   QualType LHSType = LHSExpr->getType();
7912   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7913                                              CompoundType;
7914   AssignConvertType ConvTy;
7915   if (CompoundType.isNull()) {
7916     Expr *RHSCheck = RHS.get();
7917
7918     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7919
7920     QualType LHSTy(LHSType);
7921     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7922     if (RHS.isInvalid())
7923       return QualType();
7924     // Special case of NSObject attributes on c-style pointer types.
7925     if (ConvTy == IncompatiblePointer &&
7926         ((Context.isObjCNSObjectType(LHSType) &&
7927           RHSType->isObjCObjectPointerType()) ||
7928          (Context.isObjCNSObjectType(RHSType) &&
7929           LHSType->isObjCObjectPointerType())))
7930       ConvTy = Compatible;
7931
7932     if (ConvTy == Compatible &&
7933         LHSType->isObjCObjectType())
7934         Diag(Loc, diag::err_objc_object_assignment)
7935           << LHSType;
7936
7937     // If the RHS is a unary plus or minus, check to see if they = and + are
7938     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7939     // instead of "x += 4".
7940     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7941       RHSCheck = ICE->getSubExpr();
7942     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7943       if ((UO->getOpcode() == UO_Plus ||
7944            UO->getOpcode() == UO_Minus) &&
7945           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7946           // Only if the two operators are exactly adjacent.
7947           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7948           // And there is a space or other character before the subexpr of the
7949           // unary +/-.  We don't want to warn on "x=-1".
7950           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7951           UO->getSubExpr()->getLocStart().isFileID()) {
7952         Diag(Loc, diag::warn_not_compound_assign)
7953           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7954           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7955       }
7956     }
7957
7958     if (ConvTy == Compatible) {
7959       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7960         // Warn about retain cycles where a block captures the LHS, but
7961         // not if the LHS is a simple variable into which the block is
7962         // being stored...unless that variable can be captured by reference!
7963         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7964         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7965         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7966           checkRetainCycles(LHSExpr, RHS.get());
7967
7968         // It is safe to assign a weak reference into a strong variable.
7969         // Although this code can still have problems:
7970         //   id x = self.weakProp;
7971         //   id y = self.weakProp;
7972         // we do not warn to warn spuriously when 'x' and 'y' are on separate
7973         // paths through the function. This should be revisited if
7974         // -Wrepeated-use-of-weak is made flow-sensitive.
7975         DiagnosticsEngine::Level Level =
7976           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7977                                    RHS.get()->getLocStart());
7978         if (Level != DiagnosticsEngine::Ignored)
7979           getCurFunction()->markSafeWeakUse(RHS.get());
7980
7981       } else if (getLangOpts().ObjCAutoRefCount) {
7982         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7983       }
7984     }
7985   } else {
7986     // Compound assignment "x += y"
7987     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7988   }
7989
7990   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7991                                RHS.get(), AA_Assigning))
7992     return QualType();
7993
7994   CheckForNullPointerDereference(*this, LHSExpr);
7995
7996   // C99 6.5.16p3: The type of an assignment expression is the type of the
7997   // left operand unless the left operand has qualified type, in which case
7998   // it is the unqualified version of the type of the left operand.
7999   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
8000   // is converted to the type of the assignment expression (above).
8001   // C++ 5.17p1: the type of the assignment expression is that of its left
8002   // operand.
8003   return (getLangOpts().CPlusPlus
8004           ? LHSType : LHSType.getUnqualifiedType());
8005 }
8006
8007 // C99 6.5.17
8008 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
8009                                    SourceLocation Loc) {
8010   LHS = S.CheckPlaceholderExpr(LHS.take());
8011   RHS = S.CheckPlaceholderExpr(RHS.take());
8012   if (LHS.isInvalid() || RHS.isInvalid())
8013     return QualType();
8014
8015   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
8016   // operands, but not unary promotions.
8017   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
8018
8019   // So we treat the LHS as a ignored value, and in C++ we allow the
8020   // containing site to determine what should be done with the RHS.
8021   LHS = S.IgnoredValueConversions(LHS.take());
8022   if (LHS.isInvalid())
8023     return QualType();
8024
8025   S.DiagnoseUnusedExprResult(LHS.get());
8026
8027   if (!S.getLangOpts().CPlusPlus) {
8028     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
8029     if (RHS.isInvalid())
8030       return QualType();
8031     if (!RHS.get()->getType()->isVoidType())
8032       S.RequireCompleteType(Loc, RHS.get()->getType(),
8033                             diag::err_incomplete_type);
8034   }
8035
8036   return RHS.get()->getType();
8037 }
8038
8039 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
8040 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
8041 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
8042                                                ExprValueKind &VK,
8043                                                SourceLocation OpLoc,
8044                                                bool IsInc, bool IsPrefix) {
8045   if (Op->isTypeDependent())
8046     return S.Context.DependentTy;
8047
8048   QualType ResType = Op->getType();
8049   // Atomic types can be used for increment / decrement where the non-atomic
8050   // versions can, so ignore the _Atomic() specifier for the purpose of
8051   // checking.
8052   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
8053     ResType = ResAtomicType->getValueType();
8054
8055   assert(!ResType.isNull() && "no type for increment/decrement expression");
8056
8057   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
8058     // Decrement of bool is not allowed.
8059     if (!IsInc) {
8060       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
8061       return QualType();
8062     }
8063     // Increment of bool sets it to true, but is deprecated.
8064     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
8065   } else if (ResType->isRealType()) {
8066     // OK!
8067   } else if (ResType->isPointerType()) {
8068     // C99 6.5.2.4p2, 6.5.6p2
8069     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
8070       return QualType();
8071   } else if (ResType->isObjCObjectPointerType()) {
8072     // On modern runtimes, ObjC pointer arithmetic is forbidden.
8073     // Otherwise, we just need a complete type.
8074     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
8075         checkArithmeticOnObjCPointer(S, OpLoc, Op))
8076       return QualType();    
8077   } else if (ResType->isAnyComplexType()) {
8078     // C99 does not support ++/-- on complex types, we allow as an extension.
8079     S.Diag(OpLoc, diag::ext_integer_increment_complex)
8080       << ResType << Op->getSourceRange();
8081   } else if (ResType->isPlaceholderType()) {
8082     ExprResult PR = S.CheckPlaceholderExpr(Op);
8083     if (PR.isInvalid()) return QualType();
8084     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
8085                                           IsInc, IsPrefix);
8086   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
8087     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
8088   } else {
8089     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
8090       << ResType << int(IsInc) << Op->getSourceRange();
8091     return QualType();
8092   }
8093   // At this point, we know we have a real, complex or pointer type.
8094   // Now make sure the operand is a modifiable lvalue.
8095   if (CheckForModifiableLvalue(Op, OpLoc, S))
8096     return QualType();
8097   // In C++, a prefix increment is the same type as the operand. Otherwise
8098   // (in C or with postfix), the increment is the unqualified type of the
8099   // operand.
8100   if (IsPrefix && S.getLangOpts().CPlusPlus) {
8101     VK = VK_LValue;
8102     return ResType;
8103   } else {
8104     VK = VK_RValue;
8105     return ResType.getUnqualifiedType();
8106   }
8107 }
8108   
8109
8110 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
8111 /// This routine allows us to typecheck complex/recursive expressions
8112 /// where the declaration is needed for type checking. We only need to
8113 /// handle cases when the expression references a function designator
8114 /// or is an lvalue. Here are some examples:
8115 ///  - &(x) => x
8116 ///  - &*****f => f for f a function designator.
8117 ///  - &s.xx => s
8118 ///  - &s.zz[1].yy -> s, if zz is an array
8119 ///  - *(x + 1) -> x, if x is an array
8120 ///  - &"123"[2] -> 0
8121 ///  - & __real__ x -> x
8122 static ValueDecl *getPrimaryDecl(Expr *E) {
8123   switch (E->getStmtClass()) {
8124   case Stmt::DeclRefExprClass:
8125     return cast<DeclRefExpr>(E)->getDecl();
8126   case Stmt::MemberExprClass:
8127     // If this is an arrow operator, the address is an offset from
8128     // the base's value, so the object the base refers to is
8129     // irrelevant.
8130     if (cast<MemberExpr>(E)->isArrow())
8131       return 0;
8132     // Otherwise, the expression refers to a part of the base
8133     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
8134   case Stmt::ArraySubscriptExprClass: {
8135     // FIXME: This code shouldn't be necessary!  We should catch the implicit
8136     // promotion of register arrays earlier.
8137     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
8138     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
8139       if (ICE->getSubExpr()->getType()->isArrayType())
8140         return getPrimaryDecl(ICE->getSubExpr());
8141     }
8142     return 0;
8143   }
8144   case Stmt::UnaryOperatorClass: {
8145     UnaryOperator *UO = cast<UnaryOperator>(E);
8146
8147     switch(UO->getOpcode()) {
8148     case UO_Real:
8149     case UO_Imag:
8150     case UO_Extension:
8151       return getPrimaryDecl(UO->getSubExpr());
8152     default:
8153       return 0;
8154     }
8155   }
8156   case Stmt::ParenExprClass:
8157     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
8158   case Stmt::ImplicitCastExprClass:
8159     // If the result of an implicit cast is an l-value, we care about
8160     // the sub-expression; otherwise, the result here doesn't matter.
8161     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
8162   default:
8163     return 0;
8164   }
8165 }
8166
8167 namespace {
8168   enum {
8169     AO_Bit_Field = 0,
8170     AO_Vector_Element = 1,
8171     AO_Property_Expansion = 2,
8172     AO_Register_Variable = 3,
8173     AO_No_Error = 4
8174   };
8175 }
8176 /// \brief Diagnose invalid operand for address of operations.
8177 ///
8178 /// \param Type The type of operand which cannot have its address taken.
8179 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
8180                                          Expr *E, unsigned Type) {
8181   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
8182 }
8183
8184 /// CheckAddressOfOperand - The operand of & must be either a function
8185 /// designator or an lvalue designating an object. If it is an lvalue, the
8186 /// object cannot be declared with storage class register or be a bit field.
8187 /// Note: The usual conversions are *not* applied to the operand of the &
8188 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
8189 /// In C++, the operand might be an overloaded function name, in which case
8190 /// we allow the '&' but retain the overloaded-function type.
8191 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
8192                                       SourceLocation OpLoc) {
8193   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8194     if (PTy->getKind() == BuiltinType::Overload) {
8195       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8196         assert(cast<UnaryOperator>(OrigOp.get()->IgnoreParens())->getOpcode()
8197                  == UO_AddrOf);
8198         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof_addrof_function)
8199           << OrigOp.get()->getSourceRange();
8200         return QualType();
8201       }
8202                   
8203       return S.Context.OverloadTy;
8204     }
8205
8206     if (PTy->getKind() == BuiltinType::UnknownAny)
8207       return S.Context.UnknownAnyTy;
8208
8209     if (PTy->getKind() == BuiltinType::BoundMember) {
8210       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8211         << OrigOp.get()->getSourceRange();
8212       return QualType();
8213     }
8214
8215     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8216     if (OrigOp.isInvalid()) return QualType();
8217   }
8218
8219   if (OrigOp.get()->isTypeDependent())
8220     return S.Context.DependentTy;
8221
8222   assert(!OrigOp.get()->getType()->isPlaceholderType());
8223
8224   // Make sure to ignore parentheses in subsequent checks
8225   Expr *op = OrigOp.get()->IgnoreParens();
8226
8227   if (S.getLangOpts().C99) {
8228     // Implement C99-only parts of addressof rules.
8229     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8230       if (uOp->getOpcode() == UO_Deref)
8231         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8232         // (assuming the deref expression is valid).
8233         return uOp->getSubExpr()->getType();
8234     }
8235     // Technically, there should be a check for array subscript
8236     // expressions here, but the result of one is always an lvalue anyway.
8237   }
8238   ValueDecl *dcl = getPrimaryDecl(op);
8239   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8240   unsigned AddressOfError = AO_No_Error;
8241
8242   if (lval == Expr::LV_ClassTemporary || lval == Expr::LV_ArrayTemporary) { 
8243     bool sfinae = (bool)S.isSFINAEContext();
8244     S.Diag(OpLoc, S.isSFINAEContext() ? diag::err_typecheck_addrof_temporary
8245                          : diag::ext_typecheck_addrof_temporary)
8246       << op->getType() << op->getSourceRange();
8247     if (sfinae)
8248       return QualType();
8249   } else if (isa<ObjCSelectorExpr>(op)) {
8250     return S.Context.getPointerType(op->getType());
8251   } else if (lval == Expr::LV_MemberFunction) {
8252     // If it's an instance method, make a member pointer.
8253     // The expression must have exactly the form &A::foo.
8254
8255     // If the underlying expression isn't a decl ref, give up.
8256     if (!isa<DeclRefExpr>(op)) {
8257       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8258         << OrigOp.get()->getSourceRange();
8259       return QualType();
8260     }
8261     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8262     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8263
8264     // The id-expression was parenthesized.
8265     if (OrigOp.get() != DRE) {
8266       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8267         << OrigOp.get()->getSourceRange();
8268
8269     // The method was named without a qualifier.
8270     } else if (!DRE->getQualifier()) {
8271       if (MD->getParent()->getName().empty())
8272         S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8273           << op->getSourceRange();
8274       else {
8275         SmallString<32> Str;
8276         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8277         S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8278           << op->getSourceRange()
8279           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8280       }
8281     }
8282
8283     return S.Context.getMemberPointerType(op->getType(),
8284               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8285   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8286     // C99 6.5.3.2p1
8287     // The operand must be either an l-value or a function designator
8288     if (!op->getType()->isFunctionType()) {
8289       // Use a special diagnostic for loads from property references.
8290       if (isa<PseudoObjectExpr>(op)) {
8291         AddressOfError = AO_Property_Expansion;
8292       } else {
8293         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8294           << op->getType() << op->getSourceRange();
8295         return QualType();
8296       }
8297     }
8298   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8299     // The operand cannot be a bit-field
8300     AddressOfError = AO_Bit_Field;
8301   } else if (op->getObjectKind() == OK_VectorComponent) {
8302     // The operand cannot be an element of a vector
8303     AddressOfError = AO_Vector_Element;
8304   } else if (dcl) { // C99 6.5.3.2p1
8305     // We have an lvalue with a decl. Make sure the decl is not declared
8306     // with the register storage-class specifier.
8307     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8308       // in C++ it is not error to take address of a register
8309       // variable (c++03 7.1.1P3)
8310       if (vd->getStorageClass() == SC_Register &&
8311           !S.getLangOpts().CPlusPlus) {
8312         AddressOfError = AO_Register_Variable;
8313       }
8314     } else if (isa<FunctionTemplateDecl>(dcl)) {
8315       return S.Context.OverloadTy;
8316     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8317       // Okay: we can take the address of a field.
8318       // Could be a pointer to member, though, if there is an explicit
8319       // scope qualifier for the class.
8320       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8321         DeclContext *Ctx = dcl->getDeclContext();
8322         if (Ctx && Ctx->isRecord()) {
8323           if (dcl->getType()->isReferenceType()) {
8324             S.Diag(OpLoc,
8325                    diag::err_cannot_form_pointer_to_member_of_reference_type)
8326               << dcl->getDeclName() << dcl->getType();
8327             return QualType();
8328           }
8329
8330           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8331             Ctx = Ctx->getParent();
8332           return S.Context.getMemberPointerType(op->getType(),
8333                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8334         }
8335       }
8336     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8337       llvm_unreachable("Unknown/unexpected decl type");
8338   }
8339
8340   if (AddressOfError != AO_No_Error) {
8341     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8342     return QualType();
8343   }
8344
8345   if (lval == Expr::LV_IncompleteVoidType) {
8346     // Taking the address of a void variable is technically illegal, but we
8347     // allow it in cases which are otherwise valid.
8348     // Example: "extern void x; void* y = &x;".
8349     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8350   }
8351
8352   // If the operand has type "type", the result has type "pointer to type".
8353   if (op->getType()->isObjCObjectType())
8354     return S.Context.getObjCObjectPointerType(op->getType());
8355   return S.Context.getPointerType(op->getType());
8356 }
8357
8358 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8359 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8360                                         SourceLocation OpLoc) {
8361   if (Op->isTypeDependent())
8362     return S.Context.DependentTy;
8363
8364   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8365   if (ConvResult.isInvalid())
8366     return QualType();
8367   Op = ConvResult.take();
8368   QualType OpTy = Op->getType();
8369   QualType Result;
8370
8371   if (isa<CXXReinterpretCastExpr>(Op)) {
8372     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8373     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8374                                      Op->getSourceRange());
8375   }
8376
8377   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8378   // is an incomplete type or void.  It would be possible to warn about
8379   // dereferencing a void pointer, but it's completely well-defined, and such a
8380   // warning is unlikely to catch any mistakes.
8381   if (const PointerType *PT = OpTy->getAs<PointerType>())
8382     Result = PT->getPointeeType();
8383   else if (const ObjCObjectPointerType *OPT =
8384              OpTy->getAs<ObjCObjectPointerType>())
8385     Result = OPT->getPointeeType();
8386   else {
8387     ExprResult PR = S.CheckPlaceholderExpr(Op);
8388     if (PR.isInvalid()) return QualType();
8389     if (PR.take() != Op)
8390       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8391   }
8392
8393   if (Result.isNull()) {
8394     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8395       << OpTy << Op->getSourceRange();
8396     return QualType();
8397   }
8398
8399   // Dereferences are usually l-values...
8400   VK = VK_LValue;
8401
8402   // ...except that certain expressions are never l-values in C.
8403   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8404     VK = VK_RValue;
8405   
8406   return Result;
8407 }
8408
8409 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8410   tok::TokenKind Kind) {
8411   BinaryOperatorKind Opc;
8412   switch (Kind) {
8413   default: llvm_unreachable("Unknown binop!");
8414   case tok::periodstar:           Opc = BO_PtrMemD; break;
8415   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8416   case tok::star:                 Opc = BO_Mul; break;
8417   case tok::slash:                Opc = BO_Div; break;
8418   case tok::percent:              Opc = BO_Rem; break;
8419   case tok::plus:                 Opc = BO_Add; break;
8420   case tok::minus:                Opc = BO_Sub; break;
8421   case tok::lessless:             Opc = BO_Shl; break;
8422   case tok::greatergreater:       Opc = BO_Shr; break;
8423   case tok::lessequal:            Opc = BO_LE; break;
8424   case tok::less:                 Opc = BO_LT; break;
8425   case tok::greaterequal:         Opc = BO_GE; break;
8426   case tok::greater:              Opc = BO_GT; break;
8427   case tok::exclaimequal:         Opc = BO_NE; break;
8428   case tok::equalequal:           Opc = BO_EQ; break;
8429   case tok::amp:                  Opc = BO_And; break;
8430   case tok::caret:                Opc = BO_Xor; break;
8431   case tok::pipe:                 Opc = BO_Or; break;
8432   case tok::ampamp:               Opc = BO_LAnd; break;
8433   case tok::pipepipe:             Opc = BO_LOr; break;
8434   case tok::equal:                Opc = BO_Assign; break;
8435   case tok::starequal:            Opc = BO_MulAssign; break;
8436   case tok::slashequal:           Opc = BO_DivAssign; break;
8437   case tok::percentequal:         Opc = BO_RemAssign; break;
8438   case tok::plusequal:            Opc = BO_AddAssign; break;
8439   case tok::minusequal:           Opc = BO_SubAssign; break;
8440   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8441   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8442   case tok::ampequal:             Opc = BO_AndAssign; break;
8443   case tok::caretequal:           Opc = BO_XorAssign; break;
8444   case tok::pipeequal:            Opc = BO_OrAssign; break;
8445   case tok::comma:                Opc = BO_Comma; break;
8446   }
8447   return Opc;
8448 }
8449
8450 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8451   tok::TokenKind Kind) {
8452   UnaryOperatorKind Opc;
8453   switch (Kind) {
8454   default: llvm_unreachable("Unknown unary op!");
8455   case tok::plusplus:     Opc = UO_PreInc; break;
8456   case tok::minusminus:   Opc = UO_PreDec; break;
8457   case tok::amp:          Opc = UO_AddrOf; break;
8458   case tok::star:         Opc = UO_Deref; break;
8459   case tok::plus:         Opc = UO_Plus; break;
8460   case tok::minus:        Opc = UO_Minus; break;
8461   case tok::tilde:        Opc = UO_Not; break;
8462   case tok::exclaim:      Opc = UO_LNot; break;
8463   case tok::kw___real:    Opc = UO_Real; break;
8464   case tok::kw___imag:    Opc = UO_Imag; break;
8465   case tok::kw___extension__: Opc = UO_Extension; break;
8466   }
8467   return Opc;
8468 }
8469
8470 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8471 /// This warning is only emitted for builtin assignment operations. It is also
8472 /// suppressed in the event of macro expansions.
8473 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8474                                    SourceLocation OpLoc) {
8475   if (!S.ActiveTemplateInstantiations.empty())
8476     return;
8477   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8478     return;
8479   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8480   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8481   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8482   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8483   if (!LHSDeclRef || !RHSDeclRef ||
8484       LHSDeclRef->getLocation().isMacroID() ||
8485       RHSDeclRef->getLocation().isMacroID())
8486     return;
8487   const ValueDecl *LHSDecl =
8488     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8489   const ValueDecl *RHSDecl =
8490     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8491   if (LHSDecl != RHSDecl)
8492     return;
8493   if (LHSDecl->getType().isVolatileQualified())
8494     return;
8495   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8496     if (RefTy->getPointeeType().isVolatileQualified())
8497       return;
8498
8499   S.Diag(OpLoc, diag::warn_self_assignment)
8500       << LHSDeclRef->getType()
8501       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8502 }
8503
8504 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8505 /// operator @p Opc at location @c TokLoc. This routine only supports
8506 /// built-in operations; ActOnBinOp handles overloaded operators.
8507 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8508                                     BinaryOperatorKind Opc,
8509                                     Expr *LHSExpr, Expr *RHSExpr) {
8510   if (getLangOpts().CPlusPlus11 && isa<InitListExpr>(RHSExpr)) {
8511     // The syntax only allows initializer lists on the RHS of assignment,
8512     // so we don't need to worry about accepting invalid code for
8513     // non-assignment operators.
8514     // C++11 5.17p9:
8515     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8516     //   of x = {} is x = T().
8517     InitializationKind Kind =
8518         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8519     InitializedEntity Entity =
8520         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8521     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8522     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8523     if (Init.isInvalid())
8524       return Init;
8525     RHSExpr = Init.take();
8526   }
8527
8528   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8529   QualType ResultTy;     // Result type of the binary operator.
8530   // The following two variables are used for compound assignment operators
8531   QualType CompLHSTy;    // Type of LHS after promotions for computation
8532   QualType CompResultTy; // Type of computation result
8533   ExprValueKind VK = VK_RValue;
8534   ExprObjectKind OK = OK_Ordinary;
8535
8536   switch (Opc) {
8537   case BO_Assign:
8538     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8539     if (getLangOpts().CPlusPlus &&
8540         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8541       VK = LHS.get()->getValueKind();
8542       OK = LHS.get()->getObjectKind();
8543     }
8544     if (!ResultTy.isNull())
8545       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8546     break;
8547   case BO_PtrMemD:
8548   case BO_PtrMemI:
8549     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8550                                             Opc == BO_PtrMemI);
8551     break;
8552   case BO_Mul:
8553   case BO_Div:
8554     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8555                                            Opc == BO_Div);
8556     break;
8557   case BO_Rem:
8558     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8559     break;
8560   case BO_Add:
8561     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8562     break;
8563   case BO_Sub:
8564     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8565     break;
8566   case BO_Shl:
8567   case BO_Shr:
8568     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8569     break;
8570   case BO_LE:
8571   case BO_LT:
8572   case BO_GE:
8573   case BO_GT:
8574     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8575     break;
8576   case BO_EQ:
8577   case BO_NE:
8578     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8579     break;
8580   case BO_And:
8581   case BO_Xor:
8582   case BO_Or:
8583     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8584     break;
8585   case BO_LAnd:
8586   case BO_LOr:
8587     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8588     break;
8589   case BO_MulAssign:
8590   case BO_DivAssign:
8591     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8592                                                Opc == BO_DivAssign);
8593     CompLHSTy = CompResultTy;
8594     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8595       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8596     break;
8597   case BO_RemAssign:
8598     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8599     CompLHSTy = CompResultTy;
8600     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8601       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8602     break;
8603   case BO_AddAssign:
8604     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8605     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8606       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8607     break;
8608   case BO_SubAssign:
8609     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8610     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8611       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8612     break;
8613   case BO_ShlAssign:
8614   case BO_ShrAssign:
8615     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8616     CompLHSTy = CompResultTy;
8617     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8618       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8619     break;
8620   case BO_AndAssign:
8621   case BO_XorAssign:
8622   case BO_OrAssign:
8623     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8624     CompLHSTy = CompResultTy;
8625     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8626       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8627     break;
8628   case BO_Comma:
8629     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8630     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8631       VK = RHS.get()->getValueKind();
8632       OK = RHS.get()->getObjectKind();
8633     }
8634     break;
8635   }
8636   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8637     return ExprError();
8638
8639   // Check for array bounds violations for both sides of the BinaryOperator
8640   CheckArrayAccess(LHS.get());
8641   CheckArrayAccess(RHS.get());
8642
8643   if (const ObjCIsaExpr *OISA = dyn_cast<ObjCIsaExpr>(LHS.get()->IgnoreParenCasts())) {
8644     NamedDecl *ObjectSetClass = LookupSingleName(TUScope,
8645                                                  &Context.Idents.get("object_setClass"),
8646                                                  SourceLocation(), LookupOrdinaryName);
8647     if (ObjectSetClass && isa<ObjCIsaExpr>(LHS.get())) {
8648       SourceLocation RHSLocEnd = PP.getLocForEndOfToken(RHS.get()->getLocEnd());
8649       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign) <<
8650       FixItHint::CreateInsertion(LHS.get()->getLocStart(), "object_setClass(") <<
8651       FixItHint::CreateReplacement(SourceRange(OISA->getOpLoc(), OpLoc), ",") <<
8652       FixItHint::CreateInsertion(RHSLocEnd, ")");
8653     }
8654     else
8655       Diag(LHS.get()->getExprLoc(), diag::warn_objc_isa_assign);
8656   }
8657   else if (const ObjCIvarRefExpr *OIRE =
8658            dyn_cast<ObjCIvarRefExpr>(LHS.get()->IgnoreParenCasts()))
8659     DiagnoseDirectIsaAccess(*this, OIRE, OpLoc, RHS.get());
8660   
8661   if (CompResultTy.isNull())
8662     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8663                                               ResultTy, VK, OK, OpLoc,
8664                                               FPFeatures.fp_contract));
8665   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8666       OK_ObjCProperty) {
8667     VK = VK_LValue;
8668     OK = LHS.get()->getObjectKind();
8669   }
8670   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8671                                                     ResultTy, VK, OK, CompLHSTy,
8672                                                     CompResultTy, OpLoc,
8673                                                     FPFeatures.fp_contract));
8674 }
8675
8676 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8677 /// operators are mixed in a way that suggests that the programmer forgot that
8678 /// comparison operators have higher precedence. The most typical example of
8679 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8680 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8681                                       SourceLocation OpLoc, Expr *LHSExpr,
8682                                       Expr *RHSExpr) {
8683   BinaryOperator *LHSBO = dyn_cast<BinaryOperator>(LHSExpr);
8684   BinaryOperator *RHSBO = dyn_cast<BinaryOperator>(RHSExpr);
8685
8686   // Check that one of the sides is a comparison operator.
8687   bool isLeftComp = LHSBO && LHSBO->isComparisonOp();
8688   bool isRightComp = RHSBO && RHSBO->isComparisonOp();
8689   if (!isLeftComp && !isRightComp)
8690     return;
8691
8692   // Bitwise operations are sometimes used as eager logical ops.
8693   // Don't diagnose this.
8694   bool isLeftBitwise = LHSBO && LHSBO->isBitwiseOp();
8695   bool isRightBitwise = RHSBO && RHSBO->isBitwiseOp();
8696   if ((isLeftComp || isLeftBitwise) && (isRightComp || isRightBitwise))
8697     return;
8698
8699   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8700                                                    OpLoc)
8701                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
8702   StringRef OpStr = isLeftComp ? LHSBO->getOpcodeStr() : RHSBO->getOpcodeStr();
8703   SourceRange ParensRange = isLeftComp ?
8704       SourceRange(LHSBO->getRHS()->getLocStart(), RHSExpr->getLocEnd())
8705     : SourceRange(LHSExpr->getLocStart(), RHSBO->getLHS()->getLocStart());
8706
8707   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8708     << DiagRange << BinaryOperator::getOpcodeStr(Opc) << OpStr;
8709   SuggestParentheses(Self, OpLoc,
8710     Self.PDiag(diag::note_precedence_silence) << OpStr,
8711     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8712   SuggestParentheses(Self, OpLoc,
8713     Self.PDiag(diag::note_precedence_bitwise_first)
8714       << BinaryOperator::getOpcodeStr(Opc),
8715     ParensRange);
8716 }
8717
8718 /// \brief It accepts a '&' expr that is inside a '|' one.
8719 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8720 /// in parentheses.
8721 static void
8722 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8723                                        BinaryOperator *Bop) {
8724   assert(Bop->getOpcode() == BO_And);
8725   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8726       << Bop->getSourceRange() << OpLoc;
8727   SuggestParentheses(Self, Bop->getOperatorLoc(),
8728     Self.PDiag(diag::note_precedence_silence)
8729       << Bop->getOpcodeStr(),
8730     Bop->getSourceRange());
8731 }
8732
8733 /// \brief It accepts a '&&' expr that is inside a '||' one.
8734 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8735 /// in parentheses.
8736 static void
8737 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8738                                        BinaryOperator *Bop) {
8739   assert(Bop->getOpcode() == BO_LAnd);
8740   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8741       << Bop->getSourceRange() << OpLoc;
8742   SuggestParentheses(Self, Bop->getOperatorLoc(),
8743     Self.PDiag(diag::note_precedence_silence)
8744       << Bop->getOpcodeStr(),
8745     Bop->getSourceRange());
8746 }
8747
8748 /// \brief Returns true if the given expression can be evaluated as a constant
8749 /// 'true'.
8750 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8751   bool Res;
8752   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8753 }
8754
8755 /// \brief Returns true if the given expression can be evaluated as a constant
8756 /// 'false'.
8757 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8758   bool Res;
8759   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8760 }
8761
8762 /// \brief Look for '&&' in the left hand of a '||' expr.
8763 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8764                                              Expr *LHSExpr, Expr *RHSExpr) {
8765   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8766     if (Bop->getOpcode() == BO_LAnd) {
8767       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8768       if (EvaluatesAsFalse(S, RHSExpr))
8769         return;
8770       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8771       if (!EvaluatesAsTrue(S, Bop->getLHS()))
8772         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8773     } else if (Bop->getOpcode() == BO_LOr) {
8774       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8775         // If it's "a || b && 1 || c" we didn't warn earlier for
8776         // "a || b && 1", but warn now.
8777         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8778           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8779       }
8780     }
8781   }
8782 }
8783
8784 /// \brief Look for '&&' in the right hand of a '||' expr.
8785 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8786                                              Expr *LHSExpr, Expr *RHSExpr) {
8787   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8788     if (Bop->getOpcode() == BO_LAnd) {
8789       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8790       if (EvaluatesAsFalse(S, LHSExpr))
8791         return;
8792       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8793       if (!EvaluatesAsTrue(S, Bop->getRHS()))
8794         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8795     }
8796   }
8797 }
8798
8799 /// \brief Look for '&' in the left or right hand of a '|' expr.
8800 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8801                                              Expr *OrArg) {
8802   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8803     if (Bop->getOpcode() == BO_And)
8804       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8805   }
8806 }
8807
8808 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8809                                     Expr *SubExpr, StringRef Shift) {
8810   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8811     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
8812       StringRef Op = Bop->getOpcodeStr();
8813       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
8814           << Bop->getSourceRange() << OpLoc << Shift << Op;
8815       SuggestParentheses(S, Bop->getOperatorLoc(),
8816           S.PDiag(diag::note_precedence_silence) << Op,
8817           Bop->getSourceRange());
8818     }
8819   }
8820 }
8821
8822 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8823 /// precedence.
8824 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8825                                     SourceLocation OpLoc, Expr *LHSExpr,
8826                                     Expr *RHSExpr){
8827   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8828   if (BinaryOperator::isBitwiseOp(Opc))
8829     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8830
8831   // Diagnose "arg1 & arg2 | arg3"
8832   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8833     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8834     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8835   }
8836
8837   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8838   // We don't warn for 'assert(a || b && "bad")' since this is safe.
8839   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8840     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8841     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8842   }
8843
8844   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8845       || Opc == BO_Shr) {
8846     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8847     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8848     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
8849   }
8850 }
8851
8852 // Binary Operators.  'Tok' is the token for the operator.
8853 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8854                             tok::TokenKind Kind,
8855                             Expr *LHSExpr, Expr *RHSExpr) {
8856   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8857   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8858   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8859
8860   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8861   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8862
8863   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8864 }
8865
8866 /// Build an overloaded binary operator expression in the given scope.
8867 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8868                                        BinaryOperatorKind Opc,
8869                                        Expr *LHS, Expr *RHS) {
8870   // Find all of the overloaded operators visible from this
8871   // point. We perform both an operator-name lookup from the local
8872   // scope and an argument-dependent lookup based on the types of
8873   // the arguments.
8874   UnresolvedSet<16> Functions;
8875   OverloadedOperatorKind OverOp
8876     = BinaryOperator::getOverloadedOperator(Opc);
8877   if (Sc && OverOp != OO_None)
8878     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8879                                    RHS->getType(), Functions);
8880
8881   // Build the (potentially-overloaded, potentially-dependent)
8882   // binary operation.
8883   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8884 }
8885
8886 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8887                             BinaryOperatorKind Opc,
8888                             Expr *LHSExpr, Expr *RHSExpr) {
8889   // We want to end up calling one of checkPseudoObjectAssignment
8890   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8891   // both expressions are overloadable or either is type-dependent),
8892   // or CreateBuiltinBinOp (in any other case).  We also want to get
8893   // any placeholder types out of the way.
8894
8895   // Handle pseudo-objects in the LHS.
8896   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8897     // Assignments with a pseudo-object l-value need special analysis.
8898     if (pty->getKind() == BuiltinType::PseudoObject &&
8899         BinaryOperator::isAssignmentOp(Opc))
8900       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8901
8902     // Don't resolve overloads if the other type is overloadable.
8903     if (pty->getKind() == BuiltinType::Overload) {
8904       // We can't actually test that if we still have a placeholder,
8905       // though.  Fortunately, none of the exceptions we see in that
8906       // code below are valid when the LHS is an overload set.  Note
8907       // that an overload set can be dependently-typed, but it never
8908       // instantiates to having an overloadable type.
8909       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8910       if (resolvedRHS.isInvalid()) return ExprError();
8911       RHSExpr = resolvedRHS.take();
8912
8913       if (RHSExpr->isTypeDependent() ||
8914           RHSExpr->getType()->isOverloadableType())
8915         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8916     }
8917         
8918     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8919     if (LHS.isInvalid()) return ExprError();
8920     LHSExpr = LHS.take();
8921   }
8922
8923   // Handle pseudo-objects in the RHS.
8924   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8925     // An overload in the RHS can potentially be resolved by the type
8926     // being assigned to.
8927     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8928       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8929         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8930
8931       if (LHSExpr->getType()->isOverloadableType())
8932         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8933
8934       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8935     }
8936
8937     // Don't resolve overloads if the other type is overloadable.
8938     if (pty->getKind() == BuiltinType::Overload &&
8939         LHSExpr->getType()->isOverloadableType())
8940       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8941
8942     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8943     if (!resolvedRHS.isUsable()) return ExprError();
8944     RHSExpr = resolvedRHS.take();
8945   }
8946
8947   if (getLangOpts().CPlusPlus) {
8948     // If either expression is type-dependent, always build an
8949     // overloaded op.
8950     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8951       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8952
8953     // Otherwise, build an overloaded op if either expression has an
8954     // overloadable type.
8955     if (LHSExpr->getType()->isOverloadableType() ||
8956         RHSExpr->getType()->isOverloadableType())
8957       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8958   }
8959
8960   // Build a built-in binary operation.
8961   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8962 }
8963
8964 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8965                                       UnaryOperatorKind Opc,
8966                                       Expr *InputExpr) {
8967   ExprResult Input = Owned(InputExpr);
8968   ExprValueKind VK = VK_RValue;
8969   ExprObjectKind OK = OK_Ordinary;
8970   QualType resultType;
8971   switch (Opc) {
8972   case UO_PreInc:
8973   case UO_PreDec:
8974   case UO_PostInc:
8975   case UO_PostDec:
8976     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8977                                                 Opc == UO_PreInc ||
8978                                                 Opc == UO_PostInc,
8979                                                 Opc == UO_PreInc ||
8980                                                 Opc == UO_PreDec);
8981     break;
8982   case UO_AddrOf:
8983     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8984     break;
8985   case UO_Deref: {
8986     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8987     if (Input.isInvalid()) return ExprError();
8988     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8989     break;
8990   }
8991   case UO_Plus:
8992   case UO_Minus:
8993     Input = UsualUnaryConversions(Input.take());
8994     if (Input.isInvalid()) return ExprError();
8995     resultType = Input.get()->getType();
8996     if (resultType->isDependentType())
8997       break;
8998     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8999         resultType->isVectorType()) 
9000       break;
9001     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
9002              resultType->isEnumeralType())
9003       break;
9004     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
9005              Opc == UO_Plus &&
9006              resultType->isPointerType())
9007       break;
9008
9009     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9010       << resultType << Input.get()->getSourceRange());
9011
9012   case UO_Not: // bitwise complement
9013     Input = UsualUnaryConversions(Input.take());
9014     if (Input.isInvalid())
9015       return ExprError();
9016     resultType = Input.get()->getType();
9017     if (resultType->isDependentType())
9018       break;
9019     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
9020     if (resultType->isComplexType() || resultType->isComplexIntegerType())
9021       // C99 does not support '~' for complex conjugation.
9022       Diag(OpLoc, diag::ext_integer_complement_complex)
9023           << resultType << Input.get()->getSourceRange();
9024     else if (resultType->hasIntegerRepresentation())
9025       break;
9026     else if (resultType->isExtVectorType()) {
9027       if (Context.getLangOpts().OpenCL) {
9028         // OpenCL v1.1 s6.3.f: The bitwise operator not (~) does not operate
9029         // on vector float types.
9030         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9031         if (!T->isIntegerType())
9032           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9033                            << resultType << Input.get()->getSourceRange());
9034       }
9035       break;
9036     } else {
9037       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9038                        << resultType << Input.get()->getSourceRange());
9039     }
9040     break;
9041
9042   case UO_LNot: // logical negation
9043     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
9044     Input = DefaultFunctionArrayLvalueConversion(Input.take());
9045     if (Input.isInvalid()) return ExprError();
9046     resultType = Input.get()->getType();
9047
9048     // Though we still have to promote half FP to float...
9049     if (resultType->isHalfType() && !Context.getLangOpts().NativeHalfType) {
9050       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
9051       resultType = Context.FloatTy;
9052     }
9053
9054     if (resultType->isDependentType())
9055       break;
9056     if (resultType->isScalarType()) {
9057       // C99 6.5.3.3p1: ok, fallthrough;
9058       if (Context.getLangOpts().CPlusPlus) {
9059         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
9060         // operand contextually converted to bool.
9061         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
9062                                   ScalarTypeToBooleanCastKind(resultType));
9063       } else if (Context.getLangOpts().OpenCL &&
9064                  Context.getLangOpts().OpenCLVersion < 120) {
9065         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9066         // operate on scalar float types.
9067         if (!resultType->isIntegerType())
9068           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9069                            << resultType << Input.get()->getSourceRange());
9070       }
9071     } else if (resultType->isExtVectorType()) {
9072       if (Context.getLangOpts().OpenCL &&
9073           Context.getLangOpts().OpenCLVersion < 120) {
9074         // OpenCL v1.1 6.3.h: The logical operator not (!) does not
9075         // operate on vector float types.
9076         QualType T = resultType->getAs<ExtVectorType>()->getElementType();
9077         if (!T->isIntegerType())
9078           return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9079                            << resultType << Input.get()->getSourceRange());
9080       }
9081       // Vector logical not returns the signed variant of the operand type.
9082       resultType = GetSignedVectorType(resultType);
9083       break;
9084     } else {
9085       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
9086         << resultType << Input.get()->getSourceRange());
9087     }
9088     
9089     // LNot always has type int. C99 6.5.3.3p5.
9090     // In C++, it's bool. C++ 5.3.1p8
9091     resultType = Context.getLogicalOperationType();
9092     break;
9093   case UO_Real:
9094   case UO_Imag:
9095     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
9096     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
9097     // complex l-values to ordinary l-values and all other values to r-values.
9098     if (Input.isInvalid()) return ExprError();
9099     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
9100       if (Input.get()->getValueKind() != VK_RValue &&
9101           Input.get()->getObjectKind() == OK_Ordinary)
9102         VK = Input.get()->getValueKind();
9103     } else if (!getLangOpts().CPlusPlus) {
9104       // In C, a volatile scalar is read by __imag. In C++, it is not.
9105       Input = DefaultLvalueConversion(Input.take());
9106     }
9107     break;
9108   case UO_Extension:
9109     resultType = Input.get()->getType();
9110     VK = Input.get()->getValueKind();
9111     OK = Input.get()->getObjectKind();
9112     break;
9113   }
9114   if (resultType.isNull() || Input.isInvalid())
9115     return ExprError();
9116
9117   // Check for array bounds violations in the operand of the UnaryOperator,
9118   // except for the '*' and '&' operators that have to be handled specially
9119   // by CheckArrayAccess (as there are special cases like &array[arraysize]
9120   // that are explicitly defined as valid by the standard).
9121   if (Opc != UO_AddrOf && Opc != UO_Deref)
9122     CheckArrayAccess(Input.get());
9123
9124   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
9125                                            VK, OK, OpLoc));
9126 }
9127
9128 /// \brief Determine whether the given expression is a qualified member
9129 /// access expression, of a form that could be turned into a pointer to member
9130 /// with the address-of operator.
9131 static bool isQualifiedMemberAccess(Expr *E) {
9132   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9133     if (!DRE->getQualifier())
9134       return false;
9135     
9136     ValueDecl *VD = DRE->getDecl();
9137     if (!VD->isCXXClassMember())
9138       return false;
9139     
9140     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
9141       return true;
9142     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
9143       return Method->isInstance();
9144       
9145     return false;
9146   }
9147   
9148   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9149     if (!ULE->getQualifier())
9150       return false;
9151     
9152     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
9153                                            DEnd = ULE->decls_end();
9154          D != DEnd; ++D) {
9155       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
9156         if (Method->isInstance())
9157           return true;
9158       } else {
9159         // Overload set does not contain methods.
9160         break;
9161       }
9162     }
9163     
9164     return false;
9165   }
9166   
9167   return false;
9168 }
9169
9170 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
9171                               UnaryOperatorKind Opc, Expr *Input) {
9172   // First things first: handle placeholders so that the
9173   // overloaded-operator check considers the right type.
9174   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
9175     // Increment and decrement of pseudo-object references.
9176     if (pty->getKind() == BuiltinType::PseudoObject &&
9177         UnaryOperator::isIncrementDecrementOp(Opc))
9178       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
9179
9180     // extension is always a builtin operator.
9181     if (Opc == UO_Extension)
9182       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9183
9184     // & gets special logic for several kinds of placeholder.
9185     // The builtin code knows what to do.
9186     if (Opc == UO_AddrOf &&
9187         (pty->getKind() == BuiltinType::Overload ||
9188          pty->getKind() == BuiltinType::UnknownAny ||
9189          pty->getKind() == BuiltinType::BoundMember))
9190       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9191
9192     // Anything else needs to be handled now.
9193     ExprResult Result = CheckPlaceholderExpr(Input);
9194     if (Result.isInvalid()) return ExprError();
9195     Input = Result.take();
9196   }
9197
9198   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
9199       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
9200       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
9201     // Find all of the overloaded operators visible from this
9202     // point. We perform both an operator-name lookup from the local
9203     // scope and an argument-dependent lookup based on the types of
9204     // the arguments.
9205     UnresolvedSet<16> Functions;
9206     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
9207     if (S && OverOp != OO_None)
9208       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
9209                                    Functions);
9210
9211     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
9212   }
9213
9214   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
9215 }
9216
9217 // Unary Operators.  'Tok' is the token for the operator.
9218 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
9219                               tok::TokenKind Op, Expr *Input) {
9220   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
9221 }
9222
9223 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
9224 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
9225                                 LabelDecl *TheDecl) {
9226   TheDecl->setUsed();
9227   // Create the AST node.  The address of a label always has type 'void*'.
9228   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
9229                                        Context.getPointerType(Context.VoidTy)));
9230 }
9231
9232 /// Given the last statement in a statement-expression, check whether
9233 /// the result is a producing expression (like a call to an
9234 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9235 /// release out of the full-expression.  Otherwise, return null.
9236 /// Cannot fail.
9237 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9238   // Should always be wrapped with one of these.
9239   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9240   if (!cleanups) return 0;
9241
9242   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9243   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9244     return 0;
9245
9246   // Splice out the cast.  This shouldn't modify any interesting
9247   // features of the statement.
9248   Expr *producer = cast->getSubExpr();
9249   assert(producer->getType() == cast->getType());
9250   assert(producer->getValueKind() == cast->getValueKind());
9251   cleanups->setSubExpr(producer);
9252   return cleanups;
9253 }
9254
9255 void Sema::ActOnStartStmtExpr() {
9256   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9257 }
9258
9259 void Sema::ActOnStmtExprError() {
9260   // Note that function is also called by TreeTransform when leaving a
9261   // StmtExpr scope without rebuilding anything.
9262
9263   DiscardCleanupsInEvaluationContext();
9264   PopExpressionEvaluationContext();
9265 }
9266
9267 ExprResult
9268 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9269                     SourceLocation RPLoc) { // "({..})"
9270   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9271   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9272
9273   if (hasAnyUnrecoverableErrorsInThisFunction())
9274     DiscardCleanupsInEvaluationContext();
9275   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9276   PopExpressionEvaluationContext();
9277
9278   bool isFileScope
9279     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9280   if (isFileScope)
9281     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9282
9283   // FIXME: there are a variety of strange constraints to enforce here, for
9284   // example, it is not possible to goto into a stmt expression apparently.
9285   // More semantic analysis is needed.
9286
9287   // If there are sub stmts in the compound stmt, take the type of the last one
9288   // as the type of the stmtexpr.
9289   QualType Ty = Context.VoidTy;
9290   bool StmtExprMayBindToTemp = false;
9291   if (!Compound->body_empty()) {
9292     Stmt *LastStmt = Compound->body_back();
9293     LabelStmt *LastLabelStmt = 0;
9294     // If LastStmt is a label, skip down through into the body.
9295     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9296       LastLabelStmt = Label;
9297       LastStmt = Label->getSubStmt();
9298     }
9299
9300     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9301       // Do function/array conversion on the last expression, but not
9302       // lvalue-to-rvalue.  However, initialize an unqualified type.
9303       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9304       if (LastExpr.isInvalid())
9305         return ExprError();
9306       Ty = LastExpr.get()->getType().getUnqualifiedType();
9307
9308       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9309         // In ARC, if the final expression ends in a consume, splice
9310         // the consume out and bind it later.  In the alternate case
9311         // (when dealing with a retainable type), the result
9312         // initialization will create a produce.  In both cases the
9313         // result will be +1, and we'll need to balance that out with
9314         // a bind.
9315         if (Expr *rebuiltLastStmt
9316               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9317           LastExpr = rebuiltLastStmt;
9318         } else {
9319           LastExpr = PerformCopyInitialization(
9320                             InitializedEntity::InitializeResult(LPLoc, 
9321                                                                 Ty,
9322                                                                 false),
9323                                                    SourceLocation(),
9324                                                LastExpr);
9325         }
9326
9327         if (LastExpr.isInvalid())
9328           return ExprError();
9329         if (LastExpr.get() != 0) {
9330           if (!LastLabelStmt)
9331             Compound->setLastStmt(LastExpr.take());
9332           else
9333             LastLabelStmt->setSubStmt(LastExpr.take());
9334           StmtExprMayBindToTemp = true;
9335         }
9336       }
9337     }
9338   }
9339
9340   // FIXME: Check that expression type is complete/non-abstract; statement
9341   // expressions are not lvalues.
9342   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9343   if (StmtExprMayBindToTemp)
9344     return MaybeBindToTemporary(ResStmtExpr);
9345   return Owned(ResStmtExpr);
9346 }
9347
9348 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9349                                       TypeSourceInfo *TInfo,
9350                                       OffsetOfComponent *CompPtr,
9351                                       unsigned NumComponents,
9352                                       SourceLocation RParenLoc) {
9353   QualType ArgTy = TInfo->getType();
9354   bool Dependent = ArgTy->isDependentType();
9355   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9356   
9357   // We must have at least one component that refers to the type, and the first
9358   // one is known to be a field designator.  Verify that the ArgTy represents
9359   // a struct/union/class.
9360   if (!Dependent && !ArgTy->isRecordType())
9361     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
9362                        << ArgTy << TypeRange);
9363   
9364   // Type must be complete per C99 7.17p3 because a declaring a variable
9365   // with an incomplete type would be ill-formed.
9366   if (!Dependent 
9367       && RequireCompleteType(BuiltinLoc, ArgTy,
9368                              diag::err_offsetof_incomplete_type, TypeRange))
9369     return ExprError();
9370   
9371   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9372   // GCC extension, diagnose them.
9373   // FIXME: This diagnostic isn't actually visible because the location is in
9374   // a system header!
9375   if (NumComponents != 1)
9376     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9377       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9378   
9379   bool DidWarnAboutNonPOD = false;
9380   QualType CurrentType = ArgTy;
9381   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9382   SmallVector<OffsetOfNode, 4> Comps;
9383   SmallVector<Expr*, 4> Exprs;
9384   for (unsigned i = 0; i != NumComponents; ++i) {
9385     const OffsetOfComponent &OC = CompPtr[i];
9386     if (OC.isBrackets) {
9387       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9388       if (!CurrentType->isDependentType()) {
9389         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9390         if(!AT)
9391           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9392                            << CurrentType);
9393         CurrentType = AT->getElementType();
9394       } else
9395         CurrentType = Context.DependentTy;
9396       
9397       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9398       if (IdxRval.isInvalid())
9399         return ExprError();
9400       Expr *Idx = IdxRval.take();
9401
9402       // The expression must be an integral expression.
9403       // FIXME: An integral constant expression?
9404       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9405           !Idx->getType()->isIntegerType())
9406         return ExprError(Diag(Idx->getLocStart(),
9407                               diag::err_typecheck_subscript_not_integer)
9408                          << Idx->getSourceRange());
9409
9410       // Record this array index.
9411       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9412       Exprs.push_back(Idx);
9413       continue;
9414     }
9415     
9416     // Offset of a field.
9417     if (CurrentType->isDependentType()) {
9418       // We have the offset of a field, but we can't look into the dependent
9419       // type. Just record the identifier of the field.
9420       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9421       CurrentType = Context.DependentTy;
9422       continue;
9423     }
9424     
9425     // We need to have a complete type to look into.
9426     if (RequireCompleteType(OC.LocStart, CurrentType,
9427                             diag::err_offsetof_incomplete_type))
9428       return ExprError();
9429     
9430     // Look for the designated field.
9431     const RecordType *RC = CurrentType->getAs<RecordType>();
9432     if (!RC) 
9433       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9434                        << CurrentType);
9435     RecordDecl *RD = RC->getDecl();
9436     
9437     // C++ [lib.support.types]p5:
9438     //   The macro offsetof accepts a restricted set of type arguments in this
9439     //   International Standard. type shall be a POD structure or a POD union
9440     //   (clause 9).
9441     // C++11 [support.types]p4:
9442     //   If type is not a standard-layout class (Clause 9), the results are
9443     //   undefined.
9444     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9445       bool IsSafe = LangOpts.CPlusPlus11? CRD->isStandardLayout() : CRD->isPOD();
9446       unsigned DiagID =
9447         LangOpts.CPlusPlus11? diag::warn_offsetof_non_standardlayout_type
9448                             : diag::warn_offsetof_non_pod_type;
9449
9450       if (!IsSafe && !DidWarnAboutNonPOD &&
9451           DiagRuntimeBehavior(BuiltinLoc, 0,
9452                               PDiag(DiagID)
9453                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9454                               << CurrentType))
9455         DidWarnAboutNonPOD = true;
9456     }
9457     
9458     // Look for the field.
9459     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9460     LookupQualifiedName(R, RD);
9461     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9462     IndirectFieldDecl *IndirectMemberDecl = 0;
9463     if (!MemberDecl) {
9464       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9465         MemberDecl = IndirectMemberDecl->getAnonField();
9466     }
9467
9468     if (!MemberDecl)
9469       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9470                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
9471                                                               OC.LocEnd));
9472     
9473     // C99 7.17p3:
9474     //   (If the specified member is a bit-field, the behavior is undefined.)
9475     //
9476     // We diagnose this as an error.
9477     if (MemberDecl->isBitField()) {
9478       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9479         << MemberDecl->getDeclName()
9480         << SourceRange(BuiltinLoc, RParenLoc);
9481       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9482       return ExprError();
9483     }
9484
9485     RecordDecl *Parent = MemberDecl->getParent();
9486     if (IndirectMemberDecl)
9487       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9488
9489     // If the member was found in a base class, introduce OffsetOfNodes for
9490     // the base class indirections.
9491     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9492                        /*DetectVirtual=*/false);
9493     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9494       CXXBasePath &Path = Paths.front();
9495       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9496            B != BEnd; ++B)
9497         Comps.push_back(OffsetOfNode(B->Base));
9498     }
9499
9500     if (IndirectMemberDecl) {
9501       for (IndirectFieldDecl::chain_iterator FI =
9502            IndirectMemberDecl->chain_begin(),
9503            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9504         assert(isa<FieldDecl>(*FI));
9505         Comps.push_back(OffsetOfNode(OC.LocStart,
9506                                      cast<FieldDecl>(*FI), OC.LocEnd));
9507       }
9508     } else
9509       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9510
9511     CurrentType = MemberDecl->getType().getNonReferenceType(); 
9512   }
9513   
9514   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 
9515                                     TInfo, Comps, Exprs, RParenLoc));
9516 }
9517
9518 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9519                                       SourceLocation BuiltinLoc,
9520                                       SourceLocation TypeLoc,
9521                                       ParsedType ParsedArgTy,
9522                                       OffsetOfComponent *CompPtr,
9523                                       unsigned NumComponents,
9524                                       SourceLocation RParenLoc) {
9525   
9526   TypeSourceInfo *ArgTInfo;
9527   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9528   if (ArgTy.isNull())
9529     return ExprError();
9530
9531   if (!ArgTInfo)
9532     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9533
9534   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 
9535                               RParenLoc);
9536 }
9537
9538
9539 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9540                                  Expr *CondExpr,
9541                                  Expr *LHSExpr, Expr *RHSExpr,
9542                                  SourceLocation RPLoc) {
9543   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9544
9545   ExprValueKind VK = VK_RValue;
9546   ExprObjectKind OK = OK_Ordinary;
9547   QualType resType;
9548   bool ValueDependent = false;
9549   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9550     resType = Context.DependentTy;
9551     ValueDependent = true;
9552   } else {
9553     // The conditional expression is required to be a constant expression.
9554     llvm::APSInt condEval(32);
9555     ExprResult CondICE
9556       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9557           diag::err_typecheck_choose_expr_requires_constant, false);
9558     if (CondICE.isInvalid())
9559       return ExprError();
9560     CondExpr = CondICE.take();
9561
9562     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9563     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9564
9565     resType = ActiveExpr->getType();
9566     ValueDependent = ActiveExpr->isValueDependent();
9567     VK = ActiveExpr->getValueKind();
9568     OK = ActiveExpr->getObjectKind();
9569   }
9570
9571   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9572                                         resType, VK, OK, RPLoc,
9573                                         resType->isDependentType(),
9574                                         ValueDependent));
9575 }
9576
9577 //===----------------------------------------------------------------------===//
9578 // Clang Extensions.
9579 //===----------------------------------------------------------------------===//
9580
9581 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9582 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9583   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9584   PushBlockScope(CurScope, Block);
9585   CurContext->addDecl(Block);
9586   if (CurScope)
9587     PushDeclContext(CurScope, Block);
9588   else
9589     CurContext = Block;
9590
9591   getCurBlock()->HasImplicitReturnType = true;
9592
9593   // Enter a new evaluation context to insulate the block from any
9594   // cleanups from the enclosing full-expression.
9595   PushExpressionEvaluationContext(PotentiallyEvaluated);  
9596 }
9597
9598 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9599                                Scope *CurScope) {
9600   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9601   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9602   BlockScopeInfo *CurBlock = getCurBlock();
9603
9604   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9605   QualType T = Sig->getType();
9606
9607   // FIXME: We should allow unexpanded parameter packs here, but that would,
9608   // in turn, make the block expression contain unexpanded parameter packs.
9609   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9610     // Drop the parameters.
9611     FunctionProtoType::ExtProtoInfo EPI;
9612     EPI.HasTrailingReturn = false;
9613     EPI.TypeQuals |= DeclSpec::TQ_const;
9614     T = Context.getFunctionType(Context.DependentTy, ArrayRef<QualType>(), EPI);
9615     Sig = Context.getTrivialTypeSourceInfo(T);
9616   }
9617   
9618   // GetTypeForDeclarator always produces a function type for a block
9619   // literal signature.  Furthermore, it is always a FunctionProtoType
9620   // unless the function was written with a typedef.
9621   assert(T->isFunctionType() &&
9622          "GetTypeForDeclarator made a non-function block signature");
9623
9624   // Look for an explicit signature in that function type.
9625   FunctionProtoTypeLoc ExplicitSignature;
9626
9627   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9628   if ((ExplicitSignature = tmp.getAs<FunctionProtoTypeLoc>())) {
9629
9630     // Check whether that explicit signature was synthesized by
9631     // GetTypeForDeclarator.  If so, don't save that as part of the
9632     // written signature.
9633     if (ExplicitSignature.getLocalRangeBegin() ==
9634         ExplicitSignature.getLocalRangeEnd()) {
9635       // This would be much cheaper if we stored TypeLocs instead of
9636       // TypeSourceInfos.
9637       TypeLoc Result = ExplicitSignature.getResultLoc();
9638       unsigned Size = Result.getFullDataSize();
9639       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9640       Sig->getTypeLoc().initializeFullCopy(Result, Size);
9641
9642       ExplicitSignature = FunctionProtoTypeLoc();
9643     }
9644   }
9645
9646   CurBlock->TheDecl->setSignatureAsWritten(Sig);
9647   CurBlock->FunctionType = T;
9648
9649   const FunctionType *Fn = T->getAs<FunctionType>();
9650   QualType RetTy = Fn->getResultType();
9651   bool isVariadic =
9652     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9653
9654   CurBlock->TheDecl->setIsVariadic(isVariadic);
9655
9656   // Don't allow returning a objc interface by value.
9657   if (RetTy->isObjCObjectType()) {
9658     Diag(ParamInfo.getLocStart(),
9659          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9660     return;
9661   }
9662
9663   // Context.DependentTy is used as a placeholder for a missing block
9664   // return type.  TODO:  what should we do with declarators like:
9665   //   ^ * { ... }
9666   // If the answer is "apply template argument deduction"....
9667   if (RetTy != Context.DependentTy) {
9668     CurBlock->ReturnType = RetTy;
9669     CurBlock->TheDecl->setBlockMissingReturnType(false);
9670     CurBlock->HasImplicitReturnType = false;
9671   }
9672
9673   // Push block parameters from the declarator if we had them.
9674   SmallVector<ParmVarDecl*, 8> Params;
9675   if (ExplicitSignature) {
9676     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9677       ParmVarDecl *Param = ExplicitSignature.getArg(I);
9678       if (Param->getIdentifier() == 0 &&
9679           !Param->isImplicit() &&
9680           !Param->isInvalidDecl() &&
9681           !getLangOpts().CPlusPlus)
9682         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9683       Params.push_back(Param);
9684     }
9685
9686   // Fake up parameter variables if we have a typedef, like
9687   //   ^ fntype { ... }
9688   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9689     for (FunctionProtoType::arg_type_iterator
9690            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9691       ParmVarDecl *Param =
9692         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9693                                    ParamInfo.getLocStart(),
9694                                    *I);
9695       Params.push_back(Param);
9696     }
9697   }
9698
9699   // Set the parameters on the block decl.
9700   if (!Params.empty()) {
9701     CurBlock->TheDecl->setParams(Params);
9702     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9703                              CurBlock->TheDecl->param_end(),
9704                              /*CheckParameterNames=*/false);
9705   }
9706   
9707   // Finally we can process decl attributes.
9708   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9709
9710   // Put the parameter variables in scope.  We can bail out immediately
9711   // if we don't have any.
9712   if (Params.empty())
9713     return;
9714
9715   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9716          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9717     (*AI)->setOwningFunction(CurBlock->TheDecl);
9718
9719     // If this has an identifier, add it to the scope stack.
9720     if ((*AI)->getIdentifier()) {
9721       CheckShadow(CurBlock->TheScope, *AI);
9722
9723       PushOnScopeChains(*AI, CurBlock->TheScope);
9724     }
9725   }
9726 }
9727
9728 /// ActOnBlockError - If there is an error parsing a block, this callback
9729 /// is invoked to pop the information about the block from the action impl.
9730 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9731   // Leave the expression-evaluation context.
9732   DiscardCleanupsInEvaluationContext();
9733   PopExpressionEvaluationContext();
9734
9735   // Pop off CurBlock, handle nested blocks.
9736   PopDeclContext();
9737   PopFunctionScopeInfo();
9738 }
9739
9740 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9741 /// literal was successfully completed.  ^(int x){...}
9742 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9743                                     Stmt *Body, Scope *CurScope) {
9744   // If blocks are disabled, emit an error.
9745   if (!LangOpts.Blocks)
9746     Diag(CaretLoc, diag::err_blocks_disable);
9747
9748   // Leave the expression-evaluation context.
9749   if (hasAnyUnrecoverableErrorsInThisFunction())
9750     DiscardCleanupsInEvaluationContext();
9751   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9752   PopExpressionEvaluationContext();
9753
9754   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9755
9756   if (BSI->HasImplicitReturnType)
9757     deduceClosureReturnType(*BSI);
9758
9759   PopDeclContext();
9760
9761   QualType RetTy = Context.VoidTy;
9762   if (!BSI->ReturnType.isNull())
9763     RetTy = BSI->ReturnType;
9764
9765   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9766   QualType BlockTy;
9767
9768   // Set the captured variables on the block.
9769   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9770   SmallVector<BlockDecl::Capture, 4> Captures;
9771   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9772     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9773     if (Cap.isThisCapture())
9774       continue;
9775     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9776                               Cap.isNested(), Cap.getCopyExpr());
9777     Captures.push_back(NewCap);
9778   }
9779   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9780                             BSI->CXXThisCaptureIndex != 0);
9781
9782   // If the user wrote a function type in some form, try to use that.
9783   if (!BSI->FunctionType.isNull()) {
9784     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9785
9786     FunctionType::ExtInfo Ext = FTy->getExtInfo();
9787     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9788     
9789     // Turn protoless block types into nullary block types.
9790     if (isa<FunctionNoProtoType>(FTy)) {
9791       FunctionProtoType::ExtProtoInfo EPI;
9792       EPI.ExtInfo = Ext;
9793       BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI);
9794
9795     // Otherwise, if we don't need to change anything about the function type,
9796     // preserve its sugar structure.
9797     } else if (FTy->getResultType() == RetTy &&
9798                (!NoReturn || FTy->getNoReturnAttr())) {
9799       BlockTy = BSI->FunctionType;
9800
9801     // Otherwise, make the minimal modifications to the function type.
9802     } else {
9803       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9804       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9805       EPI.TypeQuals = 0; // FIXME: silently?
9806       EPI.ExtInfo = Ext;
9807       BlockTy =
9808         Context.getFunctionType(RetTy,
9809                                 ArrayRef<QualType>(FPT->arg_type_begin(),
9810                                                    FPT->getNumArgs()),
9811                                 EPI);
9812     }
9813
9814   // If we don't have a function type, just build one from nothing.
9815   } else {
9816     FunctionProtoType::ExtProtoInfo EPI;
9817     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9818     BlockTy = Context.getFunctionType(RetTy, ArrayRef<QualType>(), EPI);
9819   }
9820
9821   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9822                            BSI->TheDecl->param_end());
9823   BlockTy = Context.getBlockPointerType(BlockTy);
9824
9825   // If needed, diagnose invalid gotos and switches in the block.
9826   if (getCurFunction()->NeedsScopeChecking() &&
9827       !hasAnyUnrecoverableErrorsInThisFunction() &&
9828       !PP.isCodeCompletionEnabled())
9829     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9830
9831   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9832
9833   // Try to apply the named return value optimization. We have to check again
9834   // if we can do this, though, because blocks keep return statements around
9835   // to deduce an implicit return type.
9836   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9837       !BSI->TheDecl->isDependentContext())
9838     computeNRVO(Body, getCurBlock());
9839   
9840   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9841   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9842   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9843
9844   // If the block isn't obviously global, i.e. it captures anything at
9845   // all, then we need to do a few things in the surrounding context:
9846   if (Result->getBlockDecl()->hasCaptures()) {
9847     // First, this expression has a new cleanup object.
9848     ExprCleanupObjects.push_back(Result->getBlockDecl());
9849     ExprNeedsCleanups = true;
9850
9851     // It also gets a branch-protected scope if any of the captured
9852     // variables needs destruction.
9853     for (BlockDecl::capture_const_iterator
9854            ci = Result->getBlockDecl()->capture_begin(),
9855            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9856       const VarDecl *var = ci->getVariable();
9857       if (var->getType().isDestructedType() != QualType::DK_none) {
9858         getCurFunction()->setHasBranchProtectedScope();
9859         break;
9860       }
9861     }
9862   }
9863
9864   return Owned(Result);
9865 }
9866
9867 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9868                                         Expr *E, ParsedType Ty,
9869                                         SourceLocation RPLoc) {
9870   TypeSourceInfo *TInfo;
9871   GetTypeFromParser(Ty, &TInfo);
9872   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9873 }
9874
9875 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9876                                 Expr *E, TypeSourceInfo *TInfo,
9877                                 SourceLocation RPLoc) {
9878   Expr *OrigExpr = E;
9879
9880   // Get the va_list type
9881   QualType VaListType = Context.getBuiltinVaListType();
9882   if (VaListType->isArrayType()) {
9883     // Deal with implicit array decay; for example, on x86-64,
9884     // va_list is an array, but it's supposed to decay to
9885     // a pointer for va_arg.
9886     VaListType = Context.getArrayDecayedType(VaListType);
9887     // Make sure the input expression also decays appropriately.
9888     ExprResult Result = UsualUnaryConversions(E);
9889     if (Result.isInvalid())
9890       return ExprError();
9891     E = Result.take();
9892   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9893     // If va_list is a record type and we are compiling in C++ mode,
9894     // check the argument using reference binding.
9895     InitializedEntity Entity
9896       = InitializedEntity::InitializeParameter(Context,
9897           Context.getLValueReferenceType(VaListType), false);
9898     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9899     if (Init.isInvalid())
9900       return ExprError();
9901     E = Init.takeAs<Expr>();
9902   } else {
9903     // Otherwise, the va_list argument must be an l-value because
9904     // it is modified by va_arg.
9905     if (!E->isTypeDependent() &&
9906         CheckForModifiableLvalue(E, BuiltinLoc, *this))
9907       return ExprError();
9908   }
9909
9910   if (!E->isTypeDependent() &&
9911       !Context.hasSameType(VaListType, E->getType())) {
9912     return ExprError(Diag(E->getLocStart(),
9913                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
9914       << OrigExpr->getType() << E->getSourceRange());
9915   }
9916
9917   if (!TInfo->getType()->isDependentType()) {
9918     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9919                             diag::err_second_parameter_to_va_arg_incomplete,
9920                             TInfo->getTypeLoc()))
9921       return ExprError();
9922
9923     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9924                                TInfo->getType(),
9925                                diag::err_second_parameter_to_va_arg_abstract,
9926                                TInfo->getTypeLoc()))
9927       return ExprError();
9928
9929     if (!TInfo->getType().isPODType(Context)) {
9930       Diag(TInfo->getTypeLoc().getBeginLoc(),
9931            TInfo->getType()->isObjCLifetimeType()
9932              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9933              : diag::warn_second_parameter_to_va_arg_not_pod)
9934         << TInfo->getType()
9935         << TInfo->getTypeLoc().getSourceRange();
9936     }
9937
9938     // Check for va_arg where arguments of the given type will be promoted
9939     // (i.e. this va_arg is guaranteed to have undefined behavior).
9940     QualType PromoteType;
9941     if (TInfo->getType()->isPromotableIntegerType()) {
9942       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9943       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9944         PromoteType = QualType();
9945     }
9946     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9947       PromoteType = Context.DoubleTy;
9948     if (!PromoteType.isNull())
9949       DiagRuntimeBehavior(TInfo->getTypeLoc().getBeginLoc(), E,
9950                   PDiag(diag::warn_second_parameter_to_va_arg_never_compatible)
9951                           << TInfo->getType()
9952                           << PromoteType
9953                           << TInfo->getTypeLoc().getSourceRange());
9954   }
9955
9956   QualType T = TInfo->getType().getNonLValueExprType(Context);
9957   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9958 }
9959
9960 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9961   // The type of __null will be int or long, depending on the size of
9962   // pointers on the target.
9963   QualType Ty;
9964   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9965   if (pw == Context.getTargetInfo().getIntWidth())
9966     Ty = Context.IntTy;
9967   else if (pw == Context.getTargetInfo().getLongWidth())
9968     Ty = Context.LongTy;
9969   else if (pw == Context.getTargetInfo().getLongLongWidth())
9970     Ty = Context.LongLongTy;
9971   else {
9972     llvm_unreachable("I don't know size of pointer!");
9973   }
9974
9975   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9976 }
9977
9978 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9979                                            Expr *SrcExpr, FixItHint &Hint) {
9980   if (!SemaRef.getLangOpts().ObjC1)
9981     return;
9982
9983   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9984   if (!PT)
9985     return;
9986
9987   // Check if the destination is of type 'id'.
9988   if (!PT->isObjCIdType()) {
9989     // Check if the destination is the 'NSString' interface.
9990     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9991     if (!ID || !ID->getIdentifier()->isStr("NSString"))
9992       return;
9993   }
9994
9995   // Ignore any parens, implicit casts (should only be
9996   // array-to-pointer decays), and not-so-opaque values.  The last is
9997   // important for making this trigger for property assignments.
9998   SrcExpr = SrcExpr->IgnoreParenImpCasts();
9999   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
10000     if (OV->getSourceExpr())
10001       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
10002
10003   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
10004   if (!SL || !SL->isAscii())
10005     return;
10006
10007   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
10008 }
10009
10010 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
10011                                     SourceLocation Loc,
10012                                     QualType DstType, QualType SrcType,
10013                                     Expr *SrcExpr, AssignmentAction Action,
10014                                     bool *Complained) {
10015   if (Complained)
10016     *Complained = false;
10017
10018   // Decode the result (notice that AST's are still created for extensions).
10019   bool CheckInferredResultType = false;
10020   bool isInvalid = false;
10021   unsigned DiagKind = 0;
10022   FixItHint Hint;
10023   ConversionFixItGenerator ConvHints;
10024   bool MayHaveConvFixit = false;
10025   bool MayHaveFunctionDiff = false;
10026
10027   switch (ConvTy) {
10028   case Compatible:
10029       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
10030       return false;
10031
10032   case PointerToInt:
10033     DiagKind = diag::ext_typecheck_convert_pointer_int;
10034     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10035     MayHaveConvFixit = true;
10036     break;
10037   case IntToPointer:
10038     DiagKind = diag::ext_typecheck_convert_int_pointer;
10039     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10040     MayHaveConvFixit = true;
10041     break;
10042   case IncompatiblePointer:
10043     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
10044     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
10045     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
10046       SrcType->isObjCObjectPointerType();
10047     if (Hint.isNull() && !CheckInferredResultType) {
10048       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10049     }
10050     MayHaveConvFixit = true;
10051     break;
10052   case IncompatiblePointerSign:
10053     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
10054     break;
10055   case FunctionVoidPointer:
10056     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
10057     break;
10058   case IncompatiblePointerDiscardsQualifiers: {
10059     // Perform array-to-pointer decay if necessary.
10060     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
10061
10062     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
10063     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
10064     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
10065       DiagKind = diag::err_typecheck_incompatible_address_space;
10066       break;
10067
10068
10069     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
10070       DiagKind = diag::err_typecheck_incompatible_ownership;
10071       break;
10072     }
10073
10074     llvm_unreachable("unknown error case for discarding qualifiers!");
10075     // fallthrough
10076   }
10077   case CompatiblePointerDiscardsQualifiers:
10078     // If the qualifiers lost were because we were applying the
10079     // (deprecated) C++ conversion from a string literal to a char*
10080     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
10081     // Ideally, this check would be performed in
10082     // checkPointerTypesForAssignment. However, that would require a
10083     // bit of refactoring (so that the second argument is an
10084     // expression, rather than a type), which should be done as part
10085     // of a larger effort to fix checkPointerTypesForAssignment for
10086     // C++ semantics.
10087     if (getLangOpts().CPlusPlus &&
10088         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
10089       return false;
10090     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
10091     break;
10092   case IncompatibleNestedPointerQualifiers:
10093     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
10094     break;
10095   case IntToBlockPointer:
10096     DiagKind = diag::err_int_to_block_pointer;
10097     break;
10098   case IncompatibleBlockPointer:
10099     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
10100     break;
10101   case IncompatibleObjCQualifiedId:
10102     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
10103     // it can give a more specific diagnostic.
10104     DiagKind = diag::warn_incompatible_qualified_id;
10105     break;
10106   case IncompatibleVectors:
10107     DiagKind = diag::warn_incompatible_vectors;
10108     break;
10109   case IncompatibleObjCWeakRef:
10110     DiagKind = diag::err_arc_weak_unavailable_assign;
10111     break;
10112   case Incompatible:
10113     DiagKind = diag::err_typecheck_convert_incompatible;
10114     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
10115     MayHaveConvFixit = true;
10116     isInvalid = true;
10117     MayHaveFunctionDiff = true;
10118     break;
10119   }
10120
10121   QualType FirstType, SecondType;
10122   switch (Action) {
10123   case AA_Assigning:
10124   case AA_Initializing:
10125     // The destination type comes first.
10126     FirstType = DstType;
10127     SecondType = SrcType;
10128     break;
10129
10130   case AA_Returning:
10131   case AA_Passing:
10132   case AA_Converting:
10133   case AA_Sending:
10134   case AA_Casting:
10135     // The source type comes first.
10136     FirstType = SrcType;
10137     SecondType = DstType;
10138     break;
10139   }
10140
10141   PartialDiagnostic FDiag = PDiag(DiagKind);
10142   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
10143
10144   // If we can fix the conversion, suggest the FixIts.
10145   assert(ConvHints.isNull() || Hint.isNull());
10146   if (!ConvHints.isNull()) {
10147     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
10148          HE = ConvHints.Hints.end(); HI != HE; ++HI)
10149       FDiag << *HI;
10150   } else {
10151     FDiag << Hint;
10152   }
10153   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
10154
10155   if (MayHaveFunctionDiff)
10156     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
10157
10158   Diag(Loc, FDiag);
10159
10160   if (SecondType == Context.OverloadTy)
10161     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
10162                               FirstType);
10163
10164   if (CheckInferredResultType)
10165     EmitRelatedResultTypeNote(SrcExpr);
10166
10167   if (Action == AA_Returning && ConvTy == IncompatiblePointer)
10168     EmitRelatedResultTypeNoteForReturn(DstType);
10169   
10170   if (Complained)
10171     *Complained = true;
10172   return isInvalid;
10173 }
10174
10175 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10176                                                  llvm::APSInt *Result) {
10177   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
10178   public:
10179     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10180       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
10181     }
10182   } Diagnoser;
10183   
10184   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
10185 }
10186
10187 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
10188                                                  llvm::APSInt *Result,
10189                                                  unsigned DiagID,
10190                                                  bool AllowFold) {
10191   class IDDiagnoser : public VerifyICEDiagnoser {
10192     unsigned DiagID;
10193     
10194   public:
10195     IDDiagnoser(unsigned DiagID)
10196       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
10197     
10198     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
10199       S.Diag(Loc, DiagID) << SR;
10200     }
10201   } Diagnoser(DiagID);
10202   
10203   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
10204 }
10205
10206 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
10207                                             SourceRange SR) {
10208   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
10209 }
10210
10211 ExprResult
10212 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
10213                                       VerifyICEDiagnoser &Diagnoser,
10214                                       bool AllowFold) {
10215   SourceLocation DiagLoc = E->getLocStart();
10216
10217   if (getLangOpts().CPlusPlus11) {
10218     // C++11 [expr.const]p5:
10219     //   If an expression of literal class type is used in a context where an
10220     //   integral constant expression is required, then that class type shall
10221     //   have a single non-explicit conversion function to an integral or
10222     //   unscoped enumeration type
10223     ExprResult Converted;
10224     if (!Diagnoser.Suppress) {
10225       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
10226       public:
10227         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
10228         
10229         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10230                                                  QualType T) {
10231           return S.Diag(Loc, diag::err_ice_not_integral) << T;
10232         }
10233         
10234         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10235                                                      SourceLocation Loc,
10236                                                      QualType T) {
10237           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10238         }
10239         
10240         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10241                                                        SourceLocation Loc,
10242                                                        QualType T,
10243                                                        QualType ConvTy) {
10244           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10245         }
10246         
10247         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10248                                                    CXXConversionDecl *Conv,
10249                                                    QualType ConvTy) {
10250           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10251                    << ConvTy->isEnumeralType() << ConvTy;
10252         }
10253         
10254         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10255                                                     QualType T) {
10256           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10257         }
10258         
10259         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10260                                                 CXXConversionDecl *Conv,
10261                                                 QualType ConvTy) {
10262           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10263                    << ConvTy->isEnumeralType() << ConvTy;
10264         }
10265         
10266         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10267                                                      SourceLocation Loc,
10268                                                      QualType T,
10269                                                      QualType ConvTy) {
10270           return DiagnosticBuilder::getEmpty();
10271         }
10272       } ConvertDiagnoser;
10273
10274       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10275                                                      ConvertDiagnoser,
10276                                              /*AllowScopedEnumerations*/ false);
10277     } else {
10278       // The caller wants to silently enquire whether this is an ICE. Don't
10279       // produce any diagnostics if it isn't.
10280       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10281       public:
10282         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10283         
10284         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10285                                                  QualType T) {
10286           return DiagnosticBuilder::getEmpty();
10287         }
10288         
10289         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10290                                                      SourceLocation Loc,
10291                                                      QualType T) {
10292           return DiagnosticBuilder::getEmpty();
10293         }
10294         
10295         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10296                                                        SourceLocation Loc,
10297                                                        QualType T,
10298                                                        QualType ConvTy) {
10299           return DiagnosticBuilder::getEmpty();
10300         }
10301         
10302         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10303                                                    CXXConversionDecl *Conv,
10304                                                    QualType ConvTy) {
10305           return DiagnosticBuilder::getEmpty();
10306         }
10307         
10308         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10309                                                     QualType T) {
10310           return DiagnosticBuilder::getEmpty();
10311         }
10312         
10313         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10314                                                 CXXConversionDecl *Conv,
10315                                                 QualType ConvTy) {
10316           return DiagnosticBuilder::getEmpty();
10317         }
10318         
10319         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10320                                                      SourceLocation Loc,
10321                                                      QualType T,
10322                                                      QualType ConvTy) {
10323           return DiagnosticBuilder::getEmpty();
10324         }
10325       } ConvertDiagnoser;
10326       
10327       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10328                                                      ConvertDiagnoser, false);
10329     }
10330     if (Converted.isInvalid())
10331       return Converted;
10332     E = Converted.take();
10333     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10334       return ExprError();
10335   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10336     // An ICE must be of integral or unscoped enumeration type.
10337     if (!Diagnoser.Suppress)
10338       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10339     return ExprError();
10340   }
10341
10342   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10343   // in the non-ICE case.
10344   if (!getLangOpts().CPlusPlus11 && E->isIntegerConstantExpr(Context)) {
10345     if (Result)
10346       *Result = E->EvaluateKnownConstInt(Context);
10347     return Owned(E);
10348   }
10349
10350   Expr::EvalResult EvalResult;
10351   SmallVector<PartialDiagnosticAt, 8> Notes;
10352   EvalResult.Diag = &Notes;
10353
10354   // Try to evaluate the expression, and produce diagnostics explaining why it's
10355   // not a constant expression as a side-effect.
10356   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10357                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10358
10359   // In C++11, we can rely on diagnostics being produced for any expression
10360   // which is not a constant expression. If no diagnostics were produced, then
10361   // this is a constant expression.
10362   if (Folded && getLangOpts().CPlusPlus11 && Notes.empty()) {
10363     if (Result)
10364       *Result = EvalResult.Val.getInt();
10365     return Owned(E);
10366   }
10367
10368   // If our only note is the usual "invalid subexpression" note, just point
10369   // the caret at its location rather than producing an essentially
10370   // redundant note.
10371   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10372         diag::note_invalid_subexpr_in_const_expr) {
10373     DiagLoc = Notes[0].first;
10374     Notes.clear();
10375   }
10376
10377   if (!Folded || !AllowFold) {
10378     if (!Diagnoser.Suppress) {
10379       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10380       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10381         Diag(Notes[I].first, Notes[I].second);
10382     }
10383
10384     return ExprError();
10385   }
10386
10387   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10388   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10389     Diag(Notes[I].first, Notes[I].second);
10390
10391   if (Result)
10392     *Result = EvalResult.Val.getInt();
10393   return Owned(E);
10394 }
10395
10396 namespace {
10397   // Handle the case where we conclude a expression which we speculatively
10398   // considered to be unevaluated is actually evaluated.
10399   class TransformToPE : public TreeTransform<TransformToPE> {
10400     typedef TreeTransform<TransformToPE> BaseTransform;
10401
10402   public:
10403     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10404
10405     // Make sure we redo semantic analysis
10406     bool AlwaysRebuild() { return true; }
10407
10408     // Make sure we handle LabelStmts correctly.
10409     // FIXME: This does the right thing, but maybe we need a more general
10410     // fix to TreeTransform?
10411     StmtResult TransformLabelStmt(LabelStmt *S) {
10412       S->getDecl()->setStmt(0);
10413       return BaseTransform::TransformLabelStmt(S);
10414     }
10415
10416     // We need to special-case DeclRefExprs referring to FieldDecls which
10417     // are not part of a member pointer formation; normal TreeTransforming
10418     // doesn't catch this case because of the way we represent them in the AST.
10419     // FIXME: This is a bit ugly; is it really the best way to handle this
10420     // case?
10421     //
10422     // Error on DeclRefExprs referring to FieldDecls.
10423     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10424       if (isa<FieldDecl>(E->getDecl()) &&
10425           !SemaRef.isUnevaluatedContext())
10426         return SemaRef.Diag(E->getLocation(),
10427                             diag::err_invalid_non_static_member_use)
10428             << E->getDecl() << E->getSourceRange();
10429
10430       return BaseTransform::TransformDeclRefExpr(E);
10431     }
10432
10433     // Exception: filter out member pointer formation
10434     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10435       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10436         return E;
10437
10438       return BaseTransform::TransformUnaryOperator(E);
10439     }
10440
10441     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10442       // Lambdas never need to be transformed.
10443       return E;
10444     }
10445   };
10446 }
10447
10448 ExprResult Sema::TransformToPotentiallyEvaluated(Expr *E) {
10449   assert(ExprEvalContexts.back().Context == Unevaluated &&
10450          "Should only transform unevaluated expressions");
10451   ExprEvalContexts.back().Context =
10452       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10453   if (ExprEvalContexts.back().Context == Unevaluated)
10454     return E;
10455   return TransformToPE(*this).TransformExpr(E);
10456 }
10457
10458 void
10459 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10460                                       Decl *LambdaContextDecl,
10461                                       bool IsDecltype) {
10462   ExprEvalContexts.push_back(
10463              ExpressionEvaluationContextRecord(NewContext,
10464                                                ExprCleanupObjects.size(),
10465                                                ExprNeedsCleanups,
10466                                                LambdaContextDecl,
10467                                                IsDecltype));
10468   ExprNeedsCleanups = false;
10469   if (!MaybeODRUseExprs.empty())
10470     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10471 }
10472
10473 void
10474 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10475                                       ReuseLambdaContextDecl_t,
10476                                       bool IsDecltype) {
10477   Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10478   PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10479 }
10480
10481 void Sema::PopExpressionEvaluationContext() {
10482   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10483
10484   if (!Rec.Lambdas.empty()) {
10485     if (Rec.Context == Unevaluated) {
10486       // C++11 [expr.prim.lambda]p2:
10487       //   A lambda-expression shall not appear in an unevaluated operand
10488       //   (Clause 5).
10489       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10490         Diag(Rec.Lambdas[I]->getLocStart(), 
10491              diag::err_lambda_unevaluated_operand);
10492     } else {
10493       // Mark the capture expressions odr-used. This was deferred
10494       // during lambda expression creation.
10495       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10496         LambdaExpr *Lambda = Rec.Lambdas[I];
10497         for (LambdaExpr::capture_init_iterator 
10498                   C = Lambda->capture_init_begin(),
10499                CEnd = Lambda->capture_init_end();
10500              C != CEnd; ++C) {
10501           MarkDeclarationsReferencedInExpr(*C);
10502         }
10503       }
10504     }
10505   }
10506
10507   // When are coming out of an unevaluated context, clear out any
10508   // temporaries that we may have created as part of the evaluation of
10509   // the expression in that context: they aren't relevant because they
10510   // will never be constructed.
10511   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10512     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10513                              ExprCleanupObjects.end());
10514     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10515     CleanupVarDeclMarking();
10516     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10517   // Otherwise, merge the contexts together.
10518   } else {
10519     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10520     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10521                             Rec.SavedMaybeODRUseExprs.end());
10522   }
10523
10524   // Pop the current expression evaluation context off the stack.
10525   ExprEvalContexts.pop_back();
10526 }
10527
10528 void Sema::DiscardCleanupsInEvaluationContext() {
10529   ExprCleanupObjects.erase(
10530          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10531          ExprCleanupObjects.end());
10532   ExprNeedsCleanups = false;
10533   MaybeODRUseExprs.clear();
10534 }
10535
10536 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10537   if (!E->getType()->isVariablyModifiedType())
10538     return E;
10539   return TransformToPotentiallyEvaluated(E);
10540 }
10541
10542 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10543   // Do not mark anything as "used" within a dependent context; wait for
10544   // an instantiation.
10545   if (SemaRef.CurContext->isDependentContext())
10546     return false;
10547
10548   switch (SemaRef.ExprEvalContexts.back().Context) {
10549     case Sema::Unevaluated:
10550       // We are in an expression that is not potentially evaluated; do nothing.
10551       // (Depending on how you read the standard, we actually do need to do
10552       // something here for null pointer constants, but the standard's
10553       // definition of a null pointer constant is completely crazy.)
10554       return false;
10555
10556     case Sema::ConstantEvaluated:
10557     case Sema::PotentiallyEvaluated:
10558       // We are in a potentially evaluated expression (or a constant-expression
10559       // in C++03); we need to do implicit template instantiation, implicitly
10560       // define class members, and mark most declarations as used.
10561       return true;
10562
10563     case Sema::PotentiallyEvaluatedIfUsed:
10564       // Referenced declarations will only be used if the construct in the
10565       // containing expression is used.
10566       return false;
10567   }
10568   llvm_unreachable("Invalid context");
10569 }
10570
10571 /// \brief Mark a function referenced, and check whether it is odr-used
10572 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10573 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10574   assert(Func && "No function?");
10575
10576   Func->setReferenced();
10577
10578   // C++11 [basic.def.odr]p3:
10579   //   A function whose name appears as a potentially-evaluated expression is
10580   //   odr-used if it is the unique lookup result or the selected member of a
10581   //   set of overloaded functions [...].
10582   //
10583   // We (incorrectly) mark overload resolution as an unevaluated context, so we
10584   // can just check that here. Skip the rest of this function if we've already
10585   // marked the function as used.
10586   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10587     // C++11 [temp.inst]p3:
10588     //   Unless a function template specialization has been explicitly
10589     //   instantiated or explicitly specialized, the function template
10590     //   specialization is implicitly instantiated when the specialization is
10591     //   referenced in a context that requires a function definition to exist.
10592     //
10593     // We consider constexpr function templates to be referenced in a context
10594     // that requires a definition to exist whenever they are referenced.
10595     //
10596     // FIXME: This instantiates constexpr functions too frequently. If this is
10597     // really an unevaluated context (and we're not just in the definition of a
10598     // function template or overload resolution or other cases which we
10599     // incorrectly consider to be unevaluated contexts), and we're not in a
10600     // subexpression which we actually need to evaluate (for instance, a
10601     // template argument, array bound or an expression in a braced-init-list),
10602     // we are not permitted to instantiate this constexpr function definition.
10603     //
10604     // FIXME: This also implicitly defines special members too frequently. They
10605     // are only supposed to be implicitly defined if they are odr-used, but they
10606     // are not odr-used from constant expressions in unevaluated contexts.
10607     // However, they cannot be referenced if they are deleted, and they are
10608     // deleted whenever the implicit definition of the special member would
10609     // fail.
10610     if (!Func->isConstexpr() || Func->getBody())
10611       return;
10612     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10613     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10614       return;
10615   }
10616
10617   // Note that this declaration has been used.
10618   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10619     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10620       if (Constructor->isDefaultConstructor()) {
10621         if (Constructor->isTrivial())
10622           return;
10623         if (!Constructor->isUsed(false))
10624           DefineImplicitDefaultConstructor(Loc, Constructor);
10625       } else if (Constructor->isCopyConstructor()) {
10626         if (!Constructor->isUsed(false))
10627           DefineImplicitCopyConstructor(Loc, Constructor);
10628       } else if (Constructor->isMoveConstructor()) {
10629         if (!Constructor->isUsed(false))
10630           DefineImplicitMoveConstructor(Loc, Constructor);
10631       }
10632     } else if (Constructor->getInheritedConstructor()) {
10633       if (!Constructor->isUsed(false))
10634         DefineInheritingConstructor(Loc, Constructor);
10635     }
10636
10637     MarkVTableUsed(Loc, Constructor->getParent());
10638   } else if (CXXDestructorDecl *Destructor =
10639                  dyn_cast<CXXDestructorDecl>(Func)) {
10640     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10641         !Destructor->isUsed(false))
10642       DefineImplicitDestructor(Loc, Destructor);
10643     if (Destructor->isVirtual())
10644       MarkVTableUsed(Loc, Destructor->getParent());
10645   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10646     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10647         MethodDecl->isOverloadedOperator() &&
10648         MethodDecl->getOverloadedOperator() == OO_Equal) {
10649       if (!MethodDecl->isUsed(false)) {
10650         if (MethodDecl->isCopyAssignmentOperator())
10651           DefineImplicitCopyAssignment(Loc, MethodDecl);
10652         else
10653           DefineImplicitMoveAssignment(Loc, MethodDecl);
10654       }
10655     } else if (isa<CXXConversionDecl>(MethodDecl) &&
10656                MethodDecl->getParent()->isLambda()) {
10657       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10658       if (Conversion->isLambdaToBlockPointerConversion())
10659         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10660       else
10661         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10662     } else if (MethodDecl->isVirtual())
10663       MarkVTableUsed(Loc, MethodDecl->getParent());
10664   }
10665
10666   // Recursive functions should be marked when used from another function.
10667   // FIXME: Is this really right?
10668   if (CurContext == Func) return;
10669
10670   // Resolve the exception specification for any function which is
10671   // used: CodeGen will need it.
10672   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10673   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10674     ResolveExceptionSpec(Loc, FPT);
10675
10676   // Implicit instantiation of function templates and member functions of
10677   // class templates.
10678   if (Func->isImplicitlyInstantiable()) {
10679     bool AlreadyInstantiated = false;
10680     SourceLocation PointOfInstantiation = Loc;
10681     if (FunctionTemplateSpecializationInfo *SpecInfo
10682                               = Func->getTemplateSpecializationInfo()) {
10683       if (SpecInfo->getPointOfInstantiation().isInvalid())
10684         SpecInfo->setPointOfInstantiation(Loc);
10685       else if (SpecInfo->getTemplateSpecializationKind()
10686                  == TSK_ImplicitInstantiation) {
10687         AlreadyInstantiated = true;
10688         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10689       }
10690     } else if (MemberSpecializationInfo *MSInfo
10691                                 = Func->getMemberSpecializationInfo()) {
10692       if (MSInfo->getPointOfInstantiation().isInvalid())
10693         MSInfo->setPointOfInstantiation(Loc);
10694       else if (MSInfo->getTemplateSpecializationKind()
10695                  == TSK_ImplicitInstantiation) {
10696         AlreadyInstantiated = true;
10697         PointOfInstantiation = MSInfo->getPointOfInstantiation();
10698       }
10699     }
10700
10701     if (!AlreadyInstantiated || Func->isConstexpr()) {
10702       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10703           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10704         PendingLocalImplicitInstantiations.push_back(
10705             std::make_pair(Func, PointOfInstantiation));
10706       else if (Func->isConstexpr())
10707         // Do not defer instantiations of constexpr functions, to avoid the
10708         // expression evaluator needing to call back into Sema if it sees a
10709         // call to such a function.
10710         InstantiateFunctionDefinition(PointOfInstantiation, Func);
10711       else {
10712         PendingInstantiations.push_back(std::make_pair(Func,
10713                                                        PointOfInstantiation));
10714         // Notify the consumer that a function was implicitly instantiated.
10715         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10716       }
10717     }
10718   } else {
10719     // Walk redefinitions, as some of them may be instantiable.
10720     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10721          e(Func->redecls_end()); i != e; ++i) {
10722       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10723         MarkFunctionReferenced(Loc, *i);
10724     }
10725   }
10726
10727   // Keep track of used but undefined functions.
10728   if (!Func->isDefined()) {
10729     if (mightHaveNonExternalLinkage(Func))
10730       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10731     else if (Func->getMostRecentDecl()->isInlined() &&
10732              (LangOpts.CPlusPlus || !LangOpts.GNUInline) &&
10733              !Func->getMostRecentDecl()->hasAttr<GNUInlineAttr>())
10734       UndefinedButUsed.insert(std::make_pair(Func->getCanonicalDecl(), Loc));
10735   }
10736
10737   // Normally the must current decl is marked used while processing the use and
10738   // any subsequent decls are marked used by decl merging. This fails with
10739   // template instantiation since marking can happen at the end of the file
10740   // and, because of the two phase lookup, this function is called with at
10741   // decl in the middle of a decl chain. We loop to maintain the invariant
10742   // that once a decl is used, all decls after it are also used.
10743   for (FunctionDecl *F = Func->getMostRecentDecl();; F = F->getPreviousDecl()) {
10744     F->setUsed(true);
10745     if (F == Func)
10746       break;
10747   }
10748 }
10749
10750 static void
10751 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10752                                    VarDecl *var, DeclContext *DC) {
10753   DeclContext *VarDC = var->getDeclContext();
10754
10755   //  If the parameter still belongs to the translation unit, then
10756   //  we're actually just using one parameter in the declaration of
10757   //  the next.
10758   if (isa<ParmVarDecl>(var) &&
10759       isa<TranslationUnitDecl>(VarDC))
10760     return;
10761
10762   // For C code, don't diagnose about capture if we're not actually in code
10763   // right now; it's impossible to write a non-constant expression outside of
10764   // function context, so we'll get other (more useful) diagnostics later.
10765   //
10766   // For C++, things get a bit more nasty... it would be nice to suppress this
10767   // diagnostic for certain cases like using a local variable in an array bound
10768   // for a member of a local class, but the correct predicate is not obvious.
10769   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10770     return;
10771
10772   if (isa<CXXMethodDecl>(VarDC) &&
10773       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10774     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10775       << var->getIdentifier();
10776   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10777     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10778       << var->getIdentifier() << fn->getDeclName();
10779   } else if (isa<BlockDecl>(VarDC)) {
10780     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10781       << var->getIdentifier();
10782   } else {
10783     // FIXME: Is there any other context where a local variable can be
10784     // declared?
10785     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10786       << var->getIdentifier();
10787   }
10788
10789   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10790     << var->getIdentifier();
10791
10792   // FIXME: Add additional diagnostic info about class etc. which prevents
10793   // capture.
10794 }
10795
10796 /// \brief Capture the given variable in the given lambda expression.
10797 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10798                                   VarDecl *Var, QualType FieldType, 
10799                                   QualType DeclRefType,
10800                                   SourceLocation Loc,
10801                                   bool RefersToEnclosingLocal) {
10802   CXXRecordDecl *Lambda = LSI->Lambda;
10803
10804   // Build the non-static data member.
10805   FieldDecl *Field
10806     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10807                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10808                         0, false, ICIS_NoInit);
10809   Field->setImplicit(true);
10810   Field->setAccess(AS_private);
10811   Lambda->addDecl(Field);
10812
10813   // C++11 [expr.prim.lambda]p21:
10814   //   When the lambda-expression is evaluated, the entities that
10815   //   are captured by copy are used to direct-initialize each
10816   //   corresponding non-static data member of the resulting closure
10817   //   object. (For array members, the array elements are
10818   //   direct-initialized in increasing subscript order.) These
10819   //   initializations are performed in the (unspecified) order in
10820   //   which the non-static data members are declared.
10821       
10822   // Introduce a new evaluation context for the initialization, so
10823   // that temporaries introduced as part of the capture are retained
10824   // to be re-"exported" from the lambda expression itself.
10825   EnterExpressionEvaluationContext scope(S, Sema::PotentiallyEvaluated);
10826
10827   // C++ [expr.prim.labda]p12:
10828   //   An entity captured by a lambda-expression is odr-used (3.2) in
10829   //   the scope containing the lambda-expression.
10830   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 
10831                                           DeclRefType, VK_LValue, Loc);
10832   Var->setReferenced(true);
10833   Var->setUsed(true);
10834
10835   // When the field has array type, create index variables for each
10836   // dimension of the array. We use these index variables to subscript
10837   // the source array, and other clients (e.g., CodeGen) will perform
10838   // the necessary iteration with these index variables.
10839   SmallVector<VarDecl *, 4> IndexVariables;
10840   QualType BaseType = FieldType;
10841   QualType SizeType = S.Context.getSizeType();
10842   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10843   while (const ConstantArrayType *Array
10844                         = S.Context.getAsConstantArrayType(BaseType)) {
10845     // Create the iteration variable for this array index.
10846     IdentifierInfo *IterationVarName = 0;
10847     {
10848       SmallString<8> Str;
10849       llvm::raw_svector_ostream OS(Str);
10850       OS << "__i" << IndexVariables.size();
10851       IterationVarName = &S.Context.Idents.get(OS.str());
10852     }
10853     VarDecl *IterationVar
10854       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10855                         IterationVarName, SizeType,
10856                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10857                         SC_None);
10858     IndexVariables.push_back(IterationVar);
10859     LSI->ArrayIndexVars.push_back(IterationVar);
10860     
10861     // Create a reference to the iteration variable.
10862     ExprResult IterationVarRef
10863       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10864     assert(!IterationVarRef.isInvalid() &&
10865            "Reference to invented variable cannot fail!");
10866     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10867     assert(!IterationVarRef.isInvalid() &&
10868            "Conversion of invented variable cannot fail!");
10869     
10870     // Subscript the array with this iteration variable.
10871     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10872                              Ref, Loc, IterationVarRef.take(), Loc);
10873     if (Subscript.isInvalid()) {
10874       S.CleanupVarDeclMarking();
10875       S.DiscardCleanupsInEvaluationContext();
10876       return ExprError();
10877     }
10878
10879     Ref = Subscript.take();
10880     BaseType = Array->getElementType();
10881   }
10882
10883   // Construct the entity that we will be initializing. For an array, this
10884   // will be first element in the array, which may require several levels
10885   // of array-subscript entities. 
10886   SmallVector<InitializedEntity, 4> Entities;
10887   Entities.reserve(1 + IndexVariables.size());
10888   Entities.push_back(
10889     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10890   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10891     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10892                                                             0,
10893                                                             Entities.back()));
10894
10895   InitializationKind InitKind
10896     = InitializationKind::CreateDirect(Loc, Loc, Loc);
10897   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10898   ExprResult Result(true);
10899   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10900     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
10901
10902   // If this initialization requires any cleanups (e.g., due to a
10903   // default argument to a copy constructor), note that for the
10904   // lambda.
10905   if (S.ExprNeedsCleanups)
10906     LSI->ExprNeedsCleanups = true;
10907
10908   // Exit the expression evaluation context used for the capture.
10909   S.CleanupVarDeclMarking();
10910   S.DiscardCleanupsInEvaluationContext();
10911   return Result;
10912 }
10913
10914 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 
10915                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
10916                               bool BuildAndDiagnose, 
10917                               QualType &CaptureType,
10918                               QualType &DeclRefType) {
10919   bool Nested = false;
10920   
10921   DeclContext *DC = CurContext;
10922   if (Var->getDeclContext() == DC) return true;
10923   if (!Var->hasLocalStorage()) return true;
10924
10925   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10926
10927   // Walk up the stack to determine whether we can capture the variable,
10928   // performing the "simple" checks that don't depend on type. We stop when
10929   // we've either hit the declared scope of the variable or find an existing
10930   // capture of that variable.
10931   CaptureType = Var->getType();
10932   DeclRefType = CaptureType.getNonReferenceType();
10933   bool Explicit = (Kind != TryCapture_Implicit);
10934   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10935   do {
10936     // Only block literals and lambda expressions can capture; other
10937     // scopes don't work.
10938     DeclContext *ParentDC;
10939     if (isa<BlockDecl>(DC))
10940       ParentDC = DC->getParent();
10941     else if (isa<CXXMethodDecl>(DC) &&
10942              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10943              cast<CXXRecordDecl>(DC->getParent())->isLambda())
10944       ParentDC = DC->getParent()->getParent();
10945     else {
10946       if (BuildAndDiagnose)
10947         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10948       return true;
10949     }
10950
10951     CapturingScopeInfo *CSI =
10952       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10953
10954     // Check whether we've already captured it.
10955     if (CSI->CaptureMap.count(Var)) {
10956       // If we found a capture, any subcaptures are nested.
10957       Nested = true;
10958       
10959       // Retrieve the capture type for this variable.
10960       CaptureType = CSI->getCapture(Var).getCaptureType();
10961       
10962       // Compute the type of an expression that refers to this variable.
10963       DeclRefType = CaptureType.getNonReferenceType();
10964       
10965       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10966       if (Cap.isCopyCapture() &&
10967           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10968         DeclRefType.addConst();
10969       break;
10970     }
10971
10972     bool IsBlock = isa<BlockScopeInfo>(CSI);
10973     bool IsLambda = !IsBlock;
10974
10975     // Lambdas are not allowed to capture unnamed variables
10976     // (e.g. anonymous unions).
10977     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10978     // assuming that's the intent.
10979     if (IsLambda && !Var->getDeclName()) {
10980       if (BuildAndDiagnose) {
10981         Diag(Loc, diag::err_lambda_capture_anonymous_var);
10982         Diag(Var->getLocation(), diag::note_declared_at);
10983       }
10984       return true;
10985     }
10986
10987     // Prohibit variably-modified types; they're difficult to deal with.
10988     if (Var->getType()->isVariablyModifiedType()) {
10989       if (BuildAndDiagnose) {
10990         if (IsBlock)
10991           Diag(Loc, diag::err_ref_vm_type);
10992         else
10993           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10994         Diag(Var->getLocation(), diag::note_previous_decl) 
10995           << Var->getDeclName();
10996       }
10997       return true;
10998     }
10999     // Prohibit structs with flexible array members too.
11000     // We cannot capture what is in the tail end of the struct.
11001     if (const RecordType *VTTy = Var->getType()->getAs<RecordType>()) {
11002       if (VTTy->getDecl()->hasFlexibleArrayMember()) {
11003         if (BuildAndDiagnose) {
11004           if (IsBlock)
11005             Diag(Loc, diag::err_ref_flexarray_type);
11006           else
11007             Diag(Loc, diag::err_lambda_capture_flexarray_type)
11008               << Var->getDeclName();
11009           Diag(Var->getLocation(), diag::note_previous_decl)
11010             << Var->getDeclName();
11011         }
11012         return true;
11013       }
11014     }
11015     // Lambdas are not allowed to capture __block variables; they don't
11016     // support the expected semantics.
11017     if (IsLambda && HasBlocksAttr) {
11018       if (BuildAndDiagnose) {
11019         Diag(Loc, diag::err_lambda_capture_block) 
11020           << Var->getDeclName();
11021         Diag(Var->getLocation(), diag::note_previous_decl) 
11022           << Var->getDeclName();
11023       }
11024       return true;
11025     }
11026
11027     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
11028       // No capture-default
11029       if (BuildAndDiagnose) {
11030         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
11031         Diag(Var->getLocation(), diag::note_previous_decl) 
11032           << Var->getDeclName();
11033         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
11034              diag::note_lambda_decl);
11035       }
11036       return true;
11037     }
11038
11039     FunctionScopesIndex--;
11040     DC = ParentDC;
11041     Explicit = false;
11042   } while (!Var->getDeclContext()->Equals(DC));
11043
11044   // Walk back down the scope stack, computing the type of the capture at
11045   // each step, checking type-specific requirements, and adding captures if
11046   // requested.
11047   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 
11048        ++I) {
11049     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
11050     
11051     // Compute the type of the capture and of a reference to the capture within
11052     // this scope.
11053     if (isa<BlockScopeInfo>(CSI)) {
11054       Expr *CopyExpr = 0;
11055       bool ByRef = false;
11056       
11057       // Blocks are not allowed to capture arrays.
11058       if (CaptureType->isArrayType()) {
11059         if (BuildAndDiagnose) {
11060           Diag(Loc, diag::err_ref_array_type);
11061           Diag(Var->getLocation(), diag::note_previous_decl) 
11062           << Var->getDeclName();
11063         }
11064         return true;
11065       }
11066
11067       // Forbid the block-capture of autoreleasing variables.
11068       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11069         if (BuildAndDiagnose) {
11070           Diag(Loc, diag::err_arc_autoreleasing_capture)
11071             << /*block*/ 0;
11072           Diag(Var->getLocation(), diag::note_previous_decl)
11073             << Var->getDeclName();
11074         }
11075         return true;
11076       }
11077
11078       if (HasBlocksAttr || CaptureType->isReferenceType()) {
11079         // Block capture by reference does not change the capture or
11080         // declaration reference types.
11081         ByRef = true;
11082       } else {
11083         // Block capture by copy introduces 'const'.
11084         CaptureType = CaptureType.getNonReferenceType().withConst();
11085         DeclRefType = CaptureType;
11086                 
11087         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
11088           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
11089             // The capture logic needs the destructor, so make sure we mark it.
11090             // Usually this is unnecessary because most local variables have
11091             // their destructors marked at declaration time, but parameters are
11092             // an exception because it's technically only the call site that
11093             // actually requires the destructor.
11094             if (isa<ParmVarDecl>(Var))
11095               FinalizeVarWithDestructor(Var, Record);
11096
11097             // Enter a new evaluation context to insulate the copy
11098             // full-expression.
11099             EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
11100
11101             // According to the blocks spec, the capture of a variable from
11102             // the stack requires a const copy constructor.  This is not true
11103             // of the copy/move done to move a __block variable to the heap.
11104             Expr *DeclRef = new (Context) DeclRefExpr(Var, Nested,
11105                                                       DeclRefType.withConst(), 
11106                                                       VK_LValue, Loc);
11107             
11108             ExprResult Result
11109               = PerformCopyInitialization(
11110                   InitializedEntity::InitializeBlock(Var->getLocation(),
11111                                                      CaptureType, false),
11112                   Loc, Owned(DeclRef));
11113             
11114             // Build a full-expression copy expression if initialization
11115             // succeeded and used a non-trivial constructor.  Recover from
11116             // errors by pretending that the copy isn't necessary.
11117             if (!Result.isInvalid() &&
11118                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
11119                    ->isTrivial()) {
11120               Result = MaybeCreateExprWithCleanups(Result);
11121               CopyExpr = Result.take();
11122             }
11123           }
11124         }
11125       }
11126
11127       // Actually capture the variable.
11128       if (BuildAndDiagnose)
11129         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
11130                         SourceLocation(), CaptureType, CopyExpr);
11131       Nested = true;
11132       continue;
11133     } 
11134     
11135     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
11136     
11137     // Determine whether we are capturing by reference or by value.
11138     bool ByRef = false;
11139     if (I == N - 1 && Kind != TryCapture_Implicit) {
11140       ByRef = (Kind == TryCapture_ExplicitByRef);
11141     } else {
11142       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
11143     }
11144     
11145     // Compute the type of the field that will capture this variable.
11146     if (ByRef) {
11147       // C++11 [expr.prim.lambda]p15:
11148       //   An entity is captured by reference if it is implicitly or
11149       //   explicitly captured but not captured by copy. It is
11150       //   unspecified whether additional unnamed non-static data
11151       //   members are declared in the closure type for entities
11152       //   captured by reference.
11153       //
11154       // FIXME: It is not clear whether we want to build an lvalue reference
11155       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
11156       // to do the former, while EDG does the latter. Core issue 1249 will 
11157       // clarify, but for now we follow GCC because it's a more permissive and
11158       // easily defensible position.
11159       CaptureType = Context.getLValueReferenceType(DeclRefType);
11160     } else {
11161       // C++11 [expr.prim.lambda]p14:
11162       //   For each entity captured by copy, an unnamed non-static
11163       //   data member is declared in the closure type. The
11164       //   declaration order of these members is unspecified. The type
11165       //   of such a data member is the type of the corresponding
11166       //   captured entity if the entity is not a reference to an
11167       //   object, or the referenced type otherwise. [Note: If the
11168       //   captured entity is a reference to a function, the
11169       //   corresponding data member is also a reference to a
11170       //   function. - end note ]
11171       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
11172         if (!RefType->getPointeeType()->isFunctionType())
11173           CaptureType = RefType->getPointeeType();
11174       }
11175
11176       // Forbid the lambda copy-capture of autoreleasing variables.
11177       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
11178         if (BuildAndDiagnose) {
11179           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
11180           Diag(Var->getLocation(), diag::note_previous_decl)
11181             << Var->getDeclName();
11182         }
11183         return true;
11184       }
11185     }
11186
11187     // Capture this variable in the lambda.
11188     Expr *CopyExpr = 0;
11189     if (BuildAndDiagnose) {
11190       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
11191                                           DeclRefType, Loc,
11192                                           Nested);
11193       if (!Result.isInvalid())
11194         CopyExpr = Result.take();
11195     }
11196     
11197     // Compute the type of a reference to this captured variable.
11198     if (ByRef)
11199       DeclRefType = CaptureType.getNonReferenceType();
11200     else {
11201       // C++ [expr.prim.lambda]p5:
11202       //   The closure type for a lambda-expression has a public inline 
11203       //   function call operator [...]. This function call operator is 
11204       //   declared const (9.3.1) if and only if the lambda-expression’s 
11205       //   parameter-declaration-clause is not followed by mutable.
11206       DeclRefType = CaptureType.getNonReferenceType();
11207       if (!LSI->Mutable && !CaptureType->isReferenceType())
11208         DeclRefType.addConst();      
11209     }
11210     
11211     // Add the capture.
11212     if (BuildAndDiagnose)
11213       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
11214                       EllipsisLoc, CaptureType, CopyExpr);
11215     Nested = true;
11216   }
11217
11218   return false;
11219 }
11220
11221 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
11222                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
11223   QualType CaptureType;
11224   QualType DeclRefType;
11225   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
11226                             /*BuildAndDiagnose=*/true, CaptureType,
11227                             DeclRefType);
11228 }
11229
11230 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
11231   QualType CaptureType;
11232   QualType DeclRefType;
11233   
11234   // Determine whether we can capture this variable.
11235   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
11236                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
11237     return QualType();
11238
11239   return DeclRefType;
11240 }
11241
11242 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
11243                                SourceLocation Loc) {
11244   // Keep track of used but undefined variables.
11245   // FIXME: We shouldn't suppress this warning for static data members.
11246   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
11247       Var->getLinkage() != ExternalLinkage &&
11248       !(Var->isStaticDataMember() && Var->hasInit())) {
11249     SourceLocation &old = SemaRef.UndefinedButUsed[Var->getCanonicalDecl()];
11250     if (old.isInvalid()) old = Loc;
11251   }
11252
11253   SemaRef.tryCaptureVariable(Var, Loc);
11254
11255   Var->setUsed(true);
11256 }
11257
11258 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
11259   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
11260   // an object that satisfies the requirements for appearing in a
11261   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
11262   // is immediately applied."  This function handles the lvalue-to-rvalue
11263   // conversion part.
11264   MaybeODRUseExprs.erase(E->IgnoreParens());
11265 }
11266
11267 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11268   if (!Res.isUsable())
11269     return Res;
11270
11271   // If a constant-expression is a reference to a variable where we delay
11272   // deciding whether it is an odr-use, just assume we will apply the
11273   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
11274   // (a non-type template argument), we have special handling anyway.
11275   UpdateMarkingForLValueToRValue(Res.get());
11276   return Res;
11277 }
11278
11279 void Sema::CleanupVarDeclMarking() {
11280   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11281                                         e = MaybeODRUseExprs.end();
11282        i != e; ++i) {
11283     VarDecl *Var;
11284     SourceLocation Loc;
11285     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11286       Var = cast<VarDecl>(DRE->getDecl());
11287       Loc = DRE->getLocation();
11288     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11289       Var = cast<VarDecl>(ME->getMemberDecl());
11290       Loc = ME->getMemberLoc();
11291     } else {
11292       llvm_unreachable("Unexpcted expression");
11293     }
11294
11295     MarkVarDeclODRUsed(*this, Var, Loc);
11296   }
11297
11298   MaybeODRUseExprs.clear();
11299 }
11300
11301 // Mark a VarDecl referenced, and perform the necessary handling to compute
11302 // odr-uses.
11303 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11304                                     VarDecl *Var, Expr *E) {
11305   Var->setReferenced();
11306
11307   if (!IsPotentiallyEvaluatedContext(SemaRef))
11308     return;
11309
11310   // Implicit instantiation of static data members of class templates.
11311   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
11312     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11313     assert(MSInfo && "Missing member specialization information?");
11314     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11315     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
11316         (!AlreadyInstantiated ||
11317          Var->isUsableInConstantExpressions(SemaRef.Context))) {
11318       if (!AlreadyInstantiated) {
11319         // This is a modification of an existing AST node. Notify listeners.
11320         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11321           L->StaticDataMemberInstantiated(Var);
11322         MSInfo->setPointOfInstantiation(Loc);
11323       }
11324       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
11325       if (Var->isUsableInConstantExpressions(SemaRef.Context))
11326         // Do not defer instantiations of variables which could be used in a
11327         // constant expression.
11328         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
11329       else
11330         SemaRef.PendingInstantiations.push_back(
11331             std::make_pair(Var, PointOfInstantiation));
11332     }
11333   }
11334
11335   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11336   // the requirements for appearing in a constant expression (5.19) and, if
11337   // it is an object, the lvalue-to-rvalue conversion (4.1)
11338   // is immediately applied."  We check the first part here, and
11339   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11340   // Note that we use the C++11 definition everywhere because nothing in
11341   // C++03 depends on whether we get the C++03 version correct. The second
11342   // part does not apply to references, since they are not objects.
11343   const VarDecl *DefVD;
11344   if (E && !isa<ParmVarDecl>(Var) &&
11345       Var->isUsableInConstantExpressions(SemaRef.Context) &&
11346       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11347     if (!Var->getType()->isReferenceType())
11348       SemaRef.MaybeODRUseExprs.insert(E);
11349   } else
11350     MarkVarDeclODRUsed(SemaRef, Var, Loc);
11351 }
11352
11353 /// \brief Mark a variable referenced, and check whether it is odr-used
11354 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
11355 /// used directly for normal expressions referring to VarDecl.
11356 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11357   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11358 }
11359
11360 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11361                                Decl *D, Expr *E, bool OdrUse) {
11362   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11363     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11364     return;
11365   }
11366
11367   SemaRef.MarkAnyDeclReferenced(Loc, D, OdrUse);
11368
11369   // If this is a call to a method via a cast, also mark the method in the
11370   // derived class used in case codegen can devirtualize the call.
11371   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11372   if (!ME)
11373     return;
11374   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11375   if (!MD)
11376     return;
11377   const Expr *Base = ME->getBase();
11378   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11379   if (!MostDerivedClassDecl)
11380     return;
11381   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11382   if (!DM || DM->isPure())
11383     return;
11384   SemaRef.MarkAnyDeclReferenced(Loc, DM, OdrUse);
11385
11386
11387 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11388 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11389   // TODO: update this with DR# once a defect report is filed.
11390   // C++11 defect. The address of a pure member should not be an ODR use, even
11391   // if it's a qualified reference.
11392   bool OdrUse = true;
11393   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getDecl()))
11394     if (Method->isVirtual())
11395       OdrUse = false;
11396   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E, OdrUse);
11397 }
11398
11399 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11400 void Sema::MarkMemberReferenced(MemberExpr *E) {
11401   // C++11 [basic.def.odr]p2:
11402   //   A non-overloaded function whose name appears as a potentially-evaluated
11403   //   expression or a member of a set of candidate functions, if selected by
11404   //   overload resolution when referred to from a potentially-evaluated
11405   //   expression, is odr-used, unless it is a pure virtual function and its
11406   //   name is not explicitly qualified.
11407   bool OdrUse = true;
11408   if (!E->hasQualifier()) {
11409     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(E->getMemberDecl()))
11410       if (Method->isPure())
11411         OdrUse = false;
11412   }
11413   SourceLocation Loc = E->getMemberLoc().isValid() ?
11414                             E->getMemberLoc() : E->getLocStart();
11415   MarkExprReferenced(*this, Loc, E->getMemberDecl(), E, OdrUse);
11416 }
11417
11418 /// \brief Perform marking for a reference to an arbitrary declaration.  It
11419 /// marks the declaration referenced, and performs odr-use checking for functions
11420 /// and variables. This method should not be used when building an normal
11421 /// expression which refers to a variable.
11422 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool OdrUse) {
11423   if (OdrUse) {
11424     if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
11425       MarkVariableReferenced(Loc, VD);
11426       return;
11427     }
11428     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
11429       MarkFunctionReferenced(Loc, FD);
11430       return;
11431     }
11432   }
11433   D->setReferenced();
11434 }
11435
11436 namespace {
11437   // Mark all of the declarations referenced
11438   // FIXME: Not fully implemented yet! We need to have a better understanding
11439   // of when we're entering
11440   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11441     Sema &S;
11442     SourceLocation Loc;
11443
11444   public:
11445     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11446
11447     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11448
11449     bool TraverseTemplateArgument(const TemplateArgument &Arg);
11450     bool TraverseRecordType(RecordType *T);
11451   };
11452 }
11453
11454 bool MarkReferencedDecls::TraverseTemplateArgument(
11455   const TemplateArgument &Arg) {
11456   if (Arg.getKind() == TemplateArgument::Declaration) {
11457     if (Decl *D = Arg.getAsDecl())
11458       S.MarkAnyDeclReferenced(Loc, D, true);
11459   }
11460
11461   return Inherited::TraverseTemplateArgument(Arg);
11462 }
11463
11464 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11465   if (ClassTemplateSpecializationDecl *Spec
11466                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11467     const TemplateArgumentList &Args = Spec->getTemplateArgs();
11468     return TraverseTemplateArguments(Args.data(), Args.size());
11469   }
11470
11471   return true;
11472 }
11473
11474 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11475   MarkReferencedDecls Marker(*this, Loc);
11476   Marker.TraverseType(Context.getCanonicalType(T));
11477 }
11478
11479 namespace {
11480   /// \brief Helper class that marks all of the declarations referenced by
11481   /// potentially-evaluated subexpressions as "referenced".
11482   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11483     Sema &S;
11484     bool SkipLocalVariables;
11485     
11486   public:
11487     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11488     
11489     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
11490       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11491     
11492     void VisitDeclRefExpr(DeclRefExpr *E) {
11493       // If we were asked not to visit local variables, don't.
11494       if (SkipLocalVariables) {
11495         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11496           if (VD->hasLocalStorage())
11497             return;
11498       }
11499       
11500       S.MarkDeclRefReferenced(E);
11501     }
11502     
11503     void VisitMemberExpr(MemberExpr *E) {
11504       S.MarkMemberReferenced(E);
11505       Inherited::VisitMemberExpr(E);
11506     }
11507     
11508     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11509       S.MarkFunctionReferenced(E->getLocStart(),
11510             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11511       Visit(E->getSubExpr());
11512     }
11513     
11514     void VisitCXXNewExpr(CXXNewExpr *E) {
11515       if (E->getOperatorNew())
11516         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11517       if (E->getOperatorDelete())
11518         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11519       Inherited::VisitCXXNewExpr(E);
11520     }
11521
11522     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11523       if (E->getOperatorDelete())
11524         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11525       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11526       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11527         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11528         S.MarkFunctionReferenced(E->getLocStart(), 
11529                                     S.LookupDestructor(Record));
11530       }
11531       
11532       Inherited::VisitCXXDeleteExpr(E);
11533     }
11534     
11535     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11536       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11537       Inherited::VisitCXXConstructExpr(E);
11538     }
11539     
11540     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11541       Visit(E->getExpr());
11542     }
11543
11544     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11545       Inherited::VisitImplicitCastExpr(E);
11546
11547       if (E->getCastKind() == CK_LValueToRValue)
11548         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11549     }
11550   };
11551 }
11552
11553 /// \brief Mark any declarations that appear within this expression or any
11554 /// potentially-evaluated subexpressions as "referenced".
11555 ///
11556 /// \param SkipLocalVariables If true, don't mark local variables as 
11557 /// 'referenced'.
11558 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
11559                                             bool SkipLocalVariables) {
11560   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11561 }
11562
11563 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11564 /// of the program being compiled.
11565 ///
11566 /// This routine emits the given diagnostic when the code currently being
11567 /// type-checked is "potentially evaluated", meaning that there is a
11568 /// possibility that the code will actually be executable. Code in sizeof()
11569 /// expressions, code used only during overload resolution, etc., are not
11570 /// potentially evaluated. This routine will suppress such diagnostics or,
11571 /// in the absolutely nutty case of potentially potentially evaluated
11572 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11573 /// later.
11574 ///
11575 /// This routine should be used for all diagnostics that describe the run-time
11576 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11577 /// Failure to do so will likely result in spurious diagnostics or failures
11578 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11579 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11580                                const PartialDiagnostic &PD) {
11581   switch (ExprEvalContexts.back().Context) {
11582   case Unevaluated:
11583     // The argument will never be evaluated, so don't complain.
11584     break;
11585
11586   case ConstantEvaluated:
11587     // Relevant diagnostics should be produced by constant evaluation.
11588     break;
11589
11590   case PotentiallyEvaluated:
11591   case PotentiallyEvaluatedIfUsed:
11592     if (Statement && getCurFunctionOrMethodDecl()) {
11593       FunctionScopes.back()->PossiblyUnreachableDiags.
11594         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11595     }
11596     else
11597       Diag(Loc, PD);
11598       
11599     return true;
11600   }
11601
11602   return false;
11603 }
11604
11605 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11606                                CallExpr *CE, FunctionDecl *FD) {
11607   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11608     return false;
11609
11610   // If we're inside a decltype's expression, don't check for a valid return
11611   // type or construct temporaries until we know whether this is the last call.
11612   if (ExprEvalContexts.back().IsDecltype) {
11613     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11614     return false;
11615   }
11616
11617   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11618     FunctionDecl *FD;
11619     CallExpr *CE;
11620     
11621   public:
11622     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11623       : FD(FD), CE(CE) { }
11624     
11625     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11626       if (!FD) {
11627         S.Diag(Loc, diag::err_call_incomplete_return)
11628           << T << CE->getSourceRange();
11629         return;
11630       }
11631       
11632       S.Diag(Loc, diag::err_call_function_incomplete_return)
11633         << CE->getSourceRange() << FD->getDeclName() << T;
11634       S.Diag(FD->getLocation(),
11635              diag::note_function_with_incomplete_return_type_declared_here)
11636         << FD->getDeclName();
11637     }
11638   } Diagnoser(FD, CE);
11639   
11640   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11641     return true;
11642
11643   return false;
11644 }
11645
11646 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11647 // will prevent this condition from triggering, which is what we want.
11648 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11649   SourceLocation Loc;
11650
11651   unsigned diagnostic = diag::warn_condition_is_assignment;
11652   bool IsOrAssign = false;
11653
11654   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11655     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11656       return;
11657
11658     IsOrAssign = Op->getOpcode() == BO_OrAssign;
11659
11660     // Greylist some idioms by putting them into a warning subcategory.
11661     if (ObjCMessageExpr *ME
11662           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11663       Selector Sel = ME->getSelector();
11664
11665       // self = [<foo> init...]
11666       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11667         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11668
11669       // <foo> = [<bar> nextObject]
11670       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11671         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11672     }
11673
11674     Loc = Op->getOperatorLoc();
11675   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11676     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11677       return;
11678
11679     IsOrAssign = Op->getOperator() == OO_PipeEqual;
11680     Loc = Op->getOperatorLoc();
11681   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11682     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11683   else {
11684     // Not an assignment.
11685     return;
11686   }
11687
11688   Diag(Loc, diagnostic) << E->getSourceRange();
11689
11690   SourceLocation Open = E->getLocStart();
11691   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11692   Diag(Loc, diag::note_condition_assign_silence)
11693         << FixItHint::CreateInsertion(Open, "(")
11694         << FixItHint::CreateInsertion(Close, ")");
11695
11696   if (IsOrAssign)
11697     Diag(Loc, diag::note_condition_or_assign_to_comparison)
11698       << FixItHint::CreateReplacement(Loc, "!=");
11699   else
11700     Diag(Loc, diag::note_condition_assign_to_comparison)
11701       << FixItHint::CreateReplacement(Loc, "==");
11702 }
11703
11704 /// \brief Redundant parentheses over an equality comparison can indicate
11705 /// that the user intended an assignment used as condition.
11706 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11707   // Don't warn if the parens came from a macro.
11708   SourceLocation parenLoc = ParenE->getLocStart();
11709   if (parenLoc.isInvalid() || parenLoc.isMacroID())
11710     return;
11711   // Don't warn for dependent expressions.
11712   if (ParenE->isTypeDependent())
11713     return;
11714
11715   Expr *E = ParenE->IgnoreParens();
11716
11717   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11718     if (opE->getOpcode() == BO_EQ &&
11719         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11720                                                            == Expr::MLV_Valid) {
11721       SourceLocation Loc = opE->getOperatorLoc();
11722       
11723       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11724       SourceRange ParenERange = ParenE->getSourceRange();
11725       Diag(Loc, diag::note_equality_comparison_silence)
11726         << FixItHint::CreateRemoval(ParenERange.getBegin())
11727         << FixItHint::CreateRemoval(ParenERange.getEnd());
11728       Diag(Loc, diag::note_equality_comparison_to_assign)
11729         << FixItHint::CreateReplacement(Loc, "=");
11730     }
11731 }
11732
11733 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11734   DiagnoseAssignmentAsCondition(E);
11735   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11736     DiagnoseEqualityWithExtraParens(parenE);
11737
11738   ExprResult result = CheckPlaceholderExpr(E);
11739   if (result.isInvalid()) return ExprError();
11740   E = result.take();
11741
11742   if (!E->isTypeDependent()) {
11743     if (getLangOpts().CPlusPlus)
11744       return CheckCXXBooleanCondition(E); // C++ 6.4p4
11745
11746     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11747     if (ERes.isInvalid())
11748       return ExprError();
11749     E = ERes.take();
11750
11751     QualType T = E->getType();
11752     if (!T->isScalarType()) { // C99 6.8.4.1p1
11753       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11754         << T << E->getSourceRange();
11755       return ExprError();
11756     }
11757   }
11758
11759   return Owned(E);
11760 }
11761
11762 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11763                                        Expr *SubExpr) {
11764   if (!SubExpr)
11765     return ExprError();
11766
11767   return CheckBooleanCondition(SubExpr, Loc);
11768 }
11769
11770 namespace {
11771   /// A visitor for rebuilding a call to an __unknown_any expression
11772   /// to have an appropriate type.
11773   struct RebuildUnknownAnyFunction
11774     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11775
11776     Sema &S;
11777
11778     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11779
11780     ExprResult VisitStmt(Stmt *S) {
11781       llvm_unreachable("unexpected statement!");
11782     }
11783
11784     ExprResult VisitExpr(Expr *E) {
11785       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11786         << E->getSourceRange();
11787       return ExprError();
11788     }
11789
11790     /// Rebuild an expression which simply semantically wraps another
11791     /// expression which it shares the type and value kind of.
11792     template <class T> ExprResult rebuildSugarExpr(T *E) {
11793       ExprResult SubResult = Visit(E->getSubExpr());
11794       if (SubResult.isInvalid()) return ExprError();
11795
11796       Expr *SubExpr = SubResult.take();
11797       E->setSubExpr(SubExpr);
11798       E->setType(SubExpr->getType());
11799       E->setValueKind(SubExpr->getValueKind());
11800       assert(E->getObjectKind() == OK_Ordinary);
11801       return E;
11802     }
11803
11804     ExprResult VisitParenExpr(ParenExpr *E) {
11805       return rebuildSugarExpr(E);
11806     }
11807
11808     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11809       return rebuildSugarExpr(E);
11810     }
11811
11812     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11813       ExprResult SubResult = Visit(E->getSubExpr());
11814       if (SubResult.isInvalid()) return ExprError();
11815
11816       Expr *SubExpr = SubResult.take();
11817       E->setSubExpr(SubExpr);
11818       E->setType(S.Context.getPointerType(SubExpr->getType()));
11819       assert(E->getValueKind() == VK_RValue);
11820       assert(E->getObjectKind() == OK_Ordinary);
11821       return E;
11822     }
11823
11824     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11825       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11826
11827       E->setType(VD->getType());
11828
11829       assert(E->getValueKind() == VK_RValue);
11830       if (S.getLangOpts().CPlusPlus &&
11831           !(isa<CXXMethodDecl>(VD) &&
11832             cast<CXXMethodDecl>(VD)->isInstance()))
11833         E->setValueKind(VK_LValue);
11834
11835       return E;
11836     }
11837
11838     ExprResult VisitMemberExpr(MemberExpr *E) {
11839       return resolveDecl(E, E->getMemberDecl());
11840     }
11841
11842     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11843       return resolveDecl(E, E->getDecl());
11844     }
11845   };
11846 }
11847
11848 /// Given a function expression of unknown-any type, try to rebuild it
11849 /// to have a function type.
11850 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11851   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11852   if (Result.isInvalid()) return ExprError();
11853   return S.DefaultFunctionArrayConversion(Result.take());
11854 }
11855
11856 namespace {
11857   /// A visitor for rebuilding an expression of type __unknown_anytype
11858   /// into one which resolves the type directly on the referring
11859   /// expression.  Strict preservation of the original source
11860   /// structure is not a goal.
11861   struct RebuildUnknownAnyExpr
11862     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11863
11864     Sema &S;
11865
11866     /// The current destination type.
11867     QualType DestType;
11868
11869     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11870       : S(S), DestType(CastType) {}
11871
11872     ExprResult VisitStmt(Stmt *S) {
11873       llvm_unreachable("unexpected statement!");
11874     }
11875
11876     ExprResult VisitExpr(Expr *E) {
11877       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11878         << E->getSourceRange();
11879       return ExprError();
11880     }
11881
11882     ExprResult VisitCallExpr(CallExpr *E);
11883     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11884
11885     /// Rebuild an expression which simply semantically wraps another
11886     /// expression which it shares the type and value kind of.
11887     template <class T> ExprResult rebuildSugarExpr(T *E) {
11888       ExprResult SubResult = Visit(E->getSubExpr());
11889       if (SubResult.isInvalid()) return ExprError();
11890       Expr *SubExpr = SubResult.take();
11891       E->setSubExpr(SubExpr);
11892       E->setType(SubExpr->getType());
11893       E->setValueKind(SubExpr->getValueKind());
11894       assert(E->getObjectKind() == OK_Ordinary);
11895       return E;
11896     }
11897
11898     ExprResult VisitParenExpr(ParenExpr *E) {
11899       return rebuildSugarExpr(E);
11900     }
11901
11902     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11903       return rebuildSugarExpr(E);
11904     }
11905
11906     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11907       const PointerType *Ptr = DestType->getAs<PointerType>();
11908       if (!Ptr) {
11909         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11910           << E->getSourceRange();
11911         return ExprError();
11912       }
11913       assert(E->getValueKind() == VK_RValue);
11914       assert(E->getObjectKind() == OK_Ordinary);
11915       E->setType(DestType);
11916
11917       // Build the sub-expression as if it were an object of the pointee type.
11918       DestType = Ptr->getPointeeType();
11919       ExprResult SubResult = Visit(E->getSubExpr());
11920       if (SubResult.isInvalid()) return ExprError();
11921       E->setSubExpr(SubResult.take());
11922       return E;
11923     }
11924
11925     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11926
11927     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11928
11929     ExprResult VisitMemberExpr(MemberExpr *E) {
11930       return resolveDecl(E, E->getMemberDecl());
11931     }
11932
11933     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11934       return resolveDecl(E, E->getDecl());
11935     }
11936   };
11937 }
11938
11939 /// Rebuilds a call expression which yielded __unknown_anytype.
11940 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11941   Expr *CalleeExpr = E->getCallee();
11942
11943   enum FnKind {
11944     FK_MemberFunction,
11945     FK_FunctionPointer,
11946     FK_BlockPointer
11947   };
11948
11949   FnKind Kind;
11950   QualType CalleeType = CalleeExpr->getType();
11951   if (CalleeType == S.Context.BoundMemberTy) {
11952     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11953     Kind = FK_MemberFunction;
11954     CalleeType = Expr::findBoundMemberType(CalleeExpr);
11955   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11956     CalleeType = Ptr->getPointeeType();
11957     Kind = FK_FunctionPointer;
11958   } else {
11959     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11960     Kind = FK_BlockPointer;
11961   }
11962   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11963
11964   // Verify that this is a legal result type of a function.
11965   if (DestType->isArrayType() || DestType->isFunctionType()) {
11966     unsigned diagID = diag::err_func_returning_array_function;
11967     if (Kind == FK_BlockPointer)
11968       diagID = diag::err_block_returning_array_function;
11969
11970     S.Diag(E->getExprLoc(), diagID)
11971       << DestType->isFunctionType() << DestType;
11972     return ExprError();
11973   }
11974
11975   // Otherwise, go ahead and set DestType as the call's result.
11976   E->setType(DestType.getNonLValueExprType(S.Context));
11977   E->setValueKind(Expr::getValueKindForType(DestType));
11978   assert(E->getObjectKind() == OK_Ordinary);
11979
11980   // Rebuild the function type, replacing the result type with DestType.
11981   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11982     DestType =
11983       S.Context.getFunctionType(DestType,
11984                                 ArrayRef<QualType>(Proto->arg_type_begin(),
11985                                                    Proto->getNumArgs()),
11986                                 Proto->getExtProtoInfo());
11987   else
11988     DestType = S.Context.getFunctionNoProtoType(DestType,
11989                                                 FnType->getExtInfo());
11990
11991   // Rebuild the appropriate pointer-to-function type.
11992   switch (Kind) { 
11993   case FK_MemberFunction:
11994     // Nothing to do.
11995     break;
11996
11997   case FK_FunctionPointer:
11998     DestType = S.Context.getPointerType(DestType);
11999     break;
12000
12001   case FK_BlockPointer:
12002     DestType = S.Context.getBlockPointerType(DestType);
12003     break;
12004   }
12005
12006   // Finally, we can recurse.
12007   ExprResult CalleeResult = Visit(CalleeExpr);
12008   if (!CalleeResult.isUsable()) return ExprError();
12009   E->setCallee(CalleeResult.take());
12010
12011   // Bind a temporary if necessary.
12012   return S.MaybeBindToTemporary(E);
12013 }
12014
12015 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
12016   // Verify that this is a legal result type of a call.
12017   if (DestType->isArrayType() || DestType->isFunctionType()) {
12018     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
12019       << DestType->isFunctionType() << DestType;
12020     return ExprError();
12021   }
12022
12023   // Rewrite the method result type if available.
12024   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
12025     assert(Method->getResultType() == S.Context.UnknownAnyTy);
12026     Method->setResultType(DestType);
12027   }
12028
12029   // Change the type of the message.
12030   E->setType(DestType.getNonReferenceType());
12031   E->setValueKind(Expr::getValueKindForType(DestType));
12032
12033   return S.MaybeBindToTemporary(E);
12034 }
12035
12036 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
12037   // The only case we should ever see here is a function-to-pointer decay.
12038   if (E->getCastKind() == CK_FunctionToPointerDecay) {
12039     assert(E->getValueKind() == VK_RValue);
12040     assert(E->getObjectKind() == OK_Ordinary);
12041   
12042     E->setType(DestType);
12043   
12044     // Rebuild the sub-expression as the pointee (function) type.
12045     DestType = DestType->castAs<PointerType>()->getPointeeType();
12046   
12047     ExprResult Result = Visit(E->getSubExpr());
12048     if (!Result.isUsable()) return ExprError();
12049   
12050     E->setSubExpr(Result.take());
12051     return S.Owned(E);
12052   } else if (E->getCastKind() == CK_LValueToRValue) {
12053     assert(E->getValueKind() == VK_RValue);
12054     assert(E->getObjectKind() == OK_Ordinary);
12055
12056     assert(isa<BlockPointerType>(E->getType()));
12057
12058     E->setType(DestType);
12059
12060     // The sub-expression has to be a lvalue reference, so rebuild it as such.
12061     DestType = S.Context.getLValueReferenceType(DestType);
12062
12063     ExprResult Result = Visit(E->getSubExpr());
12064     if (!Result.isUsable()) return ExprError();
12065
12066     E->setSubExpr(Result.take());
12067     return S.Owned(E);
12068   } else {
12069     llvm_unreachable("Unhandled cast type!");
12070   }
12071 }
12072
12073 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
12074   ExprValueKind ValueKind = VK_LValue;
12075   QualType Type = DestType;
12076
12077   // We know how to make this work for certain kinds of decls:
12078
12079   //  - functions
12080   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
12081     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
12082       DestType = Ptr->getPointeeType();
12083       ExprResult Result = resolveDecl(E, VD);
12084       if (Result.isInvalid()) return ExprError();
12085       return S.ImpCastExprToType(Result.take(), Type,
12086                                  CK_FunctionToPointerDecay, VK_RValue);
12087     }
12088
12089     if (!Type->isFunctionType()) {
12090       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
12091         << VD << E->getSourceRange();
12092       return ExprError();
12093     }
12094
12095     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
12096       if (MD->isInstance()) {
12097         ValueKind = VK_RValue;
12098         Type = S.Context.BoundMemberTy;
12099       }
12100
12101     // Function references aren't l-values in C.
12102     if (!S.getLangOpts().CPlusPlus)
12103       ValueKind = VK_RValue;
12104
12105   //  - variables
12106   } else if (isa<VarDecl>(VD)) {
12107     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
12108       Type = RefTy->getPointeeType();
12109     } else if (Type->isFunctionType()) {
12110       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
12111         << VD << E->getSourceRange();
12112       return ExprError();
12113     }
12114
12115   //  - nothing else
12116   } else {
12117     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
12118       << VD << E->getSourceRange();
12119     return ExprError();
12120   }
12121
12122   VD->setType(DestType);
12123   E->setType(Type);
12124   E->setValueKind(ValueKind);
12125   return S.Owned(E);
12126 }
12127
12128 /// Check a cast of an unknown-any type.  We intentionally only
12129 /// trigger this for C-style casts.
12130 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
12131                                      Expr *CastExpr, CastKind &CastKind,
12132                                      ExprValueKind &VK, CXXCastPath &Path) {
12133   // Rewrite the casted expression from scratch.
12134   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
12135   if (!result.isUsable()) return ExprError();
12136
12137   CastExpr = result.take();
12138   VK = CastExpr->getValueKind();
12139   CastKind = CK_NoOp;
12140
12141   return CastExpr;
12142 }
12143
12144 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
12145   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
12146 }
12147
12148 ExprResult Sema::checkUnknownAnyArg(SourceLocation callLoc,
12149                                     Expr *arg, QualType &paramType) {
12150   // If the syntactic form of the argument is not an explicit cast of
12151   // any sort, just do default argument promotion.
12152   ExplicitCastExpr *castArg = dyn_cast<ExplicitCastExpr>(arg->IgnoreParens());
12153   if (!castArg) {
12154     ExprResult result = DefaultArgumentPromotion(arg);
12155     if (result.isInvalid()) return ExprError();
12156     paramType = result.get()->getType();
12157     return result;
12158   }
12159
12160   // Otherwise, use the type that was written in the explicit cast.
12161   assert(!arg->hasPlaceholderType());
12162   paramType = castArg->getTypeAsWritten();
12163
12164   // Copy-initialize a parameter of that type.
12165   InitializedEntity entity =
12166     InitializedEntity::InitializeParameter(Context, paramType,
12167                                            /*consumed*/ false);
12168   return PerformCopyInitialization(entity, callLoc, Owned(arg));
12169 }
12170
12171 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
12172   Expr *orig = E;
12173   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
12174   while (true) {
12175     E = E->IgnoreParenImpCasts();
12176     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
12177       E = call->getCallee();
12178       diagID = diag::err_uncasted_call_of_unknown_any;
12179     } else {
12180       break;
12181     }
12182   }
12183
12184   SourceLocation loc;
12185   NamedDecl *d;
12186   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
12187     loc = ref->getLocation();
12188     d = ref->getDecl();
12189   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
12190     loc = mem->getMemberLoc();
12191     d = mem->getMemberDecl();
12192   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
12193     diagID = diag::err_uncasted_call_of_unknown_any;
12194     loc = msg->getSelectorStartLoc();
12195     d = msg->getMethodDecl();
12196     if (!d) {
12197       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
12198         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
12199         << orig->getSourceRange();
12200       return ExprError();
12201     }
12202   } else {
12203     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
12204       << E->getSourceRange();
12205     return ExprError();
12206   }
12207
12208   S.Diag(loc, diagID) << d << orig->getSourceRange();
12209
12210   // Never recoverable.
12211   return ExprError();
12212 }
12213
12214 /// Check for operands with placeholder types and complain if found.
12215 /// Returns true if there was an error and no recovery was possible.
12216 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
12217   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
12218   if (!placeholderType) return Owned(E);
12219
12220   switch (placeholderType->getKind()) {
12221
12222   // Overloaded expressions.
12223   case BuiltinType::Overload: {
12224     // Try to resolve a single function template specialization.
12225     // This is obligatory.
12226     ExprResult result = Owned(E);
12227     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
12228       return result;
12229
12230     // If that failed, try to recover with a call.
12231     } else {
12232       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
12233                            /*complain*/ true);
12234       return result;
12235     }
12236   }
12237
12238   // Bound member functions.
12239   case BuiltinType::BoundMember: {
12240     ExprResult result = Owned(E);
12241     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
12242                          /*complain*/ true);
12243     return result;
12244   }
12245
12246   // ARC unbridged casts.
12247   case BuiltinType::ARCUnbridgedCast: {
12248     Expr *realCast = stripARCUnbridgedCast(E);
12249     diagnoseARCUnbridgedCast(realCast);
12250     return Owned(realCast);
12251   }
12252
12253   // Expressions of unknown type.
12254   case BuiltinType::UnknownAny:
12255     return diagnoseUnknownAnyExpr(*this, E);
12256
12257   // Pseudo-objects.
12258   case BuiltinType::PseudoObject:
12259     return checkPseudoObjectRValue(E);
12260
12261   case BuiltinType::BuiltinFn:
12262     Diag(E->getLocStart(), diag::err_builtin_fn_use);
12263     return ExprError();
12264
12265   // Everything else should be impossible.
12266 #define BUILTIN_TYPE(Id, SingletonId) \
12267   case BuiltinType::Id:
12268 #define PLACEHOLDER_TYPE(Id, SingletonId)
12269 #include "clang/AST/BuiltinTypes.def"
12270     break;
12271   }
12272
12273   llvm_unreachable("invalid placeholder type!");
12274 }
12275
12276 bool Sema::CheckCaseExpression(Expr *E) {
12277   if (E->isTypeDependent())
12278     return true;
12279   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
12280     return E->getType()->isIntegralOrEnumerationType();
12281   return false;
12282 }
12283
12284 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
12285 ExprResult
12286 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
12287   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
12288          "Unknown Objective-C Boolean value!");
12289   QualType BoolT = Context.ObjCBuiltinBoolTy;
12290   if (!Context.getBOOLDecl()) {
12291     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
12292                         Sema::LookupOrdinaryName);
12293     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
12294       NamedDecl *ND = Result.getFoundDecl();
12295       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
12296         Context.setBOOLDecl(TD);
12297     }
12298   }
12299   if (Context.getBOOLDecl())
12300     BoolT = Context.getBOOLType();
12301   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
12302                                         BoolT, OpLoc));
12303 }