]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
MFC r244628:
[FreeBSD/stable/9.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 "clang/Sema/DelayedDiagnostic.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/Sema/AnalysisBasedWarnings.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTConsumer.h"
22 #include "clang/AST/ASTMutationListener.h"
23 #include "clang/AST/CXXInheritance.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/EvaluatedExprVisitor.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExprObjC.h"
30 #include "clang/AST/RecursiveASTVisitor.h"
31 #include "clang/AST/TypeLoc.h"
32 #include "clang/Basic/PartialDiagnostic.h"
33 #include "clang/Basic/SourceManager.h"
34 #include "clang/Basic/TargetInfo.h"
35 #include "clang/Lex/LiteralSupport.h"
36 #include "clang/Lex/Preprocessor.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/Designator.h"
39 #include "clang/Sema/Scope.h"
40 #include "clang/Sema/ScopeInfo.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/SemaFixItUtils.h"
43 #include "clang/Sema/Template.h"
44 #include "TreeTransform.h"
45 using namespace clang;
46 using namespace sema;
47
48 /// \brief Determine whether the use of this declaration is valid, without
49 /// emitting diagnostics.
50 bool Sema::CanUseDecl(NamedDecl *D) {
51   // See if this is an auto-typed variable whose initializer we are parsing.
52   if (ParsingInitForAutoVars.count(D))
53     return false;
54
55   // See if this is a deleted function.
56   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57     if (FD->isDeleted())
58       return false;
59   }
60
61   // See if this function is unavailable.
62   if (D->getAvailability() == AR_Unavailable &&
63       cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64     return false;
65
66   return true;
67 }
68
69 static void DiagnoseUnusedOfDecl(Sema &S, NamedDecl *D, SourceLocation Loc) {
70   // Warn if this is used but marked unused.
71   if (D->hasAttr<UnusedAttr>()) {
72     const Decl *DC = cast<Decl>(S.getCurObjCLexicalContext());
73     if (!DC->hasAttr<UnusedAttr>())
74       S.Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
75   }
76 }
77
78 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
79                               NamedDecl *D, SourceLocation Loc,
80                               const ObjCInterfaceDecl *UnknownObjCClass) {
81   // See if this declaration is unavailable or deprecated.
82   std::string Message;
83   AvailabilityResult Result = D->getAvailability(&Message);
84   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
85     if (Result == AR_Available) {
86       const DeclContext *DC = ECD->getDeclContext();
87       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
88         Result = TheEnumDecl->getAvailability(&Message);
89     }
90
91   const ObjCPropertyDecl *ObjCPDecl = 0;
92   if (Result == AR_Deprecated || Result == AR_Unavailable) {
93     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
94       if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) {
95         AvailabilityResult PDeclResult = PD->getAvailability(0);
96         if (PDeclResult == Result)
97           ObjCPDecl = PD;
98       }
99     }
100   }
101   
102   switch (Result) {
103     case AR_Available:
104     case AR_NotYetIntroduced:
105       break;
106             
107     case AR_Deprecated:
108       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass, ObjCPDecl);
109       break;
110             
111     case AR_Unavailable:
112       if (S.getCurContextAvailability() != AR_Unavailable) {
113         if (Message.empty()) {
114           if (!UnknownObjCClass) {
115             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
116             if (ObjCPDecl)
117               S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
118                 << ObjCPDecl->getDeclName() << 1;
119           }
120           else
121             S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 
122               << D->getDeclName();
123         }
124         else
125           S.Diag(Loc, diag::err_unavailable_message) 
126             << D->getDeclName() << Message;
127         S.Diag(D->getLocation(), diag::note_unavailable_here)
128                   << isa<FunctionDecl>(D) << false;
129         if (ObjCPDecl)
130           S.Diag(ObjCPDecl->getLocation(), diag::note_property_attribute)
131           << ObjCPDecl->getDeclName() << 1;
132       }
133       break;
134     }
135     return Result;
136 }
137
138 /// \brief Emit a note explaining that this function is deleted or unavailable.
139 void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
140   CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
141
142   if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
143     // If the method was explicitly defaulted, point at that declaration.
144     if (!Method->isImplicit())
145       Diag(Decl->getLocation(), diag::note_implicitly_deleted);
146
147     // Try to diagnose why this special member function was implicitly
148     // deleted. This might fail, if that reason no longer applies.
149     CXXSpecialMember CSM = getSpecialMember(Method);
150     if (CSM != CXXInvalid)
151       ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
152
153     return;
154   }
155
156   Diag(Decl->getLocation(), diag::note_unavailable_here)
157     << 1 << Decl->isDeleted();
158 }
159
160 /// \brief Determine whether a FunctionDecl was ever declared with an
161 /// explicit storage class.
162 static bool hasAnyExplicitStorageClass(const FunctionDecl *D) {
163   for (FunctionDecl::redecl_iterator I = D->redecls_begin(),
164                                      E = D->redecls_end();
165        I != E; ++I) {
166     if (I->getStorageClassAsWritten() != SC_None)
167       return true;
168   }
169   return false;
170 }
171
172 /// \brief Check whether we're in an extern inline function and referring to a
173 /// variable or function with internal linkage (C11 6.7.4p3).
174 ///
175 /// This is only a warning because we used to silently accept this code, but
176 /// in many cases it will not behave correctly. This is not enabled in C++ mode
177 /// because the restriction language is a bit weaker (C++11 [basic.def.odr]p6)
178 /// and so while there may still be user mistakes, most of the time we can't
179 /// prove that there are errors.
180 static void diagnoseUseOfInternalDeclInInlineFunction(Sema &S,
181                                                       const NamedDecl *D,
182                                                       SourceLocation Loc) {
183   // This is disabled under C++; there are too many ways for this to fire in
184   // contexts where the warning is a false positive, or where it is technically
185   // correct but benign.
186   if (S.getLangOpts().CPlusPlus)
187     return;
188
189   // Check if this is an inlined function or method.
190   FunctionDecl *Current = S.getCurFunctionDecl();
191   if (!Current)
192     return;
193   if (!Current->isInlined())
194     return;
195   if (Current->getLinkage() != ExternalLinkage)
196     return;
197   
198   // Check if the decl has internal linkage.
199   if (D->getLinkage() != InternalLinkage)
200     return;
201
202   // Downgrade from ExtWarn to Extension if
203   //  (1) the supposedly external inline function is in the main file,
204   //      and probably won't be included anywhere else.
205   //  (2) the thing we're referencing is a pure function.
206   //  (3) the thing we're referencing is another inline function.
207   // This last can give us false negatives, but it's better than warning on
208   // wrappers for simple C library functions.
209   const FunctionDecl *UsedFn = dyn_cast<FunctionDecl>(D);
210   bool DowngradeWarning = S.getSourceManager().isFromMainFile(Loc);
211   if (!DowngradeWarning && UsedFn)
212     DowngradeWarning = UsedFn->isInlined() || UsedFn->hasAttr<ConstAttr>();
213
214   S.Diag(Loc, DowngradeWarning ? diag::ext_internal_in_extern_inline
215                                : diag::warn_internal_in_extern_inline)
216     << /*IsVar=*/!UsedFn << D;
217
218   // Suggest "static" on the inline function, if possible.
219   if (!hasAnyExplicitStorageClass(Current)) {
220     const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
221     SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
222     S.Diag(DeclBegin, diag::note_convert_inline_to_static)
223       << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
224   }
225
226   S.Diag(D->getCanonicalDecl()->getLocation(),
227          diag::note_internal_decl_declared_here)
228     << D;
229 }
230
231 /// \brief Determine whether the use of this declaration is valid, and
232 /// emit any corresponding diagnostics.
233 ///
234 /// This routine diagnoses various problems with referencing
235 /// declarations that can occur when using a declaration. For example,
236 /// it might warn if a deprecated or unavailable declaration is being
237 /// used, or produce an error (and return true) if a C++0x deleted
238 /// function is being used.
239 ///
240 /// \returns true if there was an error (this declaration cannot be
241 /// referenced), false otherwise.
242 ///
243 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
244                              const ObjCInterfaceDecl *UnknownObjCClass) {
245   if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
246     // If there were any diagnostics suppressed by template argument deduction,
247     // emit them now.
248     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
249       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
250     if (Pos != SuppressedDiagnostics.end()) {
251       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
252       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
253         Diag(Suppressed[I].first, Suppressed[I].second);
254       
255       // Clear out the list of suppressed diagnostics, so that we don't emit
256       // them again for this specialization. However, we don't obsolete this
257       // entry from the table, because we want to avoid ever emitting these
258       // diagnostics again.
259       Suppressed.clear();
260     }
261   }
262
263   // See if this is an auto-typed variable whose initializer we are parsing.
264   if (ParsingInitForAutoVars.count(D)) {
265     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
266       << D->getDeclName();
267     return true;
268   }
269
270   // See if this is a deleted function.
271   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
272     if (FD->isDeleted()) {
273       Diag(Loc, diag::err_deleted_function_use);
274       NoteDeletedFunction(FD);
275       return true;
276     }
277   }
278   DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
279
280   DiagnoseUnusedOfDecl(*this, D, Loc);
281
282   diagnoseUseOfInternalDeclInInlineFunction(*this, D, Loc);
283
284   return false;
285 }
286
287 /// \brief Retrieve the message suffix that should be added to a
288 /// diagnostic complaining about the given function being deleted or
289 /// unavailable.
290 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
291   // FIXME: C++0x implicitly-deleted special member functions could be
292   // detected here so that we could improve diagnostics to say, e.g.,
293   // "base class 'A' had a deleted copy constructor".
294   if (FD->isDeleted())
295     return std::string();
296
297   std::string Message;
298   if (FD->getAvailability(&Message))
299     return ": " + Message;
300
301   return std::string();
302 }
303
304 /// DiagnoseSentinelCalls - This routine checks whether a call or
305 /// message-send is to a declaration with the sentinel attribute, and
306 /// if so, it checks that the requirements of the sentinel are
307 /// satisfied.
308 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
309                                  Expr **args, unsigned numArgs) {
310   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
311   if (!attr)
312     return;
313
314   // The number of formal parameters of the declaration.
315   unsigned numFormalParams;
316
317   // The kind of declaration.  This is also an index into a %select in
318   // the diagnostic.
319   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
320
321   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
322     numFormalParams = MD->param_size();
323     calleeType = CT_Method;
324   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
325     numFormalParams = FD->param_size();
326     calleeType = CT_Function;
327   } else if (isa<VarDecl>(D)) {
328     QualType type = cast<ValueDecl>(D)->getType();
329     const FunctionType *fn = 0;
330     if (const PointerType *ptr = type->getAs<PointerType>()) {
331       fn = ptr->getPointeeType()->getAs<FunctionType>();
332       if (!fn) return;
333       calleeType = CT_Function;
334     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
335       fn = ptr->getPointeeType()->castAs<FunctionType>();
336       calleeType = CT_Block;
337     } else {
338       return;
339     }
340
341     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
342       numFormalParams = proto->getNumArgs();
343     } else {
344       numFormalParams = 0;
345     }
346   } else {
347     return;
348   }
349
350   // "nullPos" is the number of formal parameters at the end which
351   // effectively count as part of the variadic arguments.  This is
352   // useful if you would prefer to not have *any* formal parameters,
353   // but the language forces you to have at least one.
354   unsigned nullPos = attr->getNullPos();
355   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
356   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
357
358   // The number of arguments which should follow the sentinel.
359   unsigned numArgsAfterSentinel = attr->getSentinel();
360
361   // If there aren't enough arguments for all the formal parameters,
362   // the sentinel, and the args after the sentinel, complain.
363   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
364     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
365     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
366     return;
367   }
368
369   // Otherwise, find the sentinel expression.
370   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
371   if (!sentinelExpr) return;
372   if (sentinelExpr->isValueDependent()) return;
373   if (Context.isSentinelNullExpr(sentinelExpr)) return;
374
375   // Pick a reasonable string to insert.  Optimistically use 'nil' or
376   // 'NULL' if those are actually defined in the context.  Only use
377   // 'nil' for ObjC methods, where it's much more likely that the
378   // variadic arguments form a list of object pointers.
379   SourceLocation MissingNilLoc
380     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
381   std::string NullValue;
382   if (calleeType == CT_Method &&
383       PP.getIdentifierInfo("nil")->hasMacroDefinition())
384     NullValue = "nil";
385   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
386     NullValue = "NULL";
387   else
388     NullValue = "(void*) 0";
389
390   if (MissingNilLoc.isInvalid())
391     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
392   else
393     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
394       << calleeType
395       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
396   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
397 }
398
399 SourceRange Sema::getExprRange(Expr *E) const {
400   return E ? E->getSourceRange() : SourceRange();
401 }
402
403 //===----------------------------------------------------------------------===//
404 //  Standard Promotions and Conversions
405 //===----------------------------------------------------------------------===//
406
407 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
408 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
409   // Handle any placeholder expressions which made it here.
410   if (E->getType()->isPlaceholderType()) {
411     ExprResult result = CheckPlaceholderExpr(E);
412     if (result.isInvalid()) return ExprError();
413     E = result.take();
414   }
415   
416   QualType Ty = E->getType();
417   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
418
419   if (Ty->isFunctionType())
420     E = ImpCastExprToType(E, Context.getPointerType(Ty),
421                           CK_FunctionToPointerDecay).take();
422   else if (Ty->isArrayType()) {
423     // In C90 mode, arrays only promote to pointers if the array expression is
424     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
425     // type 'array of type' is converted to an expression that has type 'pointer
426     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
427     // that has type 'array of type' ...".  The relevant change is "an lvalue"
428     // (C90) to "an expression" (C99).
429     //
430     // C++ 4.2p1:
431     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
432     // T" can be converted to an rvalue of type "pointer to T".
433     //
434     if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
435       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
436                             CK_ArrayToPointerDecay).take();
437   }
438   return Owned(E);
439 }
440
441 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
442   // Check to see if we are dereferencing a null pointer.  If so,
443   // and if not volatile-qualified, this is undefined behavior that the
444   // optimizer will delete, so warn about it.  People sometimes try to use this
445   // to get a deterministic trap and are surprised by clang's behavior.  This
446   // only handles the pattern "*null", which is a very syntactic check.
447   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
448     if (UO->getOpcode() == UO_Deref &&
449         UO->getSubExpr()->IgnoreParenCasts()->
450           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
451         !UO->getType().isVolatileQualified()) {
452     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
453                           S.PDiag(diag::warn_indirection_through_null)
454                             << UO->getSubExpr()->getSourceRange());
455     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
456                         S.PDiag(diag::note_indirection_through_null));
457   }
458 }
459
460 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
461   // Handle any placeholder expressions which made it here.
462   if (E->getType()->isPlaceholderType()) {
463     ExprResult result = CheckPlaceholderExpr(E);
464     if (result.isInvalid()) return ExprError();
465     E = result.take();
466   }
467   
468   // C++ [conv.lval]p1:
469   //   A glvalue of a non-function, non-array type T can be
470   //   converted to a prvalue.
471   if (!E->isGLValue()) return Owned(E);
472
473   QualType T = E->getType();
474   assert(!T.isNull() && "r-value conversion on typeless expression?");
475
476   // We don't want to throw lvalue-to-rvalue casts on top of
477   // expressions of certain types in C++.
478   if (getLangOpts().CPlusPlus &&
479       (E->getType() == Context.OverloadTy ||
480        T->isDependentType() ||
481        T->isRecordType()))
482     return Owned(E);
483
484   // The C standard is actually really unclear on this point, and
485   // DR106 tells us what the result should be but not why.  It's
486   // generally best to say that void types just doesn't undergo
487   // lvalue-to-rvalue at all.  Note that expressions of unqualified
488   // 'void' type are never l-values, but qualified void can be.
489   if (T->isVoidType())
490     return Owned(E);
491
492   CheckForNullPointerDereference(*this, E);
493
494   // C++ [conv.lval]p1:
495   //   [...] If T is a non-class type, the type of the prvalue is the
496   //   cv-unqualified version of T. Otherwise, the type of the
497   //   rvalue is T.
498   //
499   // C99 6.3.2.1p2:
500   //   If the lvalue has qualified type, the value has the unqualified
501   //   version of the type of the lvalue; otherwise, the value has the
502   //   type of the lvalue.
503   if (T.hasQualifiers())
504     T = T.getUnqualifiedType();
505
506   UpdateMarkingForLValueToRValue(E);
507
508   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
509                                                   E, 0, VK_RValue));
510
511   // C11 6.3.2.1p2:
512   //   ... if the lvalue has atomic type, the value has the non-atomic version 
513   //   of the type of the lvalue ...
514   if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
515     T = Atomic->getValueType().getUnqualifiedType();
516     Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
517                                          Res.get(), 0, VK_RValue));
518   }
519   
520   return Res;
521 }
522
523 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
524   ExprResult Res = DefaultFunctionArrayConversion(E);
525   if (Res.isInvalid())
526     return ExprError();
527   Res = DefaultLvalueConversion(Res.take());
528   if (Res.isInvalid())
529     return ExprError();
530   return Res;
531 }
532
533
534 /// UsualUnaryConversions - Performs various conversions that are common to most
535 /// operators (C99 6.3). The conversions of array and function types are
536 /// sometimes suppressed. For example, the array->pointer conversion doesn't
537 /// apply if the array is an argument to the sizeof or address (&) operators.
538 /// In these instances, this routine should *not* be called.
539 ExprResult Sema::UsualUnaryConversions(Expr *E) {
540   // First, convert to an r-value.
541   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
542   if (Res.isInvalid())
543     return Owned(E);
544   E = Res.take();
545
546   QualType Ty = E->getType();
547   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
548
549   // Half FP is a bit different: it's a storage-only type, meaning that any
550   // "use" of it should be promoted to float.
551   if (Ty->isHalfType())
552     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
553
554   // Try to perform integral promotions if the object has a theoretically
555   // promotable type.
556   if (Ty->isIntegralOrUnscopedEnumerationType()) {
557     // C99 6.3.1.1p2:
558     //
559     //   The following may be used in an expression wherever an int or
560     //   unsigned int may be used:
561     //     - an object or expression with an integer type whose integer
562     //       conversion rank is less than or equal to the rank of int
563     //       and unsigned int.
564     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
565     //
566     //   If an int can represent all values of the original type, the
567     //   value is converted to an int; otherwise, it is converted to an
568     //   unsigned int. These are called the integer promotions. All
569     //   other types are unchanged by the integer promotions.
570
571     QualType PTy = Context.isPromotableBitField(E);
572     if (!PTy.isNull()) {
573       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
574       return Owned(E);
575     }
576     if (Ty->isPromotableIntegerType()) {
577       QualType PT = Context.getPromotedIntegerType(Ty);
578       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
579       return Owned(E);
580     }
581   }
582   return Owned(E);
583 }
584
585 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
586 /// do not have a prototype. Arguments that have type float are promoted to
587 /// double. All other argument types are converted by UsualUnaryConversions().
588 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
589   QualType Ty = E->getType();
590   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
591
592   ExprResult Res = UsualUnaryConversions(E);
593   if (Res.isInvalid())
594     return Owned(E);
595   E = Res.take();
596
597   // If this is a 'float' (CVR qualified or typedef) promote to double.
598   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
599     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
600
601   // C++ performs lvalue-to-rvalue conversion as a default argument
602   // promotion, even on class types, but note:
603   //   C++11 [conv.lval]p2:
604   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
605   //     operand or a subexpression thereof the value contained in the
606   //     referenced object is not accessed. Otherwise, if the glvalue
607   //     has a class type, the conversion copy-initializes a temporary
608   //     of type T from the glvalue and the result of the conversion
609   //     is a prvalue for the temporary.
610   // FIXME: add some way to gate this entire thing for correctness in
611   // potentially potentially evaluated contexts.
612   if (getLangOpts().CPlusPlus && E->isGLValue() && !isUnevaluatedContext()) {
613     ExprResult Temp = PerformCopyInitialization(
614                        InitializedEntity::InitializeTemporary(E->getType()),
615                                                 E->getExprLoc(),
616                                                 Owned(E));
617     if (Temp.isInvalid())
618       return ExprError();
619     E = Temp.get();
620   }
621
622   return Owned(E);
623 }
624
625 /// Determine the degree of POD-ness for an expression.
626 /// Incomplete types are considered POD, since this check can be performed
627 /// when we're in an unevaluated context.
628 Sema::VarArgKind Sema::isValidVarArgType(const QualType &Ty) {
629   if (Ty->isIncompleteType()) {
630     if (Ty->isObjCObjectType())
631       return VAK_Invalid;
632     return VAK_Valid;
633   }
634
635   if (Ty.isCXX98PODType(Context))
636     return VAK_Valid;
637
638   // C++0x [expr.call]p7:
639   //   Passing a potentially-evaluated argument of class type (Clause 9) 
640   //   having a non-trivial copy constructor, a non-trivial move constructor,
641   //   or a non-trivial destructor, with no corresponding parameter, 
642   //   is conditionally-supported with implementation-defined semantics.
643   if (getLangOpts().CPlusPlus0x && !Ty->isDependentType())
644     if (CXXRecordDecl *Record = Ty->getAsCXXRecordDecl())
645       if (Record->hasTrivialCopyConstructor() &&
646           Record->hasTrivialMoveConstructor() &&
647           Record->hasTrivialDestructor())
648         return VAK_ValidInCXX11;
649
650   if (getLangOpts().ObjCAutoRefCount && Ty->isObjCLifetimeType())
651     return VAK_Valid;
652   return VAK_Invalid;
653 }
654
655 bool Sema::variadicArgumentPODCheck(const Expr *E, VariadicCallType CT) {
656   // Don't allow one to pass an Objective-C interface to a vararg.
657   const QualType & Ty = E->getType();
658
659   // Complain about passing non-POD types through varargs.
660   switch (isValidVarArgType(Ty)) {
661   case VAK_Valid:
662     break;
663   case VAK_ValidInCXX11:
664     DiagRuntimeBehavior(E->getLocStart(), 0,
665         PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
666         << E->getType() << CT);
667     break;
668   case VAK_Invalid: {
669     if (Ty->isObjCObjectType())
670       return DiagRuntimeBehavior(E->getLocStart(), 0,
671                           PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
672                             << Ty << CT);
673
674     return DiagRuntimeBehavior(E->getLocStart(), 0,
675                    PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
676                    << getLangOpts().CPlusPlus0x << Ty << CT);
677   }
678   }
679   // c++ rules are enforced elsewhere.
680   return false;
681 }
682
683 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
684 /// will create a trap if the resulting type is not a POD type.
685 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
686                                                   FunctionDecl *FDecl) {
687   if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
688     // Strip the unbridged-cast placeholder expression off, if applicable.
689     if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
690         (CT == VariadicMethod ||
691          (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
692       E = stripARCUnbridgedCast(E);
693
694     // Otherwise, do normal placeholder checking.
695     } else {
696       ExprResult ExprRes = CheckPlaceholderExpr(E);
697       if (ExprRes.isInvalid())
698         return ExprError();
699       E = ExprRes.take();
700     }
701   }
702   
703   ExprResult ExprRes = DefaultArgumentPromotion(E);
704   if (ExprRes.isInvalid())
705     return ExprError();
706   E = ExprRes.take();
707
708   // Diagnostics regarding non-POD argument types are
709   // emitted along with format string checking in Sema::CheckFunctionCall().
710   if (isValidVarArgType(E->getType()) == VAK_Invalid) {
711     // Turn this into a trap.
712     CXXScopeSpec SS;
713     SourceLocation TemplateKWLoc;
714     UnqualifiedId Name;
715     Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
716                        E->getLocStart());
717     ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc,
718                                           Name, true, false);
719     if (TrapFn.isInvalid())
720       return ExprError();
721
722     ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(),
723                                     E->getLocStart(), MultiExprArg(),
724                                     E->getLocEnd());
725     if (Call.isInvalid())
726       return ExprError();
727
728     ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
729                                   Call.get(), E);
730     if (Comma.isInvalid())
731       return ExprError();
732     return Comma.get();
733   }
734
735   if (!getLangOpts().CPlusPlus &&
736       RequireCompleteType(E->getExprLoc(), E->getType(),
737                           diag::err_call_incomplete_argument))
738     return ExprError();
739
740   return Owned(E);
741 }
742
743 /// \brief Converts an integer to complex float type.  Helper function of
744 /// UsualArithmeticConversions()
745 ///
746 /// \return false if the integer expression is an integer type and is
747 /// successfully converted to the complex type.
748 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
749                                                   ExprResult &ComplexExpr,
750                                                   QualType IntTy,
751                                                   QualType ComplexTy,
752                                                   bool SkipCast) {
753   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
754   if (SkipCast) return false;
755   if (IntTy->isIntegerType()) {
756     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
757     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
758     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
759                                   CK_FloatingRealToComplex);
760   } else {
761     assert(IntTy->isComplexIntegerType());
762     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
763                                   CK_IntegralComplexToFloatingComplex);
764   }
765   return false;
766 }
767
768 /// \brief Takes two complex float types and converts them to the same type.
769 /// Helper function of UsualArithmeticConversions()
770 static QualType
771 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
772                                             ExprResult &RHS, QualType LHSType,
773                                             QualType RHSType,
774                                             bool IsCompAssign) {
775   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
776
777   if (order < 0) {
778     // _Complex float -> _Complex double
779     if (!IsCompAssign)
780       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
781     return RHSType;
782   }
783   if (order > 0)
784     // _Complex float -> _Complex double
785     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
786   return LHSType;
787 }
788
789 /// \brief Converts otherExpr to complex float and promotes complexExpr if
790 /// necessary.  Helper function of UsualArithmeticConversions()
791 static QualType handleOtherComplexFloatConversion(Sema &S,
792                                                   ExprResult &ComplexExpr,
793                                                   ExprResult &OtherExpr,
794                                                   QualType ComplexTy,
795                                                   QualType OtherTy,
796                                                   bool ConvertComplexExpr,
797                                                   bool ConvertOtherExpr) {
798   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
799
800   // If just the complexExpr is complex, the otherExpr needs to be converted,
801   // and the complexExpr might need to be promoted.
802   if (order > 0) { // complexExpr is wider
803     // float -> _Complex double
804     if (ConvertOtherExpr) {
805       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
806       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
807       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
808                                       CK_FloatingRealToComplex);
809     }
810     return ComplexTy;
811   }
812
813   // otherTy is at least as wide.  Find its corresponding complex type.
814   QualType result = (order == 0 ? ComplexTy :
815                                   S.Context.getComplexType(OtherTy));
816
817   // double -> _Complex double
818   if (ConvertOtherExpr)
819     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
820                                     CK_FloatingRealToComplex);
821
822   // _Complex float -> _Complex double
823   if (ConvertComplexExpr && order < 0)
824     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
825                                       CK_FloatingComplexCast);
826
827   return result;
828 }
829
830 /// \brief Handle arithmetic conversion with complex types.  Helper function of
831 /// UsualArithmeticConversions()
832 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
833                                              ExprResult &RHS, QualType LHSType,
834                                              QualType RHSType,
835                                              bool IsCompAssign) {
836   // if we have an integer operand, the result is the complex type.
837   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
838                                              /*skipCast*/false))
839     return LHSType;
840   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
841                                              /*skipCast*/IsCompAssign))
842     return RHSType;
843
844   // This handles complex/complex, complex/float, or float/complex.
845   // When both operands are complex, the shorter operand is converted to the
846   // type of the longer, and that is the type of the result. This corresponds
847   // to what is done when combining two real floating-point operands.
848   // The fun begins when size promotion occur across type domains.
849   // From H&S 6.3.4: When one operand is complex and the other is a real
850   // floating-point type, the less precise type is converted, within it's
851   // real or complex domain, to the precision of the other type. For example,
852   // when combining a "long double" with a "double _Complex", the
853   // "double _Complex" is promoted to "long double _Complex".
854
855   bool LHSComplexFloat = LHSType->isComplexType();
856   bool RHSComplexFloat = RHSType->isComplexType();
857
858   // If both are complex, just cast to the more precise type.
859   if (LHSComplexFloat && RHSComplexFloat)
860     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
861                                                        LHSType, RHSType,
862                                                        IsCompAssign);
863
864   // If only one operand is complex, promote it if necessary and convert the
865   // other operand to complex.
866   if (LHSComplexFloat)
867     return handleOtherComplexFloatConversion(
868         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
869         /*convertOtherExpr*/ true);
870
871   assert(RHSComplexFloat);
872   return handleOtherComplexFloatConversion(
873       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
874       /*convertOtherExpr*/ !IsCompAssign);
875 }
876
877 /// \brief Hande arithmetic conversion from integer to float.  Helper function
878 /// of UsualArithmeticConversions()
879 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
880                                            ExprResult &IntExpr,
881                                            QualType FloatTy, QualType IntTy,
882                                            bool ConvertFloat, bool ConvertInt) {
883   if (IntTy->isIntegerType()) {
884     if (ConvertInt)
885       // Convert intExpr to the lhs floating point type.
886       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
887                                     CK_IntegralToFloating);
888     return FloatTy;
889   }
890      
891   // Convert both sides to the appropriate complex float.
892   assert(IntTy->isComplexIntegerType());
893   QualType result = S.Context.getComplexType(FloatTy);
894
895   // _Complex int -> _Complex float
896   if (ConvertInt)
897     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
898                                   CK_IntegralComplexToFloatingComplex);
899
900   // float -> _Complex float
901   if (ConvertFloat)
902     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
903                                     CK_FloatingRealToComplex);
904
905   return result;
906 }
907
908 /// \brief Handle arithmethic conversion with floating point types.  Helper
909 /// function of UsualArithmeticConversions()
910 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
911                                       ExprResult &RHS, QualType LHSType,
912                                       QualType RHSType, bool IsCompAssign) {
913   bool LHSFloat = LHSType->isRealFloatingType();
914   bool RHSFloat = RHSType->isRealFloatingType();
915
916   // If we have two real floating types, convert the smaller operand
917   // to the bigger result.
918   if (LHSFloat && RHSFloat) {
919     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
920     if (order > 0) {
921       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
922       return LHSType;
923     }
924
925     assert(order < 0 && "illegal float comparison");
926     if (!IsCompAssign)
927       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
928     return RHSType;
929   }
930
931   if (LHSFloat)
932     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
933                                       /*convertFloat=*/!IsCompAssign,
934                                       /*convertInt=*/ true);
935   assert(RHSFloat);
936   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
937                                     /*convertInt=*/ true,
938                                     /*convertFloat=*/!IsCompAssign);
939 }
940
941 /// \brief Handle conversions with GCC complex int extension.  Helper function
942 /// of UsualArithmeticConversions()
943 // FIXME: if the operands are (int, _Complex long), we currently
944 // don't promote the complex.  Also, signedness?
945 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
946                                            ExprResult &RHS, QualType LHSType,
947                                            QualType RHSType,
948                                            bool IsCompAssign) {
949   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
950   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
951
952   if (LHSComplexInt && RHSComplexInt) {
953     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
954                                               RHSComplexInt->getElementType());
955     assert(order && "inequal types with equal element ordering");
956     if (order > 0) {
957       // _Complex int -> _Complex long
958       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
959       return LHSType;
960     }
961
962     if (!IsCompAssign)
963       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
964     return RHSType;
965   }
966
967   if (LHSComplexInt) {
968     // int -> _Complex int
969     // FIXME: This needs to take integer ranks into account
970     RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
971                               CK_IntegralCast);
972     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
973     return LHSType;
974   }
975
976   assert(RHSComplexInt);
977   // int -> _Complex int
978   // FIXME: This needs to take integer ranks into account
979   if (!IsCompAssign) {
980     LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
981                               CK_IntegralCast);
982     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
983   }
984   return RHSType;
985 }
986
987 /// \brief Handle integer arithmetic conversions.  Helper function of
988 /// UsualArithmeticConversions()
989 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
990                                         ExprResult &RHS, QualType LHSType,
991                                         QualType RHSType, bool IsCompAssign) {
992   // The rules for this case are in C99 6.3.1.8
993   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
994   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
995   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
996   if (LHSSigned == RHSSigned) {
997     // Same signedness; use the higher-ranked type
998     if (order >= 0) {
999       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1000       return LHSType;
1001     } else if (!IsCompAssign)
1002       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1003     return RHSType;
1004   } else if (order != (LHSSigned ? 1 : -1)) {
1005     // The unsigned type has greater than or equal rank to the
1006     // signed type, so use the unsigned type
1007     if (RHSSigned) {
1008       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1009       return LHSType;
1010     } else if (!IsCompAssign)
1011       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1012     return RHSType;
1013   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
1014     // The two types are different widths; if we are here, that
1015     // means the signed type is larger than the unsigned type, so
1016     // use the signed type.
1017     if (LHSSigned) {
1018       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
1019       return LHSType;
1020     } else if (!IsCompAssign)
1021       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
1022     return RHSType;
1023   } else {
1024     // The signed type is higher-ranked than the unsigned type,
1025     // but isn't actually any bigger (like unsigned int and long
1026     // on most 32-bit systems).  Use the unsigned type corresponding
1027     // to the signed type.
1028     QualType result =
1029       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
1030     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
1031     if (!IsCompAssign)
1032       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
1033     return result;
1034   }
1035 }
1036
1037 /// UsualArithmeticConversions - Performs various conversions that are common to
1038 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1039 /// routine returns the first non-arithmetic type found. The client is
1040 /// responsible for emitting appropriate error diagnostics.
1041 /// FIXME: verify the conversion rules for "complex int" are consistent with
1042 /// GCC.
1043 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
1044                                           bool IsCompAssign) {
1045   if (!IsCompAssign) {
1046     LHS = UsualUnaryConversions(LHS.take());
1047     if (LHS.isInvalid())
1048       return QualType();
1049   }
1050
1051   RHS = UsualUnaryConversions(RHS.take());
1052   if (RHS.isInvalid())
1053     return QualType();
1054
1055   // For conversion purposes, we ignore any qualifiers.
1056   // For example, "const float" and "float" are equivalent.
1057   QualType LHSType =
1058     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
1059   QualType RHSType =
1060     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
1061
1062   // For conversion purposes, we ignore any atomic qualifier on the LHS.
1063   if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
1064     LHSType = AtomicLHS->getValueType();
1065
1066   // If both types are identical, no conversion is needed.
1067   if (LHSType == RHSType)
1068     return LHSType;
1069
1070   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1071   // The caller can deal with this (e.g. pointer + int).
1072   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
1073     return QualType();
1074
1075   // Apply unary and bitfield promotions to the LHS's type.
1076   QualType LHSUnpromotedType = LHSType;
1077   if (LHSType->isPromotableIntegerType())
1078     LHSType = Context.getPromotedIntegerType(LHSType);
1079   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
1080   if (!LHSBitfieldPromoteTy.isNull())
1081     LHSType = LHSBitfieldPromoteTy;
1082   if (LHSType != LHSUnpromotedType && !IsCompAssign)
1083     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
1084
1085   // If both types are identical, no conversion is needed.
1086   if (LHSType == RHSType)
1087     return LHSType;
1088
1089   // At this point, we have two different arithmetic types.
1090
1091   // Handle complex types first (C99 6.3.1.8p1).
1092   if (LHSType->isComplexType() || RHSType->isComplexType())
1093     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1094                                         IsCompAssign);
1095
1096   // Now handle "real" floating types (i.e. float, double, long double).
1097   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1098     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
1099                                  IsCompAssign);
1100
1101   // Handle GCC complex int extension.
1102   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
1103     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
1104                                       IsCompAssign);
1105
1106   // Finally, we have two differing integer types.
1107   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
1108                                  IsCompAssign);
1109 }
1110
1111 //===----------------------------------------------------------------------===//
1112 //  Semantic Analysis for various Expression Types
1113 //===----------------------------------------------------------------------===//
1114
1115
1116 ExprResult
1117 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1118                                 SourceLocation DefaultLoc,
1119                                 SourceLocation RParenLoc,
1120                                 Expr *ControllingExpr,
1121                                 MultiTypeArg ArgTypes,
1122                                 MultiExprArg ArgExprs) {
1123   unsigned NumAssocs = ArgTypes.size();
1124   assert(NumAssocs == ArgExprs.size());
1125
1126   ParsedType *ParsedTypes = ArgTypes.data();
1127   Expr **Exprs = ArgExprs.data();
1128
1129   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1130   for (unsigned i = 0; i < NumAssocs; ++i) {
1131     if (ParsedTypes[i])
1132       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1133     else
1134       Types[i] = 0;
1135   }
1136
1137   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1138                                              ControllingExpr, Types, Exprs,
1139                                              NumAssocs);
1140   delete [] Types;
1141   return ER;
1142 }
1143
1144 ExprResult
1145 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1146                                  SourceLocation DefaultLoc,
1147                                  SourceLocation RParenLoc,
1148                                  Expr *ControllingExpr,
1149                                  TypeSourceInfo **Types,
1150                                  Expr **Exprs,
1151                                  unsigned NumAssocs) {
1152   bool TypeErrorFound = false,
1153        IsResultDependent = ControllingExpr->isTypeDependent(),
1154        ContainsUnexpandedParameterPack
1155          = ControllingExpr->containsUnexpandedParameterPack();
1156
1157   for (unsigned i = 0; i < NumAssocs; ++i) {
1158     if (Exprs[i]->containsUnexpandedParameterPack())
1159       ContainsUnexpandedParameterPack = true;
1160
1161     if (Types[i]) {
1162       if (Types[i]->getType()->containsUnexpandedParameterPack())
1163         ContainsUnexpandedParameterPack = true;
1164
1165       if (Types[i]->getType()->isDependentType()) {
1166         IsResultDependent = true;
1167       } else {
1168         // C11 6.5.1.1p2 "The type name in a generic association shall specify a
1169         // complete object type other than a variably modified type."
1170         unsigned D = 0;
1171         if (Types[i]->getType()->isIncompleteType())
1172           D = diag::err_assoc_type_incomplete;
1173         else if (!Types[i]->getType()->isObjectType())
1174           D = diag::err_assoc_type_nonobject;
1175         else if (Types[i]->getType()->isVariablyModifiedType())
1176           D = diag::err_assoc_type_variably_modified;
1177
1178         if (D != 0) {
1179           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1180             << Types[i]->getTypeLoc().getSourceRange()
1181             << Types[i]->getType();
1182           TypeErrorFound = true;
1183         }
1184
1185         // C11 6.5.1.1p2 "No two generic associations in the same generic
1186         // selection shall specify compatible types."
1187         for (unsigned j = i+1; j < NumAssocs; ++j)
1188           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1189               Context.typesAreCompatible(Types[i]->getType(),
1190                                          Types[j]->getType())) {
1191             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1192                  diag::err_assoc_compatible_types)
1193               << Types[j]->getTypeLoc().getSourceRange()
1194               << Types[j]->getType()
1195               << Types[i]->getType();
1196             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1197                  diag::note_compat_assoc)
1198               << Types[i]->getTypeLoc().getSourceRange()
1199               << Types[i]->getType();
1200             TypeErrorFound = true;
1201           }
1202       }
1203     }
1204   }
1205   if (TypeErrorFound)
1206     return ExprError();
1207
1208   // If we determined that the generic selection is result-dependent, don't
1209   // try to compute the result expression.
1210   if (IsResultDependent)
1211     return Owned(new (Context) GenericSelectionExpr(
1212                    Context, KeyLoc, ControllingExpr,
1213                    llvm::makeArrayRef(Types, NumAssocs),
1214                    llvm::makeArrayRef(Exprs, NumAssocs),
1215                    DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack));
1216
1217   SmallVector<unsigned, 1> CompatIndices;
1218   unsigned DefaultIndex = -1U;
1219   for (unsigned i = 0; i < NumAssocs; ++i) {
1220     if (!Types[i])
1221       DefaultIndex = i;
1222     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1223                                         Types[i]->getType()))
1224       CompatIndices.push_back(i);
1225   }
1226
1227   // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
1228   // type compatible with at most one of the types named in its generic
1229   // association list."
1230   if (CompatIndices.size() > 1) {
1231     // We strip parens here because the controlling expression is typically
1232     // parenthesized in macro definitions.
1233     ControllingExpr = ControllingExpr->IgnoreParens();
1234     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1235       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1236       << (unsigned) CompatIndices.size();
1237     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1238          E = CompatIndices.end(); I != E; ++I) {
1239       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1240            diag::note_compat_assoc)
1241         << Types[*I]->getTypeLoc().getSourceRange()
1242         << Types[*I]->getType();
1243     }
1244     return ExprError();
1245   }
1246
1247   // C11 6.5.1.1p2 "If a generic selection has no default generic association,
1248   // its controlling expression shall have type compatible with exactly one of
1249   // the types named in its generic association list."
1250   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1251     // We strip parens here because the controlling expression is typically
1252     // parenthesized in macro definitions.
1253     ControllingExpr = ControllingExpr->IgnoreParens();
1254     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1255       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1256     return ExprError();
1257   }
1258
1259   // C11 6.5.1.1p3 "If a generic selection has a generic association with a
1260   // type name that is compatible with the type of the controlling expression,
1261   // then the result expression of the generic selection is the expression
1262   // in that generic association. Otherwise, the result expression of the
1263   // generic selection is the expression in the default generic association."
1264   unsigned ResultIndex =
1265     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1266
1267   return Owned(new (Context) GenericSelectionExpr(
1268                  Context, KeyLoc, ControllingExpr,
1269                  llvm::makeArrayRef(Types, NumAssocs),
1270                  llvm::makeArrayRef(Exprs, NumAssocs),
1271                  DefaultLoc, RParenLoc, ContainsUnexpandedParameterPack,
1272                  ResultIndex));
1273 }
1274
1275 /// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1276 /// location of the token and the offset of the ud-suffix within it.
1277 static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1278                                      unsigned Offset) {
1279   return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1280                                         S.getLangOpts());
1281 }
1282
1283 /// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1284 /// the corresponding cooked (non-raw) literal operator, and build a call to it.
1285 static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1286                                                  IdentifierInfo *UDSuffix,
1287                                                  SourceLocation UDSuffixLoc,
1288                                                  ArrayRef<Expr*> Args,
1289                                                  SourceLocation LitEndLoc) {
1290   assert(Args.size() <= 2 && "too many arguments for literal operator");
1291
1292   QualType ArgTy[2];
1293   for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1294     ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1295     if (ArgTy[ArgIdx]->isArrayType())
1296       ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1297   }
1298
1299   DeclarationName OpName =
1300     S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1301   DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1302   OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1303
1304   LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1305   if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1306                               /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1307     return ExprError();
1308
1309   return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1310 }
1311
1312 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1313 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1314 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1315 /// multiple tokens.  However, the common case is that StringToks points to one
1316 /// string.
1317 ///
1318 ExprResult
1319 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1320                          Scope *UDLScope) {
1321   assert(NumStringToks && "Must have at least one string!");
1322
1323   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1324   if (Literal.hadError)
1325     return ExprError();
1326
1327   SmallVector<SourceLocation, 4> StringTokLocs;
1328   for (unsigned i = 0; i != NumStringToks; ++i)
1329     StringTokLocs.push_back(StringToks[i].getLocation());
1330
1331   QualType StrTy = Context.CharTy;
1332   if (Literal.isWide())
1333     StrTy = Context.getWCharType();
1334   else if (Literal.isUTF16())
1335     StrTy = Context.Char16Ty;
1336   else if (Literal.isUTF32())
1337     StrTy = Context.Char32Ty;
1338   else if (Literal.isPascal())
1339     StrTy = Context.UnsignedCharTy;
1340
1341   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1342   if (Literal.isWide())
1343     Kind = StringLiteral::Wide;
1344   else if (Literal.isUTF8())
1345     Kind = StringLiteral::UTF8;
1346   else if (Literal.isUTF16())
1347     Kind = StringLiteral::UTF16;
1348   else if (Literal.isUTF32())
1349     Kind = StringLiteral::UTF32;
1350
1351   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1352   if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
1353     StrTy.addConst();
1354
1355   // Get an array type for the string, according to C99 6.4.5.  This includes
1356   // the nul terminator character as well as the string length for pascal
1357   // strings.
1358   StrTy = Context.getConstantArrayType(StrTy,
1359                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1360                                        ArrayType::Normal, 0);
1361
1362   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1363   StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1364                                              Kind, Literal.Pascal, StrTy,
1365                                              &StringTokLocs[0],
1366                                              StringTokLocs.size());
1367   if (Literal.getUDSuffix().empty())
1368     return Owned(Lit);
1369
1370   // We're building a user-defined literal.
1371   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
1372   SourceLocation UDSuffixLoc =
1373     getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1374                    Literal.getUDSuffixOffset());
1375
1376   // Make sure we're allowed user-defined literals here.
1377   if (!UDLScope)
1378     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1379
1380   // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1381   //   operator "" X (str, len)
1382   QualType SizeType = Context.getSizeType();
1383   llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1384   IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1385                                                   StringTokLocs[0]);
1386   Expr *Args[] = { Lit, LenArg };
1387   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1388                                         Args, StringTokLocs.back());
1389 }
1390
1391 ExprResult
1392 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1393                        SourceLocation Loc,
1394                        const CXXScopeSpec *SS) {
1395   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1396   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1397 }
1398
1399 /// BuildDeclRefExpr - Build an expression that references a
1400 /// declaration that does not require a closure capture.
1401 ExprResult
1402 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1403                        const DeclarationNameInfo &NameInfo,
1404                        const CXXScopeSpec *SS) {
1405   if (getLangOpts().CUDA)
1406     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1407       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1408         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1409                            CalleeTarget = IdentifyCUDATarget(Callee);
1410         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1411           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1412             << CalleeTarget << D->getIdentifier() << CallerTarget;
1413           Diag(D->getLocation(), diag::note_previous_decl)
1414             << D->getIdentifier();
1415           return ExprError();
1416         }
1417       }
1418
1419   bool refersToEnclosingScope =
1420     (CurContext != D->getDeclContext() &&
1421      D->getDeclContext()->isFunctionOrMethod());
1422
1423   DeclRefExpr *E = DeclRefExpr::Create(Context,
1424                                        SS ? SS->getWithLocInContext(Context)
1425                                               : NestedNameSpecifierLoc(),
1426                                        SourceLocation(),
1427                                        D, refersToEnclosingScope,
1428                                        NameInfo, Ty, VK);
1429
1430   MarkDeclRefReferenced(E);
1431
1432   if (getLangOpts().ObjCARCWeak && isa<VarDecl>(D) &&
1433       Ty.getObjCLifetime() == Qualifiers::OCL_Weak) {
1434     DiagnosticsEngine::Level Level =
1435       Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1436                                E->getLocStart());
1437     if (Level != DiagnosticsEngine::Ignored)
1438       getCurFunction()->recordUseOfWeak(E);
1439   }
1440
1441   // Just in case we're building an illegal pointer-to-member.
1442   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1443   if (FD && FD->isBitField())
1444     E->setObjectKind(OK_BitField);
1445
1446   return Owned(E);
1447 }
1448
1449 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1450 /// possibly a list of template arguments.
1451 ///
1452 /// If this produces template arguments, it is permitted to call
1453 /// DecomposeTemplateName.
1454 ///
1455 /// This actually loses a lot of source location information for
1456 /// non-standard name kinds; we should consider preserving that in
1457 /// some way.
1458 void
1459 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1460                              TemplateArgumentListInfo &Buffer,
1461                              DeclarationNameInfo &NameInfo,
1462                              const TemplateArgumentListInfo *&TemplateArgs) {
1463   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1464     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1465     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1466
1467     ASTTemplateArgsPtr TemplateArgsPtr(Id.TemplateId->getTemplateArgs(),
1468                                        Id.TemplateId->NumArgs);
1469     translateTemplateArguments(TemplateArgsPtr, Buffer);
1470
1471     TemplateName TName = Id.TemplateId->Template.get();
1472     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1473     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1474     TemplateArgs = &Buffer;
1475   } else {
1476     NameInfo = GetNameFromUnqualifiedId(Id);
1477     TemplateArgs = 0;
1478   }
1479 }
1480
1481 /// Diagnose an empty lookup.
1482 ///
1483 /// \return false if new lookup candidates were found
1484 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1485                                CorrectionCandidateCallback &CCC,
1486                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1487                                llvm::ArrayRef<Expr *> Args) {
1488   DeclarationName Name = R.getLookupName();
1489
1490   unsigned diagnostic = diag::err_undeclared_var_use;
1491   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1492   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1493       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1494       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1495     diagnostic = diag::err_undeclared_use;
1496     diagnostic_suggest = diag::err_undeclared_use_suggest;
1497   }
1498
1499   // If the original lookup was an unqualified lookup, fake an
1500   // unqualified lookup.  This is useful when (for example) the
1501   // original lookup would not have found something because it was a
1502   // dependent name.
1503   DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1504     ? CurContext : 0;
1505   while (DC) {
1506     if (isa<CXXRecordDecl>(DC)) {
1507       LookupQualifiedName(R, DC);
1508
1509       if (!R.empty()) {
1510         // Don't give errors about ambiguities in this lookup.
1511         R.suppressDiagnostics();
1512
1513         // During a default argument instantiation the CurContext points
1514         // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1515         // function parameter list, hence add an explicit check.
1516         bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1517                               ActiveTemplateInstantiations.back().Kind ==
1518             ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
1519         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1520         bool isInstance = CurMethod &&
1521                           CurMethod->isInstance() &&
1522                           DC == CurMethod->getParent() && !isDefaultArgument;
1523                           
1524
1525         // Give a code modification hint to insert 'this->'.
1526         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1527         // Actually quite difficult!
1528         if (getLangOpts().MicrosoftMode)
1529           diagnostic = diag::warn_found_via_dependent_bases_lookup;
1530         if (isInstance) {
1531           Diag(R.getNameLoc(), diagnostic) << Name
1532             << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1533           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1534               CallsUndergoingInstantiation.back()->getCallee());
1535
1536           
1537           CXXMethodDecl *DepMethod;
1538           if (CurMethod->getTemplatedKind() ==
1539               FunctionDecl::TK_FunctionTemplateSpecialization)
1540             DepMethod = cast<CXXMethodDecl>(CurMethod->getPrimaryTemplate()->
1541                 getInstantiatedFromMemberTemplate()->getTemplatedDecl());
1542           else
1543             DepMethod = cast<CXXMethodDecl>(
1544                 CurMethod->getInstantiatedFromMemberFunction());
1545           assert(DepMethod && "No template pattern found");
1546
1547           QualType DepThisType = DepMethod->getThisType(Context);
1548           CheckCXXThisCapture(R.getNameLoc());
1549           CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1550                                      R.getNameLoc(), DepThisType, false);
1551           TemplateArgumentListInfo TList;
1552           if (ULE->hasExplicitTemplateArgs())
1553             ULE->copyTemplateArgumentsInto(TList);
1554           
1555           CXXScopeSpec SS;
1556           SS.Adopt(ULE->getQualifierLoc());
1557           CXXDependentScopeMemberExpr *DepExpr =
1558               CXXDependentScopeMemberExpr::Create(
1559                   Context, DepThis, DepThisType, true, SourceLocation(),
1560                   SS.getWithLocInContext(Context),
1561                   ULE->getTemplateKeywordLoc(), 0,
1562                   R.getLookupNameInfo(),
1563                   ULE->hasExplicitTemplateArgs() ? &TList : 0);
1564           CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1565         } else {
1566           Diag(R.getNameLoc(), diagnostic) << Name;
1567         }
1568
1569         // Do we really want to note all of these?
1570         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1571           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1572
1573         // Return true if we are inside a default argument instantiation
1574         // and the found name refers to an instance member function, otherwise
1575         // the function calling DiagnoseEmptyLookup will try to create an
1576         // implicit member call and this is wrong for default argument.
1577         if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1578           Diag(R.getNameLoc(), diag::err_member_call_without_object);
1579           return true;
1580         }
1581
1582         // Tell the callee to try to recover.
1583         return false;
1584       }
1585
1586       R.clear();
1587     }
1588
1589     // In Microsoft mode, if we are performing lookup from within a friend
1590     // function definition declared at class scope then we must set
1591     // DC to the lexical parent to be able to search into the parent
1592     // class.
1593     if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
1594         cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1595         DC->getLexicalParent()->isRecord())
1596       DC = DC->getLexicalParent();
1597     else
1598       DC = DC->getParent();
1599   }
1600
1601   // We didn't find anything, so try to correct for a typo.
1602   TypoCorrection Corrected;
1603   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1604                                     S, &SS, CCC))) {
1605     std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1606     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
1607     R.setLookupName(Corrected.getCorrection());
1608
1609     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1610       if (Corrected.isOverloaded()) {
1611         OverloadCandidateSet OCS(R.getNameLoc());
1612         OverloadCandidateSet::iterator Best;
1613         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1614                                         CDEnd = Corrected.end();
1615              CD != CDEnd; ++CD) {
1616           if (FunctionTemplateDecl *FTD =
1617                    dyn_cast<FunctionTemplateDecl>(*CD))
1618             AddTemplateOverloadCandidate(
1619                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1620                 Args, OCS);
1621           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1622             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1623               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1624                                    Args, OCS);
1625         }
1626         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1627           case OR_Success:
1628             ND = Best->Function;
1629             break;
1630           default:
1631             break;
1632         }
1633       }
1634       R.addDecl(ND);
1635       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1636         if (SS.isEmpty())
1637           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1638             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1639         else
1640           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1641             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1642             << SS.getRange()
1643             << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
1644                                             CorrectedStr);
1645         if (ND)
1646           Diag(ND->getLocation(), diag::note_previous_decl)
1647             << CorrectedQuotedStr;
1648
1649         // Tell the callee to try to recover.
1650         return false;
1651       }
1652
1653       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1654         // FIXME: If we ended up with a typo for a type name or
1655         // Objective-C class name, we're in trouble because the parser
1656         // is in the wrong place to recover. Suggest the typo
1657         // correction, but don't make it a fix-it since we're not going
1658         // to recover well anyway.
1659         if (SS.isEmpty())
1660           Diag(R.getNameLoc(), diagnostic_suggest)
1661             << Name << CorrectedQuotedStr;
1662         else
1663           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1664             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1665             << SS.getRange();
1666
1667         // Don't try to recover; it won't work.
1668         return true;
1669       }
1670     } else {
1671       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1672       // because we aren't able to recover.
1673       if (SS.isEmpty())
1674         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1675       else
1676         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1677         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1678         << SS.getRange();
1679       return true;
1680     }
1681   }
1682   R.clear();
1683
1684   // Emit a special diagnostic for failed member lookups.
1685   // FIXME: computing the declaration context might fail here (?)
1686   if (!SS.isEmpty()) {
1687     Diag(R.getNameLoc(), diag::err_no_member)
1688       << Name << computeDeclContext(SS, false)
1689       << SS.getRange();
1690     return true;
1691   }
1692
1693   // Give up, we can't recover.
1694   Diag(R.getNameLoc(), diagnostic) << Name;
1695   return true;
1696 }
1697
1698 ExprResult Sema::ActOnIdExpression(Scope *S,
1699                                    CXXScopeSpec &SS,
1700                                    SourceLocation TemplateKWLoc,
1701                                    UnqualifiedId &Id,
1702                                    bool HasTrailingLParen,
1703                                    bool IsAddressOfOperand,
1704                                    CorrectionCandidateCallback *CCC) {
1705   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1706          "cannot be direct & operand and have a trailing lparen");
1707
1708   if (SS.isInvalid())
1709     return ExprError();
1710
1711   TemplateArgumentListInfo TemplateArgsBuffer;
1712
1713   // Decompose the UnqualifiedId into the following data.
1714   DeclarationNameInfo NameInfo;
1715   const TemplateArgumentListInfo *TemplateArgs;
1716   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1717
1718   DeclarationName Name = NameInfo.getName();
1719   IdentifierInfo *II = Name.getAsIdentifierInfo();
1720   SourceLocation NameLoc = NameInfo.getLoc();
1721
1722   // C++ [temp.dep.expr]p3:
1723   //   An id-expression is type-dependent if it contains:
1724   //     -- an identifier that was declared with a dependent type,
1725   //        (note: handled after lookup)
1726   //     -- a template-id that is dependent,
1727   //        (note: handled in BuildTemplateIdExpr)
1728   //     -- a conversion-function-id that specifies a dependent type,
1729   //     -- a nested-name-specifier that contains a class-name that
1730   //        names a dependent type.
1731   // Determine whether this is a member of an unknown specialization;
1732   // we need to handle these differently.
1733   bool DependentID = false;
1734   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1735       Name.getCXXNameType()->isDependentType()) {
1736     DependentID = true;
1737   } else if (SS.isSet()) {
1738     if (DeclContext *DC = computeDeclContext(SS, false)) {
1739       if (RequireCompleteDeclContext(SS, DC))
1740         return ExprError();
1741     } else {
1742       DependentID = true;
1743     }
1744   }
1745
1746   if (DependentID)
1747     return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1748                                       IsAddressOfOperand, TemplateArgs);
1749
1750   // Perform the required lookup.
1751   LookupResult R(*this, NameInfo, 
1752                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
1753                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1754   if (TemplateArgs) {
1755     // Lookup the template name again to correctly establish the context in
1756     // which it was found. This is really unfortunate as we already did the
1757     // lookup to determine that it was a template name in the first place. If
1758     // this becomes a performance hit, we can work harder to preserve those
1759     // results until we get here but it's likely not worth it.
1760     bool MemberOfUnknownSpecialization;
1761     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1762                        MemberOfUnknownSpecialization);
1763     
1764     if (MemberOfUnknownSpecialization ||
1765         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1766       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1767                                         IsAddressOfOperand, TemplateArgs);
1768   } else {
1769     bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
1770     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1771
1772     // If the result might be in a dependent base class, this is a dependent 
1773     // id-expression.
1774     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1775       return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1776                                         IsAddressOfOperand, TemplateArgs);
1777
1778     // If this reference is in an Objective-C method, then we need to do
1779     // some special Objective-C lookup, too.
1780     if (IvarLookupFollowUp) {
1781       ExprResult E(LookupInObjCMethod(R, S, II, true));
1782       if (E.isInvalid())
1783         return ExprError();
1784
1785       if (Expr *Ex = E.takeAs<Expr>())
1786         return Owned(Ex);
1787     }
1788   }
1789
1790   if (R.isAmbiguous())
1791     return ExprError();
1792
1793   // Determine whether this name might be a candidate for
1794   // argument-dependent lookup.
1795   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1796
1797   if (R.empty() && !ADL) {
1798     // Otherwise, this could be an implicitly declared function reference (legal
1799     // in C90, extension in C99, forbidden in C++).
1800     if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
1801       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1802       if (D) R.addDecl(D);
1803     }
1804
1805     // If this name wasn't predeclared and if this is not a function
1806     // call, diagnose the problem.
1807     if (R.empty()) {
1808
1809       // In Microsoft mode, if we are inside a template class member function
1810       // and we can't resolve an identifier then assume the identifier is type
1811       // dependent. The goal is to postpone name lookup to instantiation time 
1812       // to be able to search into type dependent base classes.
1813       if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
1814           isa<CXXMethodDecl>(CurContext))
1815         return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1816                                           IsAddressOfOperand, TemplateArgs);
1817
1818       CorrectionCandidateCallback DefaultValidator;
1819       if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
1820         return ExprError();
1821
1822       assert(!R.empty() &&
1823              "DiagnoseEmptyLookup returned false but added no results");
1824
1825       // If we found an Objective-C instance variable, let
1826       // LookupInObjCMethod build the appropriate expression to
1827       // reference the ivar.
1828       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1829         R.clear();
1830         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1831         // In a hopelessly buggy code, Objective-C instance variable
1832         // lookup fails and no expression will be built to reference it.
1833         if (!E.isInvalid() && !E.get())
1834           return ExprError();
1835         return E;
1836       }
1837     }
1838   }
1839
1840   // This is guaranteed from this point on.
1841   assert(!R.empty() || ADL);
1842
1843   // Check whether this might be a C++ implicit instance member access.
1844   // C++ [class.mfct.non-static]p3:
1845   //   When an id-expression that is not part of a class member access
1846   //   syntax and not used to form a pointer to member is used in the
1847   //   body of a non-static member function of class X, if name lookup
1848   //   resolves the name in the id-expression to a non-static non-type
1849   //   member of some class C, the id-expression is transformed into a
1850   //   class member access expression using (*this) as the
1851   //   postfix-expression to the left of the . operator.
1852   //
1853   // But we don't actually need to do this for '&' operands if R
1854   // resolved to a function or overloaded function set, because the
1855   // expression is ill-formed if it actually works out to be a
1856   // non-static member function:
1857   //
1858   // C++ [expr.ref]p4:
1859   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1860   //   [t]he expression can be used only as the left-hand operand of a
1861   //   member function call.
1862   //
1863   // There are other safeguards against such uses, but it's important
1864   // to get this right here so that we don't end up making a
1865   // spuriously dependent expression if we're inside a dependent
1866   // instance method.
1867   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1868     bool MightBeImplicitMember;
1869     if (!IsAddressOfOperand)
1870       MightBeImplicitMember = true;
1871     else if (!SS.isEmpty())
1872       MightBeImplicitMember = false;
1873     else if (R.isOverloadedResult())
1874       MightBeImplicitMember = false;
1875     else if (R.isUnresolvableResult())
1876       MightBeImplicitMember = true;
1877     else
1878       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1879                               isa<IndirectFieldDecl>(R.getFoundDecl());
1880
1881     if (MightBeImplicitMember)
1882       return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1883                                              R, TemplateArgs);
1884   }
1885
1886   if (TemplateArgs || TemplateKWLoc.isValid())
1887     return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
1888
1889   return BuildDeclarationNameExpr(SS, R, ADL);
1890 }
1891
1892 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1893 /// declaration name, generally during template instantiation.
1894 /// There's a large number of things which don't need to be done along
1895 /// this path.
1896 ExprResult
1897 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1898                                         const DeclarationNameInfo &NameInfo,
1899                                         bool IsAddressOfOperand) {
1900   DeclContext *DC = computeDeclContext(SS, false);
1901   if (!DC)
1902     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1903                                      NameInfo, /*TemplateArgs=*/0);
1904
1905   if (RequireCompleteDeclContext(SS, DC))
1906     return ExprError();
1907
1908   LookupResult R(*this, NameInfo, LookupOrdinaryName);
1909   LookupQualifiedName(R, DC);
1910
1911   if (R.isAmbiguous())
1912     return ExprError();
1913
1914   if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1915     return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1916                                      NameInfo, /*TemplateArgs=*/0);
1917
1918   if (R.empty()) {
1919     Diag(NameInfo.getLoc(), diag::err_no_member)
1920       << NameInfo.getName() << DC << SS.getRange();
1921     return ExprError();
1922   }
1923
1924   // Defend against this resolving to an implicit member access. We usually
1925   // won't get here if this might be a legitimate a class member (we end up in
1926   // BuildMemberReferenceExpr instead), but this can be valid if we're forming
1927   // a pointer-to-member or in an unevaluated context in C++11.
1928   if (!R.empty() && (*R.begin())->isCXXClassMember() && !IsAddressOfOperand)
1929     return BuildPossibleImplicitMemberExpr(SS,
1930                                            /*TemplateKWLoc=*/SourceLocation(),
1931                                            R, /*TemplateArgs=*/0);
1932
1933   return BuildDeclarationNameExpr(SS, R, /* ADL */ false);
1934 }
1935
1936 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1937 /// detected that we're currently inside an ObjC method.  Perform some
1938 /// additional lookup.
1939 ///
1940 /// Ideally, most of this would be done by lookup, but there's
1941 /// actually quite a lot of extra work involved.
1942 ///
1943 /// Returns a null sentinel to indicate trivial success.
1944 ExprResult
1945 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1946                          IdentifierInfo *II, bool AllowBuiltinCreation) {
1947   SourceLocation Loc = Lookup.getNameLoc();
1948   ObjCMethodDecl *CurMethod = getCurMethodDecl();
1949
1950   // There are two cases to handle here.  1) scoped lookup could have failed,
1951   // in which case we should look for an ivar.  2) scoped lookup could have
1952   // found a decl, but that decl is outside the current instance method (i.e.
1953   // a global variable).  In these two cases, we do a lookup for an ivar with
1954   // this name, if the lookup sucedes, we replace it our current decl.
1955
1956   // If we're in a class method, we don't normally want to look for
1957   // ivars.  But if we don't find anything else, and there's an
1958   // ivar, that's an error.
1959   bool IsClassMethod = CurMethod->isClassMethod();
1960
1961   bool LookForIvars;
1962   if (Lookup.empty())
1963     LookForIvars = true;
1964   else if (IsClassMethod)
1965     LookForIvars = false;
1966   else
1967     LookForIvars = (Lookup.isSingleResult() &&
1968                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1969   ObjCInterfaceDecl *IFace = 0;
1970   if (LookForIvars) {
1971     IFace = CurMethod->getClassInterface();
1972     ObjCInterfaceDecl *ClassDeclared;
1973     ObjCIvarDecl *IV = 0;
1974     if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
1975       // Diagnose using an ivar in a class method.
1976       if (IsClassMethod)
1977         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1978                          << IV->getDeclName());
1979
1980       // If we're referencing an invalid decl, just return this as a silent
1981       // error node.  The error diagnostic was already emitted on the decl.
1982       if (IV->isInvalidDecl())
1983         return ExprError();
1984
1985       // Check if referencing a field with __attribute__((deprecated)).
1986       if (DiagnoseUseOfDecl(IV, Loc))
1987         return ExprError();
1988
1989       // Diagnose the use of an ivar outside of the declaring class.
1990       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1991           !declaresSameEntity(ClassDeclared, IFace) &&
1992           !getLangOpts().DebuggerSupport)
1993         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1994
1995       // FIXME: This should use a new expr for a direct reference, don't
1996       // turn this into Self->ivar, just return a BareIVarExpr or something.
1997       IdentifierInfo &II = Context.Idents.get("self");
1998       UnqualifiedId SelfName;
1999       SelfName.setIdentifier(&II, SourceLocation());
2000       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
2001       CXXScopeSpec SelfScopeSpec;
2002       SourceLocation TemplateKWLoc;
2003       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
2004                                               SelfName, false, false);
2005       if (SelfExpr.isInvalid())
2006         return ExprError();
2007
2008       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
2009       if (SelfExpr.isInvalid())
2010         return ExprError();
2011
2012       MarkAnyDeclReferenced(Loc, IV);
2013       
2014       ObjCMethodFamily MF = CurMethod->getMethodFamily();
2015       if (MF != OMF_init && MF != OMF_dealloc && MF != OMF_finalize)
2016         Diag(Loc, diag::warn_direct_ivar_access) << IV->getDeclName();
2017
2018       ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2019                                                               Loc,
2020                                                               SelfExpr.take(),
2021                                                               true, true);
2022
2023       if (getLangOpts().ObjCAutoRefCount) {
2024         if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
2025           DiagnosticsEngine::Level Level =
2026             Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, Loc);
2027           if (Level != DiagnosticsEngine::Ignored)
2028             getCurFunction()->recordUseOfWeak(Result);
2029         }
2030         if (CurContext->isClosure())
2031           Diag(Loc, diag::warn_implicitly_retains_self)
2032             << FixItHint::CreateInsertion(Loc, "self->");
2033       }
2034       
2035       return Owned(Result);
2036     }
2037   } else if (CurMethod->isInstanceMethod()) {
2038     // We should warn if a local variable hides an ivar.
2039     if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
2040       ObjCInterfaceDecl *ClassDeclared;
2041       if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
2042         if (IV->getAccessControl() != ObjCIvarDecl::Private ||
2043             declaresSameEntity(IFace, ClassDeclared))
2044           Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
2045       }
2046     }
2047   } else if (Lookup.isSingleResult() &&
2048              Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
2049     // If accessing a stand-alone ivar in a class method, this is an error.
2050     if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
2051       return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
2052                        << IV->getDeclName());
2053   }
2054
2055   if (Lookup.empty() && II && AllowBuiltinCreation) {
2056     // FIXME. Consolidate this with similar code in LookupName.
2057     if (unsigned BuiltinID = II->getBuiltinID()) {
2058       if (!(getLangOpts().CPlusPlus &&
2059             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
2060         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
2061                                            S, Lookup.isForRedeclaration(),
2062                                            Lookup.getNameLoc());
2063         if (D) Lookup.addDecl(D);
2064       }
2065     }
2066   }
2067   // Sentinel value saying that we didn't do anything special.
2068   return Owned((Expr*) 0);
2069 }
2070
2071 /// \brief Cast a base object to a member's actual type.
2072 ///
2073 /// Logically this happens in three phases:
2074 ///
2075 /// * First we cast from the base type to the naming class.
2076 ///   The naming class is the class into which we were looking
2077 ///   when we found the member;  it's the qualifier type if a
2078 ///   qualifier was provided, and otherwise it's the base type.
2079 ///
2080 /// * Next we cast from the naming class to the declaring class.
2081 ///   If the member we found was brought into a class's scope by
2082 ///   a using declaration, this is that class;  otherwise it's
2083 ///   the class declaring the member.
2084 ///
2085 /// * Finally we cast from the declaring class to the "true"
2086 ///   declaring class of the member.  This conversion does not
2087 ///   obey access control.
2088 ExprResult
2089 Sema::PerformObjectMemberConversion(Expr *From,
2090                                     NestedNameSpecifier *Qualifier,
2091                                     NamedDecl *FoundDecl,
2092                                     NamedDecl *Member) {
2093   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2094   if (!RD)
2095     return Owned(From);
2096
2097   QualType DestRecordType;
2098   QualType DestType;
2099   QualType FromRecordType;
2100   QualType FromType = From->getType();
2101   bool PointerConversions = false;
2102   if (isa<FieldDecl>(Member)) {
2103     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2104
2105     if (FromType->getAs<PointerType>()) {
2106       DestType = Context.getPointerType(DestRecordType);
2107       FromRecordType = FromType->getPointeeType();
2108       PointerConversions = true;
2109     } else {
2110       DestType = DestRecordType;
2111       FromRecordType = FromType;
2112     }
2113   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2114     if (Method->isStatic())
2115       return Owned(From);
2116
2117     DestType = Method->getThisType(Context);
2118     DestRecordType = DestType->getPointeeType();
2119
2120     if (FromType->getAs<PointerType>()) {
2121       FromRecordType = FromType->getPointeeType();
2122       PointerConversions = true;
2123     } else {
2124       FromRecordType = FromType;
2125       DestType = DestRecordType;
2126     }
2127   } else {
2128     // No conversion necessary.
2129     return Owned(From);
2130   }
2131
2132   if (DestType->isDependentType() || FromType->isDependentType())
2133     return Owned(From);
2134
2135   // If the unqualified types are the same, no conversion is necessary.
2136   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2137     return Owned(From);
2138
2139   SourceRange FromRange = From->getSourceRange();
2140   SourceLocation FromLoc = FromRange.getBegin();
2141
2142   ExprValueKind VK = From->getValueKind();
2143
2144   // C++ [class.member.lookup]p8:
2145   //   [...] Ambiguities can often be resolved by qualifying a name with its
2146   //   class name.
2147   //
2148   // If the member was a qualified name and the qualified referred to a
2149   // specific base subobject type, we'll cast to that intermediate type
2150   // first and then to the object in which the member is declared. That allows
2151   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2152   //
2153   //   class Base { public: int x; };
2154   //   class Derived1 : public Base { };
2155   //   class Derived2 : public Base { };
2156   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2157   //
2158   //   void VeryDerived::f() {
2159   //     x = 17; // error: ambiguous base subobjects
2160   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2161   //   }
2162   if (Qualifier) {
2163     QualType QType = QualType(Qualifier->getAsType(), 0);
2164     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2165     assert(QType->isRecordType() && "lookup done with non-record type");
2166
2167     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2168
2169     // In C++98, the qualifier type doesn't actually have to be a base
2170     // type of the object type, in which case we just ignore it.
2171     // Otherwise build the appropriate casts.
2172     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2173       CXXCastPath BasePath;
2174       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2175                                        FromLoc, FromRange, &BasePath))
2176         return ExprError();
2177
2178       if (PointerConversions)
2179         QType = Context.getPointerType(QType);
2180       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2181                                VK, &BasePath).take();
2182
2183       FromType = QType;
2184       FromRecordType = QRecordType;
2185
2186       // If the qualifier type was the same as the destination type,
2187       // we're done.
2188       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2189         return Owned(From);
2190     }
2191   }
2192
2193   bool IgnoreAccess = false;
2194
2195   // If we actually found the member through a using declaration, cast
2196   // down to the using declaration's type.
2197   //
2198   // Pointer equality is fine here because only one declaration of a
2199   // class ever has member declarations.
2200   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2201     assert(isa<UsingShadowDecl>(FoundDecl));
2202     QualType URecordType = Context.getTypeDeclType(
2203                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2204
2205     // We only need to do this if the naming-class to declaring-class
2206     // conversion is non-trivial.
2207     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2208       assert(IsDerivedFrom(FromRecordType, URecordType));
2209       CXXCastPath BasePath;
2210       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2211                                        FromLoc, FromRange, &BasePath))
2212         return ExprError();
2213
2214       QualType UType = URecordType;
2215       if (PointerConversions)
2216         UType = Context.getPointerType(UType);
2217       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2218                                VK, &BasePath).take();
2219       FromType = UType;
2220       FromRecordType = URecordType;
2221     }
2222
2223     // We don't do access control for the conversion from the
2224     // declaring class to the true declaring class.
2225     IgnoreAccess = true;
2226   }
2227
2228   CXXCastPath BasePath;
2229   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2230                                    FromLoc, FromRange, &BasePath,
2231                                    IgnoreAccess))
2232     return ExprError();
2233
2234   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2235                            VK, &BasePath);
2236 }
2237
2238 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2239                                       const LookupResult &R,
2240                                       bool HasTrailingLParen) {
2241   // Only when used directly as the postfix-expression of a call.
2242   if (!HasTrailingLParen)
2243     return false;
2244
2245   // Never if a scope specifier was provided.
2246   if (SS.isSet())
2247     return false;
2248
2249   // Only in C++ or ObjC++.
2250   if (!getLangOpts().CPlusPlus)
2251     return false;
2252
2253   // Turn off ADL when we find certain kinds of declarations during
2254   // normal lookup:
2255   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2256     NamedDecl *D = *I;
2257
2258     // C++0x [basic.lookup.argdep]p3:
2259     //     -- a declaration of a class member
2260     // Since using decls preserve this property, we check this on the
2261     // original decl.
2262     if (D->isCXXClassMember())
2263       return false;
2264
2265     // C++0x [basic.lookup.argdep]p3:
2266     //     -- a block-scope function declaration that is not a
2267     //        using-declaration
2268     // NOTE: we also trigger this for function templates (in fact, we
2269     // don't check the decl type at all, since all other decl types
2270     // turn off ADL anyway).
2271     if (isa<UsingShadowDecl>(D))
2272       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2273     else if (D->getDeclContext()->isFunctionOrMethod())
2274       return false;
2275
2276     // C++0x [basic.lookup.argdep]p3:
2277     //     -- a declaration that is neither a function or a function
2278     //        template
2279     // And also for builtin functions.
2280     if (isa<FunctionDecl>(D)) {
2281       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2282
2283       // But also builtin functions.
2284       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2285         return false;
2286     } else if (!isa<FunctionTemplateDecl>(D))
2287       return false;
2288   }
2289
2290   return true;
2291 }
2292
2293
2294 /// Diagnoses obvious problems with the use of the given declaration
2295 /// as an expression.  This is only actually called for lookups that
2296 /// were not overloaded, and it doesn't promise that the declaration
2297 /// will in fact be used.
2298 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2299   if (isa<TypedefNameDecl>(D)) {
2300     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2301     return true;
2302   }
2303
2304   if (isa<ObjCInterfaceDecl>(D)) {
2305     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2306     return true;
2307   }
2308
2309   if (isa<NamespaceDecl>(D)) {
2310     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2311     return true;
2312   }
2313
2314   return false;
2315 }
2316
2317 ExprResult
2318 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2319                                LookupResult &R,
2320                                bool NeedsADL) {
2321   // If this is a single, fully-resolved result and we don't need ADL,
2322   // just build an ordinary singleton decl ref.
2323   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2324     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2325                                     R.getFoundDecl());
2326
2327   // We only need to check the declaration if there's exactly one
2328   // result, because in the overloaded case the results can only be
2329   // functions and function templates.
2330   if (R.isSingleResult() &&
2331       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2332     return ExprError();
2333
2334   // Otherwise, just build an unresolved lookup expression.  Suppress
2335   // any lookup-related diagnostics; we'll hash these out later, when
2336   // we've picked a target.
2337   R.suppressDiagnostics();
2338
2339   UnresolvedLookupExpr *ULE
2340     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2341                                    SS.getWithLocInContext(Context),
2342                                    R.getLookupNameInfo(),
2343                                    NeedsADL, R.isOverloadedResult(),
2344                                    R.begin(), R.end());
2345
2346   return Owned(ULE);
2347 }
2348
2349 /// \brief Complete semantic analysis for a reference to the given declaration.
2350 ExprResult
2351 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2352                                const DeclarationNameInfo &NameInfo,
2353                                NamedDecl *D) {
2354   assert(D && "Cannot refer to a NULL declaration");
2355   assert(!isa<FunctionTemplateDecl>(D) &&
2356          "Cannot refer unambiguously to a function template");
2357
2358   SourceLocation Loc = NameInfo.getLoc();
2359   if (CheckDeclInExpr(*this, Loc, D))
2360     return ExprError();
2361
2362   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2363     // Specifically diagnose references to class templates that are missing
2364     // a template argument list.
2365     Diag(Loc, diag::err_template_decl_ref)
2366       << Template << SS.getRange();
2367     Diag(Template->getLocation(), diag::note_template_decl_here);
2368     return ExprError();
2369   }
2370
2371   // Make sure that we're referring to a value.
2372   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2373   if (!VD) {
2374     Diag(Loc, diag::err_ref_non_value)
2375       << D << SS.getRange();
2376     Diag(D->getLocation(), diag::note_declared_at);
2377     return ExprError();
2378   }
2379
2380   // Check whether this declaration can be used. Note that we suppress
2381   // this check when we're going to perform argument-dependent lookup
2382   // on this function name, because this might not be the function
2383   // that overload resolution actually selects.
2384   if (DiagnoseUseOfDecl(VD, Loc))
2385     return ExprError();
2386
2387   // Only create DeclRefExpr's for valid Decl's.
2388   if (VD->isInvalidDecl())
2389     return ExprError();
2390
2391   // Handle members of anonymous structs and unions.  If we got here,
2392   // and the reference is to a class member indirect field, then this
2393   // must be the subject of a pointer-to-member expression.
2394   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2395     if (!indirectField->isCXXClassMember())
2396       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2397                                                       indirectField);
2398
2399   {
2400     QualType type = VD->getType();
2401     ExprValueKind valueKind = VK_RValue;
2402
2403     switch (D->getKind()) {
2404     // Ignore all the non-ValueDecl kinds.
2405 #define ABSTRACT_DECL(kind)
2406 #define VALUE(type, base)
2407 #define DECL(type, base) \
2408     case Decl::type:
2409 #include "clang/AST/DeclNodes.inc"
2410       llvm_unreachable("invalid value decl kind");
2411
2412     // These shouldn't make it here.
2413     case Decl::ObjCAtDefsField:
2414     case Decl::ObjCIvar:
2415       llvm_unreachable("forming non-member reference to ivar?");
2416
2417     // Enum constants are always r-values and never references.
2418     // Unresolved using declarations are dependent.
2419     case Decl::EnumConstant:
2420     case Decl::UnresolvedUsingValue:
2421       valueKind = VK_RValue;
2422       break;
2423
2424     // Fields and indirect fields that got here must be for
2425     // pointer-to-member expressions; we just call them l-values for
2426     // internal consistency, because this subexpression doesn't really
2427     // exist in the high-level semantics.
2428     case Decl::Field:
2429     case Decl::IndirectField:
2430       assert(getLangOpts().CPlusPlus &&
2431              "building reference to field in C?");
2432
2433       // These can't have reference type in well-formed programs, but
2434       // for internal consistency we do this anyway.
2435       type = type.getNonReferenceType();
2436       valueKind = VK_LValue;
2437       break;
2438
2439     // Non-type template parameters are either l-values or r-values
2440     // depending on the type.
2441     case Decl::NonTypeTemplateParm: {
2442       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2443         type = reftype->getPointeeType();
2444         valueKind = VK_LValue; // even if the parameter is an r-value reference
2445         break;
2446       }
2447
2448       // For non-references, we need to strip qualifiers just in case
2449       // the template parameter was declared as 'const int' or whatever.
2450       valueKind = VK_RValue;
2451       type = type.getUnqualifiedType();
2452       break;
2453     }
2454
2455     case Decl::Var:
2456       // In C, "extern void blah;" is valid and is an r-value.
2457       if (!getLangOpts().CPlusPlus &&
2458           !type.hasQualifiers() &&
2459           type->isVoidType()) {
2460         valueKind = VK_RValue;
2461         break;
2462       }
2463       // fallthrough
2464
2465     case Decl::ImplicitParam:
2466     case Decl::ParmVar: {
2467       // These are always l-values.
2468       valueKind = VK_LValue;
2469       type = type.getNonReferenceType();
2470
2471       // FIXME: Does the addition of const really only apply in
2472       // potentially-evaluated contexts? Since the variable isn't actually
2473       // captured in an unevaluated context, it seems that the answer is no.
2474       if (!isUnevaluatedContext()) {
2475         QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2476         if (!CapturedType.isNull())
2477           type = CapturedType;
2478       }
2479       
2480       break;
2481     }
2482         
2483     case Decl::Function: {
2484       if (unsigned BID = cast<FunctionDecl>(VD)->getBuiltinID()) {
2485         if (!Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
2486           type = Context.BuiltinFnTy;
2487           valueKind = VK_RValue;
2488           break;
2489         }
2490       }
2491
2492       const FunctionType *fty = type->castAs<FunctionType>();
2493
2494       // If we're referring to a function with an __unknown_anytype
2495       // result type, make the entire expression __unknown_anytype.
2496       if (fty->getResultType() == Context.UnknownAnyTy) {
2497         type = Context.UnknownAnyTy;
2498         valueKind = VK_RValue;
2499         break;
2500       }
2501
2502       // Functions are l-values in C++.
2503       if (getLangOpts().CPlusPlus) {
2504         valueKind = VK_LValue;
2505         break;
2506       }
2507       
2508       // C99 DR 316 says that, if a function type comes from a
2509       // function definition (without a prototype), that type is only
2510       // used for checking compatibility. Therefore, when referencing
2511       // the function, we pretend that we don't have the full function
2512       // type.
2513       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2514           isa<FunctionProtoType>(fty))
2515         type = Context.getFunctionNoProtoType(fty->getResultType(),
2516                                               fty->getExtInfo());
2517
2518       // Functions are r-values in C.
2519       valueKind = VK_RValue;
2520       break;
2521     }
2522
2523     case Decl::CXXMethod:
2524       // If we're referring to a method with an __unknown_anytype
2525       // result type, make the entire expression __unknown_anytype.
2526       // This should only be possible with a type written directly.
2527       if (const FunctionProtoType *proto
2528             = dyn_cast<FunctionProtoType>(VD->getType()))
2529         if (proto->getResultType() == Context.UnknownAnyTy) {
2530           type = Context.UnknownAnyTy;
2531           valueKind = VK_RValue;
2532           break;
2533         }
2534
2535       // C++ methods are l-values if static, r-values if non-static.
2536       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2537         valueKind = VK_LValue;
2538         break;
2539       }
2540       // fallthrough
2541
2542     case Decl::CXXConversion:
2543     case Decl::CXXDestructor:
2544     case Decl::CXXConstructor:
2545       valueKind = VK_RValue;
2546       break;
2547     }
2548
2549     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2550   }
2551 }
2552
2553 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2554   PredefinedExpr::IdentType IT;
2555
2556   switch (Kind) {
2557   default: llvm_unreachable("Unknown simple primary expr!");
2558   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2559   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2560   case tok::kw_L__FUNCTION__: IT = PredefinedExpr::LFunction; break;
2561   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2562   }
2563
2564   // Pre-defined identifiers are of type char[x], where x is the length of the
2565   // string.
2566
2567   Decl *currentDecl = getCurFunctionOrMethodDecl();
2568   if (!currentDecl && getCurBlock())
2569     currentDecl = getCurBlock()->TheDecl;
2570   if (!currentDecl) {
2571     Diag(Loc, diag::ext_predef_outside_function);
2572     currentDecl = Context.getTranslationUnitDecl();
2573   }
2574
2575   QualType ResTy;
2576   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2577     ResTy = Context.DependentTy;
2578   } else {
2579     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2580
2581     llvm::APInt LengthI(32, Length + 1);
2582     if (IT == PredefinedExpr::LFunction)
2583       ResTy = Context.WCharTy.withConst();
2584     else
2585       ResTy = Context.CharTy.withConst();
2586     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2587   }
2588   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2589 }
2590
2591 ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
2592   SmallString<16> CharBuffer;
2593   bool Invalid = false;
2594   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2595   if (Invalid)
2596     return ExprError();
2597
2598   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2599                             PP, Tok.getKind());
2600   if (Literal.hadError())
2601     return ExprError();
2602
2603   QualType Ty;
2604   if (Literal.isWide())
2605     Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
2606   else if (Literal.isUTF16())
2607     Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
2608   else if (Literal.isUTF32())
2609     Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2610   else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
2611     Ty = Context.IntTy;   // 'x' -> int in C, 'wxyz' -> int in C++.
2612   else
2613     Ty = Context.CharTy;  // 'x' -> char in C++
2614
2615   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2616   if (Literal.isWide())
2617     Kind = CharacterLiteral::Wide;
2618   else if (Literal.isUTF16())
2619     Kind = CharacterLiteral::UTF16;
2620   else if (Literal.isUTF32())
2621     Kind = CharacterLiteral::UTF32;
2622
2623   Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2624                                              Tok.getLocation());
2625
2626   if (Literal.getUDSuffix().empty())
2627     return Owned(Lit);
2628
2629   // We're building a user-defined literal.
2630   IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2631   SourceLocation UDSuffixLoc =
2632     getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2633
2634   // Make sure we're allowed user-defined literals here.
2635   if (!UDLScope)
2636     return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2637
2638   // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2639   //   operator "" X (ch)
2640   return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2641                                         llvm::makeArrayRef(&Lit, 1),
2642                                         Tok.getLocation());
2643 }
2644
2645 ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2646   unsigned IntSize = Context.getTargetInfo().getIntWidth();
2647   return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2648                                       Context.IntTy, Loc));
2649 }
2650
2651 static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2652                                   QualType Ty, SourceLocation Loc) {
2653   const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2654
2655   using llvm::APFloat;
2656   APFloat Val(Format);
2657
2658   APFloat::opStatus result = Literal.GetFloatValue(Val);
2659
2660   // Overflow is always an error, but underflow is only an error if
2661   // we underflowed to zero (APFloat reports denormals as underflow).
2662   if ((result & APFloat::opOverflow) ||
2663       ((result & APFloat::opUnderflow) && Val.isZero())) {
2664     unsigned diagnostic;
2665     SmallString<20> buffer;
2666     if (result & APFloat::opOverflow) {
2667       diagnostic = diag::warn_float_overflow;
2668       APFloat::getLargest(Format).toString(buffer);
2669     } else {
2670       diagnostic = diag::warn_float_underflow;
2671       APFloat::getSmallest(Format).toString(buffer);
2672     }
2673
2674     S.Diag(Loc, diagnostic)
2675       << Ty
2676       << StringRef(buffer.data(), buffer.size());
2677   }
2678
2679   bool isExact = (result == APFloat::opOK);
2680   return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2681 }
2682
2683 ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
2684   // Fast path for a single digit (which is quite common).  A single digit
2685   // cannot have a trigraph, escaped newline, radix prefix, or suffix.
2686   if (Tok.getLength() == 1) {
2687     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2688     return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
2689   }
2690
2691   SmallString<128> SpellingBuffer;
2692   // NumericLiteralParser wants to overread by one character.  Add padding to
2693   // the buffer in case the token is copied to the buffer.  If getSpelling()
2694   // returns a StringRef to the memory buffer, it should have a null char at
2695   // the EOF, so it is also safe.
2696   SpellingBuffer.resize(Tok.getLength() + 1);
2697
2698   // Get the spelling of the token, which eliminates trigraphs, etc.
2699   bool Invalid = false;
2700   StringRef TokSpelling = PP.getSpelling(Tok, SpellingBuffer, &Invalid);
2701   if (Invalid)
2702     return ExprError();
2703
2704   NumericLiteralParser Literal(TokSpelling, Tok.getLocation(), PP);
2705   if (Literal.hadError)
2706     return ExprError();
2707
2708   if (Literal.hasUDSuffix()) {
2709     // We're building a user-defined literal.
2710     IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2711     SourceLocation UDSuffixLoc =
2712       getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2713
2714     // Make sure we're allowed user-defined literals here.
2715     if (!UDLScope)
2716       return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
2717
2718     QualType CookedTy;
2719     if (Literal.isFloatingLiteral()) {
2720       // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2721       // long double, the literal is treated as a call of the form
2722       //   operator "" X (f L)
2723       CookedTy = Context.LongDoubleTy;
2724     } else {
2725       // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2726       // unsigned long long, the literal is treated as a call of the form
2727       //   operator "" X (n ULL)
2728       CookedTy = Context.UnsignedLongLongTy;
2729     }
2730
2731     DeclarationName OpName =
2732       Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2733     DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2734     OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2735
2736     // Perform literal operator lookup to determine if we're building a raw
2737     // literal or a cooked one.
2738     LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2739     switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2740                                   /*AllowRawAndTemplate*/true)) {
2741     case LOLR_Error:
2742       return ExprError();
2743
2744     case LOLR_Cooked: {
2745       Expr *Lit;
2746       if (Literal.isFloatingLiteral()) {
2747         Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2748       } else {
2749         llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2750         if (Literal.GetIntegerValue(ResultVal))
2751           Diag(Tok.getLocation(), diag::warn_integer_too_large);
2752         Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2753                                      Tok.getLocation());
2754       }
2755       return BuildLiteralOperatorCall(R, OpNameInfo,
2756                                       llvm::makeArrayRef(&Lit, 1),
2757                                       Tok.getLocation());
2758     }
2759
2760     case LOLR_Raw: {
2761       // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2762       // literal is treated as a call of the form
2763       //   operator "" X ("n")
2764       SourceLocation TokLoc = Tok.getLocation();
2765       unsigned Length = Literal.getUDSuffixOffset();
2766       QualType StrTy = Context.getConstantArrayType(
2767           Context.CharTy, llvm::APInt(32, Length + 1),
2768           ArrayType::Normal, 0);
2769       Expr *Lit = StringLiteral::Create(
2770           Context, StringRef(TokSpelling.data(), Length), StringLiteral::Ascii,
2771           /*Pascal*/false, StrTy, &TokLoc, 1);
2772       return BuildLiteralOperatorCall(R, OpNameInfo,
2773                                       llvm::makeArrayRef(&Lit, 1), TokLoc);
2774     }
2775
2776     case LOLR_Template:
2777       // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2778       // template), L is treated as a call fo the form
2779       //   operator "" X <'c1', 'c2', ... 'ck'>()
2780       // where n is the source character sequence c1 c2 ... ck.
2781       TemplateArgumentListInfo ExplicitArgs;
2782       unsigned CharBits = Context.getIntWidth(Context.CharTy);
2783       bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2784       llvm::APSInt Value(CharBits, CharIsUnsigned);
2785       for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2786         Value = TokSpelling[I];
2787         TemplateArgument Arg(Context, Value, Context.CharTy);
2788         TemplateArgumentLocInfo ArgInfo;
2789         ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2790       }
2791       return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2792                                       Tok.getLocation(), &ExplicitArgs);
2793     }
2794
2795     llvm_unreachable("unexpected literal operator lookup result");
2796   }
2797
2798   Expr *Res;
2799
2800   if (Literal.isFloatingLiteral()) {
2801     QualType Ty;
2802     if (Literal.isFloat)
2803       Ty = Context.FloatTy;
2804     else if (!Literal.isLong)
2805       Ty = Context.DoubleTy;
2806     else
2807       Ty = Context.LongDoubleTy;
2808
2809     Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
2810
2811     if (Ty == Context.DoubleTy) {
2812       if (getLangOpts().SinglePrecisionConstants) {
2813         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2814       } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2815         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2816         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2817       }
2818     }
2819   } else if (!Literal.isIntegerLiteral()) {
2820     return ExprError();
2821   } else {
2822     QualType Ty;
2823
2824     // 'long long' is a C99 or C++11 feature.
2825     if (!getLangOpts().C99 && Literal.isLongLong) {
2826       if (getLangOpts().CPlusPlus)
2827         Diag(Tok.getLocation(),
2828              getLangOpts().CPlusPlus0x ?
2829              diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
2830       else
2831         Diag(Tok.getLocation(), diag::ext_c99_longlong);
2832     }
2833
2834     // Get the value in the widest-possible width.
2835     unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2836     // The microsoft literal suffix extensions support 128-bit literals, which
2837     // may be wider than [u]intmax_t.
2838     if (Literal.isMicrosoftInteger && MaxWidth < 128)
2839       MaxWidth = 128;
2840     llvm::APInt ResultVal(MaxWidth, 0);
2841
2842     if (Literal.GetIntegerValue(ResultVal)) {
2843       // If this value didn't fit into uintmax_t, warn and force to ull.
2844       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2845       Ty = Context.UnsignedLongLongTy;
2846       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2847              "long long is not intmax_t?");
2848     } else {
2849       // If this value fits into a ULL, try to figure out what else it fits into
2850       // according to the rules of C99 6.4.4.1p5.
2851
2852       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2853       // be an unsigned int.
2854       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2855
2856       // Check from smallest to largest, picking the smallest type we can.
2857       unsigned Width = 0;
2858       if (!Literal.isLong && !Literal.isLongLong) {
2859         // Are int/unsigned possibilities?
2860         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2861
2862         // Does it fit in a unsigned int?
2863         if (ResultVal.isIntN(IntSize)) {
2864           // Does it fit in a signed int?
2865           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2866             Ty = Context.IntTy;
2867           else if (AllowUnsigned)
2868             Ty = Context.UnsignedIntTy;
2869           Width = IntSize;
2870         }
2871       }
2872
2873       // Are long/unsigned long possibilities?
2874       if (Ty.isNull() && !Literal.isLongLong) {
2875         unsigned LongSize = Context.getTargetInfo().getLongWidth();
2876
2877         // Does it fit in a unsigned long?
2878         if (ResultVal.isIntN(LongSize)) {
2879           // Does it fit in a signed long?
2880           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2881             Ty = Context.LongTy;
2882           else if (AllowUnsigned)
2883             Ty = Context.UnsignedLongTy;
2884           Width = LongSize;
2885         }
2886       }
2887
2888       // Check long long if needed.
2889       if (Ty.isNull()) {
2890         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2891
2892         // Does it fit in a unsigned long long?
2893         if (ResultVal.isIntN(LongLongSize)) {
2894           // Does it fit in a signed long long?
2895           // To be compatible with MSVC, hex integer literals ending with the
2896           // LL or i64 suffix are always signed in Microsoft mode.
2897           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2898               (getLangOpts().MicrosoftExt && Literal.isLongLong)))
2899             Ty = Context.LongLongTy;
2900           else if (AllowUnsigned)
2901             Ty = Context.UnsignedLongLongTy;
2902           Width = LongLongSize;
2903         }
2904       }
2905         
2906       // If it doesn't fit in unsigned long long, and we're using Microsoft
2907       // extensions, then its a 128-bit integer literal.
2908       if (Ty.isNull() && Literal.isMicrosoftInteger) {
2909         if (Literal.isUnsigned)
2910           Ty = Context.UnsignedInt128Ty;
2911         else
2912           Ty = Context.Int128Ty;
2913         Width = 128;
2914       }
2915
2916       // If we still couldn't decide a type, we probably have something that
2917       // does not fit in a signed long long, but has no U suffix.
2918       if (Ty.isNull()) {
2919         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2920         Ty = Context.UnsignedLongLongTy;
2921         Width = Context.getTargetInfo().getLongLongWidth();
2922       }
2923
2924       if (ResultVal.getBitWidth() != Width)
2925         ResultVal = ResultVal.trunc(Width);
2926     }
2927     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2928   }
2929
2930   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2931   if (Literal.isImaginary)
2932     Res = new (Context) ImaginaryLiteral(Res,
2933                                         Context.getComplexType(Res->getType()));
2934
2935   return Owned(Res);
2936 }
2937
2938 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2939   assert((E != 0) && "ActOnParenExpr() missing expr");
2940   return Owned(new (Context) ParenExpr(L, R, E));
2941 }
2942
2943 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2944                                          SourceLocation Loc,
2945                                          SourceRange ArgRange) {
2946   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2947   // scalar or vector data type argument..."
2948   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2949   // type (C99 6.2.5p18) or void.
2950   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2951     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2952       << T << ArgRange;
2953     return true;
2954   }
2955
2956   assert((T->isVoidType() || !T->isIncompleteType()) &&
2957          "Scalar types should always be complete");
2958   return false;
2959 }
2960
2961 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2962                                            SourceLocation Loc,
2963                                            SourceRange ArgRange,
2964                                            UnaryExprOrTypeTrait TraitKind) {
2965   // C99 6.5.3.4p1:
2966   if (T->isFunctionType()) {
2967     // alignof(function) is allowed as an extension.
2968     if (TraitKind == UETT_SizeOf)
2969       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2970     return false;
2971   }
2972
2973   // Allow sizeof(void)/alignof(void) as an extension.
2974   if (T->isVoidType()) {
2975     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2976     return false;
2977   }
2978
2979   return true;
2980 }
2981
2982 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2983                                              SourceLocation Loc,
2984                                              SourceRange ArgRange,
2985                                              UnaryExprOrTypeTrait TraitKind) {
2986   // Reject sizeof(interface) and sizeof(interface<proto>) if the
2987   // runtime doesn't allow it.
2988   if (!S.LangOpts.ObjCRuntime.allowsSizeofAlignof() && T->isObjCObjectType()) {
2989     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2990       << T << (TraitKind == UETT_SizeOf)
2991       << ArgRange;
2992     return true;
2993   }
2994
2995   return false;
2996 }
2997
2998 /// \brief Check the constrains on expression operands to unary type expression
2999 /// and type traits.
3000 ///
3001 /// Completes any types necessary and validates the constraints on the operand
3002 /// expression. The logic mostly mirrors the type-based overload, but may modify
3003 /// the expression as it completes the type for that expression through template
3004 /// instantiation, etc.
3005 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
3006                                             UnaryExprOrTypeTrait ExprKind) {
3007   QualType ExprTy = E->getType();
3008
3009   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3010   //   the result is the size of the referenced type."
3011   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3012   //   result shall be the alignment of the referenced type."
3013   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3014     ExprTy = Ref->getPointeeType();
3015
3016   if (ExprKind == UETT_VecStep)
3017     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
3018                                         E->getSourceRange());
3019
3020   // Whitelist some types as extensions
3021   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
3022                                       E->getSourceRange(), ExprKind))
3023     return false;
3024
3025   if (RequireCompleteExprType(E,
3026                               diag::err_sizeof_alignof_incomplete_type,
3027                               ExprKind, E->getSourceRange()))
3028     return true;
3029
3030   // Completeing the expression's type may have changed it.
3031   ExprTy = E->getType();
3032   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
3033     ExprTy = Ref->getPointeeType();
3034
3035   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
3036                                        E->getSourceRange(), ExprKind))
3037     return true;
3038
3039   if (ExprKind == UETT_SizeOf) {
3040     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3041       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
3042         QualType OType = PVD->getOriginalType();
3043         QualType Type = PVD->getType();
3044         if (Type->isPointerType() && OType->isArrayType()) {
3045           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
3046             << Type << OType;
3047           Diag(PVD->getLocation(), diag::note_declared_at);
3048         }
3049       }
3050     }
3051   }
3052
3053   return false;
3054 }
3055
3056 /// \brief Check the constraints on operands to unary expression and type
3057 /// traits.
3058 ///
3059 /// This will complete any types necessary, and validate the various constraints
3060 /// on those operands.
3061 ///
3062 /// The UsualUnaryConversions() function is *not* called by this routine.
3063 /// C99 6.3.2.1p[2-4] all state:
3064 ///   Except when it is the operand of the sizeof operator ...
3065 ///
3066 /// C++ [expr.sizeof]p4
3067 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
3068 ///   standard conversions are not applied to the operand of sizeof.
3069 ///
3070 /// This policy is followed for all of the unary trait expressions.
3071 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
3072                                             SourceLocation OpLoc,
3073                                             SourceRange ExprRange,
3074                                             UnaryExprOrTypeTrait ExprKind) {
3075   if (ExprType->isDependentType())
3076     return false;
3077
3078   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3079   //   the result is the size of the referenced type."
3080   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3081   //   result shall be the alignment of the referenced type."
3082   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
3083     ExprType = Ref->getPointeeType();
3084
3085   if (ExprKind == UETT_VecStep)
3086     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
3087
3088   // Whitelist some types as extensions
3089   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
3090                                       ExprKind))
3091     return false;
3092
3093   if (RequireCompleteType(OpLoc, ExprType,
3094                           diag::err_sizeof_alignof_incomplete_type,
3095                           ExprKind, ExprRange))
3096     return true;
3097
3098   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
3099                                        ExprKind))
3100     return true;
3101
3102   return false;
3103 }
3104
3105 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
3106   E = E->IgnoreParens();
3107
3108   // alignof decl is always ok.
3109   if (isa<DeclRefExpr>(E))
3110     return false;
3111
3112   // Cannot know anything else if the expression is dependent.
3113   if (E->isTypeDependent())
3114     return false;
3115
3116   if (E->getBitField()) {
3117     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
3118        << 1 << E->getSourceRange();
3119     return true;
3120   }
3121
3122   // Alignment of a field access is always okay, so long as it isn't a
3123   // bit-field.
3124   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
3125     if (isa<FieldDecl>(ME->getMemberDecl()))
3126       return false;
3127
3128   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
3129 }
3130
3131 bool Sema::CheckVecStepExpr(Expr *E) {
3132   E = E->IgnoreParens();
3133
3134   // Cannot know anything else if the expression is dependent.
3135   if (E->isTypeDependent())
3136     return false;
3137
3138   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
3139 }
3140
3141 /// \brief Build a sizeof or alignof expression given a type operand.
3142 ExprResult
3143 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3144                                      SourceLocation OpLoc,
3145                                      UnaryExprOrTypeTrait ExprKind,
3146                                      SourceRange R) {
3147   if (!TInfo)
3148     return ExprError();
3149
3150   QualType T = TInfo->getType();
3151
3152   if (!T->isDependentType() &&
3153       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
3154     return ExprError();
3155
3156   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3157   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3158                                                       Context.getSizeType(),
3159                                                       OpLoc, R.getEnd()));
3160 }
3161
3162 /// \brief Build a sizeof or alignof expression given an expression
3163 /// operand.
3164 ExprResult
3165 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3166                                      UnaryExprOrTypeTrait ExprKind) {
3167   ExprResult PE = CheckPlaceholderExpr(E);
3168   if (PE.isInvalid()) 
3169     return ExprError();
3170
3171   E = PE.get();
3172   
3173   // Verify that the operand is valid.
3174   bool isInvalid = false;
3175   if (E->isTypeDependent()) {
3176     // Delay type-checking for type-dependent expressions.
3177   } else if (ExprKind == UETT_AlignOf) {
3178     isInvalid = CheckAlignOfExpr(*this, E);
3179   } else if (ExprKind == UETT_VecStep) {
3180     isInvalid = CheckVecStepExpr(E);
3181   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
3182     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
3183     isInvalid = true;
3184   } else {
3185     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
3186   }
3187
3188   if (isInvalid)
3189     return ExprError();
3190
3191   if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3192     PE = TranformToPotentiallyEvaluated(E);
3193     if (PE.isInvalid()) return ExprError();
3194     E = PE.take();
3195   }
3196
3197   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
3198   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
3199       ExprKind, E, Context.getSizeType(), OpLoc,
3200       E->getSourceRange().getEnd()));
3201 }
3202
3203 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3204 /// expr and the same for @c alignof and @c __alignof
3205 /// Note that the ArgRange is invalid if isType is false.
3206 ExprResult
3207 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
3208                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
3209                                     void *TyOrEx, const SourceRange &ArgRange) {
3210   // If error parsing type, ignore.
3211   if (TyOrEx == 0) return ExprError();
3212
3213   if (IsType) {
3214     TypeSourceInfo *TInfo;
3215     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
3216     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
3217   }
3218
3219   Expr *ArgEx = (Expr *)TyOrEx;
3220   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
3221   return Result;
3222 }
3223
3224 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3225                                      bool IsReal) {
3226   if (V.get()->isTypeDependent())
3227     return S.Context.DependentTy;
3228
3229   // _Real and _Imag are only l-values for normal l-values.
3230   if (V.get()->getObjectKind() != OK_Ordinary) {
3231     V = S.DefaultLvalueConversion(V.take());
3232     if (V.isInvalid())
3233       return QualType();
3234   }
3235
3236   // These operators return the element type of a complex type.
3237   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3238     return CT->getElementType();
3239
3240   // Otherwise they pass through real integer and floating point types here.
3241   if (V.get()->getType()->isArithmeticType())
3242     return V.get()->getType();
3243
3244   // Test for placeholders.
3245   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3246   if (PR.isInvalid()) return QualType();
3247   if (PR.get() != V.get()) {
3248     V = PR;
3249     return CheckRealImagOperand(S, V, Loc, IsReal);
3250   }
3251
3252   // Reject anything else.
3253   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3254     << (IsReal ? "__real" : "__imag");
3255   return QualType();
3256 }
3257
3258
3259
3260 ExprResult
3261 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3262                           tok::TokenKind Kind, Expr *Input) {
3263   UnaryOperatorKind Opc;
3264   switch (Kind) {
3265   default: llvm_unreachable("Unknown unary op!");
3266   case tok::plusplus:   Opc = UO_PostInc; break;
3267   case tok::minusminus: Opc = UO_PostDec; break;
3268   }
3269
3270   // Since this might is a postfix expression, get rid of ParenListExprs.
3271   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3272   if (Result.isInvalid()) return ExprError();
3273   Input = Result.take();
3274
3275   return BuildUnaryOp(S, OpLoc, Opc, Input);
3276 }
3277
3278 /// \brief Diagnose if arithmetic on the given ObjC pointer is illegal.
3279 ///
3280 /// \return true on error
3281 static bool checkArithmeticOnObjCPointer(Sema &S,
3282                                          SourceLocation opLoc,
3283                                          Expr *op) {
3284   assert(op->getType()->isObjCObjectPointerType());
3285   if (S.LangOpts.ObjCRuntime.allowsPointerArithmetic())
3286     return false;
3287
3288   S.Diag(opLoc, diag::err_arithmetic_nonfragile_interface)
3289     << op->getType()->castAs<ObjCObjectPointerType>()->getPointeeType()
3290     << op->getSourceRange();
3291   return true;
3292 }
3293
3294 ExprResult
3295 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3296                               Expr *Idx, SourceLocation RLoc) {
3297   // Since this might be a postfix expression, get rid of ParenListExprs.
3298   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3299   if (Result.isInvalid()) return ExprError();
3300   Base = Result.take();
3301
3302   Expr *LHSExp = Base, *RHSExp = Idx;
3303
3304   if (getLangOpts().CPlusPlus &&
3305       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3306     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3307                                                   Context.DependentTy,
3308                                                   VK_LValue, OK_Ordinary,
3309                                                   RLoc));
3310   }
3311
3312   if (getLangOpts().CPlusPlus &&
3313       (LHSExp->getType()->isRecordType() ||
3314        LHSExp->getType()->isEnumeralType() ||
3315        RHSExp->getType()->isRecordType() ||
3316        RHSExp->getType()->isEnumeralType()) &&
3317       !LHSExp->getType()->isObjCObjectPointerType()) {
3318     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3319   }
3320
3321   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3322 }
3323
3324 ExprResult
3325 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3326                                       Expr *Idx, SourceLocation RLoc) {
3327   Expr *LHSExp = Base;
3328   Expr *RHSExp = Idx;
3329
3330   // Perform default conversions.
3331   if (!LHSExp->getType()->getAs<VectorType>()) {
3332     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3333     if (Result.isInvalid())
3334       return ExprError();
3335     LHSExp = Result.take();
3336   }
3337   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3338   if (Result.isInvalid())
3339     return ExprError();
3340   RHSExp = Result.take();
3341
3342   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3343   ExprValueKind VK = VK_LValue;
3344   ExprObjectKind OK = OK_Ordinary;
3345
3346   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3347   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3348   // in the subscript position. As a result, we need to derive the array base
3349   // and index from the expression types.
3350   Expr *BaseExpr, *IndexExpr;
3351   QualType ResultType;
3352   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3353     BaseExpr = LHSExp;
3354     IndexExpr = RHSExp;
3355     ResultType = Context.DependentTy;
3356   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3357     BaseExpr = LHSExp;
3358     IndexExpr = RHSExp;
3359     ResultType = PTy->getPointeeType();
3360   } else if (const ObjCObjectPointerType *PTy =
3361                LHSTy->getAs<ObjCObjectPointerType>()) {
3362     BaseExpr = LHSExp;
3363     IndexExpr = RHSExp;
3364
3365     // Use custom logic if this should be the pseudo-object subscript
3366     // expression.
3367     if (!LangOpts.ObjCRuntime.isSubscriptPointerArithmetic())
3368       return BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3369
3370     ResultType = PTy->getPointeeType();
3371     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3372       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3373         << ResultType << BaseExpr->getSourceRange();
3374       return ExprError();
3375     }
3376   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3377      // Handle the uncommon case of "123[Ptr]".
3378     BaseExpr = RHSExp;
3379     IndexExpr = LHSExp;
3380     ResultType = PTy->getPointeeType();
3381   } else if (const ObjCObjectPointerType *PTy =
3382                RHSTy->getAs<ObjCObjectPointerType>()) {
3383      // Handle the uncommon case of "123[Ptr]".
3384     BaseExpr = RHSExp;
3385     IndexExpr = LHSExp;
3386     ResultType = PTy->getPointeeType();
3387     if (!LangOpts.ObjCRuntime.allowsPointerArithmetic()) {
3388       Diag(LLoc, diag::err_subscript_nonfragile_interface)
3389         << ResultType << BaseExpr->getSourceRange();
3390       return ExprError();
3391     }
3392   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3393     BaseExpr = LHSExp;    // vectors: V[123]
3394     IndexExpr = RHSExp;
3395     VK = LHSExp->getValueKind();
3396     if (VK != VK_RValue)
3397       OK = OK_VectorComponent;
3398
3399     // FIXME: need to deal with const...
3400     ResultType = VTy->getElementType();
3401   } else if (LHSTy->isArrayType()) {
3402     // If we see an array that wasn't promoted by
3403     // DefaultFunctionArrayLvalueConversion, it must be an array that
3404     // wasn't promoted because of the C90 rule that doesn't
3405     // allow promoting non-lvalue arrays.  Warn, then
3406     // force the promotion here.
3407     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3408         LHSExp->getSourceRange();
3409     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3410                                CK_ArrayToPointerDecay).take();
3411     LHSTy = LHSExp->getType();
3412
3413     BaseExpr = LHSExp;
3414     IndexExpr = RHSExp;
3415     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3416   } else if (RHSTy->isArrayType()) {
3417     // Same as previous, except for 123[f().a] case
3418     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3419         RHSExp->getSourceRange();
3420     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3421                                CK_ArrayToPointerDecay).take();
3422     RHSTy = RHSExp->getType();
3423
3424     BaseExpr = RHSExp;
3425     IndexExpr = LHSExp;
3426     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3427   } else {
3428     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3429        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3430   }
3431   // C99 6.5.2.1p1
3432   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3433     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3434                      << IndexExpr->getSourceRange());
3435
3436   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3437        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3438          && !IndexExpr->isTypeDependent())
3439     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3440
3441   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3442   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3443   // type. Note that Functions are not objects, and that (in C99 parlance)
3444   // incomplete types are not object types.
3445   if (ResultType->isFunctionType()) {
3446     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3447       << ResultType << BaseExpr->getSourceRange();
3448     return ExprError();
3449   }
3450
3451   if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
3452     // GNU extension: subscripting on pointer to void
3453     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3454       << BaseExpr->getSourceRange();
3455
3456     // C forbids expressions of unqualified void type from being l-values.
3457     // See IsCForbiddenLValueType.
3458     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3459   } else if (!ResultType->isDependentType() &&
3460       RequireCompleteType(LLoc, ResultType,
3461                           diag::err_subscript_incomplete_type, BaseExpr))
3462     return ExprError();
3463
3464   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3465          !ResultType.isCForbiddenLValueType());
3466
3467   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3468                                                 ResultType, VK, OK, RLoc));
3469 }
3470
3471 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3472                                         FunctionDecl *FD,
3473                                         ParmVarDecl *Param) {
3474   if (Param->hasUnparsedDefaultArg()) {
3475     Diag(CallLoc,
3476          diag::err_use_of_default_argument_to_function_declared_later) <<
3477       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3478     Diag(UnparsedDefaultArgLocs[Param],
3479          diag::note_default_argument_declared_here);
3480     return ExprError();
3481   }
3482   
3483   if (Param->hasUninstantiatedDefaultArg()) {
3484     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3485
3486     EnterExpressionEvaluationContext EvalContext(*this, PotentiallyEvaluated,
3487                                                  Param);
3488
3489     // Instantiate the expression.
3490     MultiLevelTemplateArgumentList ArgList
3491       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3492
3493     std::pair<const TemplateArgument *, unsigned> Innermost
3494       = ArgList.getInnermost();
3495     InstantiatingTemplate Inst(*this, CallLoc, Param,
3496                                ArrayRef<TemplateArgument>(Innermost.first,
3497                                                           Innermost.second));
3498     if (Inst)
3499       return ExprError();
3500
3501     ExprResult Result;
3502     {
3503       // C++ [dcl.fct.default]p5:
3504       //   The names in the [default argument] expression are bound, and
3505       //   the semantic constraints are checked, at the point where the
3506       //   default argument expression appears.
3507       ContextRAII SavedContext(*this, FD);
3508       LocalInstantiationScope Local(*this);
3509       Result = SubstExpr(UninstExpr, ArgList);
3510     }
3511     if (Result.isInvalid())
3512       return ExprError();
3513
3514     // Check the expression as an initializer for the parameter.
3515     InitializedEntity Entity
3516       = InitializedEntity::InitializeParameter(Context, Param);
3517     InitializationKind Kind
3518       = InitializationKind::CreateCopy(Param->getLocation(),
3519              /*FIXME:EqualLoc*/UninstExpr->getLocStart());
3520     Expr *ResultE = Result.takeAs<Expr>();
3521
3522     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3523     Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3524     if (Result.isInvalid())
3525       return ExprError();
3526
3527     Expr *Arg = Result.takeAs<Expr>();
3528     CheckImplicitConversions(Arg, Param->getOuterLocStart());
3529     // Build the default argument expression.
3530     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
3531   }
3532
3533   // If the default expression creates temporaries, we need to
3534   // push them to the current stack of expression temporaries so they'll
3535   // be properly destroyed.
3536   // FIXME: We should really be rebuilding the default argument with new
3537   // bound temporaries; see the comment in PR5810.
3538   // We don't need to do that with block decls, though, because
3539   // blocks in default argument expression can never capture anything.
3540   if (isa<ExprWithCleanups>(Param->getInit())) {
3541     // Set the "needs cleanups" bit regardless of whether there are
3542     // any explicit objects.
3543     ExprNeedsCleanups = true;
3544
3545     // Append all the objects to the cleanup list.  Right now, this
3546     // should always be a no-op, because blocks in default argument
3547     // expressions should never be able to capture anything.
3548     assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3549            "default argument expression has capturing blocks?");
3550   }
3551
3552   // We already type-checked the argument, so we know it works. 
3553   // Just mark all of the declarations in this potentially-evaluated expression
3554   // as being "referenced".
3555   MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3556                                    /*SkipLocalVariables=*/true);
3557   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3558 }
3559
3560
3561 Sema::VariadicCallType
3562 Sema::getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto,
3563                           Expr *Fn) {
3564   if (Proto && Proto->isVariadic()) {
3565     if (dyn_cast_or_null<CXXConstructorDecl>(FDecl))
3566       return VariadicConstructor;
3567     else if (Fn && Fn->getType()->isBlockPointerType())
3568       return VariadicBlock;
3569     else if (FDecl) {
3570       if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3571         if (Method->isInstance())
3572           return VariadicMethod;
3573     }
3574     return VariadicFunction;
3575   }
3576   return VariadicDoesNotApply;
3577 }
3578
3579 /// ConvertArgumentsForCall - Converts the arguments specified in
3580 /// Args/NumArgs to the parameter types of the function FDecl with
3581 /// function prototype Proto. Call is the call expression itself, and
3582 /// Fn is the function expression. For a C++ member function, this
3583 /// routine does not attempt to convert the object argument. Returns
3584 /// true if the call is ill-formed.
3585 bool
3586 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3587                               FunctionDecl *FDecl,
3588                               const FunctionProtoType *Proto,
3589                               Expr **Args, unsigned NumArgs,
3590                               SourceLocation RParenLoc,
3591                               bool IsExecConfig) {
3592   // Bail out early if calling a builtin with custom typechecking.
3593   // We don't need to do this in the 
3594   if (FDecl)
3595     if (unsigned ID = FDecl->getBuiltinID())
3596       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3597         return false;
3598
3599   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3600   // assignment, to the types of the corresponding parameter, ...
3601   unsigned NumArgsInProto = Proto->getNumArgs();
3602   bool Invalid = false;
3603   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3604   unsigned FnKind = Fn->getType()->isBlockPointerType()
3605                        ? 1 /* block */
3606                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3607                                        : 0 /* function */);
3608
3609   // If too few arguments are available (and we don't have default
3610   // arguments for the remaining parameters), don't make the call.
3611   if (NumArgs < NumArgsInProto) {
3612     if (NumArgs < MinArgs) {
3613       if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3614         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3615                           ? diag::err_typecheck_call_too_few_args_one
3616                           : diag::err_typecheck_call_too_few_args_at_least_one)
3617           << FnKind
3618           << FDecl->getParamDecl(0) << Fn->getSourceRange();
3619       else
3620         Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3621                           ? diag::err_typecheck_call_too_few_args
3622                           : diag::err_typecheck_call_too_few_args_at_least)
3623           << FnKind
3624           << MinArgs << NumArgs << Fn->getSourceRange();
3625
3626       // Emit the location of the prototype.
3627       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3628         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3629           << FDecl;
3630
3631       return true;
3632     }
3633     Call->setNumArgs(Context, NumArgsInProto);
3634   }
3635
3636   // If too many are passed and not variadic, error on the extras and drop
3637   // them.
3638   if (NumArgs > NumArgsInProto) {
3639     if (!Proto->isVariadic()) {
3640       if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3641         Diag(Args[NumArgsInProto]->getLocStart(),
3642              MinArgs == NumArgsInProto
3643                ? diag::err_typecheck_call_too_many_args_one
3644                : diag::err_typecheck_call_too_many_args_at_most_one)
3645           << FnKind
3646           << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3647           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3648                          Args[NumArgs-1]->getLocEnd());
3649       else
3650         Diag(Args[NumArgsInProto]->getLocStart(),
3651              MinArgs == NumArgsInProto
3652                ? diag::err_typecheck_call_too_many_args
3653                : diag::err_typecheck_call_too_many_args_at_most)
3654           << FnKind
3655           << NumArgsInProto << NumArgs << Fn->getSourceRange()
3656           << SourceRange(Args[NumArgsInProto]->getLocStart(),
3657                          Args[NumArgs-1]->getLocEnd());
3658
3659       // Emit the location of the prototype.
3660       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3661         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3662           << FDecl;
3663       
3664       // This deletes the extra arguments.
3665       Call->setNumArgs(Context, NumArgsInProto);
3666       return true;
3667     }
3668   }
3669   SmallVector<Expr *, 8> AllArgs;
3670   VariadicCallType CallType = getVariadicCallType(FDecl, Proto, Fn);
3671   
3672   Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
3673                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3674   if (Invalid)
3675     return true;
3676   unsigned TotalNumArgs = AllArgs.size();
3677   for (unsigned i = 0; i < TotalNumArgs; ++i)
3678     Call->setArg(i, AllArgs[i]);
3679
3680   return false;
3681 }
3682
3683 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3684                                   FunctionDecl *FDecl,
3685                                   const FunctionProtoType *Proto,
3686                                   unsigned FirstProtoArg,
3687                                   Expr **Args, unsigned NumArgs,
3688                                   SmallVector<Expr *, 8> &AllArgs,
3689                                   VariadicCallType CallType,
3690                                   bool AllowExplicit) {
3691   unsigned NumArgsInProto = Proto->getNumArgs();
3692   unsigned NumArgsToCheck = NumArgs;
3693   bool Invalid = false;
3694   if (NumArgs != NumArgsInProto)
3695     // Use default arguments for missing arguments
3696     NumArgsToCheck = NumArgsInProto;
3697   unsigned ArgIx = 0;
3698   // Continue to check argument types (even if we have too few/many args).
3699   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3700     QualType ProtoArgType = Proto->getArgType(i);
3701
3702     Expr *Arg;
3703     ParmVarDecl *Param;
3704     if (ArgIx < NumArgs) {
3705       Arg = Args[ArgIx++];
3706
3707       if (RequireCompleteType(Arg->getLocStart(),
3708                               ProtoArgType,
3709                               diag::err_call_incomplete_argument, Arg))
3710         return true;
3711
3712       // Pass the argument
3713       Param = 0;
3714       if (FDecl && i < FDecl->getNumParams())
3715         Param = FDecl->getParamDecl(i);
3716
3717       // Strip the unbridged-cast placeholder expression off, if applicable.
3718       if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3719           FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3720           (!Param || !Param->hasAttr<CFConsumedAttr>()))
3721         Arg = stripARCUnbridgedCast(Arg);
3722
3723       InitializedEntity Entity =
3724         Param? InitializedEntity::InitializeParameter(Context, Param)
3725              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3726                                                       Proto->isArgConsumed(i));
3727       ExprResult ArgE = PerformCopyInitialization(Entity,
3728                                                   SourceLocation(),
3729                                                   Owned(Arg),
3730                                                   /*TopLevelOfInitList=*/false,
3731                                                   AllowExplicit);
3732       if (ArgE.isInvalid())
3733         return true;
3734
3735       Arg = ArgE.takeAs<Expr>();
3736     } else {
3737       Param = FDecl->getParamDecl(i);
3738
3739       ExprResult ArgExpr =
3740         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3741       if (ArgExpr.isInvalid())
3742         return true;
3743
3744       Arg = ArgExpr.takeAs<Expr>();
3745     }
3746
3747     // Check for array bounds violations for each argument to the call. This
3748     // check only triggers warnings when the argument isn't a more complex Expr
3749     // with its own checking, such as a BinaryOperator.
3750     CheckArrayAccess(Arg);
3751
3752     // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3753     CheckStaticArrayArgument(CallLoc, Param, Arg);
3754
3755     AllArgs.push_back(Arg);
3756   }
3757
3758   // If this is a variadic call, handle args passed through "...".
3759   if (CallType != VariadicDoesNotApply) {
3760     // Assume that extern "C" functions with variadic arguments that
3761     // return __unknown_anytype aren't *really* variadic.
3762     if (Proto->getResultType() == Context.UnknownAnyTy &&
3763         FDecl && FDecl->isExternC()) {
3764       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3765         ExprResult arg;
3766         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3767           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3768         else
3769           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3770         Invalid |= arg.isInvalid();
3771         AllArgs.push_back(arg.take());
3772       }
3773
3774     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3775     } else {
3776       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3777         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3778                                                           FDecl);
3779         Invalid |= Arg.isInvalid();
3780         AllArgs.push_back(Arg.take());
3781       }
3782     }
3783
3784     // Check for array bounds violations.
3785     for (unsigned i = ArgIx; i != NumArgs; ++i)
3786       CheckArrayAccess(Args[i]);
3787   }
3788   return Invalid;
3789 }
3790
3791 static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3792   TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3793   if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3794     S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3795       << ATL->getLocalSourceRange();
3796 }
3797
3798 /// CheckStaticArrayArgument - If the given argument corresponds to a static
3799 /// array parameter, check that it is non-null, and that if it is formed by
3800 /// array-to-pointer decay, the underlying array is sufficiently large.
3801 ///
3802 /// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3803 /// array type derivation, then for each call to the function, the value of the
3804 /// corresponding actual argument shall provide access to the first element of
3805 /// an array with at least as many elements as specified by the size expression.
3806 void
3807 Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3808                                ParmVarDecl *Param,
3809                                const Expr *ArgExpr) {
3810   // Static array parameters are not supported in C++.
3811   if (!Param || getLangOpts().CPlusPlus)
3812     return;
3813
3814   QualType OrigTy = Param->getOriginalType();
3815
3816   const ArrayType *AT = Context.getAsArrayType(OrigTy);
3817   if (!AT || AT->getSizeModifier() != ArrayType::Static)
3818     return;
3819
3820   if (ArgExpr->isNullPointerConstant(Context,
3821                                      Expr::NPC_NeverValueDependent)) {
3822     Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3823     DiagnoseCalleeStaticArrayParam(*this, Param);
3824     return;
3825   }
3826
3827   const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3828   if (!CAT)
3829     return;
3830
3831   const ConstantArrayType *ArgCAT =
3832     Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3833   if (!ArgCAT)
3834     return;
3835
3836   if (ArgCAT->getSize().ult(CAT->getSize())) {
3837     Diag(CallLoc, diag::warn_static_array_too_small)
3838       << ArgExpr->getSourceRange()
3839       << (unsigned) ArgCAT->getSize().getZExtValue()
3840       << (unsigned) CAT->getSize().getZExtValue();
3841     DiagnoseCalleeStaticArrayParam(*this, Param);
3842   }
3843 }
3844
3845 /// Given a function expression of unknown-any type, try to rebuild it
3846 /// to have a function type.
3847 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3848
3849 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3850 /// This provides the location of the left/right parens and a list of comma
3851 /// locations.
3852 ExprResult
3853 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3854                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
3855                     Expr *ExecConfig, bool IsExecConfig) {
3856   // Since this might be a postfix expression, get rid of ParenListExprs.
3857   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3858   if (Result.isInvalid()) return ExprError();
3859   Fn = Result.take();
3860
3861   if (getLangOpts().CPlusPlus) {
3862     // If this is a pseudo-destructor expression, build the call immediately.
3863     if (isa<CXXPseudoDestructorExpr>(Fn)) {
3864       if (!ArgExprs.empty()) {
3865         // Pseudo-destructor calls should not have any arguments.
3866         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3867           << FixItHint::CreateRemoval(
3868                                     SourceRange(ArgExprs[0]->getLocStart(),
3869                                                 ArgExprs.back()->getLocEnd()));
3870       }
3871
3872       return Owned(new (Context) CallExpr(Context, Fn, MultiExprArg(),
3873                                           Context.VoidTy, VK_RValue,
3874                                           RParenLoc));
3875     }
3876
3877     // Determine whether this is a dependent call inside a C++ template,
3878     // in which case we won't do any semantic analysis now.
3879     // FIXME: Will need to cache the results of name lookup (including ADL) in
3880     // Fn.
3881     bool Dependent = false;
3882     if (Fn->isTypeDependent())
3883       Dependent = true;
3884     else if (Expr::hasAnyTypeDependentArguments(ArgExprs))
3885       Dependent = true;
3886
3887     if (Dependent) {
3888       if (ExecConfig) {
3889         return Owned(new (Context) CUDAKernelCallExpr(
3890             Context, Fn, cast<CallExpr>(ExecConfig), ArgExprs,
3891             Context.DependentTy, VK_RValue, RParenLoc));
3892       } else {
3893         return Owned(new (Context) CallExpr(Context, Fn, ArgExprs,
3894                                             Context.DependentTy, VK_RValue,
3895                                             RParenLoc));
3896       }
3897     }
3898
3899     // Determine whether this is a call to an object (C++ [over.call.object]).
3900     if (Fn->getType()->isRecordType())
3901       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc,
3902                                                 ArgExprs.data(),
3903                                                 ArgExprs.size(), RParenLoc));
3904
3905     if (Fn->getType() == Context.UnknownAnyTy) {
3906       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3907       if (result.isInvalid()) return ExprError();
3908       Fn = result.take();
3909     }
3910
3911     if (Fn->getType() == Context.BoundMemberTy) {
3912       return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3913                                        ArgExprs.size(), RParenLoc);
3914     }
3915   }
3916
3917   // Check for overloaded calls.  This can happen even in C due to extensions.
3918   if (Fn->getType() == Context.OverloadTy) {
3919     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3920
3921     // We aren't supposed to apply this logic for if there's an '&' involved.
3922     if (!find.HasFormOfMemberPointer) {
3923       OverloadExpr *ovl = find.Expression;
3924       if (isa<UnresolvedLookupExpr>(ovl)) {
3925         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3926         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, ArgExprs.data(),
3927                                        ArgExprs.size(), RParenLoc, ExecConfig);
3928       } else {
3929         return BuildCallToMemberFunction(S, Fn, LParenLoc, ArgExprs.data(),
3930                                          ArgExprs.size(), RParenLoc);
3931       }
3932     }
3933   }
3934
3935   // If we're directly calling a function, get the appropriate declaration.
3936   if (Fn->getType() == Context.UnknownAnyTy) {
3937     ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3938     if (result.isInvalid()) return ExprError();
3939     Fn = result.take();
3940   }
3941
3942   Expr *NakedFn = Fn->IgnoreParens();
3943
3944   NamedDecl *NDecl = 0;
3945   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3946     if (UnOp->getOpcode() == UO_AddrOf)
3947       NakedFn = UnOp->getSubExpr()->IgnoreParens();
3948   
3949   if (isa<DeclRefExpr>(NakedFn))
3950     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3951   else if (isa<MemberExpr>(NakedFn))
3952     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3953
3954   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, ArgExprs.data(),
3955                                ArgExprs.size(), RParenLoc, ExecConfig,
3956                                IsExecConfig);
3957 }
3958
3959 ExprResult
3960 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3961                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3962   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3963   if (!ConfigDecl)
3964     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3965                           << "cudaConfigureCall");
3966   QualType ConfigQTy = ConfigDecl->getType();
3967
3968   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3969       ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
3970   MarkFunctionReferenced(LLLLoc, ConfigDecl);
3971
3972   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3973                        /*IsExecConfig=*/true);
3974 }
3975
3976 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3977 ///
3978 /// __builtin_astype( value, dst type )
3979 ///
3980 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3981                                  SourceLocation BuiltinLoc,
3982                                  SourceLocation RParenLoc) {
3983   ExprValueKind VK = VK_RValue;
3984   ExprObjectKind OK = OK_Ordinary;
3985   QualType DstTy = GetTypeFromParser(ParsedDestTy);
3986   QualType SrcTy = E->getType();
3987   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3988     return ExprError(Diag(BuiltinLoc,
3989                           diag::err_invalid_astype_of_different_size)
3990                      << DstTy
3991                      << SrcTy
3992                      << E->getSourceRange());
3993   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3994                RParenLoc));
3995 }
3996
3997 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3998 /// i.e. an expression not of \p OverloadTy.  The expression should
3999 /// unary-convert to an expression of function-pointer or
4000 /// block-pointer type.
4001 ///
4002 /// \param NDecl the declaration being called, if available
4003 ExprResult
4004 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
4005                             SourceLocation LParenLoc,
4006                             Expr **Args, unsigned NumArgs,
4007                             SourceLocation RParenLoc,
4008                             Expr *Config, bool IsExecConfig) {
4009   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
4010   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
4011
4012   // Promote the function operand.
4013   // We special-case function promotion here because we only allow promoting
4014   // builtin functions to function pointers in the callee of a call.
4015   ExprResult Result;
4016   if (BuiltinID &&
4017       Fn->getType()->isSpecificBuiltinType(BuiltinType::BuiltinFn)) {
4018     Result = ImpCastExprToType(Fn, Context.getPointerType(FDecl->getType()),
4019                                CK_BuiltinFnToFnPtr).take();
4020   } else {
4021     Result = UsualUnaryConversions(Fn);
4022   }
4023   if (Result.isInvalid())
4024     return ExprError();
4025   Fn = Result.take();
4026
4027   // Make the call expr early, before semantic checks.  This guarantees cleanup
4028   // of arguments and function on error.
4029   CallExpr *TheCall;
4030   if (Config)
4031     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
4032                                                cast<CallExpr>(Config),
4033                                                llvm::makeArrayRef(Args,NumArgs),
4034                                                Context.BoolTy,
4035                                                VK_RValue,
4036                                                RParenLoc);
4037   else
4038     TheCall = new (Context) CallExpr(Context, Fn,
4039                                      llvm::makeArrayRef(Args, NumArgs),
4040                                      Context.BoolTy,
4041                                      VK_RValue,
4042                                      RParenLoc);
4043
4044   // Bail out early if calling a builtin with custom typechecking.
4045   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
4046     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4047
4048  retry:
4049   const FunctionType *FuncT;
4050   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
4051     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
4052     // have type pointer to function".
4053     FuncT = PT->getPointeeType()->getAs<FunctionType>();
4054     if (FuncT == 0)
4055       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4056                          << Fn->getType() << Fn->getSourceRange());
4057   } else if (const BlockPointerType *BPT =
4058                Fn->getType()->getAs<BlockPointerType>()) {
4059     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
4060   } else {
4061     // Handle calls to expressions of unknown-any type.
4062     if (Fn->getType() == Context.UnknownAnyTy) {
4063       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
4064       if (rewrite.isInvalid()) return ExprError();
4065       Fn = rewrite.take();
4066       TheCall->setCallee(Fn);
4067       goto retry;
4068     }
4069
4070     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
4071       << Fn->getType() << Fn->getSourceRange());
4072   }
4073
4074   if (getLangOpts().CUDA) {
4075     if (Config) {
4076       // CUDA: Kernel calls must be to global functions
4077       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
4078         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
4079             << FDecl->getName() << Fn->getSourceRange());
4080
4081       // CUDA: Kernel function must have 'void' return type
4082       if (!FuncT->getResultType()->isVoidType())
4083         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
4084             << Fn->getType() << Fn->getSourceRange());
4085     } else {
4086       // CUDA: Calls to global functions must be configured
4087       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
4088         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
4089             << FDecl->getName() << Fn->getSourceRange());
4090     }
4091   }
4092
4093   // Check for a valid return type
4094   if (CheckCallReturnType(FuncT->getResultType(),
4095                           Fn->getLocStart(), TheCall,
4096                           FDecl))
4097     return ExprError();
4098
4099   // We know the result type of the call, set it.
4100   TheCall->setType(FuncT->getCallResultType(Context));
4101   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
4102
4103   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT);
4104   if (Proto) {
4105     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
4106                                 RParenLoc, IsExecConfig))
4107       return ExprError();
4108   } else {
4109     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
4110
4111     if (FDecl) {
4112       // Check if we have too few/too many template arguments, based
4113       // on our knowledge of the function definition.
4114       const FunctionDecl *Def = 0;
4115       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
4116         Proto = Def->getType()->getAs<FunctionProtoType>();
4117         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
4118           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
4119             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
4120       }
4121       
4122       // If the function we're calling isn't a function prototype, but we have
4123       // a function prototype from a prior declaratiom, use that prototype.
4124       if (!FDecl->hasPrototype())
4125         Proto = FDecl->getType()->getAs<FunctionProtoType>();
4126     }
4127
4128     // Promote the arguments (C99 6.5.2.2p6).
4129     for (unsigned i = 0; i != NumArgs; i++) {
4130       Expr *Arg = Args[i];
4131
4132       if (Proto && i < Proto->getNumArgs()) {
4133         InitializedEntity Entity
4134           = InitializedEntity::InitializeParameter(Context, 
4135                                                    Proto->getArgType(i),
4136                                                    Proto->isArgConsumed(i));
4137         ExprResult ArgE = PerformCopyInitialization(Entity,
4138                                                     SourceLocation(),
4139                                                     Owned(Arg));
4140         if (ArgE.isInvalid())
4141           return true;
4142         
4143         Arg = ArgE.takeAs<Expr>();
4144
4145       } else {
4146         ExprResult ArgE = DefaultArgumentPromotion(Arg);
4147
4148         if (ArgE.isInvalid())
4149           return true;
4150
4151         Arg = ArgE.takeAs<Expr>();
4152       }
4153       
4154       if (RequireCompleteType(Arg->getLocStart(),
4155                               Arg->getType(),
4156                               diag::err_call_incomplete_argument, Arg))
4157         return ExprError();
4158
4159       TheCall->setArg(i, Arg);
4160     }
4161   }
4162
4163   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
4164     if (!Method->isStatic())
4165       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
4166         << Fn->getSourceRange());
4167
4168   // Check for sentinels
4169   if (NDecl)
4170     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
4171
4172   // Do special checking on direct calls to functions.
4173   if (FDecl) {
4174     if (CheckFunctionCall(FDecl, TheCall, Proto))
4175       return ExprError();
4176
4177     if (BuiltinID)
4178       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
4179   } else if (NDecl) {
4180     if (CheckBlockCall(NDecl, TheCall, Proto))
4181       return ExprError();
4182   }
4183
4184   return MaybeBindToTemporary(TheCall);
4185 }
4186
4187 ExprResult
4188 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
4189                            SourceLocation RParenLoc, Expr *InitExpr) {
4190   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
4191   // FIXME: put back this assert when initializers are worked out.
4192   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
4193
4194   TypeSourceInfo *TInfo;
4195   QualType literalType = GetTypeFromParser(Ty, &TInfo);
4196   if (!TInfo)
4197     TInfo = Context.getTrivialTypeSourceInfo(literalType);
4198
4199   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
4200 }
4201
4202 ExprResult
4203 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
4204                                SourceLocation RParenLoc, Expr *LiteralExpr) {
4205   QualType literalType = TInfo->getType();
4206
4207   if (literalType->isArrayType()) {
4208     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
4209           diag::err_illegal_decl_array_incomplete_type,
4210           SourceRange(LParenLoc,
4211                       LiteralExpr->getSourceRange().getEnd())))
4212       return ExprError();
4213     if (literalType->isVariableArrayType())
4214       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
4215         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
4216   } else if (!literalType->isDependentType() &&
4217              RequireCompleteType(LParenLoc, literalType,
4218                diag::err_typecheck_decl_incomplete_type,
4219                SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
4220     return ExprError();
4221
4222   InitializedEntity Entity
4223     = InitializedEntity::InitializeTemporary(literalType);
4224   InitializationKind Kind
4225     = InitializationKind::CreateCStyleCast(LParenLoc, 
4226                                            SourceRange(LParenLoc, RParenLoc),
4227                                            /*InitList=*/true);
4228   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
4229   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, LiteralExpr,
4230                                       &literalType);
4231   if (Result.isInvalid())
4232     return ExprError();
4233   LiteralExpr = Result.get();
4234
4235   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4236   if (isFileScope) { // 6.5.2.5p3
4237     if (CheckForConstantInitializer(LiteralExpr, literalType))
4238       return ExprError();
4239   }
4240
4241   // In C, compound literals are l-values for some reason.
4242   ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
4243
4244   return MaybeBindToTemporary(
4245            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
4246                                              VK, LiteralExpr, isFileScope));
4247 }
4248
4249 ExprResult
4250 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
4251                     SourceLocation RBraceLoc) {
4252   // Immediately handle non-overload placeholders.  Overloads can be
4253   // resolved contextually, but everything else here can't.
4254   for (unsigned I = 0, E = InitArgList.size(); I != E; ++I) {
4255     if (InitArgList[I]->getType()->isNonOverloadPlaceholderType()) {
4256       ExprResult result = CheckPlaceholderExpr(InitArgList[I]);
4257
4258       // Ignore failures; dropping the entire initializer list because
4259       // of one failure would be terrible for indexing/etc.
4260       if (result.isInvalid()) continue;
4261
4262       InitArgList[I] = result.take();
4263     }
4264   }
4265
4266   // Semantic analysis for initializers is done by ActOnDeclarator() and
4267   // CheckInitializer() - it requires knowledge of the object being intialized.
4268
4269   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitArgList,
4270                                                RBraceLoc);
4271   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
4272   return Owned(E);
4273 }
4274
4275 /// Do an explicit extend of the given block pointer if we're in ARC.
4276 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4277   assert(E.get()->getType()->isBlockPointerType());
4278   assert(E.get()->isRValue());
4279
4280   // Only do this in an r-value context.
4281   if (!S.getLangOpts().ObjCAutoRefCount) return;
4282
4283   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
4284                                CK_ARCExtendBlockObject, E.get(),
4285                                /*base path*/ 0, VK_RValue);
4286   S.ExprNeedsCleanups = true;
4287 }
4288
4289 /// Prepare a conversion of the given expression to an ObjC object
4290 /// pointer type.
4291 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4292   QualType type = E.get()->getType();
4293   if (type->isObjCObjectPointerType()) {
4294     return CK_BitCast;
4295   } else if (type->isBlockPointerType()) {
4296     maybeExtendBlockObject(*this, E);
4297     return CK_BlockPointerToObjCPointerCast;
4298   } else {
4299     assert(type->isPointerType());
4300     return CK_CPointerToObjCPointerCast;
4301   }
4302 }
4303
4304 /// Prepares for a scalar cast, performing all the necessary stages
4305 /// except the final cast and returning the kind required.
4306 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
4307   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4308   // Also, callers should have filtered out the invalid cases with
4309   // pointers.  Everything else should be possible.
4310
4311   QualType SrcTy = Src.get()->getType();
4312   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
4313     return CK_NoOp;
4314
4315   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
4316   case Type::STK_MemberPointer:
4317     llvm_unreachable("member pointer type in C");
4318
4319   case Type::STK_CPointer:
4320   case Type::STK_BlockPointer:
4321   case Type::STK_ObjCObjectPointer:
4322     switch (DestTy->getScalarTypeKind()) {
4323     case Type::STK_CPointer:
4324       return CK_BitCast;
4325     case Type::STK_BlockPointer:
4326       return (SrcKind == Type::STK_BlockPointer
4327                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4328     case Type::STK_ObjCObjectPointer:
4329       if (SrcKind == Type::STK_ObjCObjectPointer)
4330         return CK_BitCast;
4331       if (SrcKind == Type::STK_CPointer)
4332         return CK_CPointerToObjCPointerCast;
4333       maybeExtendBlockObject(*this, Src);
4334       return CK_BlockPointerToObjCPointerCast;
4335     case Type::STK_Bool:
4336       return CK_PointerToBoolean;
4337     case Type::STK_Integral:
4338       return CK_PointerToIntegral;
4339     case Type::STK_Floating:
4340     case Type::STK_FloatingComplex:
4341     case Type::STK_IntegralComplex:
4342     case Type::STK_MemberPointer:
4343       llvm_unreachable("illegal cast from pointer");
4344     }
4345     llvm_unreachable("Should have returned before this");
4346
4347   case Type::STK_Bool: // casting from bool is like casting from an integer
4348   case Type::STK_Integral:
4349     switch (DestTy->getScalarTypeKind()) {
4350     case Type::STK_CPointer:
4351     case Type::STK_ObjCObjectPointer:
4352     case Type::STK_BlockPointer:
4353       if (Src.get()->isNullPointerConstant(Context,
4354                                            Expr::NPC_ValueDependentIsNull))
4355         return CK_NullToPointer;
4356       return CK_IntegralToPointer;
4357     case Type::STK_Bool:
4358       return CK_IntegralToBoolean;
4359     case Type::STK_Integral:
4360       return CK_IntegralCast;
4361     case Type::STK_Floating:
4362       return CK_IntegralToFloating;
4363     case Type::STK_IntegralComplex:
4364       Src = ImpCastExprToType(Src.take(),
4365                               DestTy->castAs<ComplexType>()->getElementType(),
4366                               CK_IntegralCast);
4367       return CK_IntegralRealToComplex;
4368     case Type::STK_FloatingComplex:
4369       Src = ImpCastExprToType(Src.take(),
4370                               DestTy->castAs<ComplexType>()->getElementType(),
4371                               CK_IntegralToFloating);
4372       return CK_FloatingRealToComplex;
4373     case Type::STK_MemberPointer:
4374       llvm_unreachable("member pointer type in C");
4375     }
4376     llvm_unreachable("Should have returned before this");
4377
4378   case Type::STK_Floating:
4379     switch (DestTy->getScalarTypeKind()) {
4380     case Type::STK_Floating:
4381       return CK_FloatingCast;
4382     case Type::STK_Bool:
4383       return CK_FloatingToBoolean;
4384     case Type::STK_Integral:
4385       return CK_FloatingToIntegral;
4386     case Type::STK_FloatingComplex:
4387       Src = ImpCastExprToType(Src.take(),
4388                               DestTy->castAs<ComplexType>()->getElementType(),
4389                               CK_FloatingCast);
4390       return CK_FloatingRealToComplex;
4391     case Type::STK_IntegralComplex:
4392       Src = ImpCastExprToType(Src.take(),
4393                               DestTy->castAs<ComplexType>()->getElementType(),
4394                               CK_FloatingToIntegral);
4395       return CK_IntegralRealToComplex;
4396     case Type::STK_CPointer:
4397     case Type::STK_ObjCObjectPointer:
4398     case Type::STK_BlockPointer:
4399       llvm_unreachable("valid float->pointer cast?");
4400     case Type::STK_MemberPointer:
4401       llvm_unreachable("member pointer type in C");
4402     }
4403     llvm_unreachable("Should have returned before this");
4404
4405   case Type::STK_FloatingComplex:
4406     switch (DestTy->getScalarTypeKind()) {
4407     case Type::STK_FloatingComplex:
4408       return CK_FloatingComplexCast;
4409     case Type::STK_IntegralComplex:
4410       return CK_FloatingComplexToIntegralComplex;
4411     case Type::STK_Floating: {
4412       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4413       if (Context.hasSameType(ET, DestTy))
4414         return CK_FloatingComplexToReal;
4415       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4416       return CK_FloatingCast;
4417     }
4418     case Type::STK_Bool:
4419       return CK_FloatingComplexToBoolean;
4420     case Type::STK_Integral:
4421       Src = ImpCastExprToType(Src.take(),
4422                               SrcTy->castAs<ComplexType>()->getElementType(),
4423                               CK_FloatingComplexToReal);
4424       return CK_FloatingToIntegral;
4425     case Type::STK_CPointer:
4426     case Type::STK_ObjCObjectPointer:
4427     case Type::STK_BlockPointer:
4428       llvm_unreachable("valid complex float->pointer cast?");
4429     case Type::STK_MemberPointer:
4430       llvm_unreachable("member pointer type in C");
4431     }
4432     llvm_unreachable("Should have returned before this");
4433
4434   case Type::STK_IntegralComplex:
4435     switch (DestTy->getScalarTypeKind()) {
4436     case Type::STK_FloatingComplex:
4437       return CK_IntegralComplexToFloatingComplex;
4438     case Type::STK_IntegralComplex:
4439       return CK_IntegralComplexCast;
4440     case Type::STK_Integral: {
4441       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4442       if (Context.hasSameType(ET, DestTy))
4443         return CK_IntegralComplexToReal;
4444       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4445       return CK_IntegralCast;
4446     }
4447     case Type::STK_Bool:
4448       return CK_IntegralComplexToBoolean;
4449     case Type::STK_Floating:
4450       Src = ImpCastExprToType(Src.take(),
4451                               SrcTy->castAs<ComplexType>()->getElementType(),
4452                               CK_IntegralComplexToReal);
4453       return CK_IntegralToFloating;
4454     case Type::STK_CPointer:
4455     case Type::STK_ObjCObjectPointer:
4456     case Type::STK_BlockPointer:
4457       llvm_unreachable("valid complex int->pointer cast?");
4458     case Type::STK_MemberPointer:
4459       llvm_unreachable("member pointer type in C");
4460     }
4461     llvm_unreachable("Should have returned before this");
4462   }
4463
4464   llvm_unreachable("Unhandled scalar cast");
4465 }
4466
4467 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4468                            CastKind &Kind) {
4469   assert(VectorTy->isVectorType() && "Not a vector type!");
4470
4471   if (Ty->isVectorType() || Ty->isIntegerType()) {
4472     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4473       return Diag(R.getBegin(),
4474                   Ty->isVectorType() ?
4475                   diag::err_invalid_conversion_between_vectors :
4476                   diag::err_invalid_conversion_between_vector_and_integer)
4477         << VectorTy << Ty << R;
4478   } else
4479     return Diag(R.getBegin(),
4480                 diag::err_invalid_conversion_between_vector_and_scalar)
4481       << VectorTy << Ty << R;
4482
4483   Kind = CK_BitCast;
4484   return false;
4485 }
4486
4487 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4488                                     Expr *CastExpr, CastKind &Kind) {
4489   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4490
4491   QualType SrcTy = CastExpr->getType();
4492
4493   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4494   // an ExtVectorType.
4495   // In OpenCL, casts between vectors of different types are not allowed.
4496   // (See OpenCL 6.2).
4497   if (SrcTy->isVectorType()) {
4498     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4499         || (getLangOpts().OpenCL &&
4500             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4501       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4502         << DestTy << SrcTy << R;
4503       return ExprError();
4504     }
4505     Kind = CK_BitCast;
4506     return Owned(CastExpr);
4507   }
4508
4509   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4510   // conversion will take place first from scalar to elt type, and then
4511   // splat from elt type to vector.
4512   if (SrcTy->isPointerType())
4513     return Diag(R.getBegin(),
4514                 diag::err_invalid_conversion_between_vector_and_scalar)
4515       << DestTy << SrcTy << R;
4516
4517   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4518   ExprResult CastExprRes = Owned(CastExpr);
4519   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4520   if (CastExprRes.isInvalid())
4521     return ExprError();
4522   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4523
4524   Kind = CK_VectorSplat;
4525   return Owned(CastExpr);
4526 }
4527
4528 ExprResult
4529 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4530                     Declarator &D, ParsedType &Ty,
4531                     SourceLocation RParenLoc, Expr *CastExpr) {
4532   assert(!D.isInvalidType() && (CastExpr != 0) &&
4533          "ActOnCastExpr(): missing type or expr");
4534
4535   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4536   if (D.isInvalidType())
4537     return ExprError();
4538
4539   if (getLangOpts().CPlusPlus) {
4540     // Check that there are no default arguments (C++ only).
4541     CheckExtraCXXDefaultArguments(D);
4542   }
4543
4544   checkUnusedDeclAttributes(D);
4545
4546   QualType castType = castTInfo->getType();
4547   Ty = CreateParsedType(castType, castTInfo);
4548
4549   bool isVectorLiteral = false;
4550
4551   // Check for an altivec or OpenCL literal,
4552   // i.e. all the elements are integer constants.
4553   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4554   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4555   if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
4556        && castType->isVectorType() && (PE || PLE)) {
4557     if (PLE && PLE->getNumExprs() == 0) {
4558       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4559       return ExprError();
4560     }
4561     if (PE || PLE->getNumExprs() == 1) {
4562       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4563       if (!E->getType()->isVectorType())
4564         isVectorLiteral = true;
4565     }
4566     else
4567       isVectorLiteral = true;
4568   }
4569
4570   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4571   // then handle it as such.
4572   if (isVectorLiteral)
4573     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4574
4575   // If the Expr being casted is a ParenListExpr, handle it specially.
4576   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4577   // sequence of BinOp comma operators.
4578   if (isa<ParenListExpr>(CastExpr)) {
4579     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4580     if (Result.isInvalid()) return ExprError();
4581     CastExpr = Result.take();
4582   }
4583
4584   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4585 }
4586
4587 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4588                                     SourceLocation RParenLoc, Expr *E,
4589                                     TypeSourceInfo *TInfo) {
4590   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4591          "Expected paren or paren list expression");
4592
4593   Expr **exprs;
4594   unsigned numExprs;
4595   Expr *subExpr;
4596   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4597     exprs = PE->getExprs();
4598     numExprs = PE->getNumExprs();
4599   } else {
4600     subExpr = cast<ParenExpr>(E)->getSubExpr();
4601     exprs = &subExpr;
4602     numExprs = 1;
4603   }
4604
4605   QualType Ty = TInfo->getType();
4606   assert(Ty->isVectorType() && "Expected vector type");
4607
4608   SmallVector<Expr *, 8> initExprs;
4609   const VectorType *VTy = Ty->getAs<VectorType>();
4610   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4611   
4612   // '(...)' form of vector initialization in AltiVec: the number of
4613   // initializers must be one or must match the size of the vector.
4614   // If a single value is specified in the initializer then it will be
4615   // replicated to all the components of the vector
4616   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4617     // The number of initializers must be one or must match the size of the
4618     // vector. If a single value is specified in the initializer then it will
4619     // be replicated to all the components of the vector
4620     if (numExprs == 1) {
4621       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4622       ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4623       if (Literal.isInvalid())
4624         return ExprError();
4625       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4626                                   PrepareScalarCast(Literal, ElemTy));
4627       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4628     }
4629     else if (numExprs < numElems) {
4630       Diag(E->getExprLoc(),
4631            diag::err_incorrect_number_of_vector_initializers);
4632       return ExprError();
4633     }
4634     else
4635       initExprs.append(exprs, exprs + numExprs);
4636   }
4637   else {
4638     // For OpenCL, when the number of initializers is a single value,
4639     // it will be replicated to all components of the vector.
4640     if (getLangOpts().OpenCL &&
4641         VTy->getVectorKind() == VectorType::GenericVector &&
4642         numExprs == 1) {
4643         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4644         ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4645         if (Literal.isInvalid())
4646           return ExprError();
4647         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4648                                     PrepareScalarCast(Literal, ElemTy));
4649         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4650     }
4651     
4652     initExprs.append(exprs, exprs + numExprs);
4653   }
4654   // FIXME: This means that pretty-printing the final AST will produce curly
4655   // braces instead of the original commas.
4656   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4657                                                    initExprs, RParenLoc);
4658   initE->setType(Ty);
4659   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4660 }
4661
4662 /// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4663 /// the ParenListExpr into a sequence of comma binary operators.
4664 ExprResult
4665 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4666   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4667   if (!E)
4668     return Owned(OrigExpr);
4669
4670   ExprResult Result(E->getExpr(0));
4671
4672   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4673     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4674                         E->getExpr(i));
4675
4676   if (Result.isInvalid()) return ExprError();
4677
4678   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4679 }
4680
4681 ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4682                                     SourceLocation R,
4683                                     MultiExprArg Val) {
4684   assert(Val.data() != 0 && "ActOnParenOrParenListExpr() missing expr list");
4685   Expr *expr = new (Context) ParenListExpr(Context, L, Val, R);
4686   return Owned(expr);
4687 }
4688
4689 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4690 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4691 /// emitted.
4692 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4693                                       SourceLocation QuestionLoc) {
4694   Expr *NullExpr = LHSExpr;
4695   Expr *NonPointerExpr = RHSExpr;
4696   Expr::NullPointerConstantKind NullKind =
4697       NullExpr->isNullPointerConstant(Context,
4698                                       Expr::NPC_ValueDependentIsNotNull);
4699
4700   if (NullKind == Expr::NPCK_NotNull) {
4701     NullExpr = RHSExpr;
4702     NonPointerExpr = LHSExpr;
4703     NullKind =
4704         NullExpr->isNullPointerConstant(Context,
4705                                         Expr::NPC_ValueDependentIsNotNull);
4706   }
4707
4708   if (NullKind == Expr::NPCK_NotNull)
4709     return false;
4710
4711   if (NullKind == Expr::NPCK_ZeroExpression)
4712     return false;
4713
4714   if (NullKind == Expr::NPCK_ZeroLiteral) {
4715     // In this case, check to make sure that we got here from a "NULL"
4716     // string in the source code.
4717     NullExpr = NullExpr->IgnoreParenImpCasts();
4718     SourceLocation loc = NullExpr->getExprLoc();
4719     if (!findMacroSpelling(loc, "NULL"))
4720       return false;
4721   }
4722
4723   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4724   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4725       << NonPointerExpr->getType() << DiagType
4726       << NonPointerExpr->getSourceRange();
4727   return true;
4728 }
4729
4730 /// \brief Return false if the condition expression is valid, true otherwise.
4731 static bool checkCondition(Sema &S, Expr *Cond) {
4732   QualType CondTy = Cond->getType();
4733
4734   // C99 6.5.15p2
4735   if (CondTy->isScalarType()) return false;
4736
4737   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4738   if (S.getLangOpts().OpenCL && CondTy->isVectorType())
4739     return false;
4740
4741   // Emit the proper error message.
4742   S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
4743                               diag::err_typecheck_cond_expect_scalar :
4744                               diag::err_typecheck_cond_expect_scalar_or_vector)
4745     << CondTy;
4746   return true;
4747 }
4748
4749 /// \brief Return false if the two expressions can be converted to a vector,
4750 /// true otherwise
4751 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4752                                                     ExprResult &RHS,
4753                                                     QualType CondTy) {
4754   // Both operands should be of scalar type.
4755   if (!LHS.get()->getType()->isScalarType()) {
4756     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4757       << CondTy;
4758     return true;
4759   }
4760   if (!RHS.get()->getType()->isScalarType()) {
4761     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4762       << CondTy;
4763     return true;
4764   }
4765
4766   // Implicity convert these scalars to the type of the condition.
4767   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4768   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4769   return false;
4770 }
4771
4772 /// \brief Handle when one or both operands are void type.
4773 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4774                                          ExprResult &RHS) {
4775     Expr *LHSExpr = LHS.get();
4776     Expr *RHSExpr = RHS.get();
4777
4778     if (!LHSExpr->getType()->isVoidType())
4779       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4780         << RHSExpr->getSourceRange();
4781     if (!RHSExpr->getType()->isVoidType())
4782       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4783         << LHSExpr->getSourceRange();
4784     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4785     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4786     return S.Context.VoidTy;
4787 }
4788
4789 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4790 /// true otherwise.
4791 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4792                                         QualType PointerTy) {
4793   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4794       !NullExpr.get()->isNullPointerConstant(S.Context,
4795                                             Expr::NPC_ValueDependentIsNull))
4796     return true;
4797
4798   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4799   return false;
4800 }
4801
4802 /// \brief Checks compatibility between two pointers and return the resulting
4803 /// type.
4804 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4805                                                      ExprResult &RHS,
4806                                                      SourceLocation Loc) {
4807   QualType LHSTy = LHS.get()->getType();
4808   QualType RHSTy = RHS.get()->getType();
4809
4810   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4811     // Two identical pointers types are always compatible.
4812     return LHSTy;
4813   }
4814
4815   QualType lhptee, rhptee;
4816
4817   // Get the pointee types.
4818   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4819     lhptee = LHSBTy->getPointeeType();
4820     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4821   } else {
4822     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4823     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4824   }
4825
4826   // C99 6.5.15p6: If both operands are pointers to compatible types or to
4827   // differently qualified versions of compatible types, the result type is
4828   // a pointer to an appropriately qualified version of the composite
4829   // type.
4830
4831   // Only CVR-qualifiers exist in the standard, and the differently-qualified
4832   // clause doesn't make sense for our extensions. E.g. address space 2 should
4833   // be incompatible with address space 3: they may live on different devices or
4834   // anything.
4835   Qualifiers lhQual = lhptee.getQualifiers();
4836   Qualifiers rhQual = rhptee.getQualifiers();
4837
4838   unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4839   lhQual.removeCVRQualifiers();
4840   rhQual.removeCVRQualifiers();
4841
4842   lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4843   rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4844
4845   QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4846
4847   if (CompositeTy.isNull()) {
4848     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4849       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4850       << RHS.get()->getSourceRange();
4851     // In this situation, we assume void* type. No especially good
4852     // reason, but this is what gcc does, and we do have to pick
4853     // to get a consistent AST.
4854     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4855     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4856     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4857     return incompatTy;
4858   }
4859
4860   // The pointer types are compatible.
4861   QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4862   ResultTy = S.Context.getPointerType(ResultTy);
4863
4864   LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4865   RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4866   return ResultTy;
4867 }
4868
4869 /// \brief Return the resulting type when the operands are both block pointers.
4870 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4871                                                           ExprResult &LHS,
4872                                                           ExprResult &RHS,
4873                                                           SourceLocation Loc) {
4874   QualType LHSTy = LHS.get()->getType();
4875   QualType RHSTy = RHS.get()->getType();
4876
4877   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4878     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4879       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4880       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4881       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4882       return destType;
4883     }
4884     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4885       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4886       << RHS.get()->getSourceRange();
4887     return QualType();
4888   }
4889
4890   // We have 2 block pointer types.
4891   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4892 }
4893
4894 /// \brief Return the resulting type when the operands are both pointers.
4895 static QualType
4896 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4897                                             ExprResult &RHS,
4898                                             SourceLocation Loc) {
4899   // get the pointer types
4900   QualType LHSTy = LHS.get()->getType();
4901   QualType RHSTy = RHS.get()->getType();
4902
4903   // get the "pointed to" types
4904   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4905   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4906
4907   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4908   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4909     // Figure out necessary qualifiers (C99 6.5.15p6)
4910     QualType destPointee
4911       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4912     QualType destType = S.Context.getPointerType(destPointee);
4913     // Add qualifiers if necessary.
4914     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4915     // Promote to void*.
4916     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4917     return destType;
4918   }
4919   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4920     QualType destPointee
4921       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4922     QualType destType = S.Context.getPointerType(destPointee);
4923     // Add qualifiers if necessary.
4924     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4925     // Promote to void*.
4926     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4927     return destType;
4928   }
4929
4930   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4931 }
4932
4933 /// \brief Return false if the first expression is not an integer and the second
4934 /// expression is not a pointer, true otherwise.
4935 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4936                                         Expr* PointerExpr, SourceLocation Loc,
4937                                         bool IsIntFirstExpr) {
4938   if (!PointerExpr->getType()->isPointerType() ||
4939       !Int.get()->getType()->isIntegerType())
4940     return false;
4941
4942   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4943   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4944
4945   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4946     << Expr1->getType() << Expr2->getType()
4947     << Expr1->getSourceRange() << Expr2->getSourceRange();
4948   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4949                             CK_IntegralToPointer);
4950   return true;
4951 }
4952
4953 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4954 /// In that case, LHS = cond.
4955 /// C99 6.5.15
4956 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4957                                         ExprResult &RHS, ExprValueKind &VK,
4958                                         ExprObjectKind &OK,
4959                                         SourceLocation QuestionLoc) {
4960
4961   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4962   if (!LHSResult.isUsable()) return QualType();
4963   LHS = LHSResult;
4964
4965   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4966   if (!RHSResult.isUsable()) return QualType();
4967   RHS = RHSResult;
4968
4969   // C++ is sufficiently different to merit its own checker.
4970   if (getLangOpts().CPlusPlus)
4971     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4972
4973   VK = VK_RValue;
4974   OK = OK_Ordinary;
4975
4976   Cond = UsualUnaryConversions(Cond.take());
4977   if (Cond.isInvalid())
4978     return QualType();
4979   LHS = UsualUnaryConversions(LHS.take());
4980   if (LHS.isInvalid())
4981     return QualType();
4982   RHS = UsualUnaryConversions(RHS.take());
4983   if (RHS.isInvalid())
4984     return QualType();
4985
4986   QualType CondTy = Cond.get()->getType();
4987   QualType LHSTy = LHS.get()->getType();
4988   QualType RHSTy = RHS.get()->getType();
4989
4990   // first, check the condition.
4991   if (checkCondition(*this, Cond.get()))
4992     return QualType();
4993
4994   // Now check the two expressions.
4995   if (LHSTy->isVectorType() || RHSTy->isVectorType())
4996     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4997
4998   // OpenCL: If the condition is a vector, and both operands are scalar,
4999   // attempt to implicity convert them to the vector type to act like the
5000   // built in select.
5001   if (getLangOpts().OpenCL && CondTy->isVectorType())
5002     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
5003       return QualType();
5004   
5005   // If both operands have arithmetic type, do the usual arithmetic conversions
5006   // to find a common type: C99 6.5.15p3,5.
5007   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
5008     UsualArithmeticConversions(LHS, RHS);
5009     if (LHS.isInvalid() || RHS.isInvalid())
5010       return QualType();
5011     return LHS.get()->getType();
5012   }
5013
5014   // If both operands are the same structure or union type, the result is that
5015   // type.
5016   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
5017     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
5018       if (LHSRT->getDecl() == RHSRT->getDecl())
5019         // "If both the operands have structure or union type, the result has
5020         // that type."  This implies that CV qualifiers are dropped.
5021         return LHSTy.getUnqualifiedType();
5022     // FIXME: Type of conditional expression must be complete in C mode.
5023   }
5024
5025   // C99 6.5.15p5: "If both operands have void type, the result has void type."
5026   // The following || allows only one side to be void (a GCC-ism).
5027   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
5028     return checkConditionalVoidType(*this, LHS, RHS);
5029   }
5030
5031   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
5032   // the type of the other operand."
5033   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
5034   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
5035
5036   // All objective-c pointer type analysis is done here.
5037   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
5038                                                         QuestionLoc);
5039   if (LHS.isInvalid() || RHS.isInvalid())
5040     return QualType();
5041   if (!compositeType.isNull())
5042     return compositeType;
5043
5044
5045   // Handle block pointer types.
5046   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
5047     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
5048                                                      QuestionLoc);
5049
5050   // Check constraints for C object pointers types (C99 6.5.15p3,6).
5051   if (LHSTy->isPointerType() && RHSTy->isPointerType())
5052     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
5053                                                        QuestionLoc);
5054
5055   // GCC compatibility: soften pointer/integer mismatch.  Note that
5056   // null pointers have been filtered out by this point.
5057   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
5058       /*isIntFirstExpr=*/true))
5059     return RHSTy;
5060   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
5061       /*isIntFirstExpr=*/false))
5062     return LHSTy;
5063
5064   // Emit a better diagnostic if one of the expressions is a null pointer
5065   // constant and the other is not a pointer type. In this case, the user most
5066   // likely forgot to take the address of the other expression.
5067   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5068     return QualType();
5069
5070   // Otherwise, the operands are not compatible.
5071   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5072     << LHSTy << RHSTy << LHS.get()->getSourceRange()
5073     << RHS.get()->getSourceRange();
5074   return QualType();
5075 }
5076
5077 /// FindCompositeObjCPointerType - Helper method to find composite type of
5078 /// two objective-c pointer types of the two input expressions.
5079 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
5080                                             SourceLocation QuestionLoc) {
5081   QualType LHSTy = LHS.get()->getType();
5082   QualType RHSTy = RHS.get()->getType();
5083
5084   // Handle things like Class and struct objc_class*.  Here we case the result
5085   // to the pseudo-builtin, because that will be implicitly cast back to the
5086   // redefinition type if an attempt is made to access its fields.
5087   if (LHSTy->isObjCClassType() &&
5088       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
5089     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5090     return LHSTy;
5091   }
5092   if (RHSTy->isObjCClassType() &&
5093       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
5094     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5095     return RHSTy;
5096   }
5097   // And the same for struct objc_object* / id
5098   if (LHSTy->isObjCIdType() &&
5099       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
5100     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
5101     return LHSTy;
5102   }
5103   if (RHSTy->isObjCIdType() &&
5104       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
5105     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
5106     return RHSTy;
5107   }
5108   // And the same for struct objc_selector* / SEL
5109   if (Context.isObjCSelType(LHSTy) &&
5110       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
5111     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
5112     return LHSTy;
5113   }
5114   if (Context.isObjCSelType(RHSTy) &&
5115       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
5116     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
5117     return RHSTy;
5118   }
5119   // Check constraints for Objective-C object pointers types.
5120   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
5121
5122     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
5123       // Two identical object pointer types are always compatible.
5124       return LHSTy;
5125     }
5126     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
5127     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
5128     QualType compositeType = LHSTy;
5129
5130     // If both operands are interfaces and either operand can be
5131     // assigned to the other, use that type as the composite
5132     // type. This allows
5133     //   xxx ? (A*) a : (B*) b
5134     // where B is a subclass of A.
5135     //
5136     // Additionally, as for assignment, if either type is 'id'
5137     // allow silent coercion. Finally, if the types are
5138     // incompatible then make sure to use 'id' as the composite
5139     // type so the result is acceptable for sending messages to.
5140
5141     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
5142     // It could return the composite type.
5143     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
5144       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
5145     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
5146       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
5147     } else if ((LHSTy->isObjCQualifiedIdType() ||
5148                 RHSTy->isObjCQualifiedIdType()) &&
5149                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
5150       // Need to handle "id<xx>" explicitly.
5151       // GCC allows qualified id and any Objective-C type to devolve to
5152       // id. Currently localizing to here until clear this should be
5153       // part of ObjCQualifiedIdTypesAreCompatible.
5154       compositeType = Context.getObjCIdType();
5155     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
5156       compositeType = Context.getObjCIdType();
5157     } else if (!(compositeType =
5158                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
5159       ;
5160     else {
5161       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
5162       << LHSTy << RHSTy
5163       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5164       QualType incompatTy = Context.getObjCIdType();
5165       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
5166       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
5167       return incompatTy;
5168     }
5169     // The object pointer types are compatible.
5170     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
5171     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
5172     return compositeType;
5173   }
5174   // Check Objective-C object pointer types and 'void *'
5175   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
5176     if (getLangOpts().ObjCAutoRefCount) {
5177       // ARC forbids the implicit conversion of object pointers to 'void *',
5178       // so these types are not compatible.
5179       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5180           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5181       LHS = RHS = true;
5182       return QualType();
5183     }
5184     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5185     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5186     QualType destPointee
5187     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5188     QualType destType = Context.getPointerType(destPointee);
5189     // Add qualifiers if necessary.
5190     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
5191     // Promote to void*.
5192     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
5193     return destType;
5194   }
5195   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
5196     if (getLangOpts().ObjCAutoRefCount) {
5197       // ARC forbids the implicit conversion of object pointers to 'void *',
5198       // so these types are not compatible.
5199       Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5200           << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5201       LHS = RHS = true;
5202       return QualType();
5203     }
5204     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5205     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5206     QualType destPointee
5207     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5208     QualType destType = Context.getPointerType(destPointee);
5209     // Add qualifiers if necessary.
5210     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
5211     // Promote to void*.
5212     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
5213     return destType;
5214   }
5215   return QualType();
5216 }
5217
5218 /// SuggestParentheses - Emit a note with a fixit hint that wraps
5219 /// ParenRange in parentheses.
5220 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
5221                                const PartialDiagnostic &Note,
5222                                SourceRange ParenRange) {
5223   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5224   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5225       EndLoc.isValid()) {
5226     Self.Diag(Loc, Note)
5227       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5228       << FixItHint::CreateInsertion(EndLoc, ")");
5229   } else {
5230     // We can't display the parentheses, so just show the bare note.
5231     Self.Diag(Loc, Note) << ParenRange;
5232   }
5233 }
5234
5235 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5236   return Opc >= BO_Mul && Opc <= BO_Shr;
5237 }
5238
5239 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5240 /// expression, either using a built-in or overloaded operator,
5241 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5242 /// expression.
5243 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
5244                                    Expr **RHSExprs) {
5245   // Don't strip parenthesis: we should not warn if E is in parenthesis.
5246   E = E->IgnoreImpCasts();
5247   E = E->IgnoreConversionOperator();
5248   E = E->IgnoreImpCasts();
5249
5250   // Built-in binary operator.
5251   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5252     if (IsArithmeticOp(OP->getOpcode())) {
5253       *Opcode = OP->getOpcode();
5254       *RHSExprs = OP->getRHS();
5255       return true;
5256     }
5257   }
5258
5259   // Overloaded operator.
5260   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5261     if (Call->getNumArgs() != 2)
5262       return false;
5263
5264     // Make sure this is really a binary operator that is safe to pass into
5265     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5266     OverloadedOperatorKind OO = Call->getOperator();
5267     if (OO < OO_Plus || OO > OO_Arrow)
5268       return false;
5269
5270     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5271     if (IsArithmeticOp(OpKind)) {
5272       *Opcode = OpKind;
5273       *RHSExprs = Call->getArg(1);
5274       return true;
5275     }
5276   }
5277
5278   return false;
5279 }
5280
5281 static bool IsLogicOp(BinaryOperatorKind Opc) {
5282   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5283 }
5284
5285 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5286 /// or is a logical expression such as (x==y) which has int type, but is
5287 /// commonly interpreted as boolean.
5288 static bool ExprLooksBoolean(Expr *E) {
5289   E = E->IgnoreParenImpCasts();
5290
5291   if (E->getType()->isBooleanType())
5292     return true;
5293   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5294     return IsLogicOp(OP->getOpcode());
5295   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5296     return OP->getOpcode() == UO_LNot;
5297
5298   return false;
5299 }
5300
5301 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5302 /// and binary operator are mixed in a way that suggests the programmer assumed
5303 /// the conditional operator has higher precedence, for example:
5304 /// "int x = a + someBinaryCondition ? 1 : 2".
5305 static void DiagnoseConditionalPrecedence(Sema &Self,
5306                                           SourceLocation OpLoc,
5307                                           Expr *Condition,
5308                                           Expr *LHSExpr,
5309                                           Expr *RHSExpr) {
5310   BinaryOperatorKind CondOpcode;
5311   Expr *CondRHS;
5312
5313   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
5314     return;
5315   if (!ExprLooksBoolean(CondRHS))
5316     return;
5317
5318   // The condition is an arithmetic binary expression, with a right-
5319   // hand side that looks boolean, so warn.
5320
5321   Self.Diag(OpLoc, diag::warn_precedence_conditional)
5322       << Condition->getSourceRange()
5323       << BinaryOperator::getOpcodeStr(CondOpcode);
5324
5325   SuggestParentheses(Self, OpLoc,
5326     Self.PDiag(diag::note_precedence_silence)
5327       << BinaryOperator::getOpcodeStr(CondOpcode),
5328     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
5329
5330   SuggestParentheses(Self, OpLoc,
5331     Self.PDiag(diag::note_precedence_conditional_first),
5332     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
5333 }
5334
5335 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
5336 /// in the case of a the GNU conditional expr extension.
5337 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
5338                                     SourceLocation ColonLoc,
5339                                     Expr *CondExpr, Expr *LHSExpr,
5340                                     Expr *RHSExpr) {
5341   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5342   // was the condition.
5343   OpaqueValueExpr *opaqueValue = 0;
5344   Expr *commonExpr = 0;
5345   if (LHSExpr == 0) {
5346     commonExpr = CondExpr;
5347
5348     // We usually want to apply unary conversions *before* saving, except
5349     // in the special case of a C++ l-value conditional.
5350     if (!(getLangOpts().CPlusPlus
5351           && !commonExpr->isTypeDependent()
5352           && commonExpr->getValueKind() == RHSExpr->getValueKind()
5353           && commonExpr->isGLValue()
5354           && commonExpr->isOrdinaryOrBitFieldObject()
5355           && RHSExpr->isOrdinaryOrBitFieldObject()
5356           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
5357       ExprResult commonRes = UsualUnaryConversions(commonExpr);
5358       if (commonRes.isInvalid())
5359         return ExprError();
5360       commonExpr = commonRes.take();
5361     }
5362
5363     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5364                                                 commonExpr->getType(),
5365                                                 commonExpr->getValueKind(),
5366                                                 commonExpr->getObjectKind(),
5367                                                 commonExpr);
5368     LHSExpr = CondExpr = opaqueValue;
5369   }
5370
5371   ExprValueKind VK = VK_RValue;
5372   ExprObjectKind OK = OK_Ordinary;
5373   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5374   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
5375                                              VK, OK, QuestionLoc);
5376   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5377       RHS.isInvalid())
5378     return ExprError();
5379
5380   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5381                                 RHS.get());
5382
5383   if (!commonExpr)
5384     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5385                                                    LHS.take(), ColonLoc, 
5386                                                    RHS.take(), result, VK, OK));
5387
5388   return Owned(new (Context)
5389     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
5390                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
5391                               OK));
5392 }
5393
5394 // checkPointerTypesForAssignment - This is a very tricky routine (despite
5395 // being closely modeled after the C99 spec:-). The odd characteristic of this
5396 // routine is it effectively iqnores the qualifiers on the top level pointee.
5397 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5398 // FIXME: add a couple examples in this comment.
5399 static Sema::AssignConvertType
5400 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5401   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5402   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5403
5404   // get the "pointed to" type (ignoring qualifiers at the top level)
5405   const Type *lhptee, *rhptee;
5406   Qualifiers lhq, rhq;
5407   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5408   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
5409
5410   Sema::AssignConvertType ConvTy = Sema::Compatible;
5411
5412   // C99 6.5.16.1p1: This following citation is common to constraints
5413   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5414   // qualifiers of the type *pointed to* by the right;
5415   Qualifiers lq;
5416
5417   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5418   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5419       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5420     // Ignore lifetime for further calculation.
5421     lhq.removeObjCLifetime();
5422     rhq.removeObjCLifetime();
5423   }
5424
5425   if (!lhq.compatiblyIncludes(rhq)) {
5426     // Treat address-space mismatches as fatal.  TODO: address subspaces
5427     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5428       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5429
5430     // It's okay to add or remove GC or lifetime qualifiers when converting to
5431     // and from void*.
5432     else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
5433                         .compatiblyIncludes(
5434                                 rhq.withoutObjCGCAttr().withoutObjCLifetime())
5435              && (lhptee->isVoidType() || rhptee->isVoidType()))
5436       ; // keep old
5437
5438     // Treat lifetime mismatches as fatal.
5439     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5440       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5441     
5442     // For GCC compatibility, other qualifier mismatches are treated
5443     // as still compatible in C.
5444     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5445   }
5446
5447   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5448   // incomplete type and the other is a pointer to a qualified or unqualified
5449   // version of void...
5450   if (lhptee->isVoidType()) {
5451     if (rhptee->isIncompleteOrObjectType())
5452       return ConvTy;
5453
5454     // As an extension, we allow cast to/from void* to function pointer.
5455     assert(rhptee->isFunctionType());
5456     return Sema::FunctionVoidPointer;
5457   }
5458
5459   if (rhptee->isVoidType()) {
5460     if (lhptee->isIncompleteOrObjectType())
5461       return ConvTy;
5462
5463     // As an extension, we allow cast to/from void* to function pointer.
5464     assert(lhptee->isFunctionType());
5465     return Sema::FunctionVoidPointer;
5466   }
5467
5468   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5469   // unqualified versions of compatible types, ...
5470   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5471   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5472     // Check if the pointee types are compatible ignoring the sign.
5473     // We explicitly check for char so that we catch "char" vs
5474     // "unsigned char" on systems where "char" is unsigned.
5475     if (lhptee->isCharType())
5476       ltrans = S.Context.UnsignedCharTy;
5477     else if (lhptee->hasSignedIntegerRepresentation())
5478       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5479
5480     if (rhptee->isCharType())
5481       rtrans = S.Context.UnsignedCharTy;
5482     else if (rhptee->hasSignedIntegerRepresentation())
5483       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5484
5485     if (ltrans == rtrans) {
5486       // Types are compatible ignoring the sign. Qualifier incompatibility
5487       // takes priority over sign incompatibility because the sign
5488       // warning can be disabled.
5489       if (ConvTy != Sema::Compatible)
5490         return ConvTy;
5491
5492       return Sema::IncompatiblePointerSign;
5493     }
5494
5495     // If we are a multi-level pointer, it's possible that our issue is simply
5496     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5497     // the eventual target type is the same and the pointers have the same
5498     // level of indirection, this must be the issue.
5499     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5500       do {
5501         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5502         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5503       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5504
5505       if (lhptee == rhptee)
5506         return Sema::IncompatibleNestedPointerQualifiers;
5507     }
5508
5509     // General pointer incompatibility takes priority over qualifiers.
5510     return Sema::IncompatiblePointer;
5511   }
5512   if (!S.getLangOpts().CPlusPlus &&
5513       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5514     return Sema::IncompatiblePointer;
5515   return ConvTy;
5516 }
5517
5518 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5519 /// block pointer types are compatible or whether a block and normal pointer
5520 /// are compatible. It is more restrict than comparing two function pointer
5521 // types.
5522 static Sema::AssignConvertType
5523 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5524                                     QualType RHSType) {
5525   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5526   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5527
5528   QualType lhptee, rhptee;
5529
5530   // get the "pointed to" type (ignoring qualifiers at the top level)
5531   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5532   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5533
5534   // In C++, the types have to match exactly.
5535   if (S.getLangOpts().CPlusPlus)
5536     return Sema::IncompatibleBlockPointer;
5537
5538   Sema::AssignConvertType ConvTy = Sema::Compatible;
5539
5540   // For blocks we enforce that qualifiers are identical.
5541   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5542     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5543
5544   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5545     return Sema::IncompatibleBlockPointer;
5546
5547   return ConvTy;
5548 }
5549
5550 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5551 /// for assignment compatibility.
5552 static Sema::AssignConvertType
5553 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5554                                    QualType RHSType) {
5555   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5556   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5557
5558   if (LHSType->isObjCBuiltinType()) {
5559     // Class is not compatible with ObjC object pointers.
5560     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5561         !RHSType->isObjCQualifiedClassType())
5562       return Sema::IncompatiblePointer;
5563     return Sema::Compatible;
5564   }
5565   if (RHSType->isObjCBuiltinType()) {
5566     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5567         !LHSType->isObjCQualifiedClassType())
5568       return Sema::IncompatiblePointer;
5569     return Sema::Compatible;
5570   }
5571   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5572   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5573
5574   if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5575       // make an exception for id<P>
5576       !LHSType->isObjCQualifiedIdType())
5577     return Sema::CompatiblePointerDiscardsQualifiers;
5578
5579   if (S.Context.typesAreCompatible(LHSType, RHSType))
5580     return Sema::Compatible;
5581   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5582     return Sema::IncompatibleObjCQualifiedId;
5583   return Sema::IncompatiblePointer;
5584 }
5585
5586 Sema::AssignConvertType
5587 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5588                                  QualType LHSType, QualType RHSType) {
5589   // Fake up an opaque expression.  We don't actually care about what
5590   // cast operations are required, so if CheckAssignmentConstraints
5591   // adds casts to this they'll be wasted, but fortunately that doesn't
5592   // usually happen on valid code.
5593   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5594   ExprResult RHSPtr = &RHSExpr;
5595   CastKind K = CK_Invalid;
5596
5597   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5598 }
5599
5600 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5601 /// has code to accommodate several GCC extensions when type checking
5602 /// pointers. Here are some objectionable examples that GCC considers warnings:
5603 ///
5604 ///  int a, *pint;
5605 ///  short *pshort;
5606 ///  struct foo *pfoo;
5607 ///
5608 ///  pint = pshort; // warning: assignment from incompatible pointer type
5609 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5610 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5611 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5612 ///
5613 /// As a result, the code for dealing with pointers is more complex than the
5614 /// C99 spec dictates.
5615 ///
5616 /// Sets 'Kind' for any result kind except Incompatible.
5617 Sema::AssignConvertType
5618 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5619                                  CastKind &Kind) {
5620   QualType RHSType = RHS.get()->getType();
5621   QualType OrigLHSType = LHSType;
5622
5623   // Get canonical types.  We're not formatting these types, just comparing
5624   // them.
5625   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5626   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5627
5628
5629   // Common case: no conversion required.
5630   if (LHSType == RHSType) {
5631     Kind = CK_NoOp;
5632     return Compatible;
5633   }
5634
5635   // If we have an atomic type, try a non-atomic assignment, then just add an
5636   // atomic qualification step.
5637   if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5638     Sema::AssignConvertType result =
5639       CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5640     if (result != Compatible)
5641       return result;
5642     if (Kind != CK_NoOp)
5643       RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5644     Kind = CK_NonAtomicToAtomic;
5645     return Compatible;
5646   }
5647
5648   // If the left-hand side is a reference type, then we are in a
5649   // (rare!) case where we've allowed the use of references in C,
5650   // e.g., as a parameter type in a built-in function. In this case,
5651   // just make sure that the type referenced is compatible with the
5652   // right-hand side type. The caller is responsible for adjusting
5653   // LHSType so that the resulting expression does not have reference
5654   // type.
5655   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5656     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5657       Kind = CK_LValueBitCast;
5658       return Compatible;
5659     }
5660     return Incompatible;
5661   }
5662
5663   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5664   // to the same ExtVector type.
5665   if (LHSType->isExtVectorType()) {
5666     if (RHSType->isExtVectorType())
5667       return Incompatible;
5668     if (RHSType->isArithmeticType()) {
5669       // CK_VectorSplat does T -> vector T, so first cast to the
5670       // element type.
5671       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5672       if (elType != RHSType) {
5673         Kind = PrepareScalarCast(RHS, elType);
5674         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5675       }
5676       Kind = CK_VectorSplat;
5677       return Compatible;
5678     }
5679   }
5680
5681   // Conversions to or from vector type.
5682   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5683     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5684       // Allow assignments of an AltiVec vector type to an equivalent GCC
5685       // vector type and vice versa
5686       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5687         Kind = CK_BitCast;
5688         return Compatible;
5689       }
5690
5691       // If we are allowing lax vector conversions, and LHS and RHS are both
5692       // vectors, the total size only needs to be the same. This is a bitcast;
5693       // no bits are changed but the result type is different.
5694       if (getLangOpts().LaxVectorConversions &&
5695           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5696         Kind = CK_BitCast;
5697         return IncompatibleVectors;
5698       }
5699     }
5700     return Incompatible;
5701   }
5702
5703   // Arithmetic conversions.
5704   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5705       !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
5706     Kind = PrepareScalarCast(RHS, LHSType);
5707     return Compatible;
5708   }
5709
5710   // Conversions to normal pointers.
5711   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5712     // U* -> T*
5713     if (isa<PointerType>(RHSType)) {
5714       Kind = CK_BitCast;
5715       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5716     }
5717
5718     // int -> T*
5719     if (RHSType->isIntegerType()) {
5720       Kind = CK_IntegralToPointer; // FIXME: null?
5721       return IntToPointer;
5722     }
5723
5724     // C pointers are not compatible with ObjC object pointers,
5725     // with two exceptions:
5726     if (isa<ObjCObjectPointerType>(RHSType)) {
5727       //  - conversions to void*
5728       if (LHSPointer->getPointeeType()->isVoidType()) {
5729         Kind = CK_BitCast;
5730         return Compatible;
5731       }
5732
5733       //  - conversions from 'Class' to the redefinition type
5734       if (RHSType->isObjCClassType() &&
5735           Context.hasSameType(LHSType, 
5736                               Context.getObjCClassRedefinitionType())) {
5737         Kind = CK_BitCast;
5738         return Compatible;
5739       }
5740
5741       Kind = CK_BitCast;
5742       return IncompatiblePointer;
5743     }
5744
5745     // U^ -> void*
5746     if (RHSType->getAs<BlockPointerType>()) {
5747       if (LHSPointer->getPointeeType()->isVoidType()) {
5748         Kind = CK_BitCast;
5749         return Compatible;
5750       }
5751     }
5752
5753     return Incompatible;
5754   }
5755
5756   // Conversions to block pointers.
5757   if (isa<BlockPointerType>(LHSType)) {
5758     // U^ -> T^
5759     if (RHSType->isBlockPointerType()) {
5760       Kind = CK_BitCast;
5761       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5762     }
5763
5764     // int or null -> T^
5765     if (RHSType->isIntegerType()) {
5766       Kind = CK_IntegralToPointer; // FIXME: null
5767       return IntToBlockPointer;
5768     }
5769
5770     // id -> T^
5771     if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
5772       Kind = CK_AnyPointerToBlockPointerCast;
5773       return Compatible;
5774     }
5775
5776     // void* -> T^
5777     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5778       if (RHSPT->getPointeeType()->isVoidType()) {
5779         Kind = CK_AnyPointerToBlockPointerCast;
5780         return Compatible;
5781       }
5782
5783     return Incompatible;
5784   }
5785
5786   // Conversions to Objective-C pointers.
5787   if (isa<ObjCObjectPointerType>(LHSType)) {
5788     // A* -> B*
5789     if (RHSType->isObjCObjectPointerType()) {
5790       Kind = CK_BitCast;
5791       Sema::AssignConvertType result = 
5792         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5793       if (getLangOpts().ObjCAutoRefCount &&
5794           result == Compatible && 
5795           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5796         result = IncompatibleObjCWeakRef;
5797       return result;
5798     }
5799
5800     // int or null -> A*
5801     if (RHSType->isIntegerType()) {
5802       Kind = CK_IntegralToPointer; // FIXME: null
5803       return IntToPointer;
5804     }
5805
5806     // In general, C pointers are not compatible with ObjC object pointers,
5807     // with two exceptions:
5808     if (isa<PointerType>(RHSType)) {
5809       Kind = CK_CPointerToObjCPointerCast;
5810
5811       //  - conversions from 'void*'
5812       if (RHSType->isVoidPointerType()) {
5813         return Compatible;
5814       }
5815
5816       //  - conversions to 'Class' from its redefinition type
5817       if (LHSType->isObjCClassType() &&
5818           Context.hasSameType(RHSType, 
5819                               Context.getObjCClassRedefinitionType())) {
5820         return Compatible;
5821       }
5822
5823       return IncompatiblePointer;
5824     }
5825
5826     // T^ -> A*
5827     if (RHSType->isBlockPointerType()) {
5828       maybeExtendBlockObject(*this, RHS);
5829       Kind = CK_BlockPointerToObjCPointerCast;
5830       return Compatible;
5831     }
5832
5833     return Incompatible;
5834   }
5835
5836   // Conversions from pointers that are not covered by the above.
5837   if (isa<PointerType>(RHSType)) {
5838     // T* -> _Bool
5839     if (LHSType == Context.BoolTy) {
5840       Kind = CK_PointerToBoolean;
5841       return Compatible;
5842     }
5843
5844     // T* -> int
5845     if (LHSType->isIntegerType()) {
5846       Kind = CK_PointerToIntegral;
5847       return PointerToInt;
5848     }
5849
5850     return Incompatible;
5851   }
5852
5853   // Conversions from Objective-C pointers that are not covered by the above.
5854   if (isa<ObjCObjectPointerType>(RHSType)) {
5855     // T* -> _Bool
5856     if (LHSType == Context.BoolTy) {
5857       Kind = CK_PointerToBoolean;
5858       return Compatible;
5859     }
5860
5861     // T* -> int
5862     if (LHSType->isIntegerType()) {
5863       Kind = CK_PointerToIntegral;
5864       return PointerToInt;
5865     }
5866
5867     return Incompatible;
5868   }
5869
5870   // struct A -> struct B
5871   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5872     if (Context.typesAreCompatible(LHSType, RHSType)) {
5873       Kind = CK_NoOp;
5874       return Compatible;
5875     }
5876   }
5877
5878   return Incompatible;
5879 }
5880
5881 /// \brief Constructs a transparent union from an expression that is
5882 /// used to initialize the transparent union.
5883 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5884                                       ExprResult &EResult, QualType UnionType,
5885                                       FieldDecl *Field) {
5886   // Build an initializer list that designates the appropriate member
5887   // of the transparent union.
5888   Expr *E = EResult.take();
5889   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5890                                                    E, SourceLocation());
5891   Initializer->setType(UnionType);
5892   Initializer->setInitializedFieldInUnion(Field);
5893
5894   // Build a compound literal constructing a value of the transparent
5895   // union type from this initializer list.
5896   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5897   EResult = S.Owned(
5898     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5899                                 VK_RValue, Initializer, false));
5900 }
5901
5902 Sema::AssignConvertType
5903 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5904                                                ExprResult &RHS) {
5905   QualType RHSType = RHS.get()->getType();
5906
5907   // If the ArgType is a Union type, we want to handle a potential
5908   // transparent_union GCC extension.
5909   const RecordType *UT = ArgType->getAsUnionType();
5910   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5911     return Incompatible;
5912
5913   // The field to initialize within the transparent union.
5914   RecordDecl *UD = UT->getDecl();
5915   FieldDecl *InitField = 0;
5916   // It's compatible if the expression matches any of the fields.
5917   for (RecordDecl::field_iterator it = UD->field_begin(),
5918          itend = UD->field_end();
5919        it != itend; ++it) {
5920     if (it->getType()->isPointerType()) {
5921       // If the transparent union contains a pointer type, we allow:
5922       // 1) void pointer
5923       // 2) null pointer constant
5924       if (RHSType->isPointerType())
5925         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5926           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5927           InitField = *it;
5928           break;
5929         }
5930
5931       if (RHS.get()->isNullPointerConstant(Context,
5932                                            Expr::NPC_ValueDependentIsNull)) {
5933         RHS = ImpCastExprToType(RHS.take(), it->getType(),
5934                                 CK_NullToPointer);
5935         InitField = *it;
5936         break;
5937       }
5938     }
5939
5940     CastKind Kind = CK_Invalid;
5941     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5942           == Compatible) {
5943       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5944       InitField = *it;
5945       break;
5946     }
5947   }
5948
5949   if (!InitField)
5950     return Incompatible;
5951
5952   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5953   return Compatible;
5954 }
5955
5956 Sema::AssignConvertType
5957 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5958                                        bool Diagnose) {
5959   if (getLangOpts().CPlusPlus) {
5960     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5961       // C++ 5.17p3: If the left operand is not of class type, the
5962       // expression is implicitly converted (C++ 4) to the
5963       // cv-unqualified type of the left operand.
5964       ExprResult Res;
5965       if (Diagnose) {
5966         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5967                                         AA_Assigning);
5968       } else {
5969         ImplicitConversionSequence ICS =
5970             TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5971                                   /*SuppressUserConversions=*/false,
5972                                   /*AllowExplicit=*/false,
5973                                   /*InOverloadResolution=*/false,
5974                                   /*CStyle=*/false,
5975                                   /*AllowObjCWritebackConversion=*/false);
5976         if (ICS.isFailure())
5977           return Incompatible;
5978         Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5979                                         ICS, AA_Assigning);
5980       }
5981       if (Res.isInvalid())
5982         return Incompatible;
5983       Sema::AssignConvertType result = Compatible;
5984       if (getLangOpts().ObjCAutoRefCount &&
5985           !CheckObjCARCUnavailableWeakConversion(LHSType,
5986                                                  RHS.get()->getType()))
5987         result = IncompatibleObjCWeakRef;
5988       RHS = Res;
5989       return result;
5990     }
5991
5992     // FIXME: Currently, we fall through and treat C++ classes like C
5993     // structures.
5994     // FIXME: We also fall through for atomics; not sure what should
5995     // happen there, though.
5996   }
5997
5998   // C99 6.5.16.1p1: the left operand is a pointer and the right is
5999   // a null pointer constant.
6000   if ((LHSType->isPointerType() ||
6001        LHSType->isObjCObjectPointerType() ||
6002        LHSType->isBlockPointerType())
6003       && RHS.get()->isNullPointerConstant(Context,
6004                                           Expr::NPC_ValueDependentIsNull)) {
6005     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6006     return Compatible;
6007   }
6008
6009   // This check seems unnatural, however it is necessary to ensure the proper
6010   // conversion of functions/arrays. If the conversion were done for all
6011   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
6012   // expressions that suppress this implicit conversion (&, sizeof).
6013   //
6014   // Suppress this for references: C++ 8.5.3p5.
6015   if (!LHSType->isReferenceType()) {
6016     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6017     if (RHS.isInvalid())
6018       return Incompatible;
6019   }
6020
6021   CastKind Kind = CK_Invalid;
6022   Sema::AssignConvertType result =
6023     CheckAssignmentConstraints(LHSType, RHS, Kind);
6024
6025   // C99 6.5.16.1p2: The value of the right operand is converted to the
6026   // type of the assignment expression.
6027   // CheckAssignmentConstraints allows the left-hand side to be a reference,
6028   // so that we can use references in built-in functions even in C.
6029   // The getNonReferenceType() call makes sure that the resulting expression
6030   // does not have reference type.
6031   if (result != Incompatible && RHS.get()->getType() != LHSType)
6032     RHS = ImpCastExprToType(RHS.take(),
6033                             LHSType.getNonLValueExprType(Context), Kind);
6034   return result;
6035 }
6036
6037 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
6038                                ExprResult &RHS) {
6039   Diag(Loc, diag::err_typecheck_invalid_operands)
6040     << LHS.get()->getType() << RHS.get()->getType()
6041     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6042   return QualType();
6043 }
6044
6045 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
6046                                    SourceLocation Loc, bool IsCompAssign) {
6047   if (!IsCompAssign) {
6048     LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
6049     if (LHS.isInvalid())
6050       return QualType();
6051   }
6052   RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
6053   if (RHS.isInvalid())
6054     return QualType();
6055
6056   // For conversion purposes, we ignore any qualifiers.
6057   // For example, "const float" and "float" are equivalent.
6058   QualType LHSType =
6059     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
6060   QualType RHSType =
6061     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
6062
6063   // If the vector types are identical, return.
6064   if (LHSType == RHSType)
6065     return LHSType;
6066
6067   // Handle the case of equivalent AltiVec and GCC vector types
6068   if (LHSType->isVectorType() && RHSType->isVectorType() &&
6069       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
6070     if (LHSType->isExtVectorType()) {
6071       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6072       return LHSType;
6073     }
6074
6075     if (!IsCompAssign)
6076       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6077     return RHSType;
6078   }
6079
6080   if (getLangOpts().LaxVectorConversions &&
6081       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
6082     // If we are allowing lax vector conversions, and LHS and RHS are both
6083     // vectors, the total size only needs to be the same. This is a
6084     // bitcast; no bits are changed but the result type is different.
6085     // FIXME: Should we really be allowing this?
6086     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6087     return LHSType;
6088   }
6089
6090   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
6091   // swap back (so that we don't reverse the inputs to a subtract, for instance.
6092   bool swapped = false;
6093   if (RHSType->isExtVectorType() && !IsCompAssign) {
6094     swapped = true;
6095     std::swap(RHS, LHS);
6096     std::swap(RHSType, LHSType);
6097   }
6098
6099   // Handle the case of an ext vector and scalar.
6100   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
6101     QualType EltTy = LV->getElementType();
6102     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
6103       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
6104       if (order > 0)
6105         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
6106       if (order >= 0) {
6107         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6108         if (swapped) std::swap(RHS, LHS);
6109         return LHSType;
6110       }
6111     }
6112     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
6113         RHSType->isRealFloatingType()) {
6114       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
6115       if (order > 0)
6116         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
6117       if (order >= 0) {
6118         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
6119         if (swapped) std::swap(RHS, LHS);
6120         return LHSType;
6121       }
6122     }
6123   }
6124
6125   // Vectors of different size or scalar and non-ext-vector are errors.
6126   if (swapped) std::swap(RHS, LHS);
6127   Diag(Loc, diag::err_typecheck_vector_not_convertable)
6128     << LHS.get()->getType() << RHS.get()->getType()
6129     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6130   return QualType();
6131 }
6132
6133 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
6134 // expression.  These are mainly cases where the null pointer is used as an
6135 // integer instead of a pointer.
6136 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
6137                                 SourceLocation Loc, bool IsCompare) {
6138   // The canonical way to check for a GNU null is with isNullPointerConstant,
6139   // but we use a bit of a hack here for speed; this is a relatively
6140   // hot path, and isNullPointerConstant is slow.
6141   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
6142   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
6143
6144   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
6145
6146   // Avoid analyzing cases where the result will either be invalid (and
6147   // diagnosed as such) or entirely valid and not something to warn about.
6148   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
6149       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
6150     return;
6151
6152   // Comparison operations would not make sense with a null pointer no matter
6153   // what the other expression is.
6154   if (!IsCompare) {
6155     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
6156         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
6157         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
6158     return;
6159   }
6160
6161   // The rest of the operations only make sense with a null pointer
6162   // if the other expression is a pointer.
6163   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
6164       NonNullType->canDecayToPointerType())
6165     return;
6166
6167   S.Diag(Loc, diag::warn_null_in_comparison_operation)
6168       << LHSNull /* LHS is NULL */ << NonNullType
6169       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6170 }
6171
6172 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
6173                                            SourceLocation Loc,
6174                                            bool IsCompAssign, bool IsDiv) {
6175   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6176
6177   if (LHS.get()->getType()->isVectorType() ||
6178       RHS.get()->getType()->isVectorType())
6179     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6180
6181   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6182   if (LHS.isInvalid() || RHS.isInvalid())
6183     return QualType();
6184
6185
6186   if (compType.isNull() || !compType->isArithmeticType())
6187     return InvalidOperands(Loc, LHS, RHS);
6188
6189   // Check for division by zero.
6190   if (IsDiv &&
6191       RHS.get()->isNullPointerConstant(Context,
6192                                        Expr::NPC_ValueDependentIsNotNull))
6193     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6194                                           << RHS.get()->getSourceRange());
6195
6196   return compType;
6197 }
6198
6199 QualType Sema::CheckRemainderOperands(
6200   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6201   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6202
6203   if (LHS.get()->getType()->isVectorType() ||
6204       RHS.get()->getType()->isVectorType()) {
6205     if (LHS.get()->getType()->hasIntegerRepresentation() && 
6206         RHS.get()->getType()->hasIntegerRepresentation())
6207       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6208     return InvalidOperands(Loc, LHS, RHS);
6209   }
6210
6211   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
6212   if (LHS.isInvalid() || RHS.isInvalid())
6213     return QualType();
6214
6215   if (compType.isNull() || !compType->isIntegerType())
6216     return InvalidOperands(Loc, LHS, RHS);
6217
6218   // Check for remainder by zero.
6219   if (RHS.get()->isNullPointerConstant(Context,
6220                                        Expr::NPC_ValueDependentIsNotNull))
6221     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6222                                  << RHS.get()->getSourceRange());
6223
6224   return compType;
6225 }
6226
6227 /// \brief Diagnose invalid arithmetic on two void pointers.
6228 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
6229                                                 Expr *LHSExpr, Expr *RHSExpr) {
6230   S.Diag(Loc, S.getLangOpts().CPlusPlus
6231                 ? diag::err_typecheck_pointer_arith_void_type
6232                 : diag::ext_gnu_void_ptr)
6233     << 1 /* two pointers */ << LHSExpr->getSourceRange()
6234                             << RHSExpr->getSourceRange();
6235 }
6236
6237 /// \brief Diagnose invalid arithmetic on a void pointer.
6238 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6239                                             Expr *Pointer) {
6240   S.Diag(Loc, S.getLangOpts().CPlusPlus
6241                 ? diag::err_typecheck_pointer_arith_void_type
6242                 : diag::ext_gnu_void_ptr)
6243     << 0 /* one pointer */ << Pointer->getSourceRange();
6244 }
6245
6246 /// \brief Diagnose invalid arithmetic on two function pointers.
6247 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6248                                                     Expr *LHS, Expr *RHS) {
6249   assert(LHS->getType()->isAnyPointerType());
6250   assert(RHS->getType()->isAnyPointerType());
6251   S.Diag(Loc, S.getLangOpts().CPlusPlus
6252                 ? diag::err_typecheck_pointer_arith_function_type
6253                 : diag::ext_gnu_ptr_func_arith)
6254     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6255     // We only show the second type if it differs from the first.
6256     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6257                                                    RHS->getType())
6258     << RHS->getType()->getPointeeType()
6259     << LHS->getSourceRange() << RHS->getSourceRange();
6260 }
6261
6262 /// \brief Diagnose invalid arithmetic on a function pointer.
6263 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6264                                                 Expr *Pointer) {
6265   assert(Pointer->getType()->isAnyPointerType());
6266   S.Diag(Loc, S.getLangOpts().CPlusPlus
6267                 ? diag::err_typecheck_pointer_arith_function_type
6268                 : diag::ext_gnu_ptr_func_arith)
6269     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6270     << 0 /* one pointer, so only one type */
6271     << Pointer->getSourceRange();
6272 }
6273
6274 /// \brief Emit error if Operand is incomplete pointer type
6275 ///
6276 /// \returns True if pointer has incomplete type
6277 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6278                                                  Expr *Operand) {
6279   assert(Operand->getType()->isAnyPointerType() &&
6280          !Operand->getType()->isDependentType());
6281   QualType PointeeTy = Operand->getType()->getPointeeType();
6282   return S.RequireCompleteType(Loc, PointeeTy,
6283                                diag::err_typecheck_arithmetic_incomplete_type,
6284                                PointeeTy, Operand->getSourceRange());
6285 }
6286
6287 /// \brief Check the validity of an arithmetic pointer operand.
6288 ///
6289 /// If the operand has pointer type, this code will check for pointer types
6290 /// which are invalid in arithmetic operations. These will be diagnosed
6291 /// appropriately, including whether or not the use is supported as an
6292 /// extension.
6293 ///
6294 /// \returns True when the operand is valid to use (even if as an extension).
6295 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6296                                             Expr *Operand) {
6297   if (!Operand->getType()->isAnyPointerType()) return true;
6298
6299   QualType PointeeTy = Operand->getType()->getPointeeType();
6300   if (PointeeTy->isVoidType()) {
6301     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6302     return !S.getLangOpts().CPlusPlus;
6303   }
6304   if (PointeeTy->isFunctionType()) {
6305     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6306     return !S.getLangOpts().CPlusPlus;
6307   }
6308
6309   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
6310
6311   return true;
6312 }
6313
6314 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6315 /// operands.
6316 ///
6317 /// This routine will diagnose any invalid arithmetic on pointer operands much
6318 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
6319 /// for emitting a single diagnostic even for operations where both LHS and RHS
6320 /// are (potentially problematic) pointers.
6321 ///
6322 /// \returns True when the operand is valid to use (even if as an extension).
6323 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
6324                                                 Expr *LHSExpr, Expr *RHSExpr) {
6325   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6326   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
6327   if (!isLHSPointer && !isRHSPointer) return true;
6328
6329   QualType LHSPointeeTy, RHSPointeeTy;
6330   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6331   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
6332
6333   // Check for arithmetic on pointers to incomplete types.
6334   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6335   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6336   if (isLHSVoidPtr || isRHSVoidPtr) {
6337     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6338     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6339     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
6340
6341     return !S.getLangOpts().CPlusPlus;
6342   }
6343
6344   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6345   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6346   if (isLHSFuncPtr || isRHSFuncPtr) {
6347     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6348     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6349                                                                 RHSExpr);
6350     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
6351
6352     return !S.getLangOpts().CPlusPlus;
6353   }
6354
6355   if (isLHSPointer && checkArithmeticIncompletePointerType(S, Loc, LHSExpr))
6356     return false;
6357   if (isRHSPointer && checkArithmeticIncompletePointerType(S, Loc, RHSExpr))
6358     return false;
6359
6360   return true;
6361 }
6362
6363 /// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6364 /// literal.
6365 static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6366                                   Expr *LHSExpr, Expr *RHSExpr) {
6367   StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6368   Expr* IndexExpr = RHSExpr;
6369   if (!StrExpr) {
6370     StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6371     IndexExpr = LHSExpr;
6372   }
6373
6374   bool IsStringPlusInt = StrExpr &&
6375       IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6376   if (!IsStringPlusInt)
6377     return;
6378
6379   llvm::APSInt index;
6380   if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6381     unsigned StrLenWithNull = StrExpr->getLength() + 1;
6382     if (index.isNonNegative() &&
6383         index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6384                               index.isUnsigned()))
6385       return;
6386   }
6387
6388   SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6389   Self.Diag(OpLoc, diag::warn_string_plus_int)
6390       << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6391
6392   // Only print a fixit for "str" + int, not for int + "str".
6393   if (IndexExpr == RHSExpr) {
6394     SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6395     Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6396         << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6397         << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6398         << FixItHint::CreateInsertion(EndLoc, "]");
6399   } else
6400     Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6401 }
6402
6403 /// \brief Emit error when two pointers are incompatible.
6404 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
6405                                            Expr *LHSExpr, Expr *RHSExpr) {
6406   assert(LHSExpr->getType()->isAnyPointerType());
6407   assert(RHSExpr->getType()->isAnyPointerType());
6408   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
6409     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6410     << RHSExpr->getSourceRange();
6411 }
6412
6413 QualType Sema::CheckAdditionOperands( // C99 6.5.6
6414     ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6415     QualType* CompLHSTy) {
6416   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6417
6418   if (LHS.get()->getType()->isVectorType() ||
6419       RHS.get()->getType()->isVectorType()) {
6420     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6421     if (CompLHSTy) *CompLHSTy = compType;
6422     return compType;
6423   }
6424
6425   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6426   if (LHS.isInvalid() || RHS.isInvalid())
6427     return QualType();
6428
6429   // Diagnose "string literal" '+' int.
6430   if (Opc == BO_Add)
6431     diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6432
6433   // handle the common case first (both operands are arithmetic).
6434   if (!compType.isNull() && compType->isArithmeticType()) {
6435     if (CompLHSTy) *CompLHSTy = compType;
6436     return compType;
6437   }
6438
6439   // Type-checking.  Ultimately the pointer's going to be in PExp;
6440   // note that we bias towards the LHS being the pointer.
6441   Expr *PExp = LHS.get(), *IExp = RHS.get();
6442
6443   bool isObjCPointer;
6444   if (PExp->getType()->isPointerType()) {
6445     isObjCPointer = false;
6446   } else if (PExp->getType()->isObjCObjectPointerType()) {
6447     isObjCPointer = true;
6448   } else {
6449     std::swap(PExp, IExp);
6450     if (PExp->getType()->isPointerType()) {
6451       isObjCPointer = false;
6452     } else if (PExp->getType()->isObjCObjectPointerType()) {
6453       isObjCPointer = true;
6454     } else {
6455       return InvalidOperands(Loc, LHS, RHS);
6456     }
6457   }
6458   assert(PExp->getType()->isAnyPointerType());
6459
6460   if (!IExp->getType()->isIntegerType())
6461     return InvalidOperands(Loc, LHS, RHS);
6462
6463   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6464     return QualType();
6465
6466   if (isObjCPointer && checkArithmeticOnObjCPointer(*this, Loc, PExp))
6467     return QualType();
6468
6469   // Check array bounds for pointer arithemtic
6470   CheckArrayAccess(PExp, IExp);
6471
6472   if (CompLHSTy) {
6473     QualType LHSTy = Context.isPromotableBitField(LHS.get());
6474     if (LHSTy.isNull()) {
6475       LHSTy = LHS.get()->getType();
6476       if (LHSTy->isPromotableIntegerType())
6477         LHSTy = Context.getPromotedIntegerType(LHSTy);
6478     }
6479     *CompLHSTy = LHSTy;
6480   }
6481
6482   return PExp->getType();
6483 }
6484
6485 // C99 6.5.6
6486 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6487                                         SourceLocation Loc,
6488                                         QualType* CompLHSTy) {
6489   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6490
6491   if (LHS.get()->getType()->isVectorType() ||
6492       RHS.get()->getType()->isVectorType()) {
6493     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6494     if (CompLHSTy) *CompLHSTy = compType;
6495     return compType;
6496   }
6497
6498   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6499   if (LHS.isInvalid() || RHS.isInvalid())
6500     return QualType();
6501
6502   // Enforce type constraints: C99 6.5.6p3.
6503
6504   // Handle the common case first (both operands are arithmetic).
6505   if (!compType.isNull() && compType->isArithmeticType()) {
6506     if (CompLHSTy) *CompLHSTy = compType;
6507     return compType;
6508   }
6509
6510   // Either ptr - int   or   ptr - ptr.
6511   if (LHS.get()->getType()->isAnyPointerType()) {
6512     QualType lpointee = LHS.get()->getType()->getPointeeType();
6513
6514     // Diagnose bad cases where we step over interface counts.
6515     if (LHS.get()->getType()->isObjCObjectPointerType() &&
6516         checkArithmeticOnObjCPointer(*this, Loc, LHS.get()))
6517       return QualType();
6518
6519     // The result type of a pointer-int computation is the pointer type.
6520     if (RHS.get()->getType()->isIntegerType()) {
6521       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6522         return QualType();
6523
6524       // Check array bounds for pointer arithemtic
6525       CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6526                        /*AllowOnePastEnd*/true, /*IndexNegated*/true);
6527
6528       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6529       return LHS.get()->getType();
6530     }
6531
6532     // Handle pointer-pointer subtractions.
6533     if (const PointerType *RHSPTy
6534           = RHS.get()->getType()->getAs<PointerType>()) {
6535       QualType rpointee = RHSPTy->getPointeeType();
6536
6537       if (getLangOpts().CPlusPlus) {
6538         // Pointee types must be the same: C++ [expr.add]
6539         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6540           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6541         }
6542       } else {
6543         // Pointee types must be compatible C99 6.5.6p3
6544         if (!Context.typesAreCompatible(
6545                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6546                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6547           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6548           return QualType();
6549         }
6550       }
6551
6552       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6553                                                LHS.get(), RHS.get()))
6554         return QualType();
6555
6556       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6557       return Context.getPointerDiffType();
6558     }
6559   }
6560
6561   return InvalidOperands(Loc, LHS, RHS);
6562 }
6563
6564 static bool isScopedEnumerationType(QualType T) {
6565   if (const EnumType *ET = dyn_cast<EnumType>(T))
6566     return ET->getDecl()->isScoped();
6567   return false;
6568 }
6569
6570 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6571                                    SourceLocation Loc, unsigned Opc,
6572                                    QualType LHSType) {
6573   llvm::APSInt Right;
6574   // Check right/shifter operand
6575   if (RHS.get()->isValueDependent() ||
6576       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6577     return;
6578
6579   if (Right.isNegative()) {
6580     S.DiagRuntimeBehavior(Loc, RHS.get(),
6581                           S.PDiag(diag::warn_shift_negative)
6582                             << RHS.get()->getSourceRange());
6583     return;
6584   }
6585   llvm::APInt LeftBits(Right.getBitWidth(),
6586                        S.Context.getTypeSize(LHS.get()->getType()));
6587   if (Right.uge(LeftBits)) {
6588     S.DiagRuntimeBehavior(Loc, RHS.get(),
6589                           S.PDiag(diag::warn_shift_gt_typewidth)
6590                             << RHS.get()->getSourceRange());
6591     return;
6592   }
6593   if (Opc != BO_Shl)
6594     return;
6595
6596   // When left shifting an ICE which is signed, we can check for overflow which
6597   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6598   // integers have defined behavior modulo one more than the maximum value
6599   // representable in the result type, so never warn for those.
6600   llvm::APSInt Left;
6601   if (LHS.get()->isValueDependent() ||
6602       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6603       LHSType->hasUnsignedIntegerRepresentation())
6604     return;
6605   llvm::APInt ResultBits =
6606       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6607   if (LeftBits.uge(ResultBits))
6608     return;
6609   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6610   Result = Result.shl(Right);
6611
6612   // Print the bit representation of the signed integer as an unsigned
6613   // hexadecimal number.
6614   SmallString<40> HexResult;
6615   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6616
6617   // If we are only missing a sign bit, this is less likely to result in actual
6618   // bugs -- if the result is cast back to an unsigned type, it will have the
6619   // expected value. Thus we place this behind a different warning that can be
6620   // turned off separately if needed.
6621   if (LeftBits == ResultBits - 1) {
6622     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6623         << HexResult.str() << LHSType
6624         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6625     return;
6626   }
6627
6628   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6629     << HexResult.str() << Result.getMinSignedBits() << LHSType
6630     << Left.getBitWidth() << LHS.get()->getSourceRange()
6631     << RHS.get()->getSourceRange();
6632 }
6633
6634 // C99 6.5.7
6635 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6636                                   SourceLocation Loc, unsigned Opc,
6637                                   bool IsCompAssign) {
6638   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6639
6640   // C99 6.5.7p2: Each of the operands shall have integer type.
6641   if (!LHS.get()->getType()->hasIntegerRepresentation() || 
6642       !RHS.get()->getType()->hasIntegerRepresentation())
6643     return InvalidOperands(Loc, LHS, RHS);
6644
6645   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6646   // hasIntegerRepresentation() above instead of this.
6647   if (isScopedEnumerationType(LHS.get()->getType()) ||
6648       isScopedEnumerationType(RHS.get()->getType())) {
6649     return InvalidOperands(Loc, LHS, RHS);
6650   }
6651
6652   // Vector shifts promote their scalar inputs to vector type.
6653   if (LHS.get()->getType()->isVectorType() ||
6654       RHS.get()->getType()->isVectorType())
6655     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6656
6657   // Shifts don't perform usual arithmetic conversions, they just do integer
6658   // promotions on each operand. C99 6.5.7p3
6659
6660   // For the LHS, do usual unary conversions, but then reset them away
6661   // if this is a compound assignment.
6662   ExprResult OldLHS = LHS;
6663   LHS = UsualUnaryConversions(LHS.take());
6664   if (LHS.isInvalid())
6665     return QualType();
6666   QualType LHSType = LHS.get()->getType();
6667   if (IsCompAssign) LHS = OldLHS;
6668
6669   // The RHS is simpler.
6670   RHS = UsualUnaryConversions(RHS.take());
6671   if (RHS.isInvalid())
6672     return QualType();
6673
6674   // Sanity-check shift operands
6675   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6676
6677   // "The type of the result is that of the promoted left operand."
6678   return LHSType;
6679 }
6680
6681 static bool IsWithinTemplateSpecialization(Decl *D) {
6682   if (DeclContext *DC = D->getDeclContext()) {
6683     if (isa<ClassTemplateSpecializationDecl>(DC))
6684       return true;
6685     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6686       return FD->isFunctionTemplateSpecialization();
6687   }
6688   return false;
6689 }
6690
6691 /// If two different enums are compared, raise a warning.
6692 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6693                                 ExprResult &RHS) {
6694   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6695   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6696
6697   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6698   if (!LHSEnumType)
6699     return;
6700   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6701   if (!RHSEnumType)
6702     return;
6703
6704   // Ignore anonymous enums.
6705   if (!LHSEnumType->getDecl()->getIdentifier())
6706     return;
6707   if (!RHSEnumType->getDecl()->getIdentifier())
6708     return;
6709
6710   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6711     return;
6712
6713   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6714       << LHSStrippedType << RHSStrippedType
6715       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6716 }
6717
6718 /// \brief Diagnose bad pointer comparisons.
6719 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6720                                               ExprResult &LHS, ExprResult &RHS,
6721                                               bool IsError) {
6722   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6723                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6724     << LHS.get()->getType() << RHS.get()->getType()
6725     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6726 }
6727
6728 /// \brief Returns false if the pointers are converted to a composite type,
6729 /// true otherwise.
6730 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6731                                            ExprResult &LHS, ExprResult &RHS) {
6732   // C++ [expr.rel]p2:
6733   //   [...] Pointer conversions (4.10) and qualification
6734   //   conversions (4.4) are performed on pointer operands (or on
6735   //   a pointer operand and a null pointer constant) to bring
6736   //   them to their composite pointer type. [...]
6737   //
6738   // C++ [expr.eq]p1 uses the same notion for (in)equality
6739   // comparisons of pointers.
6740
6741   // C++ [expr.eq]p2:
6742   //   In addition, pointers to members can be compared, or a pointer to
6743   //   member and a null pointer constant. Pointer to member conversions
6744   //   (4.11) and qualification conversions (4.4) are performed to bring
6745   //   them to a common type. If one operand is a null pointer constant,
6746   //   the common type is the type of the other operand. Otherwise, the
6747   //   common type is a pointer to member type similar (4.4) to the type
6748   //   of one of the operands, with a cv-qualification signature (4.4)
6749   //   that is the union of the cv-qualification signatures of the operand
6750   //   types.
6751
6752   QualType LHSType = LHS.get()->getType();
6753   QualType RHSType = RHS.get()->getType();
6754   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6755          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6756
6757   bool NonStandardCompositeType = false;
6758   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6759   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6760   if (T.isNull()) {
6761     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6762     return true;
6763   }
6764
6765   if (NonStandardCompositeType)
6766     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6767       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6768       << RHS.get()->getSourceRange();
6769
6770   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6771   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6772   return false;
6773 }
6774
6775 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6776                                                     ExprResult &LHS,
6777                                                     ExprResult &RHS,
6778                                                     bool IsError) {
6779   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6780                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6781     << LHS.get()->getType() << RHS.get()->getType()
6782     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6783 }
6784
6785 static bool isObjCObjectLiteral(ExprResult &E) {
6786   switch (E.get()->IgnoreParenImpCasts()->getStmtClass()) {
6787   case Stmt::ObjCArrayLiteralClass:
6788   case Stmt::ObjCDictionaryLiteralClass:
6789   case Stmt::ObjCStringLiteralClass:
6790   case Stmt::ObjCBoxedExprClass:
6791     return true;
6792   default:
6793     // Note that ObjCBoolLiteral is NOT an object literal!
6794     return false;
6795   }
6796 }
6797
6798 static bool hasIsEqualMethod(Sema &S, const Expr *LHS, const Expr *RHS) {
6799   // Get the LHS object's interface type.
6800   QualType Type = LHS->getType();
6801   QualType InterfaceType;
6802   if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6803     InterfaceType = PTy->getPointeeType();
6804     if (const ObjCObjectType *iQFaceTy =
6805         InterfaceType->getAsObjCQualifiedInterfaceType())
6806       InterfaceType = iQFaceTy->getBaseType();
6807   } else {
6808     // If this is not actually an Objective-C object, bail out.
6809     return false;
6810   }
6811
6812   // If the RHS isn't an Objective-C object, bail out.
6813   if (!RHS->getType()->isObjCObjectPointerType())
6814     return false;
6815
6816   // Try to find the -isEqual: method.
6817   Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6818   ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6819                                                       InterfaceType,
6820                                                       /*instance=*/true);
6821   if (!Method) {
6822     if (Type->isObjCIdType()) {
6823       // For 'id', just check the global pool.
6824       Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6825                                                   /*receiverId=*/true,
6826                                                   /*warn=*/false);
6827     } else {
6828       // Check protocols.
6829       Method = S.LookupMethodInQualifiedType(IsEqualSel,
6830                                              cast<ObjCObjectPointerType>(Type),
6831                                              /*instance=*/true);
6832     }
6833   }
6834
6835   if (!Method)
6836     return false;
6837
6838   QualType T = Method->param_begin()[0]->getType();
6839   if (!T->isObjCObjectPointerType())
6840     return false;
6841   
6842   QualType R = Method->getResultType();
6843   if (!R->isScalarType())
6844     return false;
6845
6846   return true;
6847 }
6848
6849 static void diagnoseObjCLiteralComparison(Sema &S, SourceLocation Loc,
6850                                           ExprResult &LHS, ExprResult &RHS,
6851                                           BinaryOperator::Opcode Opc){
6852   Expr *Literal;
6853   Expr *Other;
6854   if (isObjCObjectLiteral(LHS)) {
6855     Literal = LHS.get();
6856     Other = RHS.get();
6857   } else {
6858     Literal = RHS.get();
6859     Other = LHS.get();
6860   }
6861
6862   // Don't warn on comparisons against nil.
6863   Other = Other->IgnoreParenCasts();
6864   if (Other->isNullPointerConstant(S.getASTContext(),
6865                                    Expr::NPC_ValueDependentIsNotNull))
6866     return;
6867
6868   // This should be kept in sync with warn_objc_literal_comparison.
6869   // LK_String should always be last, since it has its own warning flag.
6870   enum {
6871     LK_Array,
6872     LK_Dictionary,
6873     LK_Numeric,
6874     LK_Boxed,
6875     LK_String
6876   } LiteralKind;
6877
6878   Literal = Literal->IgnoreParenImpCasts();
6879   switch (Literal->getStmtClass()) {
6880   case Stmt::ObjCStringLiteralClass:
6881     // "string literal"
6882     LiteralKind = LK_String;
6883     break;
6884   case Stmt::ObjCArrayLiteralClass:
6885     // "array literal"
6886     LiteralKind = LK_Array;
6887     break;
6888   case Stmt::ObjCDictionaryLiteralClass:
6889     // "dictionary literal"
6890     LiteralKind = LK_Dictionary;
6891     break;
6892   case Stmt::ObjCBoxedExprClass: {
6893     Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6894     switch (Inner->getStmtClass()) {
6895     case Stmt::IntegerLiteralClass:
6896     case Stmt::FloatingLiteralClass:
6897     case Stmt::CharacterLiteralClass:
6898     case Stmt::ObjCBoolLiteralExprClass:
6899     case Stmt::CXXBoolLiteralExprClass:
6900       // "numeric literal"
6901       LiteralKind = LK_Numeric;
6902       break;
6903     case Stmt::ImplicitCastExprClass: {
6904       CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6905       // Boolean literals can be represented by implicit casts.
6906       if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6907         LiteralKind = LK_Numeric;
6908         break;
6909       }
6910       // FALLTHROUGH
6911     }
6912     default:
6913       // "boxed expression"
6914       LiteralKind = LK_Boxed;
6915       break;
6916     }
6917     break;
6918   }
6919   default:
6920     llvm_unreachable("Unknown Objective-C object literal kind");
6921   }
6922
6923   if (LiteralKind == LK_String)
6924     S.Diag(Loc, diag::warn_objc_string_literal_comparison)
6925       << Literal->getSourceRange();
6926   else
6927     S.Diag(Loc, diag::warn_objc_literal_comparison)
6928       << LiteralKind << Literal->getSourceRange();
6929
6930   if (BinaryOperator::isEqualityOp(Opc) &&
6931       hasIsEqualMethod(S, LHS.get(), RHS.get())) {
6932     SourceLocation Start = LHS.get()->getLocStart();
6933     SourceLocation End = S.PP.getLocForEndOfToken(RHS.get()->getLocEnd());
6934     SourceRange OpRange(Loc, S.PP.getLocForEndOfToken(Loc));
6935
6936     S.Diag(Loc, diag::note_objc_literal_comparison_isequal)
6937       << FixItHint::CreateInsertion(Start, Opc == BO_EQ ? "[" : "![")
6938       << FixItHint::CreateReplacement(OpRange, "isEqual:")
6939       << FixItHint::CreateInsertion(End, "]");
6940   }
6941 }
6942
6943 // C99 6.5.8, C++ [expr.rel]
6944 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6945                                     SourceLocation Loc, unsigned OpaqueOpc,
6946                                     bool IsRelational) {
6947   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6948
6949   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6950
6951   // Handle vector comparisons separately.
6952   if (LHS.get()->getType()->isVectorType() ||
6953       RHS.get()->getType()->isVectorType())
6954     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6955
6956   QualType LHSType = LHS.get()->getType();
6957   QualType RHSType = RHS.get()->getType();
6958
6959   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6960   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6961
6962   checkEnumComparison(*this, Loc, LHS, RHS);
6963
6964   if (!LHSType->hasFloatingRepresentation() &&
6965       !(LHSType->isBlockPointerType() && IsRelational) &&
6966       !LHS.get()->getLocStart().isMacroID() &&
6967       !RHS.get()->getLocStart().isMacroID()) {
6968     // For non-floating point types, check for self-comparisons of the form
6969     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6970     // often indicate logic errors in the program.
6971     //
6972     // NOTE: Don't warn about comparison expressions resulting from macro
6973     // expansion. Also don't warn about comparisons which are only self
6974     // comparisons within a template specialization. The warnings should catch
6975     // obvious cases in the definition of the template anyways. The idea is to
6976     // warn when the typed comparison operator will always evaluate to the same
6977     // result.
6978     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6979       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6980         if (DRL->getDecl() == DRR->getDecl() &&
6981             !IsWithinTemplateSpecialization(DRL->getDecl())) {
6982           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6983                               << 0 // self-
6984                               << (Opc == BO_EQ
6985                                   || Opc == BO_LE
6986                                   || Opc == BO_GE));
6987         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6988                    !DRL->getDecl()->getType()->isReferenceType() &&
6989                    !DRR->getDecl()->getType()->isReferenceType()) {
6990             // what is it always going to eval to?
6991             char always_evals_to;
6992             switch(Opc) {
6993             case BO_EQ: // e.g. array1 == array2
6994               always_evals_to = 0; // false
6995               break;
6996             case BO_NE: // e.g. array1 != array2
6997               always_evals_to = 1; // true
6998               break;
6999             default:
7000               // best we can say is 'a constant'
7001               always_evals_to = 2; // e.g. array1 <= array2
7002               break;
7003             }
7004             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
7005                                 << 1 // array
7006                                 << always_evals_to);
7007         }
7008       }
7009     }
7010
7011     if (isa<CastExpr>(LHSStripped))
7012       LHSStripped = LHSStripped->IgnoreParenCasts();
7013     if (isa<CastExpr>(RHSStripped))
7014       RHSStripped = RHSStripped->IgnoreParenCasts();
7015
7016     // Warn about comparisons against a string constant (unless the other
7017     // operand is null), the user probably wants strcmp.
7018     Expr *literalString = 0;
7019     Expr *literalStringStripped = 0;
7020     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
7021         !RHSStripped->isNullPointerConstant(Context,
7022                                             Expr::NPC_ValueDependentIsNull)) {
7023       literalString = LHS.get();
7024       literalStringStripped = LHSStripped;
7025     } else if ((isa<StringLiteral>(RHSStripped) ||
7026                 isa<ObjCEncodeExpr>(RHSStripped)) &&
7027                !LHSStripped->isNullPointerConstant(Context,
7028                                             Expr::NPC_ValueDependentIsNull)) {
7029       literalString = RHS.get();
7030       literalStringStripped = RHSStripped;
7031     }
7032
7033     if (literalString) {
7034       std::string resultComparison;
7035       switch (Opc) {
7036       case BO_LT: resultComparison = ") < 0"; break;
7037       case BO_GT: resultComparison = ") > 0"; break;
7038       case BO_LE: resultComparison = ") <= 0"; break;
7039       case BO_GE: resultComparison = ") >= 0"; break;
7040       case BO_EQ: resultComparison = ") == 0"; break;
7041       case BO_NE: resultComparison = ") != 0"; break;
7042       default: llvm_unreachable("Invalid comparison operator");
7043       }
7044
7045       DiagRuntimeBehavior(Loc, 0,
7046         PDiag(diag::warn_stringcompare)
7047           << isa<ObjCEncodeExpr>(literalStringStripped)
7048           << literalString->getSourceRange());
7049     }
7050   }
7051
7052   // C99 6.5.8p3 / C99 6.5.9p4
7053   if (LHS.get()->getType()->isArithmeticType() &&
7054       RHS.get()->getType()->isArithmeticType()) {
7055     UsualArithmeticConversions(LHS, RHS);
7056     if (LHS.isInvalid() || RHS.isInvalid())
7057       return QualType();
7058   }
7059   else {
7060     LHS = UsualUnaryConversions(LHS.take());
7061     if (LHS.isInvalid())
7062       return QualType();
7063
7064     RHS = UsualUnaryConversions(RHS.take());
7065     if (RHS.isInvalid())
7066       return QualType();
7067   }
7068
7069   LHSType = LHS.get()->getType();
7070   RHSType = RHS.get()->getType();
7071
7072   // The result of comparisons is 'bool' in C++, 'int' in C.
7073   QualType ResultTy = Context.getLogicalOperationType();
7074
7075   if (IsRelational) {
7076     if (LHSType->isRealType() && RHSType->isRealType())
7077       return ResultTy;
7078   } else {
7079     // Check for comparisons of floating point operands using != and ==.
7080     if (LHSType->hasFloatingRepresentation())
7081       CheckFloatComparison(Loc, LHS.get(), RHS.get());
7082
7083     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
7084       return ResultTy;
7085   }
7086
7087   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
7088                                               Expr::NPC_ValueDependentIsNull);
7089   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
7090                                               Expr::NPC_ValueDependentIsNull);
7091
7092   // All of the following pointer-related warnings are GCC extensions, except
7093   // when handling null pointer constants. 
7094   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
7095     QualType LCanPointeeTy =
7096       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7097     QualType RCanPointeeTy =
7098       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
7099
7100     if (getLangOpts().CPlusPlus) {
7101       if (LCanPointeeTy == RCanPointeeTy)
7102         return ResultTy;
7103       if (!IsRelational &&
7104           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7105         // Valid unless comparison between non-null pointer and function pointer
7106         // This is a gcc extension compatibility comparison.
7107         // In a SFINAE context, we treat this as a hard error to maintain
7108         // conformance with the C++ standard.
7109         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7110             && !LHSIsNull && !RHSIsNull) {
7111           diagnoseFunctionPointerToVoidComparison(
7112               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
7113           
7114           if (isSFINAEContext())
7115             return QualType();
7116           
7117           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7118           return ResultTy;
7119         }
7120       }
7121
7122       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7123         return QualType();
7124       else
7125         return ResultTy;
7126     }
7127     // C99 6.5.9p2 and C99 6.5.8p2
7128     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
7129                                    RCanPointeeTy.getUnqualifiedType())) {
7130       // Valid unless a relational comparison of function pointers
7131       if (IsRelational && LCanPointeeTy->isFunctionType()) {
7132         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
7133           << LHSType << RHSType << LHS.get()->getSourceRange()
7134           << RHS.get()->getSourceRange();
7135       }
7136     } else if (!IsRelational &&
7137                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
7138       // Valid unless comparison between non-null pointer and function pointer
7139       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
7140           && !LHSIsNull && !RHSIsNull)
7141         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
7142                                                 /*isError*/false);
7143     } else {
7144       // Invalid
7145       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
7146     }
7147     if (LCanPointeeTy != RCanPointeeTy) {
7148       if (LHSIsNull && !RHSIsNull)
7149         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7150       else
7151         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7152     }
7153     return ResultTy;
7154   }
7155
7156   if (getLangOpts().CPlusPlus) {
7157     // Comparison of nullptr_t with itself.
7158     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
7159       return ResultTy;
7160     
7161     // Comparison of pointers with null pointer constants and equality
7162     // comparisons of member pointers to null pointer constants.
7163     if (RHSIsNull &&
7164         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
7165          (!IsRelational && 
7166           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
7167       RHS = ImpCastExprToType(RHS.take(), LHSType, 
7168                         LHSType->isMemberPointerType()
7169                           ? CK_NullToMemberPointer
7170                           : CK_NullToPointer);
7171       return ResultTy;
7172     }
7173     if (LHSIsNull &&
7174         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
7175          (!IsRelational && 
7176           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
7177       LHS = ImpCastExprToType(LHS.take(), RHSType, 
7178                         RHSType->isMemberPointerType()
7179                           ? CK_NullToMemberPointer
7180                           : CK_NullToPointer);
7181       return ResultTy;
7182     }
7183
7184     // Comparison of member pointers.
7185     if (!IsRelational &&
7186         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
7187       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
7188         return QualType();
7189       else
7190         return ResultTy;
7191     }
7192
7193     // Handle scoped enumeration types specifically, since they don't promote
7194     // to integers.
7195     if (LHS.get()->getType()->isEnumeralType() &&
7196         Context.hasSameUnqualifiedType(LHS.get()->getType(),
7197                                        RHS.get()->getType()))
7198       return ResultTy;
7199   }
7200
7201   // Handle block pointer types.
7202   if (!IsRelational && LHSType->isBlockPointerType() &&
7203       RHSType->isBlockPointerType()) {
7204     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7205     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
7206
7207     if (!LHSIsNull && !RHSIsNull &&
7208         !Context.typesAreCompatible(lpointee, rpointee)) {
7209       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7210         << LHSType << RHSType << LHS.get()->getSourceRange()
7211         << RHS.get()->getSourceRange();
7212     }
7213     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7214     return ResultTy;
7215   }
7216
7217   // Allow block pointers to be compared with null pointer constants.
7218   if (!IsRelational
7219       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7220           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
7221     if (!LHSIsNull && !RHSIsNull) {
7222       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
7223              ->getPointeeType()->isVoidType())
7224             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
7225                 ->getPointeeType()->isVoidType())))
7226         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
7227           << LHSType << RHSType << LHS.get()->getSourceRange()
7228           << RHS.get()->getSourceRange();
7229     }
7230     if (LHSIsNull && !RHSIsNull)
7231       LHS = ImpCastExprToType(LHS.take(), RHSType,
7232                               RHSType->isPointerType() ? CK_BitCast
7233                                 : CK_AnyPointerToBlockPointerCast);
7234     else
7235       RHS = ImpCastExprToType(RHS.take(), LHSType,
7236                               LHSType->isPointerType() ? CK_BitCast
7237                                 : CK_AnyPointerToBlockPointerCast);
7238     return ResultTy;
7239   }
7240
7241   if (LHSType->isObjCObjectPointerType() ||
7242       RHSType->isObjCObjectPointerType()) {
7243     const PointerType *LPT = LHSType->getAs<PointerType>();
7244     const PointerType *RPT = RHSType->getAs<PointerType>();
7245     if (LPT || RPT) {
7246       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7247       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
7248
7249       if (!LPtrToVoid && !RPtrToVoid &&
7250           !Context.typesAreCompatible(LHSType, RHSType)) {
7251         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7252                                           /*isError*/false);
7253       }
7254       if (LHSIsNull && !RHSIsNull)
7255         LHS = ImpCastExprToType(LHS.take(), RHSType,
7256                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7257       else
7258         RHS = ImpCastExprToType(RHS.take(), LHSType,
7259                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
7260       return ResultTy;
7261     }
7262     if (LHSType->isObjCObjectPointerType() &&
7263         RHSType->isObjCObjectPointerType()) {
7264       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7265         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
7266                                           /*isError*/false);
7267       if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7268         diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS, Opc);
7269
7270       if (LHSIsNull && !RHSIsNull)
7271         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
7272       else
7273         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
7274       return ResultTy;
7275     }
7276   }
7277   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7278       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
7279     unsigned DiagID = 0;
7280     bool isError = false;
7281     if (LangOpts.DebuggerSupport) {
7282       // Under a debugger, allow the comparison of pointers to integers,
7283       // since users tend to want to compare addresses.
7284     } else if ((LHSIsNull && LHSType->isIntegerType()) ||
7285         (RHSIsNull && RHSType->isIntegerType())) {
7286       if (IsRelational && !getLangOpts().CPlusPlus)
7287         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
7288     } else if (IsRelational && !getLangOpts().CPlusPlus)
7289       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
7290     else if (getLangOpts().CPlusPlus) {
7291       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7292       isError = true;
7293     } else
7294       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
7295
7296     if (DiagID) {
7297       Diag(Loc, DiagID)
7298         << LHSType << RHSType << LHS.get()->getSourceRange()
7299         << RHS.get()->getSourceRange();
7300       if (isError)
7301         return QualType();
7302     }
7303     
7304     if (LHSType->isIntegerType())
7305       LHS = ImpCastExprToType(LHS.take(), RHSType,
7306                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7307     else
7308       RHS = ImpCastExprToType(RHS.take(), LHSType,
7309                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
7310     return ResultTy;
7311   }
7312   
7313   // Handle block pointers.
7314   if (!IsRelational && RHSIsNull
7315       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7316     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
7317     return ResultTy;
7318   }
7319   if (!IsRelational && LHSIsNull
7320       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7321     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
7322     return ResultTy;
7323   }
7324
7325   return InvalidOperands(Loc, LHS, RHS);
7326 }
7327
7328
7329 // Return a signed type that is of identical size and number of elements.
7330 // For floating point vectors, return an integer type of identical size 
7331 // and number of elements.
7332 QualType Sema::GetSignedVectorType(QualType V) {
7333   const VectorType *VTy = V->getAs<VectorType>();
7334   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7335   if (TypeSize == Context.getTypeSize(Context.CharTy))
7336     return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7337   else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7338     return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7339   else if (TypeSize == Context.getTypeSize(Context.IntTy))
7340     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7341   else if (TypeSize == Context.getTypeSize(Context.LongTy))
7342     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7343   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7344          "Unhandled vector element size in vector compare");
7345   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7346 }
7347
7348 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
7349 /// operates on extended vector types.  Instead of producing an IntTy result,
7350 /// like a scalar comparison, a vector comparison produces a vector of integer
7351 /// types.
7352 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
7353                                           SourceLocation Loc,
7354                                           bool IsRelational) {
7355   // Check to make sure we're operating on vectors of the same type and width,
7356   // Allowing one side to be a scalar of element type.
7357   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
7358   if (vType.isNull())
7359     return vType;
7360
7361   QualType LHSType = LHS.get()->getType();
7362
7363   // If AltiVec, the comparison results in a numeric type, i.e.
7364   // bool for C++, int for C
7365   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
7366     return Context.getLogicalOperationType();
7367
7368   // For non-floating point types, check for self-comparisons of the form
7369   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
7370   // often indicate logic errors in the program.
7371   if (!LHSType->hasFloatingRepresentation()) {
7372     if (DeclRefExpr* DRL
7373           = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7374       if (DeclRefExpr* DRR
7375             = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
7376         if (DRL->getDecl() == DRR->getDecl())
7377           DiagRuntimeBehavior(Loc, 0,
7378                               PDiag(diag::warn_comparison_always)
7379                                 << 0 // self-
7380                                 << 2 // "a constant"
7381                               );
7382   }
7383
7384   // Check for comparisons of floating point operands using != and ==.
7385   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
7386     assert (RHS.get()->getType()->hasFloatingRepresentation());
7387     CheckFloatComparison(Loc, LHS.get(), RHS.get());
7388   }
7389   
7390   // Return a signed type for the vector.
7391   return GetSignedVectorType(LHSType);
7392 }
7393
7394 QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7395                                           SourceLocation Loc) {
7396   // Ensure that either both operands are of the same vector type, or
7397   // one operand is of a vector type and the other is of its element type.
7398   QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7399   if (vType.isNull() || vType->isFloatingType())
7400     return InvalidOperands(Loc, LHS, RHS);
7401   
7402   return GetSignedVectorType(LHS.get()->getType());
7403 }
7404
7405 inline QualType Sema::CheckBitwiseOperands(
7406   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
7407   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7408
7409   if (LHS.get()->getType()->isVectorType() ||
7410       RHS.get()->getType()->isVectorType()) {
7411     if (LHS.get()->getType()->hasIntegerRepresentation() &&
7412         RHS.get()->getType()->hasIntegerRepresentation())
7413       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
7414     
7415     return InvalidOperands(Loc, LHS, RHS);
7416   }
7417
7418   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7419   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
7420                                                  IsCompAssign);
7421   if (LHSResult.isInvalid() || RHSResult.isInvalid())
7422     return QualType();
7423   LHS = LHSResult.take();
7424   RHS = RHSResult.take();
7425
7426   if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
7427     return compType;
7428   return InvalidOperands(Loc, LHS, RHS);
7429 }
7430
7431 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
7432   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
7433   
7434   // Check vector operands differently.
7435   if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7436     return CheckVectorLogicalOperands(LHS, RHS, Loc);
7437   
7438   // Diagnose cases where the user write a logical and/or but probably meant a
7439   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
7440   // is a constant.
7441   if (LHS.get()->getType()->isIntegerType() &&
7442       !LHS.get()->getType()->isBooleanType() &&
7443       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
7444       // Don't warn in macros or template instantiations.
7445       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
7446     // If the RHS can be constant folded, and if it constant folds to something
7447     // that isn't 0 or 1 (which indicate a potential logical operation that
7448     // happened to fold to true/false) then warn.
7449     // Parens on the RHS are ignored.
7450     llvm::APSInt Result;
7451     if (RHS.get()->EvaluateAsInt(Result, Context))
7452       if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
7453           (Result != 0 && Result != 1)) {
7454         Diag(Loc, diag::warn_logical_instead_of_bitwise)
7455           << RHS.get()->getSourceRange()
7456           << (Opc == BO_LAnd ? "&&" : "||");
7457         // Suggest replacing the logical operator with the bitwise version
7458         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7459             << (Opc == BO_LAnd ? "&" : "|")
7460             << FixItHint::CreateReplacement(SourceRange(
7461                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7462                                                 getLangOpts())),
7463                                             Opc == BO_LAnd ? "&" : "|");
7464         if (Opc == BO_LAnd)
7465           // Suggest replacing "Foo() && kNonZero" with "Foo()"
7466           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7467               << FixItHint::CreateRemoval(
7468                   SourceRange(
7469                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
7470                                                  0, getSourceManager(),
7471                                                  getLangOpts()),
7472                       RHS.get()->getLocEnd()));
7473       }
7474   }
7475   
7476   if (!Context.getLangOpts().CPlusPlus) {
7477     LHS = UsualUnaryConversions(LHS.take());
7478     if (LHS.isInvalid())
7479       return QualType();
7480
7481     RHS = UsualUnaryConversions(RHS.take());
7482     if (RHS.isInvalid())
7483       return QualType();
7484
7485     if (!LHS.get()->getType()->isScalarType() ||
7486         !RHS.get()->getType()->isScalarType())
7487       return InvalidOperands(Loc, LHS, RHS);
7488
7489     return Context.IntTy;
7490   }
7491
7492   // The following is safe because we only use this method for
7493   // non-overloadable operands.
7494
7495   // C++ [expr.log.and]p1
7496   // C++ [expr.log.or]p1
7497   // The operands are both contextually converted to type bool.
7498   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7499   if (LHSRes.isInvalid())
7500     return InvalidOperands(Loc, LHS, RHS);
7501   LHS = LHSRes;
7502
7503   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7504   if (RHSRes.isInvalid())
7505     return InvalidOperands(Loc, LHS, RHS);
7506   RHS = RHSRes;
7507
7508   // C++ [expr.log.and]p2
7509   // C++ [expr.log.or]p2
7510   // The result is a bool.
7511   return Context.BoolTy;
7512 }
7513
7514 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7515 /// is a read-only property; return true if so. A readonly property expression
7516 /// depends on various declarations and thus must be treated specially.
7517 ///
7518 static bool IsReadonlyProperty(Expr *E, Sema &S) {
7519   const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7520   if (!PropExpr) return false;
7521   if (PropExpr->isImplicitProperty()) return false;
7522
7523   ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7524   QualType BaseType = PropExpr->isSuperReceiver() ? 
7525                             PropExpr->getSuperReceiverType() :  
7526                             PropExpr->getBase()->getType();
7527       
7528   if (const ObjCObjectPointerType *OPT =
7529       BaseType->getAsObjCInterfacePointerType())
7530     if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7531       if (S.isPropertyReadonly(PDecl, IFace))
7532         return true;
7533   return false;
7534 }
7535
7536 static bool IsReadonlyMessage(Expr *E, Sema &S) {
7537   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7538   if (!ME) return false;
7539   if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7540   ObjCMessageExpr *Base =
7541     dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7542   if (!Base) return false;
7543   return Base->getMethodDecl() != 0;
7544 }
7545
7546 /// Is the given expression (which must be 'const') a reference to a
7547 /// variable which was originally non-const, but which has become
7548 /// 'const' due to being captured within a block?
7549 enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7550 static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7551   assert(E->isLValue() && E->getType().isConstQualified());
7552   E = E->IgnoreParens();
7553
7554   // Must be a reference to a declaration from an enclosing scope.
7555   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7556   if (!DRE) return NCCK_None;
7557   if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7558
7559   // The declaration must be a variable which is not declared 'const'.
7560   VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7561   if (!var) return NCCK_None;
7562   if (var->getType().isConstQualified()) return NCCK_None;
7563   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7564
7565   // Decide whether the first capture was for a block or a lambda.
7566   DeclContext *DC = S.CurContext;
7567   while (DC->getParent() != var->getDeclContext())
7568     DC = DC->getParent();
7569   return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7570 }
7571
7572 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
7573 /// emit an error and return true.  If so, return false.
7574 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
7575   assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
7576   SourceLocation OrigLoc = Loc;
7577   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
7578                                                               &Loc);
7579   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7580     IsLV = Expr::MLV_ReadonlyProperty;
7581   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7582     IsLV = Expr::MLV_InvalidMessageExpression;
7583   if (IsLV == Expr::MLV_Valid)
7584     return false;
7585
7586   unsigned Diag = 0;
7587   bool NeedType = false;
7588   switch (IsLV) { // C99 6.5.16p2
7589   case Expr::MLV_ConstQualified:
7590     Diag = diag::err_typecheck_assign_const;
7591
7592     // Use a specialized diagnostic when we're assigning to an object
7593     // from an enclosing function or block.
7594     if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7595       if (NCCK == NCCK_Block)
7596         Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7597       else
7598         Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7599       break;
7600     }
7601
7602     // In ARC, use some specialized diagnostics for occasions where we
7603     // infer 'const'.  These are always pseudo-strong variables.
7604     if (S.getLangOpts().ObjCAutoRefCount) {
7605       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7606       if (declRef && isa<VarDecl>(declRef->getDecl())) {
7607         VarDecl *var = cast<VarDecl>(declRef->getDecl());
7608
7609         // Use the normal diagnostic if it's pseudo-__strong but the
7610         // user actually wrote 'const'.
7611         if (var->isARCPseudoStrong() &&
7612             (!var->getTypeSourceInfo() ||
7613              !var->getTypeSourceInfo()->getType().isConstQualified())) {
7614           // There are two pseudo-strong cases:
7615           //  - self
7616           ObjCMethodDecl *method = S.getCurMethodDecl();
7617           if (method && var == method->getSelfDecl())
7618             Diag = method->isClassMethod()
7619               ? diag::err_typecheck_arc_assign_self_class_method
7620               : diag::err_typecheck_arc_assign_self;
7621
7622           //  - fast enumeration variables
7623           else
7624             Diag = diag::err_typecheck_arr_assign_enumeration;
7625
7626           SourceRange Assign;
7627           if (Loc != OrigLoc)
7628             Assign = SourceRange(OrigLoc, OrigLoc);
7629           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7630           // We need to preserve the AST regardless, so migration tool 
7631           // can do its job.
7632           return false;
7633         }
7634       }
7635     }
7636
7637     break;
7638   case Expr::MLV_ArrayType:
7639   case Expr::MLV_ArrayTemporary:
7640     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7641     NeedType = true;
7642     break;
7643   case Expr::MLV_NotObjectType:
7644     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7645     NeedType = true;
7646     break;
7647   case Expr::MLV_LValueCast:
7648     Diag = diag::err_typecheck_lvalue_casts_not_supported;
7649     break;
7650   case Expr::MLV_Valid:
7651     llvm_unreachable("did not take early return for MLV_Valid");
7652   case Expr::MLV_InvalidExpression:
7653   case Expr::MLV_MemberFunction:
7654   case Expr::MLV_ClassTemporary:
7655     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7656     break;
7657   case Expr::MLV_IncompleteType:
7658   case Expr::MLV_IncompleteVoidType:
7659     return S.RequireCompleteType(Loc, E->getType(),
7660              diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
7661   case Expr::MLV_DuplicateVectorComponents:
7662     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7663     break;
7664   case Expr::MLV_ReadonlyProperty:
7665   case Expr::MLV_NoSetterProperty:
7666     llvm_unreachable("readonly properties should be processed differently");
7667   case Expr::MLV_InvalidMessageExpression:
7668     Diag = diag::error_readonly_message_assignment;
7669     break;
7670   case Expr::MLV_SubObjCPropertySetting:
7671     Diag = diag::error_no_subobject_property_setting;
7672     break;
7673   }
7674
7675   SourceRange Assign;
7676   if (Loc != OrigLoc)
7677     Assign = SourceRange(OrigLoc, OrigLoc);
7678   if (NeedType)
7679     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7680   else
7681     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7682   return true;
7683 }
7684
7685 static void CheckIdentityFieldAssignment(Expr *LHSExpr, Expr *RHSExpr,
7686                                          SourceLocation Loc,
7687                                          Sema &Sema) {
7688   // C / C++ fields
7689   MemberExpr *ML = dyn_cast<MemberExpr>(LHSExpr);
7690   MemberExpr *MR = dyn_cast<MemberExpr>(RHSExpr);
7691   if (ML && MR && ML->getMemberDecl() == MR->getMemberDecl()) {
7692     if (isa<CXXThisExpr>(ML->getBase()) && isa<CXXThisExpr>(MR->getBase()))
7693       Sema.Diag(Loc, diag::warn_identity_field_assign) << 0;
7694   }
7695
7696   // Objective-C instance variables
7697   ObjCIvarRefExpr *OL = dyn_cast<ObjCIvarRefExpr>(LHSExpr);
7698   ObjCIvarRefExpr *OR = dyn_cast<ObjCIvarRefExpr>(RHSExpr);
7699   if (OL && OR && OL->getDecl() == OR->getDecl()) {
7700     DeclRefExpr *RL = dyn_cast<DeclRefExpr>(OL->getBase()->IgnoreImpCasts());
7701     DeclRefExpr *RR = dyn_cast<DeclRefExpr>(OR->getBase()->IgnoreImpCasts());
7702     if (RL && RR && RL->getDecl() == RR->getDecl())
7703       Sema.Diag(Loc, diag::warn_identity_field_assign) << 1;
7704   }
7705 }
7706
7707 // C99 6.5.16.1
7708 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7709                                        SourceLocation Loc,
7710                                        QualType CompoundType) {
7711   assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7712
7713   // Verify that LHS is a modifiable lvalue, and emit error if not.
7714   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7715     return QualType();
7716
7717   QualType LHSType = LHSExpr->getType();
7718   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7719                                              CompoundType;
7720   AssignConvertType ConvTy;
7721   if (CompoundType.isNull()) {
7722     Expr *RHSCheck = RHS.get();
7723
7724     CheckIdentityFieldAssignment(LHSExpr, RHSCheck, Loc, *this);
7725
7726     QualType LHSTy(LHSType);
7727     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7728     if (RHS.isInvalid())
7729       return QualType();
7730     // Special case of NSObject attributes on c-style pointer types.
7731     if (ConvTy == IncompatiblePointer &&
7732         ((Context.isObjCNSObjectType(LHSType) &&
7733           RHSType->isObjCObjectPointerType()) ||
7734          (Context.isObjCNSObjectType(RHSType) &&
7735           LHSType->isObjCObjectPointerType())))
7736       ConvTy = Compatible;
7737
7738     if (ConvTy == Compatible &&
7739         LHSType->isObjCObjectType())
7740         Diag(Loc, diag::err_objc_object_assignment)
7741           << LHSType;
7742
7743     // If the RHS is a unary plus or minus, check to see if they = and + are
7744     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7745     // instead of "x += 4".
7746     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7747       RHSCheck = ICE->getSubExpr();
7748     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7749       if ((UO->getOpcode() == UO_Plus ||
7750            UO->getOpcode() == UO_Minus) &&
7751           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7752           // Only if the two operators are exactly adjacent.
7753           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7754           // And there is a space or other character before the subexpr of the
7755           // unary +/-.  We don't want to warn on "x=-1".
7756           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7757           UO->getSubExpr()->getLocStart().isFileID()) {
7758         Diag(Loc, diag::warn_not_compound_assign)
7759           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7760           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7761       }
7762     }
7763
7764     if (ConvTy == Compatible) {
7765       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong) {
7766         // Warn about retain cycles where a block captures the LHS, but
7767         // not if the LHS is a simple variable into which the block is
7768         // being stored...unless that variable can be captured by reference!
7769         const Expr *InnerLHS = LHSExpr->IgnoreParenCasts();
7770         const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InnerLHS);
7771         if (!DRE || DRE->getDecl()->hasAttr<BlocksAttr>())
7772           checkRetainCycles(LHSExpr, RHS.get());
7773
7774         // It is safe to assign a weak reference into a strong variable.
7775         // Although this code can still have problems:
7776         //   id x = self.weakProp;
7777         //   id y = self.weakProp;
7778         // we do not warn to warn spuriously when 'x' and 'y' are on separate
7779         // paths through the function. This should be revisited if
7780         // -Wrepeated-use-of-weak is made flow-sensitive.
7781         DiagnosticsEngine::Level Level =
7782           Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
7783                                    RHS.get()->getLocStart());
7784         if (Level != DiagnosticsEngine::Ignored)
7785           getCurFunction()->markSafeWeakUse(RHS.get());
7786
7787       } else if (getLangOpts().ObjCAutoRefCount) {
7788         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7789       }
7790     }
7791   } else {
7792     // Compound assignment "x += y"
7793     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7794   }
7795
7796   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7797                                RHS.get(), AA_Assigning))
7798     return QualType();
7799
7800   CheckForNullPointerDereference(*this, LHSExpr);
7801
7802   // C99 6.5.16p3: The type of an assignment expression is the type of the
7803   // left operand unless the left operand has qualified type, in which case
7804   // it is the unqualified version of the type of the left operand.
7805   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7806   // is converted to the type of the assignment expression (above).
7807   // C++ 5.17p1: the type of the assignment expression is that of its left
7808   // operand.
7809   return (getLangOpts().CPlusPlus
7810           ? LHSType : LHSType.getUnqualifiedType());
7811 }
7812
7813 // C99 6.5.17
7814 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7815                                    SourceLocation Loc) {
7816   LHS = S.CheckPlaceholderExpr(LHS.take());
7817   RHS = S.CheckPlaceholderExpr(RHS.take());
7818   if (LHS.isInvalid() || RHS.isInvalid())
7819     return QualType();
7820
7821   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7822   // operands, but not unary promotions.
7823   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7824
7825   // So we treat the LHS as a ignored value, and in C++ we allow the
7826   // containing site to determine what should be done with the RHS.
7827   LHS = S.IgnoredValueConversions(LHS.take());
7828   if (LHS.isInvalid())
7829     return QualType();
7830
7831   S.DiagnoseUnusedExprResult(LHS.get());
7832
7833   if (!S.getLangOpts().CPlusPlus) {
7834     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7835     if (RHS.isInvalid())
7836       return QualType();
7837     if (!RHS.get()->getType()->isVoidType())
7838       S.RequireCompleteType(Loc, RHS.get()->getType(),
7839                             diag::err_incomplete_type);
7840   }
7841
7842   return RHS.get()->getType();
7843 }
7844
7845 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7846 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7847 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7848                                                ExprValueKind &VK,
7849                                                SourceLocation OpLoc,
7850                                                bool IsInc, bool IsPrefix) {
7851   if (Op->isTypeDependent())
7852     return S.Context.DependentTy;
7853
7854   QualType ResType = Op->getType();
7855   // Atomic types can be used for increment / decrement where the non-atomic
7856   // versions can, so ignore the _Atomic() specifier for the purpose of
7857   // checking.
7858   if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7859     ResType = ResAtomicType->getValueType();
7860
7861   assert(!ResType.isNull() && "no type for increment/decrement expression");
7862
7863   if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
7864     // Decrement of bool is not allowed.
7865     if (!IsInc) {
7866       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7867       return QualType();
7868     }
7869     // Increment of bool sets it to true, but is deprecated.
7870     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7871   } else if (ResType->isRealType()) {
7872     // OK!
7873   } else if (ResType->isPointerType()) {
7874     // C99 6.5.2.4p2, 6.5.6p2
7875     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7876       return QualType();
7877   } else if (ResType->isObjCObjectPointerType()) {
7878     // On modern runtimes, ObjC pointer arithmetic is forbidden.
7879     // Otherwise, we just need a complete type.
7880     if (checkArithmeticIncompletePointerType(S, OpLoc, Op) ||
7881         checkArithmeticOnObjCPointer(S, OpLoc, Op))
7882       return QualType();    
7883   } else if (ResType->isAnyComplexType()) {
7884     // C99 does not support ++/-- on complex types, we allow as an extension.
7885     S.Diag(OpLoc, diag::ext_integer_increment_complex)
7886       << ResType << Op->getSourceRange();
7887   } else if (ResType->isPlaceholderType()) {
7888     ExprResult PR = S.CheckPlaceholderExpr(Op);
7889     if (PR.isInvalid()) return QualType();
7890     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7891                                           IsInc, IsPrefix);
7892   } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
7893     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7894   } else {
7895     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7896       << ResType << int(IsInc) << Op->getSourceRange();
7897     return QualType();
7898   }
7899   // At this point, we know we have a real, complex or pointer type.
7900   // Now make sure the operand is a modifiable lvalue.
7901   if (CheckForModifiableLvalue(Op, OpLoc, S))
7902     return QualType();
7903   // In C++, a prefix increment is the same type as the operand. Otherwise
7904   // (in C or with postfix), the increment is the unqualified type of the
7905   // operand.
7906   if (IsPrefix && S.getLangOpts().CPlusPlus) {
7907     VK = VK_LValue;
7908     return ResType;
7909   } else {
7910     VK = VK_RValue;
7911     return ResType.getUnqualifiedType();
7912   }
7913 }
7914   
7915
7916 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7917 /// This routine allows us to typecheck complex/recursive expressions
7918 /// where the declaration is needed for type checking. We only need to
7919 /// handle cases when the expression references a function designator
7920 /// or is an lvalue. Here are some examples:
7921 ///  - &(x) => x
7922 ///  - &*****f => f for f a function designator.
7923 ///  - &s.xx => s
7924 ///  - &s.zz[1].yy -> s, if zz is an array
7925 ///  - *(x + 1) -> x, if x is an array
7926 ///  - &"123"[2] -> 0
7927 ///  - & __real__ x -> x
7928 static ValueDecl *getPrimaryDecl(Expr *E) {
7929   switch (E->getStmtClass()) {
7930   case Stmt::DeclRefExprClass:
7931     return cast<DeclRefExpr>(E)->getDecl();
7932   case Stmt::MemberExprClass:
7933     // If this is an arrow operator, the address is an offset from
7934     // the base's value, so the object the base refers to is
7935     // irrelevant.
7936     if (cast<MemberExpr>(E)->isArrow())
7937       return 0;
7938     // Otherwise, the expression refers to a part of the base
7939     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7940   case Stmt::ArraySubscriptExprClass: {
7941     // FIXME: This code shouldn't be necessary!  We should catch the implicit
7942     // promotion of register arrays earlier.
7943     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7944     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7945       if (ICE->getSubExpr()->getType()->isArrayType())
7946         return getPrimaryDecl(ICE->getSubExpr());
7947     }
7948     return 0;
7949   }
7950   case Stmt::UnaryOperatorClass: {
7951     UnaryOperator *UO = cast<UnaryOperator>(E);
7952
7953     switch(UO->getOpcode()) {
7954     case UO_Real:
7955     case UO_Imag:
7956     case UO_Extension:
7957       return getPrimaryDecl(UO->getSubExpr());
7958     default:
7959       return 0;
7960     }
7961   }
7962   case Stmt::ParenExprClass:
7963     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7964   case Stmt::ImplicitCastExprClass:
7965     // If the result of an implicit cast is an l-value, we care about
7966     // the sub-expression; otherwise, the result here doesn't matter.
7967     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7968   default:
7969     return 0;
7970   }
7971 }
7972
7973 namespace {
7974   enum {
7975     AO_Bit_Field = 0,
7976     AO_Vector_Element = 1,
7977     AO_Property_Expansion = 2,
7978     AO_Register_Variable = 3,
7979     AO_No_Error = 4
7980   };
7981 }
7982 /// \brief Diagnose invalid operand for address of operations.
7983 ///
7984 /// \param Type The type of operand which cannot have its address taken.
7985 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7986                                          Expr *E, unsigned Type) {
7987   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7988 }
7989
7990 /// CheckAddressOfOperand - The operand of & must be either a function
7991 /// designator or an lvalue designating an object. If it is an lvalue, the
7992 /// object cannot be declared with storage class register or be a bit field.
7993 /// Note: The usual conversions are *not* applied to the operand of the &
7994 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7995 /// In C++, the operand might be an overloaded function name, in which case
7996 /// we allow the '&' but retain the overloaded-function type.
7997 static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
7998                                       SourceLocation OpLoc) {
7999   if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
8000     if (PTy->getKind() == BuiltinType::Overload) {
8001       if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
8002         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8003           << OrigOp.get()->getSourceRange();
8004         return QualType();
8005       }
8006                   
8007       return S.Context.OverloadTy;
8008     }
8009
8010     if (PTy->getKind() == BuiltinType::UnknownAny)
8011       return S.Context.UnknownAnyTy;
8012
8013     if (PTy->getKind() == BuiltinType::BoundMember) {
8014       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8015         << OrigOp.get()->getSourceRange();
8016       return QualType();
8017     }
8018
8019     OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
8020     if (OrigOp.isInvalid()) return QualType();
8021   }
8022
8023   if (OrigOp.get()->isTypeDependent())
8024     return S.Context.DependentTy;
8025
8026   assert(!OrigOp.get()->getType()->isPlaceholderType());
8027
8028   // Make sure to ignore parentheses in subsequent checks
8029   Expr *op = OrigOp.get()->IgnoreParens();
8030
8031   if (S.getLangOpts().C99) {
8032     // Implement C99-only parts of addressof rules.
8033     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
8034       if (uOp->getOpcode() == UO_Deref)
8035         // Per C99 6.5.3.2, the address of a deref always returns a valid result
8036         // (assuming the deref expression is valid).
8037         return uOp->getSubExpr()->getType();
8038     }
8039     // Technically, there should be a check for array subscript
8040     // expressions here, but the result of one is always an lvalue anyway.
8041   }
8042   ValueDecl *dcl = getPrimaryDecl(op);
8043   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
8044   unsigned AddressOfError = AO_No_Error;
8045
8046   if (lval == Expr::LV_ClassTemporary) { 
8047     bool sfinae = S.isSFINAEContext();
8048     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
8049                          : diag::ext_typecheck_addrof_class_temporary)
8050       << op->getType() << op->getSourceRange();
8051     if (sfinae)
8052       return QualType();
8053   } else if (isa<ObjCSelectorExpr>(op)) {
8054     return S.Context.getPointerType(op->getType());
8055   } else if (lval == Expr::LV_MemberFunction) {
8056     // If it's an instance method, make a member pointer.
8057     // The expression must have exactly the form &A::foo.
8058
8059     // If the underlying expression isn't a decl ref, give up.
8060     if (!isa<DeclRefExpr>(op)) {
8061       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
8062         << OrigOp.get()->getSourceRange();
8063       return QualType();
8064     }
8065     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
8066     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
8067
8068     // The id-expression was parenthesized.
8069     if (OrigOp.get() != DRE) {
8070       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
8071         << OrigOp.get()->getSourceRange();
8072
8073     // The method was named without a qualifier.
8074     } else if (!DRE->getQualifier()) {
8075       if (MD->getParent()->getName().empty())
8076         S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8077           << op->getSourceRange();
8078       else {
8079         SmallString<32> Str;
8080         StringRef Qual = (MD->getParent()->getName() + "::").toStringRef(Str);
8081         S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
8082           << op->getSourceRange()
8083           << FixItHint::CreateInsertion(op->getSourceRange().getBegin(), Qual);
8084       }
8085     }
8086
8087     return S.Context.getMemberPointerType(op->getType(),
8088               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
8089   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
8090     // C99 6.5.3.2p1
8091     // The operand must be either an l-value or a function designator
8092     if (!op->getType()->isFunctionType()) {
8093       // Use a special diagnostic for loads from property references.
8094       if (isa<PseudoObjectExpr>(op)) {
8095         AddressOfError = AO_Property_Expansion;
8096       } else {
8097         // FIXME: emit more specific diag...
8098         S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
8099           << op->getSourceRange();
8100         return QualType();
8101       }
8102     }
8103   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
8104     // The operand cannot be a bit-field
8105     AddressOfError = AO_Bit_Field;
8106   } else if (op->getObjectKind() == OK_VectorComponent) {
8107     // The operand cannot be an element of a vector
8108     AddressOfError = AO_Vector_Element;
8109   } else if (dcl) { // C99 6.5.3.2p1
8110     // We have an lvalue with a decl. Make sure the decl is not declared
8111     // with the register storage-class specifier.
8112     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
8113       // in C++ it is not error to take address of a register
8114       // variable (c++03 7.1.1P3)
8115       if (vd->getStorageClass() == SC_Register &&
8116           !S.getLangOpts().CPlusPlus) {
8117         AddressOfError = AO_Register_Variable;
8118       }
8119     } else if (isa<FunctionTemplateDecl>(dcl)) {
8120       return S.Context.OverloadTy;
8121     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
8122       // Okay: we can take the address of a field.
8123       // Could be a pointer to member, though, if there is an explicit
8124       // scope qualifier for the class.
8125       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
8126         DeclContext *Ctx = dcl->getDeclContext();
8127         if (Ctx && Ctx->isRecord()) {
8128           if (dcl->getType()->isReferenceType()) {
8129             S.Diag(OpLoc,
8130                    diag::err_cannot_form_pointer_to_member_of_reference_type)
8131               << dcl->getDeclName() << dcl->getType();
8132             return QualType();
8133           }
8134
8135           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
8136             Ctx = Ctx->getParent();
8137           return S.Context.getMemberPointerType(op->getType(),
8138                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
8139         }
8140       }
8141     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
8142       llvm_unreachable("Unknown/unexpected decl type");
8143   }
8144
8145   if (AddressOfError != AO_No_Error) {
8146     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
8147     return QualType();
8148   }
8149
8150   if (lval == Expr::LV_IncompleteVoidType) {
8151     // Taking the address of a void variable is technically illegal, but we
8152     // allow it in cases which are otherwise valid.
8153     // Example: "extern void x; void* y = &x;".
8154     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
8155   }
8156
8157   // If the operand has type "type", the result has type "pointer to type".
8158   if (op->getType()->isObjCObjectType())
8159     return S.Context.getObjCObjectPointerType(op->getType());
8160   return S.Context.getPointerType(op->getType());
8161 }
8162
8163 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
8164 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
8165                                         SourceLocation OpLoc) {
8166   if (Op->isTypeDependent())
8167     return S.Context.DependentTy;
8168
8169   ExprResult ConvResult = S.UsualUnaryConversions(Op);
8170   if (ConvResult.isInvalid())
8171     return QualType();
8172   Op = ConvResult.take();
8173   QualType OpTy = Op->getType();
8174   QualType Result;
8175
8176   if (isa<CXXReinterpretCastExpr>(Op)) {
8177     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
8178     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
8179                                      Op->getSourceRange());
8180   }
8181
8182   // Note that per both C89 and C99, indirection is always legal, even if OpTy
8183   // is an incomplete type or void.  It would be possible to warn about
8184   // dereferencing a void pointer, but it's completely well-defined, and such a
8185   // warning is unlikely to catch any mistakes.
8186   if (const PointerType *PT = OpTy->getAs<PointerType>())
8187     Result = PT->getPointeeType();
8188   else if (const ObjCObjectPointerType *OPT =
8189              OpTy->getAs<ObjCObjectPointerType>())
8190     Result = OPT->getPointeeType();
8191   else {
8192     ExprResult PR = S.CheckPlaceholderExpr(Op);
8193     if (PR.isInvalid()) return QualType();
8194     if (PR.take() != Op)
8195       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
8196   }
8197
8198   if (Result.isNull()) {
8199     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
8200       << OpTy << Op->getSourceRange();
8201     return QualType();
8202   }
8203
8204   // Dereferences are usually l-values...
8205   VK = VK_LValue;
8206
8207   // ...except that certain expressions are never l-values in C.
8208   if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
8209     VK = VK_RValue;
8210   
8211   return Result;
8212 }
8213
8214 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
8215   tok::TokenKind Kind) {
8216   BinaryOperatorKind Opc;
8217   switch (Kind) {
8218   default: llvm_unreachable("Unknown binop!");
8219   case tok::periodstar:           Opc = BO_PtrMemD; break;
8220   case tok::arrowstar:            Opc = BO_PtrMemI; break;
8221   case tok::star:                 Opc = BO_Mul; break;
8222   case tok::slash:                Opc = BO_Div; break;
8223   case tok::percent:              Opc = BO_Rem; break;
8224   case tok::plus:                 Opc = BO_Add; break;
8225   case tok::minus:                Opc = BO_Sub; break;
8226   case tok::lessless:             Opc = BO_Shl; break;
8227   case tok::greatergreater:       Opc = BO_Shr; break;
8228   case tok::lessequal:            Opc = BO_LE; break;
8229   case tok::less:                 Opc = BO_LT; break;
8230   case tok::greaterequal:         Opc = BO_GE; break;
8231   case tok::greater:              Opc = BO_GT; break;
8232   case tok::exclaimequal:         Opc = BO_NE; break;
8233   case tok::equalequal:           Opc = BO_EQ; break;
8234   case tok::amp:                  Opc = BO_And; break;
8235   case tok::caret:                Opc = BO_Xor; break;
8236   case tok::pipe:                 Opc = BO_Or; break;
8237   case tok::ampamp:               Opc = BO_LAnd; break;
8238   case tok::pipepipe:             Opc = BO_LOr; break;
8239   case tok::equal:                Opc = BO_Assign; break;
8240   case tok::starequal:            Opc = BO_MulAssign; break;
8241   case tok::slashequal:           Opc = BO_DivAssign; break;
8242   case tok::percentequal:         Opc = BO_RemAssign; break;
8243   case tok::plusequal:            Opc = BO_AddAssign; break;
8244   case tok::minusequal:           Opc = BO_SubAssign; break;
8245   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
8246   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
8247   case tok::ampequal:             Opc = BO_AndAssign; break;
8248   case tok::caretequal:           Opc = BO_XorAssign; break;
8249   case tok::pipeequal:            Opc = BO_OrAssign; break;
8250   case tok::comma:                Opc = BO_Comma; break;
8251   }
8252   return Opc;
8253 }
8254
8255 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
8256   tok::TokenKind Kind) {
8257   UnaryOperatorKind Opc;
8258   switch (Kind) {
8259   default: llvm_unreachable("Unknown unary op!");
8260   case tok::plusplus:     Opc = UO_PreInc; break;
8261   case tok::minusminus:   Opc = UO_PreDec; break;
8262   case tok::amp:          Opc = UO_AddrOf; break;
8263   case tok::star:         Opc = UO_Deref; break;
8264   case tok::plus:         Opc = UO_Plus; break;
8265   case tok::minus:        Opc = UO_Minus; break;
8266   case tok::tilde:        Opc = UO_Not; break;
8267   case tok::exclaim:      Opc = UO_LNot; break;
8268   case tok::kw___real:    Opc = UO_Real; break;
8269   case tok::kw___imag:    Opc = UO_Imag; break;
8270   case tok::kw___extension__: Opc = UO_Extension; break;
8271   }
8272   return Opc;
8273 }
8274
8275 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8276 /// This warning is only emitted for builtin assignment operations. It is also
8277 /// suppressed in the event of macro expansions.
8278 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
8279                                    SourceLocation OpLoc) {
8280   if (!S.ActiveTemplateInstantiations.empty())
8281     return;
8282   if (OpLoc.isInvalid() || OpLoc.isMacroID())
8283     return;
8284   LHSExpr = LHSExpr->IgnoreParenImpCasts();
8285   RHSExpr = RHSExpr->IgnoreParenImpCasts();
8286   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8287   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8288   if (!LHSDeclRef || !RHSDeclRef ||
8289       LHSDeclRef->getLocation().isMacroID() ||
8290       RHSDeclRef->getLocation().isMacroID())
8291     return;
8292   const ValueDecl *LHSDecl =
8293     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8294   const ValueDecl *RHSDecl =
8295     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8296   if (LHSDecl != RHSDecl)
8297     return;
8298   if (LHSDecl->getType().isVolatileQualified())
8299     return;
8300   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
8301     if (RefTy->getPointeeType().isVolatileQualified())
8302       return;
8303
8304   S.Diag(OpLoc, diag::warn_self_assignment)
8305       << LHSDeclRef->getType()
8306       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
8307 }
8308
8309 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
8310 /// operator @p Opc at location @c TokLoc. This routine only supports
8311 /// built-in operations; ActOnBinOp handles overloaded operators.
8312 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
8313                                     BinaryOperatorKind Opc,
8314                                     Expr *LHSExpr, Expr *RHSExpr) {
8315   if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
8316     // The syntax only allows initializer lists on the RHS of assignment,
8317     // so we don't need to worry about accepting invalid code for
8318     // non-assignment operators.
8319     // C++11 5.17p9:
8320     //   The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8321     //   of x = {} is x = T().
8322     InitializationKind Kind =
8323         InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8324     InitializedEntity Entity =
8325         InitializedEntity::InitializeTemporary(LHSExpr->getType());
8326     InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8327     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, RHSExpr);
8328     if (Init.isInvalid())
8329       return Init;
8330     RHSExpr = Init.take();
8331   }
8332
8333   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
8334   QualType ResultTy;     // Result type of the binary operator.
8335   // The following two variables are used for compound assignment operators
8336   QualType CompLHSTy;    // Type of LHS after promotions for computation
8337   QualType CompResultTy; // Type of computation result
8338   ExprValueKind VK = VK_RValue;
8339   ExprObjectKind OK = OK_Ordinary;
8340
8341   switch (Opc) {
8342   case BO_Assign:
8343     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
8344     if (getLangOpts().CPlusPlus &&
8345         LHS.get()->getObjectKind() != OK_ObjCProperty) {
8346       VK = LHS.get()->getValueKind();
8347       OK = LHS.get()->getObjectKind();
8348     }
8349     if (!ResultTy.isNull())
8350       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
8351     break;
8352   case BO_PtrMemD:
8353   case BO_PtrMemI:
8354     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
8355                                             Opc == BO_PtrMemI);
8356     break;
8357   case BO_Mul:
8358   case BO_Div:
8359     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
8360                                            Opc == BO_Div);
8361     break;
8362   case BO_Rem:
8363     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
8364     break;
8365   case BO_Add:
8366     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
8367     break;
8368   case BO_Sub:
8369     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
8370     break;
8371   case BO_Shl:
8372   case BO_Shr:
8373     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
8374     break;
8375   case BO_LE:
8376   case BO_LT:
8377   case BO_GE:
8378   case BO_GT:
8379     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
8380     break;
8381   case BO_EQ:
8382   case BO_NE:
8383     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
8384     break;
8385   case BO_And:
8386   case BO_Xor:
8387   case BO_Or:
8388     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
8389     break;
8390   case BO_LAnd:
8391   case BO_LOr:
8392     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
8393     break;
8394   case BO_MulAssign:
8395   case BO_DivAssign:
8396     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
8397                                                Opc == BO_DivAssign);
8398     CompLHSTy = CompResultTy;
8399     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8400       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8401     break;
8402   case BO_RemAssign:
8403     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
8404     CompLHSTy = CompResultTy;
8405     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8406       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8407     break;
8408   case BO_AddAssign:
8409     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
8410     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8411       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8412     break;
8413   case BO_SubAssign:
8414     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8415     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8416       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8417     break;
8418   case BO_ShlAssign:
8419   case BO_ShrAssign:
8420     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
8421     CompLHSTy = CompResultTy;
8422     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8423       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8424     break;
8425   case BO_AndAssign:
8426   case BO_XorAssign:
8427   case BO_OrAssign:
8428     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
8429     CompLHSTy = CompResultTy;
8430     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8431       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
8432     break;
8433   case BO_Comma:
8434     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
8435     if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
8436       VK = RHS.get()->getValueKind();
8437       OK = RHS.get()->getObjectKind();
8438     }
8439     break;
8440   }
8441   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
8442     return ExprError();
8443
8444   // Check for array bounds violations for both sides of the BinaryOperator
8445   CheckArrayAccess(LHS.get());
8446   CheckArrayAccess(RHS.get());
8447
8448   if (CompResultTy.isNull())
8449     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
8450                                               ResultTy, VK, OK, OpLoc,
8451                                               FPFeatures.fp_contract));
8452   if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
8453       OK_ObjCProperty) {
8454     VK = VK_LValue;
8455     OK = LHS.get()->getObjectKind();
8456   }
8457   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
8458                                                     ResultTy, VK, OK, CompLHSTy,
8459                                                     CompResultTy, OpLoc,
8460                                                     FPFeatures.fp_contract));
8461 }
8462
8463 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8464 /// operators are mixed in a way that suggests that the programmer forgot that
8465 /// comparison operators have higher precedence. The most typical example of
8466 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
8467 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
8468                                       SourceLocation OpLoc, Expr *LHSExpr,
8469                                       Expr *RHSExpr) {
8470   typedef BinaryOperator BinOp;
8471   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8472                 RHSopc = static_cast<BinOp::Opcode>(-1);
8473   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8474     LHSopc = BO->getOpcode();
8475   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8476     RHSopc = BO->getOpcode();
8477
8478   // Subs are not binary operators.
8479   if (LHSopc == -1 && RHSopc == -1)
8480     return;
8481
8482   // Bitwise operations are sometimes used as eager logical ops.
8483   // Don't diagnose this.
8484   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8485       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
8486     return;
8487
8488   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8489   bool isRightComp = BinOp::isComparisonOp(RHSopc);
8490   if (!isLeftComp && !isRightComp) return;
8491
8492   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8493                                                    OpLoc)
8494                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
8495   StringRef OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8496                                : BinOp::getOpcodeStr(RHSopc);
8497   SourceRange ParensRange = isLeftComp ?
8498       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8499                   RHSExpr->getLocEnd())
8500     : SourceRange(LHSExpr->getLocStart(),
8501                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
8502
8503   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8504     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8505   SuggestParentheses(Self, OpLoc,
8506     Self.PDiag(diag::note_precedence_silence) << OpStr,
8507     (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
8508   SuggestParentheses(Self, OpLoc,
8509     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8510     ParensRange);
8511 }
8512
8513 /// \brief It accepts a '&' expr that is inside a '|' one.
8514 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8515 /// in parentheses.
8516 static void
8517 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8518                                        BinaryOperator *Bop) {
8519   assert(Bop->getOpcode() == BO_And);
8520   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8521       << Bop->getSourceRange() << OpLoc;
8522   SuggestParentheses(Self, Bop->getOperatorLoc(),
8523     Self.PDiag(diag::note_precedence_silence)
8524       << Bop->getOpcodeStr(),
8525     Bop->getSourceRange());
8526 }
8527
8528 /// \brief It accepts a '&&' expr that is inside a '||' one.
8529 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8530 /// in parentheses.
8531 static void
8532 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
8533                                        BinaryOperator *Bop) {
8534   assert(Bop->getOpcode() == BO_LAnd);
8535   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8536       << Bop->getSourceRange() << OpLoc;
8537   SuggestParentheses(Self, Bop->getOperatorLoc(),
8538     Self.PDiag(diag::note_precedence_silence)
8539       << Bop->getOpcodeStr(),
8540     Bop->getSourceRange());
8541 }
8542
8543 /// \brief Returns true if the given expression can be evaluated as a constant
8544 /// 'true'.
8545 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8546   bool Res;
8547   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8548 }
8549
8550 /// \brief Returns true if the given expression can be evaluated as a constant
8551 /// 'false'.
8552 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8553   bool Res;
8554   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8555 }
8556
8557 /// \brief Look for '&&' in the left hand of a '||' expr.
8558 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
8559                                              Expr *LHSExpr, Expr *RHSExpr) {
8560   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
8561     if (Bop->getOpcode() == BO_LAnd) {
8562       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
8563       if (EvaluatesAsFalse(S, RHSExpr))
8564         return;
8565       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8566       if (!EvaluatesAsTrue(S, Bop->getLHS()))
8567         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8568     } else if (Bop->getOpcode() == BO_LOr) {
8569       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8570         // If it's "a || b && 1 || c" we didn't warn earlier for
8571         // "a || b && 1", but warn now.
8572         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8573           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8574       }
8575     }
8576   }
8577 }
8578
8579 /// \brief Look for '&&' in the right hand of a '||' expr.
8580 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
8581                                              Expr *LHSExpr, Expr *RHSExpr) {
8582   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
8583     if (Bop->getOpcode() == BO_LAnd) {
8584       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
8585       if (EvaluatesAsFalse(S, LHSExpr))
8586         return;
8587       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8588       if (!EvaluatesAsTrue(S, Bop->getRHS()))
8589         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8590     }
8591   }
8592 }
8593
8594 /// \brief Look for '&' in the left or right hand of a '|' expr.
8595 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8596                                              Expr *OrArg) {
8597   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8598     if (Bop->getOpcode() == BO_And)
8599       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8600   }
8601 }
8602
8603 static void DiagnoseAdditionInShift(Sema &S, SourceLocation OpLoc,
8604                                     Expr *SubExpr, StringRef Shift) {
8605   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(SubExpr)) {
8606     if (Bop->getOpcode() == BO_Add || Bop->getOpcode() == BO_Sub) {
8607       StringRef Op = Bop->getOpcodeStr();
8608       S.Diag(Bop->getOperatorLoc(), diag::warn_addition_in_bitshift)
8609           << Bop->getSourceRange() << OpLoc << Shift << Op;
8610       SuggestParentheses(S, Bop->getOperatorLoc(),
8611           S.PDiag(diag::note_precedence_silence) << Op,
8612           Bop->getSourceRange());
8613     }
8614   }
8615 }
8616
8617 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
8618 /// precedence.
8619 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
8620                                     SourceLocation OpLoc, Expr *LHSExpr,
8621                                     Expr *RHSExpr){
8622   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
8623   if (BinaryOperator::isBitwiseOp(Opc))
8624     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
8625
8626   // Diagnose "arg1 & arg2 | arg3"
8627   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8628     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8629     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
8630   }
8631
8632   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8633   // We don't warn for 'assert(a || b && "bad")' since this is safe.
8634   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
8635     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8636     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
8637   }
8638
8639   if ((Opc == BO_Shl && LHSExpr->getType()->isIntegralType(Self.getASTContext()))
8640       || Opc == BO_Shr) {
8641     StringRef Shift = BinaryOperator::getOpcodeStr(Opc);
8642     DiagnoseAdditionInShift(Self, OpLoc, LHSExpr, Shift);
8643     DiagnoseAdditionInShift(Self, OpLoc, RHSExpr, Shift);
8644   }
8645 }
8646
8647 // Binary Operators.  'Tok' is the token for the operator.
8648 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
8649                             tok::TokenKind Kind,
8650                             Expr *LHSExpr, Expr *RHSExpr) {
8651   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
8652   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8653   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
8654
8655   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
8656   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
8657
8658   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
8659 }
8660
8661 /// Build an overloaded binary operator expression in the given scope.
8662 static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8663                                        BinaryOperatorKind Opc,
8664                                        Expr *LHS, Expr *RHS) {
8665   // Find all of the overloaded operators visible from this
8666   // point. We perform both an operator-name lookup from the local
8667   // scope and an argument-dependent lookup based on the types of
8668   // the arguments.
8669   UnresolvedSet<16> Functions;
8670   OverloadedOperatorKind OverOp
8671     = BinaryOperator::getOverloadedOperator(Opc);
8672   if (Sc && OverOp != OO_None)
8673     S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8674                                    RHS->getType(), Functions);
8675
8676   // Build the (potentially-overloaded, potentially-dependent)
8677   // binary operation.
8678   return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8679 }
8680
8681 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
8682                             BinaryOperatorKind Opc,
8683                             Expr *LHSExpr, Expr *RHSExpr) {
8684   // We want to end up calling one of checkPseudoObjectAssignment
8685   // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8686   // both expressions are overloadable or either is type-dependent),
8687   // or CreateBuiltinBinOp (in any other case).  We also want to get
8688   // any placeholder types out of the way.
8689
8690   // Handle pseudo-objects in the LHS.
8691   if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8692     // Assignments with a pseudo-object l-value need special analysis.
8693     if (pty->getKind() == BuiltinType::PseudoObject &&
8694         BinaryOperator::isAssignmentOp(Opc))
8695       return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8696
8697     // Don't resolve overloads if the other type is overloadable.
8698     if (pty->getKind() == BuiltinType::Overload) {
8699       // We can't actually test that if we still have a placeholder,
8700       // though.  Fortunately, none of the exceptions we see in that
8701       // code below are valid when the LHS is an overload set.  Note
8702       // that an overload set can be dependently-typed, but it never
8703       // instantiates to having an overloadable type.
8704       ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8705       if (resolvedRHS.isInvalid()) return ExprError();
8706       RHSExpr = resolvedRHS.take();
8707
8708       if (RHSExpr->isTypeDependent() ||
8709           RHSExpr->getType()->isOverloadableType())
8710         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8711     }
8712         
8713     ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8714     if (LHS.isInvalid()) return ExprError();
8715     LHSExpr = LHS.take();
8716   }
8717
8718   // Handle pseudo-objects in the RHS.
8719   if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8720     // An overload in the RHS can potentially be resolved by the type
8721     // being assigned to.
8722     if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8723       if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8724         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8725
8726       if (LHSExpr->getType()->isOverloadableType())
8727         return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8728
8729       return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8730     }
8731
8732     // Don't resolve overloads if the other type is overloadable.
8733     if (pty->getKind() == BuiltinType::Overload &&
8734         LHSExpr->getType()->isOverloadableType())
8735       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8736
8737     ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8738     if (!resolvedRHS.isUsable()) return ExprError();
8739     RHSExpr = resolvedRHS.take();
8740   }
8741
8742   if (getLangOpts().CPlusPlus) {
8743     // If either expression is type-dependent, always build an
8744     // overloaded op.
8745     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8746       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8747
8748     // Otherwise, build an overloaded op if either expression has an
8749     // overloadable type.
8750     if (LHSExpr->getType()->isOverloadableType() ||
8751         RHSExpr->getType()->isOverloadableType())
8752       return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8753   }
8754
8755   // Build a built-in binary operation.
8756   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8757 }
8758
8759 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8760                                       UnaryOperatorKind Opc,
8761                                       Expr *InputExpr) {
8762   ExprResult Input = Owned(InputExpr);
8763   ExprValueKind VK = VK_RValue;
8764   ExprObjectKind OK = OK_Ordinary;
8765   QualType resultType;
8766   switch (Opc) {
8767   case UO_PreInc:
8768   case UO_PreDec:
8769   case UO_PostInc:
8770   case UO_PostDec:
8771     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8772                                                 Opc == UO_PreInc ||
8773                                                 Opc == UO_PostInc,
8774                                                 Opc == UO_PreInc ||
8775                                                 Opc == UO_PreDec);
8776     break;
8777   case UO_AddrOf:
8778     resultType = CheckAddressOfOperand(*this, Input, OpLoc);
8779     break;
8780   case UO_Deref: {
8781     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8782     if (Input.isInvalid()) return ExprError();
8783     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8784     break;
8785   }
8786   case UO_Plus:
8787   case UO_Minus:
8788     Input = UsualUnaryConversions(Input.take());
8789     if (Input.isInvalid()) return ExprError();
8790     resultType = Input.get()->getType();
8791     if (resultType->isDependentType())
8792       break;
8793     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8794         resultType->isVectorType()) 
8795       break;
8796     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
8797              resultType->isEnumeralType())
8798       break;
8799     else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
8800              Opc == UO_Plus &&
8801              resultType->isPointerType())
8802       break;
8803
8804     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8805       << resultType << Input.get()->getSourceRange());
8806
8807   case UO_Not: // bitwise complement
8808     Input = UsualUnaryConversions(Input.take());
8809     if (Input.isInvalid()) return ExprError();
8810     resultType = Input.get()->getType();
8811     if (resultType->isDependentType())
8812       break;
8813     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8814     if (resultType->isComplexType() || resultType->isComplexIntegerType())
8815       // C99 does not support '~' for complex conjugation.
8816       Diag(OpLoc, diag::ext_integer_complement_complex)
8817         << resultType << Input.get()->getSourceRange();
8818     else if (resultType->hasIntegerRepresentation())
8819       break;
8820     else {
8821       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8822         << resultType << Input.get()->getSourceRange());
8823     }
8824     break;
8825
8826   case UO_LNot: // logical negation
8827     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8828     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8829     if (Input.isInvalid()) return ExprError();
8830     resultType = Input.get()->getType();
8831
8832     // Though we still have to promote half FP to float...
8833     if (resultType->isHalfType()) {
8834       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8835       resultType = Context.FloatTy;
8836     }
8837
8838     if (resultType->isDependentType())
8839       break;
8840     if (resultType->isScalarType()) {
8841       // C99 6.5.3.3p1: ok, fallthrough;
8842       if (Context.getLangOpts().CPlusPlus) {
8843         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8844         // operand contextually converted to bool.
8845         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8846                                   ScalarTypeToBooleanCastKind(resultType));
8847       }
8848     } else if (resultType->isExtVectorType()) {
8849       // Vector logical not returns the signed variant of the operand type.
8850       resultType = GetSignedVectorType(resultType);
8851       break;
8852     } else {
8853       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8854         << resultType << Input.get()->getSourceRange());
8855     }
8856     
8857     // LNot always has type int. C99 6.5.3.3p5.
8858     // In C++, it's bool. C++ 5.3.1p8
8859     resultType = Context.getLogicalOperationType();
8860     break;
8861   case UO_Real:
8862   case UO_Imag:
8863     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8864     // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8865     // complex l-values to ordinary l-values and all other values to r-values.
8866     if (Input.isInvalid()) return ExprError();
8867     if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8868       if (Input.get()->getValueKind() != VK_RValue &&
8869           Input.get()->getObjectKind() == OK_Ordinary)
8870         VK = Input.get()->getValueKind();
8871     } else if (!getLangOpts().CPlusPlus) {
8872       // In C, a volatile scalar is read by __imag. In C++, it is not.
8873       Input = DefaultLvalueConversion(Input.take());
8874     }
8875     break;
8876   case UO_Extension:
8877     resultType = Input.get()->getType();
8878     VK = Input.get()->getValueKind();
8879     OK = Input.get()->getObjectKind();
8880     break;
8881   }
8882   if (resultType.isNull() || Input.isInvalid())
8883     return ExprError();
8884
8885   // Check for array bounds violations in the operand of the UnaryOperator,
8886   // except for the '*' and '&' operators that have to be handled specially
8887   // by CheckArrayAccess (as there are special cases like &array[arraysize]
8888   // that are explicitly defined as valid by the standard).
8889   if (Opc != UO_AddrOf && Opc != UO_Deref)
8890     CheckArrayAccess(Input.get());
8891
8892   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8893                                            VK, OK, OpLoc));
8894 }
8895
8896 /// \brief Determine whether the given expression is a qualified member
8897 /// access expression, of a form that could be turned into a pointer to member
8898 /// with the address-of operator.
8899 static bool isQualifiedMemberAccess(Expr *E) {
8900   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8901     if (!DRE->getQualifier())
8902       return false;
8903     
8904     ValueDecl *VD = DRE->getDecl();
8905     if (!VD->isCXXClassMember())
8906       return false;
8907     
8908     if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8909       return true;
8910     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8911       return Method->isInstance();
8912       
8913     return false;
8914   }
8915   
8916   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8917     if (!ULE->getQualifier())
8918       return false;
8919     
8920     for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8921                                            DEnd = ULE->decls_end();
8922          D != DEnd; ++D) {
8923       if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8924         if (Method->isInstance())
8925           return true;
8926       } else {
8927         // Overload set does not contain methods.
8928         break;
8929       }
8930     }
8931     
8932     return false;
8933   }
8934   
8935   return false;
8936 }
8937
8938 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8939                               UnaryOperatorKind Opc, Expr *Input) {
8940   // First things first: handle placeholders so that the
8941   // overloaded-operator check considers the right type.
8942   if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8943     // Increment and decrement of pseudo-object references.
8944     if (pty->getKind() == BuiltinType::PseudoObject &&
8945         UnaryOperator::isIncrementDecrementOp(Opc))
8946       return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8947
8948     // extension is always a builtin operator.
8949     if (Opc == UO_Extension)
8950       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8951
8952     // & gets special logic for several kinds of placeholder.
8953     // The builtin code knows what to do.
8954     if (Opc == UO_AddrOf &&
8955         (pty->getKind() == BuiltinType::Overload ||
8956          pty->getKind() == BuiltinType::UnknownAny ||
8957          pty->getKind() == BuiltinType::BoundMember))
8958       return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8959
8960     // Anything else needs to be handled now.
8961     ExprResult Result = CheckPlaceholderExpr(Input);
8962     if (Result.isInvalid()) return ExprError();
8963     Input = Result.take();
8964   }
8965
8966   if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
8967       UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8968       !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
8969     // Find all of the overloaded operators visible from this
8970     // point. We perform both an operator-name lookup from the local
8971     // scope and an argument-dependent lookup based on the types of
8972     // the arguments.
8973     UnresolvedSet<16> Functions;
8974     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8975     if (S && OverOp != OO_None)
8976       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8977                                    Functions);
8978
8979     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8980   }
8981
8982   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8983 }
8984
8985 // Unary Operators.  'Tok' is the token for the operator.
8986 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8987                               tok::TokenKind Op, Expr *Input) {
8988   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8989 }
8990
8991 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8992 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8993                                 LabelDecl *TheDecl) {
8994   TheDecl->setUsed();
8995   // Create the AST node.  The address of a label always has type 'void*'.
8996   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8997                                        Context.getPointerType(Context.VoidTy)));
8998 }
8999
9000 /// Given the last statement in a statement-expression, check whether
9001 /// the result is a producing expression (like a call to an
9002 /// ns_returns_retained function) and, if so, rebuild it to hoist the
9003 /// release out of the full-expression.  Otherwise, return null.
9004 /// Cannot fail.
9005 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
9006   // Should always be wrapped with one of these.
9007   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
9008   if (!cleanups) return 0;
9009
9010   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
9011   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
9012     return 0;
9013
9014   // Splice out the cast.  This shouldn't modify any interesting
9015   // features of the statement.
9016   Expr *producer = cast->getSubExpr();
9017   assert(producer->getType() == cast->getType());
9018   assert(producer->getValueKind() == cast->getValueKind());
9019   cleanups->setSubExpr(producer);
9020   return cleanups;
9021 }
9022
9023 void Sema::ActOnStartStmtExpr() {
9024   PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
9025 }
9026
9027 void Sema::ActOnStmtExprError() {
9028   // Note that function is also called by TreeTransform when leaving a
9029   // StmtExpr scope without rebuilding anything.
9030
9031   DiscardCleanupsInEvaluationContext();
9032   PopExpressionEvaluationContext();
9033 }
9034
9035 ExprResult
9036 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
9037                     SourceLocation RPLoc) { // "({..})"
9038   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
9039   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
9040
9041   if (hasAnyUnrecoverableErrorsInThisFunction())
9042     DiscardCleanupsInEvaluationContext();
9043   assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
9044   PopExpressionEvaluationContext();
9045
9046   bool isFileScope
9047     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
9048   if (isFileScope)
9049     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
9050
9051   // FIXME: there are a variety of strange constraints to enforce here, for
9052   // example, it is not possible to goto into a stmt expression apparently.
9053   // More semantic analysis is needed.
9054
9055   // If there are sub stmts in the compound stmt, take the type of the last one
9056   // as the type of the stmtexpr.
9057   QualType Ty = Context.VoidTy;
9058   bool StmtExprMayBindToTemp = false;
9059   if (!Compound->body_empty()) {
9060     Stmt *LastStmt = Compound->body_back();
9061     LabelStmt *LastLabelStmt = 0;
9062     // If LastStmt is a label, skip down through into the body.
9063     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
9064       LastLabelStmt = Label;
9065       LastStmt = Label->getSubStmt();
9066     }
9067
9068     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
9069       // Do function/array conversion on the last expression, but not
9070       // lvalue-to-rvalue.  However, initialize an unqualified type.
9071       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
9072       if (LastExpr.isInvalid())
9073         return ExprError();
9074       Ty = LastExpr.get()->getType().getUnqualifiedType();
9075
9076       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
9077         // In ARC, if the final expression ends in a consume, splice
9078         // the consume out and bind it later.  In the alternate case
9079         // (when dealing with a retainable type), the result
9080         // initialization will create a produce.  In both cases the
9081         // result will be +1, and we'll need to balance that out with
9082         // a bind.
9083         if (Expr *rebuiltLastStmt
9084               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
9085           LastExpr = rebuiltLastStmt;
9086         } else {
9087           LastExpr = PerformCopyInitialization(
9088                             InitializedEntity::InitializeResult(LPLoc, 
9089                                                                 Ty,
9090                                                                 false),
9091                                                    SourceLocation(),
9092                                                LastExpr);
9093         }
9094
9095         if (LastExpr.isInvalid())
9096           return ExprError();
9097         if (LastExpr.get() != 0) {
9098           if (!LastLabelStmt)
9099             Compound->setLastStmt(LastExpr.take());
9100           else
9101             LastLabelStmt->setSubStmt(LastExpr.take());
9102           StmtExprMayBindToTemp = true;
9103         }
9104       }
9105     }
9106   }
9107
9108   // FIXME: Check that expression type is complete/non-abstract; statement
9109   // expressions are not lvalues.
9110   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
9111   if (StmtExprMayBindToTemp)
9112     return MaybeBindToTemporary(ResStmtExpr);
9113   return Owned(ResStmtExpr);
9114 }
9115
9116 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
9117                                       TypeSourceInfo *TInfo,
9118                                       OffsetOfComponent *CompPtr,
9119                                       unsigned NumComponents,
9120                                       SourceLocation RParenLoc) {
9121   QualType ArgTy = TInfo->getType();
9122   bool Dependent = ArgTy->isDependentType();
9123   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
9124   
9125   // We must have at least one component that refers to the type, and the first
9126   // one is known to be a field designator.  Verify that the ArgTy represents
9127   // a struct/union/class.
9128   if (!Dependent && !ArgTy->isRecordType())
9129     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
9130                        << ArgTy << TypeRange);
9131   
9132   // Type must be complete per C99 7.17p3 because a declaring a variable
9133   // with an incomplete type would be ill-formed.
9134   if (!Dependent 
9135       && RequireCompleteType(BuiltinLoc, ArgTy,
9136                              diag::err_offsetof_incomplete_type, TypeRange))
9137     return ExprError();
9138   
9139   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
9140   // GCC extension, diagnose them.
9141   // FIXME: This diagnostic isn't actually visible because the location is in
9142   // a system header!
9143   if (NumComponents != 1)
9144     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
9145       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
9146   
9147   bool DidWarnAboutNonPOD = false;
9148   QualType CurrentType = ArgTy;
9149   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
9150   SmallVector<OffsetOfNode, 4> Comps;
9151   SmallVector<Expr*, 4> Exprs;
9152   for (unsigned i = 0; i != NumComponents; ++i) {
9153     const OffsetOfComponent &OC = CompPtr[i];
9154     if (OC.isBrackets) {
9155       // Offset of an array sub-field.  TODO: Should we allow vector elements?
9156       if (!CurrentType->isDependentType()) {
9157         const ArrayType *AT = Context.getAsArrayType(CurrentType);
9158         if(!AT)
9159           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
9160                            << CurrentType);
9161         CurrentType = AT->getElementType();
9162       } else
9163         CurrentType = Context.DependentTy;
9164       
9165       ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
9166       if (IdxRval.isInvalid())
9167         return ExprError();
9168       Expr *Idx = IdxRval.take();
9169
9170       // The expression must be an integral expression.
9171       // FIXME: An integral constant expression?
9172       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
9173           !Idx->getType()->isIntegerType())
9174         return ExprError(Diag(Idx->getLocStart(),
9175                               diag::err_typecheck_subscript_not_integer)
9176                          << Idx->getSourceRange());
9177
9178       // Record this array index.
9179       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
9180       Exprs.push_back(Idx);
9181       continue;
9182     }
9183     
9184     // Offset of a field.
9185     if (CurrentType->isDependentType()) {
9186       // We have the offset of a field, but we can't look into the dependent
9187       // type. Just record the identifier of the field.
9188       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
9189       CurrentType = Context.DependentTy;
9190       continue;
9191     }
9192     
9193     // We need to have a complete type to look into.
9194     if (RequireCompleteType(OC.LocStart, CurrentType,
9195                             diag::err_offsetof_incomplete_type))
9196       return ExprError();
9197     
9198     // Look for the designated field.
9199     const RecordType *RC = CurrentType->getAs<RecordType>();
9200     if (!RC) 
9201       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
9202                        << CurrentType);
9203     RecordDecl *RD = RC->getDecl();
9204     
9205     // C++ [lib.support.types]p5:
9206     //   The macro offsetof accepts a restricted set of type arguments in this
9207     //   International Standard. type shall be a POD structure or a POD union
9208     //   (clause 9).
9209     // C++11 [support.types]p4:
9210     //   If type is not a standard-layout class (Clause 9), the results are
9211     //   undefined.
9212     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
9213       bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
9214       unsigned DiagID =
9215         LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
9216                             : diag::warn_offsetof_non_pod_type;
9217
9218       if (!IsSafe && !DidWarnAboutNonPOD &&
9219           DiagRuntimeBehavior(BuiltinLoc, 0,
9220                               PDiag(DiagID)
9221                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
9222                               << CurrentType))
9223         DidWarnAboutNonPOD = true;
9224     }
9225     
9226     // Look for the field.
9227     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
9228     LookupQualifiedName(R, RD);
9229     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
9230     IndirectFieldDecl *IndirectMemberDecl = 0;
9231     if (!MemberDecl) {
9232       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
9233         MemberDecl = IndirectMemberDecl->getAnonField();
9234     }
9235
9236     if (!MemberDecl)
9237       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
9238                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
9239                                                               OC.LocEnd));
9240     
9241     // C99 7.17p3:
9242     //   (If the specified member is a bit-field, the behavior is undefined.)
9243     //
9244     // We diagnose this as an error.
9245     if (MemberDecl->isBitField()) {
9246       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
9247         << MemberDecl->getDeclName()
9248         << SourceRange(BuiltinLoc, RParenLoc);
9249       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
9250       return ExprError();
9251     }
9252
9253     RecordDecl *Parent = MemberDecl->getParent();
9254     if (IndirectMemberDecl)
9255       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
9256
9257     // If the member was found in a base class, introduce OffsetOfNodes for
9258     // the base class indirections.
9259     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9260                        /*DetectVirtual=*/false);
9261     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
9262       CXXBasePath &Path = Paths.front();
9263       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
9264            B != BEnd; ++B)
9265         Comps.push_back(OffsetOfNode(B->Base));
9266     }
9267
9268     if (IndirectMemberDecl) {
9269       for (IndirectFieldDecl::chain_iterator FI =
9270            IndirectMemberDecl->chain_begin(),
9271            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9272         assert(isa<FieldDecl>(*FI));
9273         Comps.push_back(OffsetOfNode(OC.LocStart,
9274                                      cast<FieldDecl>(*FI), OC.LocEnd));
9275       }
9276     } else
9277       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
9278
9279     CurrentType = MemberDecl->getType().getNonReferenceType(); 
9280   }
9281   
9282   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 
9283                                     TInfo, Comps, Exprs, RParenLoc));
9284 }
9285
9286 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
9287                                       SourceLocation BuiltinLoc,
9288                                       SourceLocation TypeLoc,
9289                                       ParsedType ParsedArgTy,
9290                                       OffsetOfComponent *CompPtr,
9291                                       unsigned NumComponents,
9292                                       SourceLocation RParenLoc) {
9293   
9294   TypeSourceInfo *ArgTInfo;
9295   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
9296   if (ArgTy.isNull())
9297     return ExprError();
9298
9299   if (!ArgTInfo)
9300     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9301
9302   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 
9303                               RParenLoc);
9304 }
9305
9306
9307 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
9308                                  Expr *CondExpr,
9309                                  Expr *LHSExpr, Expr *RHSExpr,
9310                                  SourceLocation RPLoc) {
9311   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9312
9313   ExprValueKind VK = VK_RValue;
9314   ExprObjectKind OK = OK_Ordinary;
9315   QualType resType;
9316   bool ValueDependent = false;
9317   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
9318     resType = Context.DependentTy;
9319     ValueDependent = true;
9320   } else {
9321     // The conditional expression is required to be a constant expression.
9322     llvm::APSInt condEval(32);
9323     ExprResult CondICE
9324       = VerifyIntegerConstantExpression(CondExpr, &condEval,
9325           diag::err_typecheck_choose_expr_requires_constant, false);
9326     if (CondICE.isInvalid())
9327       return ExprError();
9328     CondExpr = CondICE.take();
9329
9330     // If the condition is > zero, then the AST type is the same as the LSHExpr.
9331     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9332
9333     resType = ActiveExpr->getType();
9334     ValueDependent = ActiveExpr->isValueDependent();
9335     VK = ActiveExpr->getValueKind();
9336     OK = ActiveExpr->getObjectKind();
9337   }
9338
9339   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
9340                                         resType, VK, OK, RPLoc,
9341                                         resType->isDependentType(),
9342                                         ValueDependent));
9343 }
9344
9345 //===----------------------------------------------------------------------===//
9346 // Clang Extensions.
9347 //===----------------------------------------------------------------------===//
9348
9349 /// ActOnBlockStart - This callback is invoked when a block literal is started.
9350 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
9351   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
9352   PushBlockScope(CurScope, Block);
9353   CurContext->addDecl(Block);
9354   if (CurScope)
9355     PushDeclContext(CurScope, Block);
9356   else
9357     CurContext = Block;
9358
9359   getCurBlock()->HasImplicitReturnType = true;
9360
9361   // Enter a new evaluation context to insulate the block from any
9362   // cleanups from the enclosing full-expression.
9363   PushExpressionEvaluationContext(PotentiallyEvaluated);  
9364 }
9365
9366 void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9367                                Scope *CurScope) {
9368   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
9369   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
9370   BlockScopeInfo *CurBlock = getCurBlock();
9371
9372   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
9373   QualType T = Sig->getType();
9374
9375   // FIXME: We should allow unexpanded parameter packs here, but that would,
9376   // in turn, make the block expression contain unexpanded parameter packs.
9377   if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9378     // Drop the parameters.
9379     FunctionProtoType::ExtProtoInfo EPI;
9380     EPI.HasTrailingReturn = false;
9381     EPI.TypeQuals |= DeclSpec::TQ_const;
9382     T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9383                                 EPI);
9384     Sig = Context.getTrivialTypeSourceInfo(T);
9385   }
9386   
9387   // GetTypeForDeclarator always produces a function type for a block
9388   // literal signature.  Furthermore, it is always a FunctionProtoType
9389   // unless the function was written with a typedef.
9390   assert(T->isFunctionType() &&
9391          "GetTypeForDeclarator made a non-function block signature");
9392
9393   // Look for an explicit signature in that function type.
9394   FunctionProtoTypeLoc ExplicitSignature;
9395
9396   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9397   if (isa<FunctionProtoTypeLoc>(tmp)) {
9398     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9399
9400     // Check whether that explicit signature was synthesized by
9401     // GetTypeForDeclarator.  If so, don't save that as part of the
9402     // written signature.
9403     if (ExplicitSignature.getLocalRangeBegin() ==
9404         ExplicitSignature.getLocalRangeEnd()) {
9405       // This would be much cheaper if we stored TypeLocs instead of
9406       // TypeSourceInfos.
9407       TypeLoc Result = ExplicitSignature.getResultLoc();
9408       unsigned Size = Result.getFullDataSize();
9409       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9410       Sig->getTypeLoc().initializeFullCopy(Result, Size);
9411
9412       ExplicitSignature = FunctionProtoTypeLoc();
9413     }
9414   }
9415
9416   CurBlock->TheDecl->setSignatureAsWritten(Sig);
9417   CurBlock->FunctionType = T;
9418
9419   const FunctionType *Fn = T->getAs<FunctionType>();
9420   QualType RetTy = Fn->getResultType();
9421   bool isVariadic =
9422     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9423
9424   CurBlock->TheDecl->setIsVariadic(isVariadic);
9425
9426   // Don't allow returning a objc interface by value.
9427   if (RetTy->isObjCObjectType()) {
9428     Diag(ParamInfo.getLocStart(),
9429          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9430     return;
9431   }
9432
9433   // Context.DependentTy is used as a placeholder for a missing block
9434   // return type.  TODO:  what should we do with declarators like:
9435   //   ^ * { ... }
9436   // If the answer is "apply template argument deduction"....
9437   if (RetTy != Context.DependentTy) {
9438     CurBlock->ReturnType = RetTy;
9439     CurBlock->TheDecl->setBlockMissingReturnType(false);
9440     CurBlock->HasImplicitReturnType = false;
9441   }
9442
9443   // Push block parameters from the declarator if we had them.
9444   SmallVector<ParmVarDecl*, 8> Params;
9445   if (ExplicitSignature) {
9446     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9447       ParmVarDecl *Param = ExplicitSignature.getArg(I);
9448       if (Param->getIdentifier() == 0 &&
9449           !Param->isImplicit() &&
9450           !Param->isInvalidDecl() &&
9451           !getLangOpts().CPlusPlus)
9452         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
9453       Params.push_back(Param);
9454     }
9455
9456   // Fake up parameter variables if we have a typedef, like
9457   //   ^ fntype { ... }
9458   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9459     for (FunctionProtoType::arg_type_iterator
9460            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9461       ParmVarDecl *Param =
9462         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
9463                                    ParamInfo.getLocStart(),
9464                                    *I);
9465       Params.push_back(Param);
9466     }
9467   }
9468
9469   // Set the parameters on the block decl.
9470   if (!Params.empty()) {
9471     CurBlock->TheDecl->setParams(Params);
9472     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9473                              CurBlock->TheDecl->param_end(),
9474                              /*CheckParameterNames=*/false);
9475   }
9476   
9477   // Finally we can process decl attributes.
9478   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
9479
9480   // Put the parameter variables in scope.  We can bail out immediately
9481   // if we don't have any.
9482   if (Params.empty())
9483     return;
9484
9485   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
9486          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9487     (*AI)->setOwningFunction(CurBlock->TheDecl);
9488
9489     // If this has an identifier, add it to the scope stack.
9490     if ((*AI)->getIdentifier()) {
9491       CheckShadow(CurBlock->TheScope, *AI);
9492
9493       PushOnScopeChains(*AI, CurBlock->TheScope);
9494     }
9495   }
9496 }
9497
9498 /// ActOnBlockError - If there is an error parsing a block, this callback
9499 /// is invoked to pop the information about the block from the action impl.
9500 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
9501   // Leave the expression-evaluation context.
9502   DiscardCleanupsInEvaluationContext();
9503   PopExpressionEvaluationContext();
9504
9505   // Pop off CurBlock, handle nested blocks.
9506   PopDeclContext();
9507   PopFunctionScopeInfo();
9508 }
9509
9510 /// ActOnBlockStmtExpr - This is called when the body of a block statement
9511 /// literal was successfully completed.  ^(int x){...}
9512 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
9513                                     Stmt *Body, Scope *CurScope) {
9514   // If blocks are disabled, emit an error.
9515   if (!LangOpts.Blocks)
9516     Diag(CaretLoc, diag::err_blocks_disable);
9517
9518   // Leave the expression-evaluation context.
9519   if (hasAnyUnrecoverableErrorsInThisFunction())
9520     DiscardCleanupsInEvaluationContext();
9521   assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9522   PopExpressionEvaluationContext();
9523
9524   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
9525
9526   if (BSI->HasImplicitReturnType)
9527     deduceClosureReturnType(*BSI);
9528
9529   PopDeclContext();
9530
9531   QualType RetTy = Context.VoidTy;
9532   if (!BSI->ReturnType.isNull())
9533     RetTy = BSI->ReturnType;
9534
9535   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
9536   QualType BlockTy;
9537
9538   // Set the captured variables on the block.
9539   // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9540   SmallVector<BlockDecl::Capture, 4> Captures;
9541   for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9542     CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9543     if (Cap.isThisCapture())
9544       continue;
9545     BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
9546                               Cap.isNested(), Cap.getCopyExpr());
9547     Captures.push_back(NewCap);
9548   }
9549   BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9550                             BSI->CXXThisCaptureIndex != 0);
9551
9552   // If the user wrote a function type in some form, try to use that.
9553   if (!BSI->FunctionType.isNull()) {
9554     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9555
9556     FunctionType::ExtInfo Ext = FTy->getExtInfo();
9557     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9558     
9559     // Turn protoless block types into nullary block types.
9560     if (isa<FunctionNoProtoType>(FTy)) {
9561       FunctionProtoType::ExtProtoInfo EPI;
9562       EPI.ExtInfo = Ext;
9563       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9564
9565     // Otherwise, if we don't need to change anything about the function type,
9566     // preserve its sugar structure.
9567     } else if (FTy->getResultType() == RetTy &&
9568                (!NoReturn || FTy->getNoReturnAttr())) {
9569       BlockTy = BSI->FunctionType;
9570
9571     // Otherwise, make the minimal modifications to the function type.
9572     } else {
9573       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
9574       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9575       EPI.TypeQuals = 0; // FIXME: silently?
9576       EPI.ExtInfo = Ext;
9577       BlockTy = Context.getFunctionType(RetTy,
9578                                         FPT->arg_type_begin(),
9579                                         FPT->getNumArgs(),
9580                                         EPI);
9581     }
9582
9583   // If we don't have a function type, just build one from nothing.
9584   } else {
9585     FunctionProtoType::ExtProtoInfo EPI;
9586     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
9587     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
9588   }
9589
9590   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9591                            BSI->TheDecl->param_end());
9592   BlockTy = Context.getBlockPointerType(BlockTy);
9593
9594   // If needed, diagnose invalid gotos and switches in the block.
9595   if (getCurFunction()->NeedsScopeChecking() &&
9596       !hasAnyUnrecoverableErrorsInThisFunction() &&
9597       !PP.isCodeCompletionEnabled())
9598     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
9599
9600   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
9601
9602   // Try to apply the named return value optimization. We have to check again
9603   // if we can do this, though, because blocks keep return statements around
9604   // to deduce an implicit return type.
9605   if (getLangOpts().CPlusPlus && RetTy->isRecordType() &&
9606       !BSI->TheDecl->isDependentContext())
9607     computeNRVO(Body, getCurBlock());
9608   
9609   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9610   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
9611   PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
9612
9613   // If the block isn't obviously global, i.e. it captures anything at
9614   // all, then we need to do a few things in the surrounding context:
9615   if (Result->getBlockDecl()->hasCaptures()) {
9616     // First, this expression has a new cleanup object.
9617     ExprCleanupObjects.push_back(Result->getBlockDecl());
9618     ExprNeedsCleanups = true;
9619
9620     // It also gets a branch-protected scope if any of the captured
9621     // variables needs destruction.
9622     for (BlockDecl::capture_const_iterator
9623            ci = Result->getBlockDecl()->capture_begin(),
9624            ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9625       const VarDecl *var = ci->getVariable();
9626       if (var->getType().isDestructedType() != QualType::DK_none) {
9627         getCurFunction()->setHasBranchProtectedScope();
9628         break;
9629       }
9630     }
9631   }
9632
9633   return Owned(Result);
9634 }
9635
9636 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
9637                                         Expr *E, ParsedType Ty,
9638                                         SourceLocation RPLoc) {
9639   TypeSourceInfo *TInfo;
9640   GetTypeFromParser(Ty, &TInfo);
9641   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
9642 }
9643
9644 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
9645                                 Expr *E, TypeSourceInfo *TInfo,
9646                                 SourceLocation RPLoc) {
9647   Expr *OrigExpr = E;
9648
9649   // Get the va_list type
9650   QualType VaListType = Context.getBuiltinVaListType();
9651   if (VaListType->isArrayType()) {
9652     // Deal with implicit array decay; for example, on x86-64,
9653     // va_list is an array, but it's supposed to decay to
9654     // a pointer for va_arg.
9655     VaListType = Context.getArrayDecayedType(VaListType);
9656     // Make sure the input expression also decays appropriately.
9657     ExprResult Result = UsualUnaryConversions(E);
9658     if (Result.isInvalid())
9659       return ExprError();
9660     E = Result.take();
9661   } else if (VaListType->isRecordType() && getLangOpts().CPlusPlus) {
9662     // If va_list is a record type and we are compiling in C++ mode,
9663     // check the argument using reference binding.
9664     InitializedEntity Entity
9665       = InitializedEntity::InitializeParameter(Context,
9666           Context.getLValueReferenceType(VaListType), false);
9667     ExprResult Init = PerformCopyInitialization(Entity, SourceLocation(), E);
9668     if (Init.isInvalid())
9669       return ExprError();
9670     E = Init.takeAs<Expr>();
9671   } else {
9672     // Otherwise, the va_list argument must be an l-value because
9673     // it is modified by va_arg.
9674     if (!E->isTypeDependent() &&
9675         CheckForModifiableLvalue(E, BuiltinLoc, *this))
9676       return ExprError();
9677   }
9678
9679   if (!E->isTypeDependent() &&
9680       !Context.hasSameType(VaListType, E->getType())) {
9681     return ExprError(Diag(E->getLocStart(),
9682                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
9683       << OrigExpr->getType() << E->getSourceRange());
9684   }
9685
9686   if (!TInfo->getType()->isDependentType()) {
9687     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9688                             diag::err_second_parameter_to_va_arg_incomplete,
9689                             TInfo->getTypeLoc()))
9690       return ExprError();
9691
9692     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9693                                TInfo->getType(),
9694                                diag::err_second_parameter_to_va_arg_abstract,
9695                                TInfo->getTypeLoc()))
9696       return ExprError();
9697
9698     if (!TInfo->getType().isPODType(Context)) {
9699       Diag(TInfo->getTypeLoc().getBeginLoc(),
9700            TInfo->getType()->isObjCLifetimeType()
9701              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9702              : diag::warn_second_parameter_to_va_arg_not_pod)
9703         << TInfo->getType()
9704         << TInfo->getTypeLoc().getSourceRange();
9705     }
9706
9707     // Check for va_arg where arguments of the given type will be promoted
9708     // (i.e. this va_arg is guaranteed to have undefined behavior).
9709     QualType PromoteType;
9710     if (TInfo->getType()->isPromotableIntegerType()) {
9711       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9712       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9713         PromoteType = QualType();
9714     }
9715     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9716       PromoteType = Context.DoubleTy;
9717     if (!PromoteType.isNull())
9718       Diag(TInfo->getTypeLoc().getBeginLoc(),
9719           diag::warn_second_parameter_to_va_arg_never_compatible)
9720         << TInfo->getType()
9721         << PromoteType
9722         << TInfo->getTypeLoc().getSourceRange();
9723   }
9724
9725   QualType T = TInfo->getType().getNonLValueExprType(Context);
9726   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
9727 }
9728
9729 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
9730   // The type of __null will be int or long, depending on the size of
9731   // pointers on the target.
9732   QualType Ty;
9733   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9734   if (pw == Context.getTargetInfo().getIntWidth())
9735     Ty = Context.IntTy;
9736   else if (pw == Context.getTargetInfo().getLongWidth())
9737     Ty = Context.LongTy;
9738   else if (pw == Context.getTargetInfo().getLongLongWidth())
9739     Ty = Context.LongLongTy;
9740   else {
9741     llvm_unreachable("I don't know size of pointer!");
9742   }
9743
9744   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
9745 }
9746
9747 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
9748                                            Expr *SrcExpr, FixItHint &Hint) {
9749   if (!SemaRef.getLangOpts().ObjC1)
9750     return;
9751
9752   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9753   if (!PT)
9754     return;
9755
9756   // Check if the destination is of type 'id'.
9757   if (!PT->isObjCIdType()) {
9758     // Check if the destination is the 'NSString' interface.
9759     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9760     if (!ID || !ID->getIdentifier()->isStr("NSString"))
9761       return;
9762   }
9763
9764   // Ignore any parens, implicit casts (should only be
9765   // array-to-pointer decays), and not-so-opaque values.  The last is
9766   // important for making this trigger for property assignments.
9767   SrcExpr = SrcExpr->IgnoreParenImpCasts();
9768   if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9769     if (OV->getSourceExpr())
9770       SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9771
9772   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
9773   if (!SL || !SL->isAscii())
9774     return;
9775
9776   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
9777 }
9778
9779 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9780                                     SourceLocation Loc,
9781                                     QualType DstType, QualType SrcType,
9782                                     Expr *SrcExpr, AssignmentAction Action,
9783                                     bool *Complained) {
9784   if (Complained)
9785     *Complained = false;
9786
9787   // Decode the result (notice that AST's are still created for extensions).
9788   bool CheckInferredResultType = false;
9789   bool isInvalid = false;
9790   unsigned DiagKind = 0;
9791   FixItHint Hint;
9792   ConversionFixItGenerator ConvHints;
9793   bool MayHaveConvFixit = false;
9794   bool MayHaveFunctionDiff = false;
9795
9796   switch (ConvTy) {
9797   case Compatible:
9798       DiagnoseAssignmentEnum(DstType, SrcType, SrcExpr);
9799       return false;
9800
9801   case PointerToInt:
9802     DiagKind = diag::ext_typecheck_convert_pointer_int;
9803     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9804     MayHaveConvFixit = true;
9805     break;
9806   case IntToPointer:
9807     DiagKind = diag::ext_typecheck_convert_int_pointer;
9808     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9809     MayHaveConvFixit = true;
9810     break;
9811   case IncompatiblePointer:
9812     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
9813     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
9814     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9815       SrcType->isObjCObjectPointerType();
9816     if (Hint.isNull() && !CheckInferredResultType) {
9817       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9818     }
9819     MayHaveConvFixit = true;
9820     break;
9821   case IncompatiblePointerSign:
9822     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9823     break;
9824   case FunctionVoidPointer:
9825     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9826     break;
9827   case IncompatiblePointerDiscardsQualifiers: {
9828     // Perform array-to-pointer decay if necessary.
9829     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9830
9831     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9832     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9833     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9834       DiagKind = diag::err_typecheck_incompatible_address_space;
9835       break;
9836
9837
9838     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
9839       DiagKind = diag::err_typecheck_incompatible_ownership;
9840       break;
9841     }
9842
9843     llvm_unreachable("unknown error case for discarding qualifiers!");
9844     // fallthrough
9845   }
9846   case CompatiblePointerDiscardsQualifiers:
9847     // If the qualifiers lost were because we were applying the
9848     // (deprecated) C++ conversion from a string literal to a char*
9849     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
9850     // Ideally, this check would be performed in
9851     // checkPointerTypesForAssignment. However, that would require a
9852     // bit of refactoring (so that the second argument is an
9853     // expression, rather than a type), which should be done as part
9854     // of a larger effort to fix checkPointerTypesForAssignment for
9855     // C++ semantics.
9856     if (getLangOpts().CPlusPlus &&
9857         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9858       return false;
9859     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9860     break;
9861   case IncompatibleNestedPointerQualifiers:
9862     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
9863     break;
9864   case IntToBlockPointer:
9865     DiagKind = diag::err_int_to_block_pointer;
9866     break;
9867   case IncompatibleBlockPointer:
9868     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
9869     break;
9870   case IncompatibleObjCQualifiedId:
9871     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
9872     // it can give a more specific diagnostic.
9873     DiagKind = diag::warn_incompatible_qualified_id;
9874     break;
9875   case IncompatibleVectors:
9876     DiagKind = diag::warn_incompatible_vectors;
9877     break;
9878   case IncompatibleObjCWeakRef:
9879     DiagKind = diag::err_arc_weak_unavailable_assign;
9880     break;
9881   case Incompatible:
9882     DiagKind = diag::err_typecheck_convert_incompatible;
9883     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9884     MayHaveConvFixit = true;
9885     isInvalid = true;
9886     MayHaveFunctionDiff = true;
9887     break;
9888   }
9889
9890   QualType FirstType, SecondType;
9891   switch (Action) {
9892   case AA_Assigning:
9893   case AA_Initializing:
9894     // The destination type comes first.
9895     FirstType = DstType;
9896     SecondType = SrcType;
9897     break;
9898
9899   case AA_Returning:
9900   case AA_Passing:
9901   case AA_Converting:
9902   case AA_Sending:
9903   case AA_Casting:
9904     // The source type comes first.
9905     FirstType = SrcType;
9906     SecondType = DstType;
9907     break;
9908   }
9909
9910   PartialDiagnostic FDiag = PDiag(DiagKind);
9911   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9912
9913   // If we can fix the conversion, suggest the FixIts.
9914   assert(ConvHints.isNull() || Hint.isNull());
9915   if (!ConvHints.isNull()) {
9916     for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9917          HE = ConvHints.Hints.end(); HI != HE; ++HI)
9918       FDiag << *HI;
9919   } else {
9920     FDiag << Hint;
9921   }
9922   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9923
9924   if (MayHaveFunctionDiff)
9925     HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9926
9927   Diag(Loc, FDiag);
9928
9929   if (SecondType == Context.OverloadTy)
9930     NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9931                               FirstType);
9932
9933   if (CheckInferredResultType)
9934     EmitRelatedResultTypeNote(SrcExpr);
9935   
9936   if (Complained)
9937     *Complained = true;
9938   return isInvalid;
9939 }
9940
9941 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9942                                                  llvm::APSInt *Result) {
9943   class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9944   public:
9945     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9946       S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9947     }
9948   } Diagnoser;
9949   
9950   return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9951 }
9952
9953 ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9954                                                  llvm::APSInt *Result,
9955                                                  unsigned DiagID,
9956                                                  bool AllowFold) {
9957   class IDDiagnoser : public VerifyICEDiagnoser {
9958     unsigned DiagID;
9959     
9960   public:
9961     IDDiagnoser(unsigned DiagID)
9962       : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9963     
9964     virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9965       S.Diag(Loc, DiagID) << SR;
9966     }
9967   } Diagnoser(DiagID);
9968   
9969   return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9970 }
9971
9972 void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9973                                             SourceRange SR) {
9974   S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
9975 }
9976
9977 ExprResult
9978 Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9979                                       VerifyICEDiagnoser &Diagnoser,
9980                                       bool AllowFold) {
9981   SourceLocation DiagLoc = E->getLocStart();
9982
9983   if (getLangOpts().CPlusPlus0x) {
9984     // C++11 [expr.const]p5:
9985     //   If an expression of literal class type is used in a context where an
9986     //   integral constant expression is required, then that class type shall
9987     //   have a single non-explicit conversion function to an integral or
9988     //   unscoped enumeration type
9989     ExprResult Converted;
9990     if (!Diagnoser.Suppress) {
9991       class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9992       public:
9993         CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9994         
9995         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9996                                                  QualType T) {
9997           return S.Diag(Loc, diag::err_ice_not_integral) << T;
9998         }
9999         
10000         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10001                                                      SourceLocation Loc,
10002                                                      QualType T) {
10003           return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
10004         }
10005         
10006         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10007                                                        SourceLocation Loc,
10008                                                        QualType T,
10009                                                        QualType ConvTy) {
10010           return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
10011         }
10012         
10013         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10014                                                    CXXConversionDecl *Conv,
10015                                                    QualType ConvTy) {
10016           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10017                    << ConvTy->isEnumeralType() << ConvTy;
10018         }
10019         
10020         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10021                                                     QualType T) {
10022           return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
10023         }
10024         
10025         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10026                                                 CXXConversionDecl *Conv,
10027                                                 QualType ConvTy) {
10028           return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
10029                    << ConvTy->isEnumeralType() << ConvTy;
10030         }
10031         
10032         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10033                                                      SourceLocation Loc,
10034                                                      QualType T,
10035                                                      QualType ConvTy) {
10036           return DiagnosticBuilder::getEmpty();
10037         }
10038       } ConvertDiagnoser;
10039
10040       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10041                                                      ConvertDiagnoser,
10042                                              /*AllowScopedEnumerations*/ false);
10043     } else {
10044       // The caller wants to silently enquire whether this is an ICE. Don't
10045       // produce any diagnostics if it isn't.
10046       class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
10047       public:
10048         SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
10049         
10050         virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
10051                                                  QualType T) {
10052           return DiagnosticBuilder::getEmpty();
10053         }
10054         
10055         virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
10056                                                      SourceLocation Loc,
10057                                                      QualType T) {
10058           return DiagnosticBuilder::getEmpty();
10059         }
10060         
10061         virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
10062                                                        SourceLocation Loc,
10063                                                        QualType T,
10064                                                        QualType ConvTy) {
10065           return DiagnosticBuilder::getEmpty();
10066         }
10067         
10068         virtual DiagnosticBuilder noteExplicitConv(Sema &S,
10069                                                    CXXConversionDecl *Conv,
10070                                                    QualType ConvTy) {
10071           return DiagnosticBuilder::getEmpty();
10072         }
10073         
10074         virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
10075                                                     QualType T) {
10076           return DiagnosticBuilder::getEmpty();
10077         }
10078         
10079         virtual DiagnosticBuilder noteAmbiguous(Sema &S,
10080                                                 CXXConversionDecl *Conv,
10081                                                 QualType ConvTy) {
10082           return DiagnosticBuilder::getEmpty();
10083         }
10084         
10085         virtual DiagnosticBuilder diagnoseConversion(Sema &S,
10086                                                      SourceLocation Loc,
10087                                                      QualType T,
10088                                                      QualType ConvTy) {
10089           return DiagnosticBuilder::getEmpty();
10090         }
10091       } ConvertDiagnoser;
10092       
10093       Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
10094                                                      ConvertDiagnoser, false);
10095     }
10096     if (Converted.isInvalid())
10097       return Converted;
10098     E = Converted.take();
10099     if (!E->getType()->isIntegralOrUnscopedEnumerationType())
10100       return ExprError();
10101   } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
10102     // An ICE must be of integral or unscoped enumeration type.
10103     if (!Diagnoser.Suppress)
10104       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10105     return ExprError();
10106   }
10107
10108   // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
10109   // in the non-ICE case.
10110   if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
10111     if (Result)
10112       *Result = E->EvaluateKnownConstInt(Context);
10113     return Owned(E);
10114   }
10115
10116   Expr::EvalResult EvalResult;
10117   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
10118   EvalResult.Diag = &Notes;
10119
10120   // Try to evaluate the expression, and produce diagnostics explaining why it's
10121   // not a constant expression as a side-effect.
10122   bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
10123                 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
10124
10125   // In C++11, we can rely on diagnostics being produced for any expression
10126   // which is not a constant expression. If no diagnostics were produced, then
10127   // this is a constant expression.
10128   if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
10129     if (Result)
10130       *Result = EvalResult.Val.getInt();
10131     return Owned(E);
10132   }
10133
10134   // If our only note is the usual "invalid subexpression" note, just point
10135   // the caret at its location rather than producing an essentially
10136   // redundant note.
10137   if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10138         diag::note_invalid_subexpr_in_const_expr) {
10139     DiagLoc = Notes[0].first;
10140     Notes.clear();
10141   }
10142
10143   if (!Folded || !AllowFold) {
10144     if (!Diagnoser.Suppress) {
10145       Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
10146       for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10147         Diag(Notes[I].first, Notes[I].second);
10148     }
10149
10150     return ExprError();
10151   }
10152
10153   Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
10154   for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10155     Diag(Notes[I].first, Notes[I].second);
10156
10157   if (Result)
10158     *Result = EvalResult.Val.getInt();
10159   return Owned(E);
10160 }
10161
10162 namespace {
10163   // Handle the case where we conclude a expression which we speculatively
10164   // considered to be unevaluated is actually evaluated.
10165   class TransformToPE : public TreeTransform<TransformToPE> {
10166     typedef TreeTransform<TransformToPE> BaseTransform;
10167
10168   public:
10169     TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
10170
10171     // Make sure we redo semantic analysis
10172     bool AlwaysRebuild() { return true; }
10173
10174     // Make sure we handle LabelStmts correctly.
10175     // FIXME: This does the right thing, but maybe we need a more general
10176     // fix to TreeTransform?
10177     StmtResult TransformLabelStmt(LabelStmt *S) {
10178       S->getDecl()->setStmt(0);
10179       return BaseTransform::TransformLabelStmt(S);
10180     }
10181
10182     // We need to special-case DeclRefExprs referring to FieldDecls which
10183     // are not part of a member pointer formation; normal TreeTransforming
10184     // doesn't catch this case because of the way we represent them in the AST.
10185     // FIXME: This is a bit ugly; is it really the best way to handle this
10186     // case?
10187     //
10188     // Error on DeclRefExprs referring to FieldDecls.
10189     ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
10190       if (isa<FieldDecl>(E->getDecl()) &&
10191           !SemaRef.isUnevaluatedContext())
10192         return SemaRef.Diag(E->getLocation(),
10193                             diag::err_invalid_non_static_member_use)
10194             << E->getDecl() << E->getSourceRange();
10195
10196       return BaseTransform::TransformDeclRefExpr(E);
10197     }
10198
10199     // Exception: filter out member pointer formation
10200     ExprResult TransformUnaryOperator(UnaryOperator *E) {
10201       if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
10202         return E;
10203
10204       return BaseTransform::TransformUnaryOperator(E);
10205     }
10206
10207     ExprResult TransformLambdaExpr(LambdaExpr *E) {
10208       // Lambdas never need to be transformed.
10209       return E;
10210     }
10211   };
10212 }
10213
10214 ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
10215   assert(ExprEvalContexts.back().Context == Unevaluated &&
10216          "Should only transform unevaluated expressions");
10217   ExprEvalContexts.back().Context =
10218       ExprEvalContexts[ExprEvalContexts.size()-2].Context;
10219   if (ExprEvalContexts.back().Context == Unevaluated)
10220     return E;
10221   return TransformToPE(*this).TransformExpr(E);
10222 }
10223
10224 void
10225 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10226                                       Decl *LambdaContextDecl,
10227                                       bool IsDecltype) {
10228   ExprEvalContexts.push_back(
10229              ExpressionEvaluationContextRecord(NewContext,
10230                                                ExprCleanupObjects.size(),
10231                                                ExprNeedsCleanups,
10232                                                LambdaContextDecl,
10233                                                IsDecltype));
10234   ExprNeedsCleanups = false;
10235   if (!MaybeODRUseExprs.empty())
10236     std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
10237 }
10238
10239 void
10240 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
10241                                       ReuseLambdaContextDecl_t,
10242                                       bool IsDecltype) {
10243   Decl *LambdaContextDecl = ExprEvalContexts.back().LambdaContextDecl;
10244   PushExpressionEvaluationContext(NewContext, LambdaContextDecl, IsDecltype);
10245 }
10246
10247 void Sema::PopExpressionEvaluationContext() {
10248   ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
10249
10250   if (!Rec.Lambdas.empty()) {
10251     if (Rec.Context == Unevaluated) {
10252       // C++11 [expr.prim.lambda]p2:
10253       //   A lambda-expression shall not appear in an unevaluated operand
10254       //   (Clause 5).
10255       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
10256         Diag(Rec.Lambdas[I]->getLocStart(), 
10257              diag::err_lambda_unevaluated_operand);
10258     } else {
10259       // Mark the capture expressions odr-used. This was deferred
10260       // during lambda expression creation.
10261       for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
10262         LambdaExpr *Lambda = Rec.Lambdas[I];
10263         for (LambdaExpr::capture_init_iterator 
10264                   C = Lambda->capture_init_begin(),
10265                CEnd = Lambda->capture_init_end();
10266              C != CEnd; ++C) {
10267           MarkDeclarationsReferencedInExpr(*C);
10268         }
10269       }
10270     }
10271   }
10272
10273   // When are coming out of an unevaluated context, clear out any
10274   // temporaries that we may have created as part of the evaluation of
10275   // the expression in that context: they aren't relevant because they
10276   // will never be constructed.
10277   if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
10278     ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
10279                              ExprCleanupObjects.end());
10280     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
10281     CleanupVarDeclMarking();
10282     std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
10283   // Otherwise, merge the contexts together.
10284   } else {
10285     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
10286     MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
10287                             Rec.SavedMaybeODRUseExprs.end());
10288   }
10289
10290   // Pop the current expression evaluation context off the stack.
10291   ExprEvalContexts.pop_back();
10292 }
10293
10294 void Sema::DiscardCleanupsInEvaluationContext() {
10295   ExprCleanupObjects.erase(
10296          ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10297          ExprCleanupObjects.end());
10298   ExprNeedsCleanups = false;
10299   MaybeODRUseExprs.clear();
10300 }
10301
10302 ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10303   if (!E->getType()->isVariablyModifiedType())
10304     return E;
10305   return TranformToPotentiallyEvaluated(E);
10306 }
10307
10308 static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
10309   // Do not mark anything as "used" within a dependent context; wait for
10310   // an instantiation.
10311   if (SemaRef.CurContext->isDependentContext())
10312     return false;
10313
10314   switch (SemaRef.ExprEvalContexts.back().Context) {
10315     case Sema::Unevaluated:
10316       // We are in an expression that is not potentially evaluated; do nothing.
10317       // (Depending on how you read the standard, we actually do need to do
10318       // something here for null pointer constants, but the standard's
10319       // definition of a null pointer constant is completely crazy.)
10320       return false;
10321
10322     case Sema::ConstantEvaluated:
10323     case Sema::PotentiallyEvaluated:
10324       // We are in a potentially evaluated expression (or a constant-expression
10325       // in C++03); we need to do implicit template instantiation, implicitly
10326       // define class members, and mark most declarations as used.
10327       return true;
10328
10329     case Sema::PotentiallyEvaluatedIfUsed:
10330       // Referenced declarations will only be used if the construct in the
10331       // containing expression is used.
10332       return false;
10333   }
10334   llvm_unreachable("Invalid context");
10335 }
10336
10337 /// \brief Mark a function referenced, and check whether it is odr-used
10338 /// (C++ [basic.def.odr]p2, C99 6.9p3)
10339 void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10340   assert(Func && "No function?");
10341
10342   Func->setReferenced();
10343
10344   // C++11 [basic.def.odr]p3:
10345   //   A function whose name appears as a potentially-evaluated expression is
10346   //   odr-used if it is the unique lookup result or the selected member of a
10347   //   set of overloaded functions [...].
10348   //
10349   // We (incorrectly) mark overload resolution as an unevaluated context, so we
10350   // can just check that here. Skip the rest of this function if we've already
10351   // marked the function as used.
10352   if (Func->isUsed(false) || !IsPotentiallyEvaluatedContext(*this)) {
10353     // C++11 [temp.inst]p3:
10354     //   Unless a function template specialization has been explicitly
10355     //   instantiated or explicitly specialized, the function template
10356     //   specialization is implicitly instantiated when the specialization is
10357     //   referenced in a context that requires a function definition to exist.
10358     //
10359     // We consider constexpr function templates to be referenced in a context
10360     // that requires a definition to exist whenever they are referenced.
10361     //
10362     // FIXME: This instantiates constexpr functions too frequently. If this is
10363     // really an unevaluated context (and we're not just in the definition of a
10364     // function template or overload resolution or other cases which we
10365     // incorrectly consider to be unevaluated contexts), and we're not in a
10366     // subexpression which we actually need to evaluate (for instance, a
10367     // template argument, array bound or an expression in a braced-init-list),
10368     // we are not permitted to instantiate this constexpr function definition.
10369     //
10370     // FIXME: This also implicitly defines special members too frequently. They
10371     // are only supposed to be implicitly defined if they are odr-used, but they
10372     // are not odr-used from constant expressions in unevaluated contexts.
10373     // However, they cannot be referenced if they are deleted, and they are
10374     // deleted whenever the implicit definition of the special member would
10375     // fail.
10376     if (!Func->isConstexpr() || Func->getBody())
10377       return;
10378     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Func);
10379     if (!Func->isImplicitlyInstantiable() && (!MD || MD->isUserProvided()))
10380       return;
10381   }
10382
10383   // Note that this declaration has been used.
10384   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
10385     if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
10386       if (Constructor->isDefaultConstructor()) {
10387         if (Constructor->isTrivial())
10388           return;
10389         if (!Constructor->isUsed(false))
10390           DefineImplicitDefaultConstructor(Loc, Constructor);
10391       } else if (Constructor->isCopyConstructor()) {
10392         if (!Constructor->isUsed(false))
10393           DefineImplicitCopyConstructor(Loc, Constructor);
10394       } else if (Constructor->isMoveConstructor()) {
10395         if (!Constructor->isUsed(false))
10396           DefineImplicitMoveConstructor(Loc, Constructor);
10397       }
10398     }
10399
10400     MarkVTableUsed(Loc, Constructor->getParent());
10401   } else if (CXXDestructorDecl *Destructor =
10402                  dyn_cast<CXXDestructorDecl>(Func)) {
10403     if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10404         !Destructor->isUsed(false))
10405       DefineImplicitDestructor(Loc, Destructor);
10406     if (Destructor->isVirtual())
10407       MarkVTableUsed(Loc, Destructor->getParent());
10408   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
10409     if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10410         MethodDecl->isOverloadedOperator() &&
10411         MethodDecl->getOverloadedOperator() == OO_Equal) {
10412       if (!MethodDecl->isUsed(false)) {
10413         if (MethodDecl->isCopyAssignmentOperator())
10414           DefineImplicitCopyAssignment(Loc, MethodDecl);
10415         else
10416           DefineImplicitMoveAssignment(Loc, MethodDecl);
10417       }
10418     } else if (isa<CXXConversionDecl>(MethodDecl) &&
10419                MethodDecl->getParent()->isLambda()) {
10420       CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10421       if (Conversion->isLambdaToBlockPointerConversion())
10422         DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10423       else
10424         DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
10425     } else if (MethodDecl->isVirtual())
10426       MarkVTableUsed(Loc, MethodDecl->getParent());
10427   }
10428
10429   // Recursive functions should be marked when used from another function.
10430   // FIXME: Is this really right?
10431   if (CurContext == Func) return;
10432
10433   // Resolve the exception specification for any function which is
10434   // used: CodeGen will need it.
10435   const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10436   if (FPT && isUnresolvedExceptionSpec(FPT->getExceptionSpecType()))
10437     ResolveExceptionSpec(Loc, FPT);
10438
10439   // Implicit instantiation of function templates and member functions of
10440   // class templates.
10441   if (Func->isImplicitlyInstantiable()) {
10442     bool AlreadyInstantiated = false;
10443     SourceLocation PointOfInstantiation = Loc;
10444     if (FunctionTemplateSpecializationInfo *SpecInfo
10445                               = Func->getTemplateSpecializationInfo()) {
10446       if (SpecInfo->getPointOfInstantiation().isInvalid())
10447         SpecInfo->setPointOfInstantiation(Loc);
10448       else if (SpecInfo->getTemplateSpecializationKind()
10449                  == TSK_ImplicitInstantiation) {
10450         AlreadyInstantiated = true;
10451         PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10452       }
10453     } else if (MemberSpecializationInfo *MSInfo
10454                                 = Func->getMemberSpecializationInfo()) {
10455       if (MSInfo->getPointOfInstantiation().isInvalid())
10456         MSInfo->setPointOfInstantiation(Loc);
10457       else if (MSInfo->getTemplateSpecializationKind()
10458                  == TSK_ImplicitInstantiation) {
10459         AlreadyInstantiated = true;
10460         PointOfInstantiation = MSInfo->getPointOfInstantiation();
10461       }
10462     }
10463
10464     if (!AlreadyInstantiated || Func->isConstexpr()) {
10465       if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10466           cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
10467         PendingLocalImplicitInstantiations.push_back(
10468             std::make_pair(Func, PointOfInstantiation));
10469       else if (Func->isConstexpr())
10470         // Do not defer instantiations of constexpr functions, to avoid the
10471         // expression evaluator needing to call back into Sema if it sees a
10472         // call to such a function.
10473         InstantiateFunctionDefinition(PointOfInstantiation, Func);
10474       else {
10475         PendingInstantiations.push_back(std::make_pair(Func,
10476                                                        PointOfInstantiation));
10477         // Notify the consumer that a function was implicitly instantiated.
10478         Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10479       }
10480     }
10481   } else {
10482     // Walk redefinitions, as some of them may be instantiable.
10483     for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10484          e(Func->redecls_end()); i != e; ++i) {
10485       if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10486         MarkFunctionReferenced(Loc, *i);
10487     }
10488   }
10489
10490   // Keep track of used but undefined functions.
10491   if (!Func->isPure() && !Func->hasBody() &&
10492       Func->getLinkage() != ExternalLinkage) {
10493     SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10494     if (old.isInvalid()) old = Loc;
10495   }
10496
10497   Func->setUsed(true);
10498 }
10499
10500 static void
10501 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10502                                    VarDecl *var, DeclContext *DC) {
10503   DeclContext *VarDC = var->getDeclContext();
10504
10505   //  If the parameter still belongs to the translation unit, then
10506   //  we're actually just using one parameter in the declaration of
10507   //  the next.
10508   if (isa<ParmVarDecl>(var) &&
10509       isa<TranslationUnitDecl>(VarDC))
10510     return;
10511
10512   // For C code, don't diagnose about capture if we're not actually in code
10513   // right now; it's impossible to write a non-constant expression outside of
10514   // function context, so we'll get other (more useful) diagnostics later.
10515   //
10516   // For C++, things get a bit more nasty... it would be nice to suppress this
10517   // diagnostic for certain cases like using a local variable in an array bound
10518   // for a member of a local class, but the correct predicate is not obvious.
10519   if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
10520     return;
10521
10522   if (isa<CXXMethodDecl>(VarDC) &&
10523       cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10524     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10525       << var->getIdentifier();
10526   } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10527     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10528       << var->getIdentifier() << fn->getDeclName();
10529   } else if (isa<BlockDecl>(VarDC)) {
10530     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10531       << var->getIdentifier();
10532   } else {
10533     // FIXME: Is there any other context where a local variable can be
10534     // declared?
10535     S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10536       << var->getIdentifier();
10537   }
10538
10539   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10540     << var->getIdentifier();
10541
10542   // FIXME: Add additional diagnostic info about class etc. which prevents
10543   // capture.
10544 }
10545
10546 /// \brief Capture the given variable in the given lambda expression.
10547 static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
10548                                   VarDecl *Var, QualType FieldType, 
10549                                   QualType DeclRefType,
10550                                   SourceLocation Loc,
10551                                   bool RefersToEnclosingLocal) {
10552   CXXRecordDecl *Lambda = LSI->Lambda;
10553
10554   // Build the non-static data member.
10555   FieldDecl *Field
10556     = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10557                         S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
10558                         0, false, ICIS_NoInit);
10559   Field->setImplicit(true);
10560   Field->setAccess(AS_private);
10561   Lambda->addDecl(Field);
10562
10563   // C++11 [expr.prim.lambda]p21:
10564   //   When the lambda-expression is evaluated, the entities that
10565   //   are captured by copy are used to direct-initialize each
10566   //   corresponding non-static data member of the resulting closure
10567   //   object. (For array members, the array elements are
10568   //   direct-initialized in increasing subscript order.) These
10569   //   initializations are performed in the (unspecified) order in
10570   //   which the non-static data members are declared.
10571       
10572   // Introduce a new evaluation context for the initialization, so
10573   // that temporaries introduced as part of the capture are retained
10574   // to be re-"exported" from the lambda expression itself.
10575   S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10576
10577   // C++ [expr.prim.labda]p12:
10578   //   An entity captured by a lambda-expression is odr-used (3.2) in
10579   //   the scope containing the lambda-expression.
10580   Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal, 
10581                                           DeclRefType, VK_LValue, Loc);
10582   Var->setReferenced(true);
10583   Var->setUsed(true);
10584
10585   // When the field has array type, create index variables for each
10586   // dimension of the array. We use these index variables to subscript
10587   // the source array, and other clients (e.g., CodeGen) will perform
10588   // the necessary iteration with these index variables.
10589   SmallVector<VarDecl *, 4> IndexVariables;
10590   QualType BaseType = FieldType;
10591   QualType SizeType = S.Context.getSizeType();
10592   LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
10593   while (const ConstantArrayType *Array
10594                         = S.Context.getAsConstantArrayType(BaseType)) {
10595     // Create the iteration variable for this array index.
10596     IdentifierInfo *IterationVarName = 0;
10597     {
10598       SmallString<8> Str;
10599       llvm::raw_svector_ostream OS(Str);
10600       OS << "__i" << IndexVariables.size();
10601       IterationVarName = &S.Context.Idents.get(OS.str());
10602     }
10603     VarDecl *IterationVar
10604       = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10605                         IterationVarName, SizeType,
10606                         S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10607                         SC_None, SC_None);
10608     IndexVariables.push_back(IterationVar);
10609     LSI->ArrayIndexVars.push_back(IterationVar);
10610     
10611     // Create a reference to the iteration variable.
10612     ExprResult IterationVarRef
10613       = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10614     assert(!IterationVarRef.isInvalid() &&
10615            "Reference to invented variable cannot fail!");
10616     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10617     assert(!IterationVarRef.isInvalid() &&
10618            "Conversion of invented variable cannot fail!");
10619     
10620     // Subscript the array with this iteration variable.
10621     ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10622                              Ref, Loc, IterationVarRef.take(), Loc);
10623     if (Subscript.isInvalid()) {
10624       S.CleanupVarDeclMarking();
10625       S.DiscardCleanupsInEvaluationContext();
10626       S.PopExpressionEvaluationContext();
10627       return ExprError();
10628     }
10629
10630     Ref = Subscript.take();
10631     BaseType = Array->getElementType();
10632   }
10633
10634   // Construct the entity that we will be initializing. For an array, this
10635   // will be first element in the array, which may require several levels
10636   // of array-subscript entities. 
10637   SmallVector<InitializedEntity, 4> Entities;
10638   Entities.reserve(1 + IndexVariables.size());
10639   Entities.push_back(
10640     InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
10641   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10642     Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10643                                                             0,
10644                                                             Entities.back()));
10645
10646   InitializationKind InitKind
10647     = InitializationKind::CreateDirect(Loc, Loc, Loc);
10648   InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
10649   ExprResult Result(true);
10650   if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10651     Result = Init.Perform(S, Entities.back(), InitKind, Ref);
10652
10653   // If this initialization requires any cleanups (e.g., due to a
10654   // default argument to a copy constructor), note that for the
10655   // lambda.
10656   if (S.ExprNeedsCleanups)
10657     LSI->ExprNeedsCleanups = true;
10658
10659   // Exit the expression evaluation context used for the capture.
10660   S.CleanupVarDeclMarking();
10661   S.DiscardCleanupsInEvaluationContext();
10662   S.PopExpressionEvaluationContext();
10663   return Result;
10664 }
10665
10666 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc, 
10667                               TryCaptureKind Kind, SourceLocation EllipsisLoc,
10668                               bool BuildAndDiagnose, 
10669                               QualType &CaptureType,
10670                               QualType &DeclRefType) {
10671   bool Nested = false;
10672   
10673   DeclContext *DC = CurContext;
10674   if (Var->getDeclContext() == DC) return true;
10675   if (!Var->hasLocalStorage()) return true;
10676
10677   bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
10678
10679   // Walk up the stack to determine whether we can capture the variable,
10680   // performing the "simple" checks that don't depend on type. We stop when
10681   // we've either hit the declared scope of the variable or find an existing
10682   // capture of that variable.
10683   CaptureType = Var->getType();
10684   DeclRefType = CaptureType.getNonReferenceType();
10685   bool Explicit = (Kind != TryCapture_Implicit);
10686   unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
10687   do {
10688     // Only block literals and lambda expressions can capture; other
10689     // scopes don't work.
10690     DeclContext *ParentDC;
10691     if (isa<BlockDecl>(DC))
10692       ParentDC = DC->getParent();
10693     else if (isa<CXXMethodDecl>(DC) &&
10694              cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
10695              cast<CXXRecordDecl>(DC->getParent())->isLambda())
10696       ParentDC = DC->getParent()->getParent();
10697     else {
10698       if (BuildAndDiagnose)
10699         diagnoseUncapturableValueReference(*this, Loc, Var, DC);
10700       return true;
10701     }
10702
10703     CapturingScopeInfo *CSI =
10704       cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
10705
10706     // Check whether we've already captured it.
10707     if (CSI->CaptureMap.count(Var)) {
10708       // If we found a capture, any subcaptures are nested.
10709       Nested = true;
10710       
10711       // Retrieve the capture type for this variable.
10712       CaptureType = CSI->getCapture(Var).getCaptureType();
10713       
10714       // Compute the type of an expression that refers to this variable.
10715       DeclRefType = CaptureType.getNonReferenceType();
10716       
10717       const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10718       if (Cap.isCopyCapture() &&
10719           !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10720         DeclRefType.addConst();
10721       break;
10722     }
10723
10724     bool IsBlock = isa<BlockScopeInfo>(CSI);
10725     bool IsLambda = !IsBlock;
10726
10727     // Lambdas are not allowed to capture unnamed variables
10728     // (e.g. anonymous unions).
10729     // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10730     // assuming that's the intent.
10731     if (IsLambda && !Var->getDeclName()) {
10732       if (BuildAndDiagnose) {
10733         Diag(Loc, diag::err_lambda_capture_anonymous_var);
10734         Diag(Var->getLocation(), diag::note_declared_at);
10735       }
10736       return true;
10737     }
10738
10739     // Prohibit variably-modified types; they're difficult to deal with.
10740     if (Var->getType()->isVariablyModifiedType()) {
10741       if (BuildAndDiagnose) {
10742         if (IsBlock)
10743           Diag(Loc, diag::err_ref_vm_type);
10744         else
10745           Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10746         Diag(Var->getLocation(), diag::note_previous_decl) 
10747           << Var->getDeclName();
10748       }
10749       return true;
10750     }
10751
10752     // Lambdas are not allowed to capture __block variables; they don't
10753     // support the expected semantics.
10754     if (IsLambda && HasBlocksAttr) {
10755       if (BuildAndDiagnose) {
10756         Diag(Loc, diag::err_lambda_capture_block) 
10757           << Var->getDeclName();
10758         Diag(Var->getLocation(), diag::note_previous_decl) 
10759           << Var->getDeclName();
10760       }
10761       return true;
10762     }
10763
10764     if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10765       // No capture-default
10766       if (BuildAndDiagnose) {
10767         Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10768         Diag(Var->getLocation(), diag::note_previous_decl) 
10769           << Var->getDeclName();
10770         Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10771              diag::note_lambda_decl);
10772       }
10773       return true;
10774     }
10775
10776     FunctionScopesIndex--;
10777     DC = ParentDC;
10778     Explicit = false;
10779   } while (!Var->getDeclContext()->Equals(DC));
10780
10781   // Walk back down the scope stack, computing the type of the capture at
10782   // each step, checking type-specific requirements, and adding captures if
10783   // requested.
10784   for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N; 
10785        ++I) {
10786     CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
10787     
10788     // Compute the type of the capture and of a reference to the capture within
10789     // this scope.
10790     if (isa<BlockScopeInfo>(CSI)) {
10791       Expr *CopyExpr = 0;
10792       bool ByRef = false;
10793       
10794       // Blocks are not allowed to capture arrays.
10795       if (CaptureType->isArrayType()) {
10796         if (BuildAndDiagnose) {
10797           Diag(Loc, diag::err_ref_array_type);
10798           Diag(Var->getLocation(), diag::note_previous_decl) 
10799           << Var->getDeclName();
10800         }
10801         return true;
10802       }
10803
10804       // Forbid the block-capture of autoreleasing variables.
10805       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10806         if (BuildAndDiagnose) {
10807           Diag(Loc, diag::err_arc_autoreleasing_capture)
10808             << /*block*/ 0;
10809           Diag(Var->getLocation(), diag::note_previous_decl)
10810             << Var->getDeclName();
10811         }
10812         return true;
10813       }
10814
10815       if (HasBlocksAttr || CaptureType->isReferenceType()) {
10816         // Block capture by reference does not change the capture or
10817         // declaration reference types.
10818         ByRef = true;
10819       } else {
10820         // Block capture by copy introduces 'const'.
10821         CaptureType = CaptureType.getNonReferenceType().withConst();
10822         DeclRefType = CaptureType;
10823                 
10824         if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
10825           if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10826             // The capture logic needs the destructor, so make sure we mark it.
10827             // Usually this is unnecessary because most local variables have
10828             // their destructors marked at declaration time, but parameters are
10829             // an exception because it's technically only the call site that
10830             // actually requires the destructor.
10831             if (isa<ParmVarDecl>(Var))
10832               FinalizeVarWithDestructor(Var, Record);
10833             
10834             // According to the blocks spec, the capture of a variable from
10835             // the stack requires a const copy constructor.  This is not true
10836             // of the copy/move done to move a __block variable to the heap.
10837             Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
10838                                                       DeclRefType.withConst(), 
10839                                                       VK_LValue, Loc);
10840             ExprResult Result
10841               = PerformCopyInitialization(
10842                   InitializedEntity::InitializeBlock(Var->getLocation(),
10843                                                      CaptureType, false),
10844                   Loc, Owned(DeclRef));
10845             
10846             // Build a full-expression copy expression if initialization
10847             // succeeded and used a non-trivial constructor.  Recover from
10848             // errors by pretending that the copy isn't necessary.
10849             if (!Result.isInvalid() &&
10850                 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10851                    ->isTrivial()) {
10852               Result = MaybeCreateExprWithCleanups(Result);
10853               CopyExpr = Result.take();
10854             }
10855           }
10856         }
10857       }
10858
10859       // Actually capture the variable.
10860       if (BuildAndDiagnose)
10861         CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc, 
10862                         SourceLocation(), CaptureType, CopyExpr);
10863       Nested = true;
10864       continue;
10865     } 
10866     
10867     LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10868     
10869     // Determine whether we are capturing by reference or by value.
10870     bool ByRef = false;
10871     if (I == N - 1 && Kind != TryCapture_Implicit) {
10872       ByRef = (Kind == TryCapture_ExplicitByRef);
10873     } else {
10874       ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
10875     }
10876     
10877     // Compute the type of the field that will capture this variable.
10878     if (ByRef) {
10879       // C++11 [expr.prim.lambda]p15:
10880       //   An entity is captured by reference if it is implicitly or
10881       //   explicitly captured but not captured by copy. It is
10882       //   unspecified whether additional unnamed non-static data
10883       //   members are declared in the closure type for entities
10884       //   captured by reference.
10885       //
10886       // FIXME: It is not clear whether we want to build an lvalue reference
10887       // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10888       // to do the former, while EDG does the latter. Core issue 1249 will 
10889       // clarify, but for now we follow GCC because it's a more permissive and
10890       // easily defensible position.
10891       CaptureType = Context.getLValueReferenceType(DeclRefType);
10892     } else {
10893       // C++11 [expr.prim.lambda]p14:
10894       //   For each entity captured by copy, an unnamed non-static
10895       //   data member is declared in the closure type. The
10896       //   declaration order of these members is unspecified. The type
10897       //   of such a data member is the type of the corresponding
10898       //   captured entity if the entity is not a reference to an
10899       //   object, or the referenced type otherwise. [Note: If the
10900       //   captured entity is a reference to a function, the
10901       //   corresponding data member is also a reference to a
10902       //   function. - end note ]
10903       if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10904         if (!RefType->getPointeeType()->isFunctionType())
10905           CaptureType = RefType->getPointeeType();
10906       }
10907
10908       // Forbid the lambda copy-capture of autoreleasing variables.
10909       if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10910         if (BuildAndDiagnose) {
10911           Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10912           Diag(Var->getLocation(), diag::note_previous_decl)
10913             << Var->getDeclName();
10914         }
10915         return true;
10916       }
10917     }
10918
10919     // Capture this variable in the lambda.
10920     Expr *CopyExpr = 0;
10921     if (BuildAndDiagnose) {
10922       ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10923                                           DeclRefType, Loc,
10924                                           I == N-1);
10925       if (!Result.isInvalid())
10926         CopyExpr = Result.take();
10927     }
10928     
10929     // Compute the type of a reference to this captured variable.
10930     if (ByRef)
10931       DeclRefType = CaptureType.getNonReferenceType();
10932     else {
10933       // C++ [expr.prim.lambda]p5:
10934       //   The closure type for a lambda-expression has a public inline 
10935       //   function call operator [...]. This function call operator is 
10936       //   declared const (9.3.1) if and only if the lambda-expression’s 
10937       //   parameter-declaration-clause is not followed by mutable.
10938       DeclRefType = CaptureType.getNonReferenceType();
10939       if (!LSI->Mutable && !CaptureType->isReferenceType())
10940         DeclRefType.addConst();      
10941     }
10942     
10943     // Add the capture.
10944     if (BuildAndDiagnose)
10945       CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10946                       EllipsisLoc, CaptureType, CopyExpr);
10947     Nested = true;
10948   }
10949
10950   return false;
10951 }
10952
10953 bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10954                               TryCaptureKind Kind, SourceLocation EllipsisLoc) {  
10955   QualType CaptureType;
10956   QualType DeclRefType;
10957   return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10958                             /*BuildAndDiagnose=*/true, CaptureType,
10959                             DeclRefType);
10960 }
10961
10962 QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10963   QualType CaptureType;
10964   QualType DeclRefType;
10965   
10966   // Determine whether we can capture this variable.
10967   if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10968                          /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10969     return QualType();
10970
10971   return DeclRefType;
10972 }
10973
10974 static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10975                                SourceLocation Loc) {
10976   // Keep track of used but undefined variables.
10977   // FIXME: We shouldn't suppress this warning for static data members.
10978   if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
10979       Var->getLinkage() != ExternalLinkage &&
10980       !(Var->isStaticDataMember() && Var->hasInit())) {
10981     SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10982     if (old.isInvalid()) old = Loc;
10983   }
10984
10985   SemaRef.tryCaptureVariable(Var, Loc);
10986
10987   Var->setUsed(true);
10988 }
10989
10990 void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10991   // Per C++11 [basic.def.odr], a variable is odr-used "unless it is 
10992   // an object that satisfies the requirements for appearing in a
10993   // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10994   // is immediately applied."  This function handles the lvalue-to-rvalue
10995   // conversion part.
10996   MaybeODRUseExprs.erase(E->IgnoreParens());
10997 }
10998
10999 ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
11000   if (!Res.isUsable())
11001     return Res;
11002
11003   // If a constant-expression is a reference to a variable where we delay
11004   // deciding whether it is an odr-use, just assume we will apply the
11005   // lvalue-to-rvalue conversion.  In the one case where this doesn't happen
11006   // (a non-type template argument), we have special handling anyway.
11007   UpdateMarkingForLValueToRValue(Res.get());
11008   return Res;
11009 }
11010
11011 void Sema::CleanupVarDeclMarking() {
11012   for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
11013                                         e = MaybeODRUseExprs.end();
11014        i != e; ++i) {
11015     VarDecl *Var;
11016     SourceLocation Loc;
11017     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
11018       Var = cast<VarDecl>(DRE->getDecl());
11019       Loc = DRE->getLocation();
11020     } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
11021       Var = cast<VarDecl>(ME->getMemberDecl());
11022       Loc = ME->getMemberLoc();
11023     } else {
11024       llvm_unreachable("Unexpcted expression");
11025     }
11026
11027     MarkVarDeclODRUsed(*this, Var, Loc);
11028   }
11029
11030   MaybeODRUseExprs.clear();
11031 }
11032
11033 // Mark a VarDecl referenced, and perform the necessary handling to compute
11034 // odr-uses.
11035 static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
11036                                     VarDecl *Var, Expr *E) {
11037   Var->setReferenced();
11038
11039   if (!IsPotentiallyEvaluatedContext(SemaRef))
11040     return;
11041
11042   // Implicit instantiation of static data members of class templates.
11043   if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
11044     MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
11045     assert(MSInfo && "Missing member specialization information?");
11046     bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
11047     if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
11048         (!AlreadyInstantiated ||
11049          Var->isUsableInConstantExpressions(SemaRef.Context))) {
11050       if (!AlreadyInstantiated) {
11051         // This is a modification of an existing AST node. Notify listeners.
11052         if (ASTMutationListener *L = SemaRef.getASTMutationListener())
11053           L->StaticDataMemberInstantiated(Var);
11054         MSInfo->setPointOfInstantiation(Loc);
11055       }
11056       SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
11057       if (Var->isUsableInConstantExpressions(SemaRef.Context))
11058         // Do not defer instantiations of variables which could be used in a
11059         // constant expression.
11060         SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
11061       else
11062         SemaRef.PendingInstantiations.push_back(
11063             std::make_pair(Var, PointOfInstantiation));
11064     }
11065   }
11066
11067   // Per C++11 [basic.def.odr], a variable is odr-used "unless it satisfies
11068   // the requirements for appearing in a constant expression (5.19) and, if
11069   // it is an object, the lvalue-to-rvalue conversion (4.1)
11070   // is immediately applied."  We check the first part here, and
11071   // Sema::UpdateMarkingForLValueToRValue deals with the second part.
11072   // Note that we use the C++11 definition everywhere because nothing in
11073   // C++03 depends on whether we get the C++03 version correct. The second
11074   // part does not apply to references, since they are not objects.
11075   const VarDecl *DefVD;
11076   if (E && !isa<ParmVarDecl>(Var) &&
11077       Var->isUsableInConstantExpressions(SemaRef.Context) &&
11078       Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE()) {
11079     if (!Var->getType()->isReferenceType())
11080       SemaRef.MaybeODRUseExprs.insert(E);
11081   } else
11082     MarkVarDeclODRUsed(SemaRef, Var, Loc);
11083 }
11084
11085 /// \brief Mark a variable referenced, and check whether it is odr-used
11086 /// (C++ [basic.def.odr]p2, C99 6.9p3).  Note that this should not be
11087 /// used directly for normal expressions referring to VarDecl.
11088 void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
11089   DoMarkVarDeclReferenced(*this, Loc, Var, 0);
11090 }
11091
11092 static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
11093                                Decl *D, Expr *E) {
11094   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
11095     DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
11096     return;
11097   }
11098
11099   SemaRef.MarkAnyDeclReferenced(Loc, D);
11100
11101   // If this is a call to a method via a cast, also mark the method in the
11102   // derived class used in case codegen can devirtualize the call.
11103   const MemberExpr *ME = dyn_cast<MemberExpr>(E);
11104   if (!ME)
11105     return;
11106   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
11107   if (!MD)
11108     return;
11109   const Expr *Base = ME->getBase();
11110   const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
11111   if (!MostDerivedClassDecl)
11112     return;
11113   CXXMethodDecl *DM = MD->getCorrespondingMethodInClass(MostDerivedClassDecl);
11114   if (!DM)
11115     return;
11116   SemaRef.MarkAnyDeclReferenced(Loc, DM);
11117
11118
11119 /// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
11120 void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
11121   MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
11122 }
11123
11124 /// \brief Perform reference-marking and odr-use handling for a MemberExpr.
11125 void Sema::MarkMemberReferenced(MemberExpr *E) {
11126   MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
11127 }
11128
11129 /// \brief Perform marking for a reference to an arbitrary declaration.  It
11130 /// marks the declaration referenced, and performs odr-use checking for functions
11131 /// and variables. This method should not be used when building an normal
11132 /// expression which refers to a variable.
11133 void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
11134   if (VarDecl *VD = dyn_cast<VarDecl>(D))
11135     MarkVariableReferenced(Loc, VD);
11136   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
11137     MarkFunctionReferenced(Loc, FD);
11138   else
11139     D->setReferenced();
11140 }
11141
11142 namespace {
11143   // Mark all of the declarations referenced
11144   // FIXME: Not fully implemented yet! We need to have a better understanding
11145   // of when we're entering
11146   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
11147     Sema &S;
11148     SourceLocation Loc;
11149
11150   public:
11151     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
11152
11153     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
11154
11155     bool TraverseTemplateArgument(const TemplateArgument &Arg);
11156     bool TraverseRecordType(RecordType *T);
11157   };
11158 }
11159
11160 bool MarkReferencedDecls::TraverseTemplateArgument(
11161   const TemplateArgument &Arg) {
11162   if (Arg.getKind() == TemplateArgument::Declaration) {
11163     if (Decl *D = Arg.getAsDecl())
11164       S.MarkAnyDeclReferenced(Loc, D);
11165   }
11166
11167   return Inherited::TraverseTemplateArgument(Arg);
11168 }
11169
11170 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
11171   if (ClassTemplateSpecializationDecl *Spec
11172                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
11173     const TemplateArgumentList &Args = Spec->getTemplateArgs();
11174     return TraverseTemplateArguments(Args.data(), Args.size());
11175   }
11176
11177   return true;
11178 }
11179
11180 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
11181   MarkReferencedDecls Marker(*this, Loc);
11182   Marker.TraverseType(Context.getCanonicalType(T));
11183 }
11184
11185 namespace {
11186   /// \brief Helper class that marks all of the declarations referenced by
11187   /// potentially-evaluated subexpressions as "referenced".
11188   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
11189     Sema &S;
11190     bool SkipLocalVariables;
11191     
11192   public:
11193     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
11194     
11195     EvaluatedExprMarker(Sema &S, bool SkipLocalVariables) 
11196       : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
11197     
11198     void VisitDeclRefExpr(DeclRefExpr *E) {
11199       // If we were asked not to visit local variables, don't.
11200       if (SkipLocalVariables) {
11201         if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
11202           if (VD->hasLocalStorage())
11203             return;
11204       }
11205       
11206       S.MarkDeclRefReferenced(E);
11207     }
11208     
11209     void VisitMemberExpr(MemberExpr *E) {
11210       S.MarkMemberReferenced(E);
11211       Inherited::VisitMemberExpr(E);
11212     }
11213     
11214     void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
11215       S.MarkFunctionReferenced(E->getLocStart(),
11216             const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
11217       Visit(E->getSubExpr());
11218     }
11219     
11220     void VisitCXXNewExpr(CXXNewExpr *E) {
11221       if (E->getOperatorNew())
11222         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
11223       if (E->getOperatorDelete())
11224         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11225       Inherited::VisitCXXNewExpr(E);
11226     }
11227
11228     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
11229       if (E->getOperatorDelete())
11230         S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
11231       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
11232       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
11233         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
11234         S.MarkFunctionReferenced(E->getLocStart(), 
11235                                     S.LookupDestructor(Record));
11236       }
11237       
11238       Inherited::VisitCXXDeleteExpr(E);
11239     }
11240     
11241     void VisitCXXConstructExpr(CXXConstructExpr *E) {
11242       S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
11243       Inherited::VisitCXXConstructExpr(E);
11244     }
11245     
11246     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
11247       Visit(E->getExpr());
11248     }
11249
11250     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11251       Inherited::VisitImplicitCastExpr(E);
11252
11253       if (E->getCastKind() == CK_LValueToRValue)
11254         S.UpdateMarkingForLValueToRValue(E->getSubExpr());
11255     }
11256   };
11257 }
11258
11259 /// \brief Mark any declarations that appear within this expression or any
11260 /// potentially-evaluated subexpressions as "referenced".
11261 ///
11262 /// \param SkipLocalVariables If true, don't mark local variables as 
11263 /// 'referenced'.
11264 void Sema::MarkDeclarationsReferencedInExpr(Expr *E, 
11265                                             bool SkipLocalVariables) {
11266   EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
11267 }
11268
11269 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
11270 /// of the program being compiled.
11271 ///
11272 /// This routine emits the given diagnostic when the code currently being
11273 /// type-checked is "potentially evaluated", meaning that there is a
11274 /// possibility that the code will actually be executable. Code in sizeof()
11275 /// expressions, code used only during overload resolution, etc., are not
11276 /// potentially evaluated. This routine will suppress such diagnostics or,
11277 /// in the absolutely nutty case of potentially potentially evaluated
11278 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
11279 /// later.
11280 ///
11281 /// This routine should be used for all diagnostics that describe the run-time
11282 /// behavior of a program, such as passing a non-POD value through an ellipsis.
11283 /// Failure to do so will likely result in spurious diagnostics or failures
11284 /// during overload resolution or within sizeof/alignof/typeof/typeid.
11285 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
11286                                const PartialDiagnostic &PD) {
11287   switch (ExprEvalContexts.back().Context) {
11288   case Unevaluated:
11289     // The argument will never be evaluated, so don't complain.
11290     break;
11291
11292   case ConstantEvaluated:
11293     // Relevant diagnostics should be produced by constant evaluation.
11294     break;
11295
11296   case PotentiallyEvaluated:
11297   case PotentiallyEvaluatedIfUsed:
11298     if (Statement && getCurFunctionOrMethodDecl()) {
11299       FunctionScopes.back()->PossiblyUnreachableDiags.
11300         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
11301     }
11302     else
11303       Diag(Loc, PD);
11304       
11305     return true;
11306   }
11307
11308   return false;
11309 }
11310
11311 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
11312                                CallExpr *CE, FunctionDecl *FD) {
11313   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
11314     return false;
11315
11316   // If we're inside a decltype's expression, don't check for a valid return
11317   // type or construct temporaries until we know whether this is the last call.
11318   if (ExprEvalContexts.back().IsDecltype) {
11319     ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
11320     return false;
11321   }
11322
11323   class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
11324     FunctionDecl *FD;
11325     CallExpr *CE;
11326     
11327   public:
11328     CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
11329       : FD(FD), CE(CE) { }
11330     
11331     virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
11332       if (!FD) {
11333         S.Diag(Loc, diag::err_call_incomplete_return)
11334           << T << CE->getSourceRange();
11335         return;
11336       }
11337       
11338       S.Diag(Loc, diag::err_call_function_incomplete_return)
11339         << CE->getSourceRange() << FD->getDeclName() << T;
11340       S.Diag(FD->getLocation(),
11341              diag::note_function_with_incomplete_return_type_declared_here)
11342         << FD->getDeclName();
11343     }
11344   } Diagnoser(FD, CE);
11345   
11346   if (RequireCompleteType(Loc, ReturnType, Diagnoser))
11347     return true;
11348
11349   return false;
11350 }
11351
11352 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
11353 // will prevent this condition from triggering, which is what we want.
11354 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11355   SourceLocation Loc;
11356
11357   unsigned diagnostic = diag::warn_condition_is_assignment;
11358   bool IsOrAssign = false;
11359
11360   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
11361     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
11362       return;
11363
11364     IsOrAssign = Op->getOpcode() == BO_OrAssign;
11365
11366     // Greylist some idioms by putting them into a warning subcategory.
11367     if (ObjCMessageExpr *ME
11368           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11369       Selector Sel = ME->getSelector();
11370
11371       // self = [<foo> init...]
11372       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
11373         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11374
11375       // <foo> = [<bar> nextObject]
11376       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
11377         diagnostic = diag::warn_condition_is_idiomatic_assignment;
11378     }
11379
11380     Loc = Op->getOperatorLoc();
11381   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
11382     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
11383       return;
11384
11385     IsOrAssign = Op->getOperator() == OO_PipeEqual;
11386     Loc = Op->getOperatorLoc();
11387   } else if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E))
11388     return DiagnoseAssignmentAsCondition(POE->getSyntacticForm());
11389   else {
11390     // Not an assignment.
11391     return;
11392   }
11393
11394   Diag(Loc, diagnostic) << E->getSourceRange();
11395
11396   SourceLocation Open = E->getLocStart();
11397   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11398   Diag(Loc, diag::note_condition_assign_silence)
11399         << FixItHint::CreateInsertion(Open, "(")
11400         << FixItHint::CreateInsertion(Close, ")");
11401
11402   if (IsOrAssign)
11403     Diag(Loc, diag::note_condition_or_assign_to_comparison)
11404       << FixItHint::CreateReplacement(Loc, "!=");
11405   else
11406     Diag(Loc, diag::note_condition_assign_to_comparison)
11407       << FixItHint::CreateReplacement(Loc, "==");
11408 }
11409
11410 /// \brief Redundant parentheses over an equality comparison can indicate
11411 /// that the user intended an assignment used as condition.
11412 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
11413   // Don't warn if the parens came from a macro.
11414   SourceLocation parenLoc = ParenE->getLocStart();
11415   if (parenLoc.isInvalid() || parenLoc.isMacroID())
11416     return;
11417   // Don't warn for dependent expressions.
11418   if (ParenE->isTypeDependent())
11419     return;
11420
11421   Expr *E = ParenE->IgnoreParens();
11422
11423   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
11424     if (opE->getOpcode() == BO_EQ &&
11425         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11426                                                            == Expr::MLV_Valid) {
11427       SourceLocation Loc = opE->getOperatorLoc();
11428       
11429       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
11430       SourceRange ParenERange = ParenE->getSourceRange();
11431       Diag(Loc, diag::note_equality_comparison_silence)
11432         << FixItHint::CreateRemoval(ParenERange.getBegin())
11433         << FixItHint::CreateRemoval(ParenERange.getEnd());
11434       Diag(Loc, diag::note_equality_comparison_to_assign)
11435         << FixItHint::CreateReplacement(Loc, "=");
11436     }
11437 }
11438
11439 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
11440   DiagnoseAssignmentAsCondition(E);
11441   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11442     DiagnoseEqualityWithExtraParens(parenE);
11443
11444   ExprResult result = CheckPlaceholderExpr(E);
11445   if (result.isInvalid()) return ExprError();
11446   E = result.take();
11447
11448   if (!E->isTypeDependent()) {
11449     if (getLangOpts().CPlusPlus)
11450       return CheckCXXBooleanCondition(E); // C++ 6.4p4
11451
11452     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11453     if (ERes.isInvalid())
11454       return ExprError();
11455     E = ERes.take();
11456
11457     QualType T = E->getType();
11458     if (!T->isScalarType()) { // C99 6.8.4.1p1
11459       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11460         << T << E->getSourceRange();
11461       return ExprError();
11462     }
11463   }
11464
11465   return Owned(E);
11466 }
11467
11468 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
11469                                        Expr *SubExpr) {
11470   if (!SubExpr)
11471     return ExprError();
11472
11473   return CheckBooleanCondition(SubExpr, Loc);
11474 }
11475
11476 namespace {
11477   /// A visitor for rebuilding a call to an __unknown_any expression
11478   /// to have an appropriate type.
11479   struct RebuildUnknownAnyFunction
11480     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11481
11482     Sema &S;
11483
11484     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11485
11486     ExprResult VisitStmt(Stmt *S) {
11487       llvm_unreachable("unexpected statement!");
11488     }
11489
11490     ExprResult VisitExpr(Expr *E) {
11491       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11492         << E->getSourceRange();
11493       return ExprError();
11494     }
11495
11496     /// Rebuild an expression which simply semantically wraps another
11497     /// expression which it shares the type and value kind of.
11498     template <class T> ExprResult rebuildSugarExpr(T *E) {
11499       ExprResult SubResult = Visit(E->getSubExpr());
11500       if (SubResult.isInvalid()) return ExprError();
11501
11502       Expr *SubExpr = SubResult.take();
11503       E->setSubExpr(SubExpr);
11504       E->setType(SubExpr->getType());
11505       E->setValueKind(SubExpr->getValueKind());
11506       assert(E->getObjectKind() == OK_Ordinary);
11507       return E;
11508     }
11509
11510     ExprResult VisitParenExpr(ParenExpr *E) {
11511       return rebuildSugarExpr(E);
11512     }
11513
11514     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11515       return rebuildSugarExpr(E);
11516     }
11517
11518     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11519       ExprResult SubResult = Visit(E->getSubExpr());
11520       if (SubResult.isInvalid()) return ExprError();
11521
11522       Expr *SubExpr = SubResult.take();
11523       E->setSubExpr(SubExpr);
11524       E->setType(S.Context.getPointerType(SubExpr->getType()));
11525       assert(E->getValueKind() == VK_RValue);
11526       assert(E->getObjectKind() == OK_Ordinary);
11527       return E;
11528     }
11529
11530     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11531       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
11532
11533       E->setType(VD->getType());
11534
11535       assert(E->getValueKind() == VK_RValue);
11536       if (S.getLangOpts().CPlusPlus &&
11537           !(isa<CXXMethodDecl>(VD) &&
11538             cast<CXXMethodDecl>(VD)->isInstance()))
11539         E->setValueKind(VK_LValue);
11540
11541       return E;
11542     }
11543
11544     ExprResult VisitMemberExpr(MemberExpr *E) {
11545       return resolveDecl(E, E->getMemberDecl());
11546     }
11547
11548     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11549       return resolveDecl(E, E->getDecl());
11550     }
11551   };
11552 }
11553
11554 /// Given a function expression of unknown-any type, try to rebuild it
11555 /// to have a function type.
11556 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11557   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11558   if (Result.isInvalid()) return ExprError();
11559   return S.DefaultFunctionArrayConversion(Result.take());
11560 }
11561
11562 namespace {
11563   /// A visitor for rebuilding an expression of type __unknown_anytype
11564   /// into one which resolves the type directly on the referring
11565   /// expression.  Strict preservation of the original source
11566   /// structure is not a goal.
11567   struct RebuildUnknownAnyExpr
11568     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
11569
11570     Sema &S;
11571
11572     /// The current destination type.
11573     QualType DestType;
11574
11575     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11576       : S(S), DestType(CastType) {}
11577
11578     ExprResult VisitStmt(Stmt *S) {
11579       llvm_unreachable("unexpected statement!");
11580     }
11581
11582     ExprResult VisitExpr(Expr *E) {
11583       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11584         << E->getSourceRange();
11585       return ExprError();
11586     }
11587
11588     ExprResult VisitCallExpr(CallExpr *E);
11589     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
11590
11591     /// Rebuild an expression which simply semantically wraps another
11592     /// expression which it shares the type and value kind of.
11593     template <class T> ExprResult rebuildSugarExpr(T *E) {
11594       ExprResult SubResult = Visit(E->getSubExpr());
11595       if (SubResult.isInvalid()) return ExprError();
11596       Expr *SubExpr = SubResult.take();
11597       E->setSubExpr(SubExpr);
11598       E->setType(SubExpr->getType());
11599       E->setValueKind(SubExpr->getValueKind());
11600       assert(E->getObjectKind() == OK_Ordinary);
11601       return E;
11602     }
11603
11604     ExprResult VisitParenExpr(ParenExpr *E) {
11605       return rebuildSugarExpr(E);
11606     }
11607
11608     ExprResult VisitUnaryExtension(UnaryOperator *E) {
11609       return rebuildSugarExpr(E);
11610     }
11611
11612     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11613       const PointerType *Ptr = DestType->getAs<PointerType>();
11614       if (!Ptr) {
11615         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11616           << E->getSourceRange();
11617         return ExprError();
11618       }
11619       assert(E->getValueKind() == VK_RValue);
11620       assert(E->getObjectKind() == OK_Ordinary);
11621       E->setType(DestType);
11622
11623       // Build the sub-expression as if it were an object of the pointee type.
11624       DestType = Ptr->getPointeeType();
11625       ExprResult SubResult = Visit(E->getSubExpr());
11626       if (SubResult.isInvalid()) return ExprError();
11627       E->setSubExpr(SubResult.take());
11628       return E;
11629     }
11630
11631     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
11632
11633     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
11634
11635     ExprResult VisitMemberExpr(MemberExpr *E) {
11636       return resolveDecl(E, E->getMemberDecl());
11637     }
11638
11639     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11640       return resolveDecl(E, E->getDecl());
11641     }
11642   };
11643 }
11644
11645 /// Rebuilds a call expression which yielded __unknown_anytype.
11646 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11647   Expr *CalleeExpr = E->getCallee();
11648
11649   enum FnKind {
11650     FK_MemberFunction,
11651     FK_FunctionPointer,
11652     FK_BlockPointer
11653   };
11654
11655   FnKind Kind;
11656   QualType CalleeType = CalleeExpr->getType();
11657   if (CalleeType == S.Context.BoundMemberTy) {
11658     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11659     Kind = FK_MemberFunction;
11660     CalleeType = Expr::findBoundMemberType(CalleeExpr);
11661   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11662     CalleeType = Ptr->getPointeeType();
11663     Kind = FK_FunctionPointer;
11664   } else {
11665     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11666     Kind = FK_BlockPointer;
11667   }
11668   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
11669
11670   // Verify that this is a legal result type of a function.
11671   if (DestType->isArrayType() || DestType->isFunctionType()) {
11672     unsigned diagID = diag::err_func_returning_array_function;
11673     if (Kind == FK_BlockPointer)
11674       diagID = diag::err_block_returning_array_function;
11675
11676     S.Diag(E->getExprLoc(), diagID)
11677       << DestType->isFunctionType() << DestType;
11678     return ExprError();
11679   }
11680
11681   // Otherwise, go ahead and set DestType as the call's result.
11682   E->setType(DestType.getNonLValueExprType(S.Context));
11683   E->setValueKind(Expr::getValueKindForType(DestType));
11684   assert(E->getObjectKind() == OK_Ordinary);
11685
11686   // Rebuild the function type, replacing the result type with DestType.
11687   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
11688     DestType = S.Context.getFunctionType(DestType,
11689                                          Proto->arg_type_begin(),
11690                                          Proto->getNumArgs(),
11691                                          Proto->getExtProtoInfo());
11692   else
11693     DestType = S.Context.getFunctionNoProtoType(DestType,
11694                                                 FnType->getExtInfo());
11695
11696   // Rebuild the appropriate pointer-to-function type.
11697   switch (Kind) { 
11698   case FK_MemberFunction:
11699     // Nothing to do.
11700     break;
11701
11702   case FK_FunctionPointer:
11703     DestType = S.Context.getPointerType(DestType);
11704     break;
11705
11706   case FK_BlockPointer:
11707     DestType = S.Context.getBlockPointerType(DestType);
11708     break;
11709   }
11710
11711   // Finally, we can recurse.
11712   ExprResult CalleeResult = Visit(CalleeExpr);
11713   if (!CalleeResult.isUsable()) return ExprError();
11714   E->setCallee(CalleeResult.take());
11715
11716   // Bind a temporary if necessary.
11717   return S.MaybeBindToTemporary(E);
11718 }
11719
11720 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
11721   // Verify that this is a legal result type of a call.
11722   if (DestType->isArrayType() || DestType->isFunctionType()) {
11723     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
11724       << DestType->isFunctionType() << DestType;
11725     return ExprError();
11726   }
11727
11728   // Rewrite the method result type if available.
11729   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11730     assert(Method->getResultType() == S.Context.UnknownAnyTy);
11731     Method->setResultType(DestType);
11732   }
11733
11734   // Change the type of the message.
11735   E->setType(DestType.getNonReferenceType());
11736   E->setValueKind(Expr::getValueKindForType(DestType));
11737
11738   return S.MaybeBindToTemporary(E);
11739 }
11740
11741 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
11742   // The only case we should ever see here is a function-to-pointer decay.
11743   if (E->getCastKind() == CK_FunctionToPointerDecay) {
11744     assert(E->getValueKind() == VK_RValue);
11745     assert(E->getObjectKind() == OK_Ordinary);
11746   
11747     E->setType(DestType);
11748   
11749     // Rebuild the sub-expression as the pointee (function) type.
11750     DestType = DestType->castAs<PointerType>()->getPointeeType();
11751   
11752     ExprResult Result = Visit(E->getSubExpr());
11753     if (!Result.isUsable()) return ExprError();
11754   
11755     E->setSubExpr(Result.take());
11756     return S.Owned(E);
11757   } else if (E->getCastKind() == CK_LValueToRValue) {
11758     assert(E->getValueKind() == VK_RValue);
11759     assert(E->getObjectKind() == OK_Ordinary);
11760
11761     assert(isa<BlockPointerType>(E->getType()));
11762
11763     E->setType(DestType);
11764
11765     // The sub-expression has to be a lvalue reference, so rebuild it as such.
11766     DestType = S.Context.getLValueReferenceType(DestType);
11767
11768     ExprResult Result = Visit(E->getSubExpr());
11769     if (!Result.isUsable()) return ExprError();
11770
11771     E->setSubExpr(Result.take());
11772     return S.Owned(E);
11773   } else {
11774     llvm_unreachable("Unhandled cast type!");
11775   }
11776 }
11777
11778 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11779   ExprValueKind ValueKind = VK_LValue;
11780   QualType Type = DestType;
11781
11782   // We know how to make this work for certain kinds of decls:
11783
11784   //  - functions
11785   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11786     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11787       DestType = Ptr->getPointeeType();
11788       ExprResult Result = resolveDecl(E, VD);
11789       if (Result.isInvalid()) return ExprError();
11790       return S.ImpCastExprToType(Result.take(), Type,
11791                                  CK_FunctionToPointerDecay, VK_RValue);
11792     }
11793
11794     if (!Type->isFunctionType()) {
11795       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11796         << VD << E->getSourceRange();
11797       return ExprError();
11798     }
11799
11800     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11801       if (MD->isInstance()) {
11802         ValueKind = VK_RValue;
11803         Type = S.Context.BoundMemberTy;
11804       }
11805
11806     // Function references aren't l-values in C.
11807     if (!S.getLangOpts().CPlusPlus)
11808       ValueKind = VK_RValue;
11809
11810   //  - variables
11811   } else if (isa<VarDecl>(VD)) {
11812     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11813       Type = RefTy->getPointeeType();
11814     } else if (Type->isFunctionType()) {
11815       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11816         << VD << E->getSourceRange();
11817       return ExprError();
11818     }
11819
11820   //  - nothing else
11821   } else {
11822     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11823       << VD << E->getSourceRange();
11824     return ExprError();
11825   }
11826
11827   VD->setType(DestType);
11828   E->setType(Type);
11829   E->setValueKind(ValueKind);
11830   return S.Owned(E);
11831 }
11832
11833 /// Check a cast of an unknown-any type.  We intentionally only
11834 /// trigger this for C-style casts.
11835 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11836                                      Expr *CastExpr, CastKind &CastKind,
11837                                      ExprValueKind &VK, CXXCastPath &Path) {
11838   // Rewrite the casted expression from scratch.
11839   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
11840   if (!result.isUsable()) return ExprError();
11841
11842   CastExpr = result.take();
11843   VK = CastExpr->getValueKind();
11844   CastKind = CK_NoOp;
11845
11846   return CastExpr;
11847 }
11848
11849 ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11850   return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11851 }
11852
11853 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11854   Expr *orig = E;
11855   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
11856   while (true) {
11857     E = E->IgnoreParenImpCasts();
11858     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11859       E = call->getCallee();
11860       diagID = diag::err_uncasted_call_of_unknown_any;
11861     } else {
11862       break;
11863     }
11864   }
11865
11866   SourceLocation loc;
11867   NamedDecl *d;
11868   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
11869     loc = ref->getLocation();
11870     d = ref->getDecl();
11871   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
11872     loc = mem->getMemberLoc();
11873     d = mem->getMemberDecl();
11874   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
11875     diagID = diag::err_uncasted_call_of_unknown_any;
11876     loc = msg->getSelectorStartLoc();
11877     d = msg->getMethodDecl();
11878     if (!d) {
11879       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11880         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11881         << orig->getSourceRange();
11882       return ExprError();
11883     }
11884   } else {
11885     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11886       << E->getSourceRange();
11887     return ExprError();
11888   }
11889
11890   S.Diag(loc, diagID) << d << orig->getSourceRange();
11891
11892   // Never recoverable.
11893   return ExprError();
11894 }
11895
11896 /// Check for operands with placeholder types and complain if found.
11897 /// Returns true if there was an error and no recovery was possible.
11898 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
11899   const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11900   if (!placeholderType) return Owned(E);
11901
11902   switch (placeholderType->getKind()) {
11903
11904   // Overloaded expressions.
11905   case BuiltinType::Overload: {
11906     // Try to resolve a single function template specialization.
11907     // This is obligatory.
11908     ExprResult result = Owned(E);
11909     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11910       return result;
11911
11912     // If that failed, try to recover with a call.
11913     } else {
11914       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11915                            /*complain*/ true);
11916       return result;
11917     }
11918   }
11919
11920   // Bound member functions.
11921   case BuiltinType::BoundMember: {
11922     ExprResult result = Owned(E);
11923     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11924                          /*complain*/ true);
11925     return result;
11926   }
11927
11928   // ARC unbridged casts.
11929   case BuiltinType::ARCUnbridgedCast: {
11930     Expr *realCast = stripARCUnbridgedCast(E);
11931     diagnoseARCUnbridgedCast(realCast);
11932     return Owned(realCast);
11933   }
11934
11935   // Expressions of unknown type.
11936   case BuiltinType::UnknownAny:
11937     return diagnoseUnknownAnyExpr(*this, E);
11938
11939   // Pseudo-objects.
11940   case BuiltinType::PseudoObject:
11941     return checkPseudoObjectRValue(E);
11942
11943   case BuiltinType::BuiltinFn:
11944     Diag(E->getLocStart(), diag::err_builtin_fn_use);
11945     return ExprError();
11946
11947   // Everything else should be impossible.
11948 #define BUILTIN_TYPE(Id, SingletonId) \
11949   case BuiltinType::Id:
11950 #define PLACEHOLDER_TYPE(Id, SingletonId)
11951 #include "clang/AST/BuiltinTypes.def"
11952     break;
11953   }
11954
11955   llvm_unreachable("invalid placeholder type!");
11956 }
11957
11958 bool Sema::CheckCaseExpression(Expr *E) {
11959   if (E->isTypeDependent())
11960     return true;
11961   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11962     return E->getType()->isIntegralOrEnumerationType();
11963   return false;
11964 }
11965
11966 /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11967 ExprResult
11968 Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11969   assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11970          "Unknown Objective-C Boolean value!");
11971   QualType BoolT = Context.ObjCBuiltinBoolTy;
11972   if (!Context.getBOOLDecl()) {
11973     LookupResult Result(*this, &Context.Idents.get("BOOL"), OpLoc,
11974                         Sema::LookupOrdinaryName);
11975     if (LookupName(Result, getCurScope()) && Result.isSingleResult()) {
11976       NamedDecl *ND = Result.getFoundDecl();
11977       if (TypedefDecl *TD = dyn_cast<TypedefDecl>(ND)) 
11978         Context.setBOOLDecl(TD);
11979     }
11980   }
11981   if (Context.getBOOLDecl())
11982     BoolT = Context.getBOOLType();
11983   return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11984                                         BoolT, OpLoc));
11985 }