]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaExpr.cpp
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.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/Initialization.h"
16 #include "clang/Sema/Lookup.h"
17 #include "clang/Sema/AnalysisBasedWarnings.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/ASTMutationListener.h"
20 #include "clang/AST/CXXInheritance.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/EvaluatedExprVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/RecursiveASTVisitor.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/LiteralSupport.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/DeclSpec.h"
35 #include "clang/Sema/Designator.h"
36 #include "clang/Sema/Scope.h"
37 #include "clang/Sema/ScopeInfo.h"
38 #include "clang/Sema/ParsedTemplate.h"
39 #include "clang/Sema/SemaFixItUtils.h"
40 #include "clang/Sema/Template.h"
41 using namespace clang;
42 using namespace sema;
43
44 /// \brief Determine whether the use of this declaration is valid, without
45 /// emitting diagnostics.
46 bool Sema::CanUseDecl(NamedDecl *D) {
47   // See if this is an auto-typed variable whose initializer we are parsing.
48   if (ParsingInitForAutoVars.count(D))
49     return false;
50
51   // See if this is a deleted function.
52   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
53     if (FD->isDeleted())
54       return false;
55   }
56   return true;
57 }
58
59 static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
60                               NamedDecl *D, SourceLocation Loc,
61                               const ObjCInterfaceDecl *UnknownObjCClass) {
62   // See if this declaration is unavailable or deprecated.
63   std::string Message;
64   AvailabilityResult Result = D->getAvailability(&Message);
65   switch (Result) {
66     case AR_Available:
67     case AR_NotYetIntroduced:
68       break;
69             
70     case AR_Deprecated:
71       S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
72       break;
73             
74     case AR_Unavailable:
75       if (S.getCurContextAvailability() != AR_Unavailable) {
76         if (Message.empty()) {
77           if (!UnknownObjCClass)
78             S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
79           else
80             S.Diag(Loc, diag::warn_unavailable_fwdclass_message) 
81               << D->getDeclName();
82         }
83         else 
84           S.Diag(Loc, diag::err_unavailable_message) 
85             << D->getDeclName() << Message;
86           S.Diag(D->getLocation(), diag::note_unavailable_here) 
87           << isa<FunctionDecl>(D) << false;
88       }
89       break;
90     }
91     return Result;
92 }
93
94 /// \brief Determine whether the use of this declaration is valid, and
95 /// emit any corresponding diagnostics.
96 ///
97 /// This routine diagnoses various problems with referencing
98 /// declarations that can occur when using a declaration. For example,
99 /// it might warn if a deprecated or unavailable declaration is being
100 /// used, or produce an error (and return true) if a C++0x deleted
101 /// function is being used.
102 ///
103 /// \returns true if there was an error (this declaration cannot be
104 /// referenced), false otherwise.
105 ///
106 bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
107                              const ObjCInterfaceDecl *UnknownObjCClass) {
108   if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
109     // If there were any diagnostics suppressed by template argument deduction,
110     // emit them now.
111     llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
112       Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
113     if (Pos != SuppressedDiagnostics.end()) {
114       SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
115       for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
116         Diag(Suppressed[I].first, Suppressed[I].second);
117       
118       // Clear out the list of suppressed diagnostics, so that we don't emit
119       // them again for this specialization. However, we don't obsolete this
120       // entry from the table, because we want to avoid ever emitting these
121       // diagnostics again.
122       Suppressed.clear();
123     }
124   }
125
126   // See if this is an auto-typed variable whose initializer we are parsing.
127   if (ParsingInitForAutoVars.count(D)) {
128     Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
129       << D->getDeclName();
130     return true;
131   }
132
133   // See if this is a deleted function.
134   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
135     if (FD->isDeleted()) {
136       Diag(Loc, diag::err_deleted_function_use);
137       Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
138       return true;
139     }
140   }
141   AvailabilityResult Result =
142     DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
143
144   // Warn if this is used but marked unused.
145   if (D->hasAttr<UnusedAttr>())
146     Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
147   // For available enumerator, it will become unavailable/deprecated
148   // if its enum declaration is as such.
149   if (Result == AR_Available)
150     if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
151       const DeclContext *DC = ECD->getDeclContext();
152       if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
153         DiagnoseAvailabilityOfDecl(*this,
154                           const_cast< EnumDecl *>(TheEnumDecl), 
155                           Loc, UnknownObjCClass);
156     }
157   return false;
158 }
159
160 /// \brief Retrieve the message suffix that should be added to a
161 /// diagnostic complaining about the given function being deleted or
162 /// unavailable.
163 std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
164   // FIXME: C++0x implicitly-deleted special member functions could be
165   // detected here so that we could improve diagnostics to say, e.g.,
166   // "base class 'A' had a deleted copy constructor".
167   if (FD->isDeleted())
168     return std::string();
169
170   std::string Message;
171   if (FD->getAvailability(&Message))
172     return ": " + Message;
173
174   return std::string();
175 }
176
177 /// DiagnoseSentinelCalls - This routine checks whether a call or
178 /// message-send is to a declaration with the sentinel attribute, and
179 /// if so, it checks that the requirements of the sentinel are
180 /// satisfied.
181 void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
182                                  Expr **args, unsigned numArgs) {
183   const SentinelAttr *attr = D->getAttr<SentinelAttr>();
184   if (!attr)
185     return;
186
187   // The number of formal parameters of the declaration.
188   unsigned numFormalParams;
189
190   // The kind of declaration.  This is also an index into a %select in
191   // the diagnostic.
192   enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
193
194   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
195     numFormalParams = MD->param_size();
196     calleeType = CT_Method;
197   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
198     numFormalParams = FD->param_size();
199     calleeType = CT_Function;
200   } else if (isa<VarDecl>(D)) {
201     QualType type = cast<ValueDecl>(D)->getType();
202     const FunctionType *fn = 0;
203     if (const PointerType *ptr = type->getAs<PointerType>()) {
204       fn = ptr->getPointeeType()->getAs<FunctionType>();
205       if (!fn) return;
206       calleeType = CT_Function;
207     } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
208       fn = ptr->getPointeeType()->castAs<FunctionType>();
209       calleeType = CT_Block;
210     } else {
211       return;
212     }
213
214     if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
215       numFormalParams = proto->getNumArgs();
216     } else {
217       numFormalParams = 0;
218     }
219   } else {
220     return;
221   }
222
223   // "nullPos" is the number of formal parameters at the end which
224   // effectively count as part of the variadic arguments.  This is
225   // useful if you would prefer to not have *any* formal parameters,
226   // but the language forces you to have at least one.
227   unsigned nullPos = attr->getNullPos();
228   assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
229   numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
230
231   // The number of arguments which should follow the sentinel.
232   unsigned numArgsAfterSentinel = attr->getSentinel();
233
234   // If there aren't enough arguments for all the formal parameters,
235   // the sentinel, and the args after the sentinel, complain.
236   if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
237     Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
238     Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
239     return;
240   }
241
242   // Otherwise, find the sentinel expression.
243   Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
244   if (!sentinelExpr) return;
245   if (sentinelExpr->isValueDependent()) return;
246
247   // nullptr_t is always treated as null.
248   if (sentinelExpr->getType()->isNullPtrType()) return;
249
250   if (sentinelExpr->getType()->isAnyPointerType() &&
251       sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
252                                             Expr::NPC_ValueDependentIsNull))
253     return;
254
255   // Unfortunately, __null has type 'int'.
256   if (isa<GNUNullExpr>(sentinelExpr)) return;
257
258   // Pick a reasonable string to insert.  Optimistically use 'nil' or
259   // 'NULL' if those are actually defined in the context.  Only use
260   // 'nil' for ObjC methods, where it's much more likely that the
261   // variadic arguments form a list of object pointers.
262   SourceLocation MissingNilLoc
263     = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
264   std::string NullValue;
265   if (calleeType == CT_Method &&
266       PP.getIdentifierInfo("nil")->hasMacroDefinition())
267     NullValue = "nil";
268   else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
269     NullValue = "NULL";
270   else
271     NullValue = "(void*) 0";
272
273   if (MissingNilLoc.isInvalid())
274     Diag(Loc, diag::warn_missing_sentinel) << calleeType;
275   else
276     Diag(MissingNilLoc, diag::warn_missing_sentinel) 
277       << calleeType
278       << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
279   Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
280 }
281
282 SourceRange Sema::getExprRange(Expr *E) const {
283   return E ? E->getSourceRange() : SourceRange();
284 }
285
286 //===----------------------------------------------------------------------===//
287 //  Standard Promotions and Conversions
288 //===----------------------------------------------------------------------===//
289
290 /// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
291 ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
292   // Handle any placeholder expressions which made it here.
293   if (E->getType()->isPlaceholderType()) {
294     ExprResult result = CheckPlaceholderExpr(E);
295     if (result.isInvalid()) return ExprError();
296     E = result.take();
297   }
298   
299   QualType Ty = E->getType();
300   assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
301
302   if (Ty->isFunctionType())
303     E = ImpCastExprToType(E, Context.getPointerType(Ty),
304                           CK_FunctionToPointerDecay).take();
305   else if (Ty->isArrayType()) {
306     // In C90 mode, arrays only promote to pointers if the array expression is
307     // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
308     // type 'array of type' is converted to an expression that has type 'pointer
309     // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
310     // that has type 'array of type' ...".  The relevant change is "an lvalue"
311     // (C90) to "an expression" (C99).
312     //
313     // C++ 4.2p1:
314     // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
315     // T" can be converted to an rvalue of type "pointer to T".
316     //
317     if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
318       E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
319                             CK_ArrayToPointerDecay).take();
320   }
321   return Owned(E);
322 }
323
324 static void CheckForNullPointerDereference(Sema &S, Expr *E) {
325   // Check to see if we are dereferencing a null pointer.  If so,
326   // and if not volatile-qualified, this is undefined behavior that the
327   // optimizer will delete, so warn about it.  People sometimes try to use this
328   // to get a deterministic trap and are surprised by clang's behavior.  This
329   // only handles the pattern "*null", which is a very syntactic check.
330   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
331     if (UO->getOpcode() == UO_Deref &&
332         UO->getSubExpr()->IgnoreParenCasts()->
333           isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
334         !UO->getType().isVolatileQualified()) {
335     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
336                           S.PDiag(diag::warn_indirection_through_null)
337                             << UO->getSubExpr()->getSourceRange());
338     S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
339                         S.PDiag(diag::note_indirection_through_null));
340   }
341 }
342
343 ExprResult Sema::DefaultLvalueConversion(Expr *E) {
344   // Handle any placeholder expressions which made it here.
345   if (E->getType()->isPlaceholderType()) {
346     ExprResult result = CheckPlaceholderExpr(E);
347     if (result.isInvalid()) return ExprError();
348     E = result.take();
349   }
350   
351   // C++ [conv.lval]p1:
352   //   A glvalue of a non-function, non-array type T can be
353   //   converted to a prvalue.
354   if (!E->isGLValue()) return Owned(E);
355
356   QualType T = E->getType();
357   assert(!T.isNull() && "r-value conversion on typeless expression?");
358
359   // We can't do lvalue-to-rvalue on atomics yet.
360   if (T->getAs<AtomicType>())
361     return Owned(E);
362
363   // Create a load out of an ObjCProperty l-value, if necessary.
364   if (E->getObjectKind() == OK_ObjCProperty) {
365     ExprResult Res = ConvertPropertyForRValue(E);
366     if (Res.isInvalid())
367       return Owned(E);
368     E = Res.take();
369     if (!E->isGLValue())
370       return Owned(E);
371   }
372
373   // We don't want to throw lvalue-to-rvalue casts on top of
374   // expressions of certain types in C++.
375   if (getLangOptions().CPlusPlus &&
376       (E->getType() == Context.OverloadTy ||
377        T->isDependentType() ||
378        T->isRecordType()))
379     return Owned(E);
380
381   // The C standard is actually really unclear on this point, and
382   // DR106 tells us what the result should be but not why.  It's
383   // generally best to say that void types just doesn't undergo
384   // lvalue-to-rvalue at all.  Note that expressions of unqualified
385   // 'void' type are never l-values, but qualified void can be.
386   if (T->isVoidType())
387     return Owned(E);
388
389   CheckForNullPointerDereference(*this, E);
390
391   // C++ [conv.lval]p1:
392   //   [...] If T is a non-class type, the type of the prvalue is the
393   //   cv-unqualified version of T. Otherwise, the type of the
394   //   rvalue is T.
395   //
396   // C99 6.3.2.1p2:
397   //   If the lvalue has qualified type, the value has the unqualified
398   //   version of the type of the lvalue; otherwise, the value has the
399   //   type of the lvalue.
400   if (T.hasQualifiers())
401     T = T.getUnqualifiedType();
402
403   ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
404                                                   E, 0, VK_RValue));
405
406   return Res;
407 }
408
409 ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
410   ExprResult Res = DefaultFunctionArrayConversion(E);
411   if (Res.isInvalid())
412     return ExprError();
413   Res = DefaultLvalueConversion(Res.take());
414   if (Res.isInvalid())
415     return ExprError();
416   return move(Res);
417 }
418
419
420 /// UsualUnaryConversions - Performs various conversions that are common to most
421 /// operators (C99 6.3). The conversions of array and function types are
422 /// sometimes suppressed. For example, the array->pointer conversion doesn't
423 /// apply if the array is an argument to the sizeof or address (&) operators.
424 /// In these instances, this routine should *not* be called.
425 ExprResult Sema::UsualUnaryConversions(Expr *E) {
426   // First, convert to an r-value.
427   ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
428   if (Res.isInvalid())
429     return Owned(E);
430   E = Res.take();
431
432   QualType Ty = E->getType();
433   assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
434
435   // Half FP is a bit different: it's a storage-only type, meaning that any
436   // "use" of it should be promoted to float.
437   if (Ty->isHalfType())
438     return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
439
440   // Try to perform integral promotions if the object has a theoretically
441   // promotable type.
442   if (Ty->isIntegralOrUnscopedEnumerationType()) {
443     // C99 6.3.1.1p2:
444     //
445     //   The following may be used in an expression wherever an int or
446     //   unsigned int may be used:
447     //     - an object or expression with an integer type whose integer
448     //       conversion rank is less than or equal to the rank of int
449     //       and unsigned int.
450     //     - A bit-field of type _Bool, int, signed int, or unsigned int.
451     //
452     //   If an int can represent all values of the original type, the
453     //   value is converted to an int; otherwise, it is converted to an
454     //   unsigned int. These are called the integer promotions. All
455     //   other types are unchanged by the integer promotions.
456
457     QualType PTy = Context.isPromotableBitField(E);
458     if (!PTy.isNull()) {
459       E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
460       return Owned(E);
461     }
462     if (Ty->isPromotableIntegerType()) {
463       QualType PT = Context.getPromotedIntegerType(Ty);
464       E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
465       return Owned(E);
466     }
467   }
468   return Owned(E);
469 }
470
471 /// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
472 /// do not have a prototype. Arguments that have type float are promoted to
473 /// double. All other argument types are converted by UsualUnaryConversions().
474 ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
475   QualType Ty = E->getType();
476   assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
477
478   ExprResult Res = UsualUnaryConversions(E);
479   if (Res.isInvalid())
480     return Owned(E);
481   E = Res.take();
482
483   // If this is a 'float' (CVR qualified or typedef) promote to double.
484   if (Ty->isSpecificBuiltinType(BuiltinType::Float))
485     E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
486
487   // C++ performs lvalue-to-rvalue conversion as a default argument
488   // promotion, even on class types, but note:
489   //   C++11 [conv.lval]p2:
490   //     When an lvalue-to-rvalue conversion occurs in an unevaluated
491   //     operand or a subexpression thereof the value contained in the
492   //     referenced object is not accessed. Otherwise, if the glvalue
493   //     has a class type, the conversion copy-initializes a temporary
494   //     of type T from the glvalue and the result of the conversion
495   //     is a prvalue for the temporary.
496   // FIXME: add some way to gate this entire thing for correctness in
497   // potentially potentially evaluated contexts.
498   if (getLangOptions().CPlusPlus && E->isGLValue() && 
499       ExprEvalContexts.back().Context != Unevaluated) {
500     ExprResult Temp = PerformCopyInitialization(
501                        InitializedEntity::InitializeTemporary(E->getType()),
502                                                 E->getExprLoc(),
503                                                 Owned(E));
504     if (Temp.isInvalid())
505       return ExprError();
506     E = Temp.get();
507   }
508
509   return Owned(E);
510 }
511
512 /// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
513 /// will warn if the resulting type is not a POD type, and rejects ObjC
514 /// interfaces passed by value.
515 ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
516                                                   FunctionDecl *FDecl) {
517   ExprResult ExprRes = CheckPlaceholderExpr(E);
518   if (ExprRes.isInvalid())
519     return ExprError();
520   
521   ExprRes = DefaultArgumentPromotion(E);
522   if (ExprRes.isInvalid())
523     return ExprError();
524   E = ExprRes.take();
525
526   // Don't allow one to pass an Objective-C interface to a vararg.
527   if (E->getType()->isObjCObjectType() &&
528     DiagRuntimeBehavior(E->getLocStart(), 0,
529                         PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
530                           << E->getType() << CT))
531     return ExprError();
532
533   // Complain about passing non-POD types through varargs. However, don't
534   // perform this check for incomplete types, which we can get here when we're
535   // in an unevaluated context.
536   if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) {
537     // C++0x [expr.call]p7:
538     //   Passing a potentially-evaluated argument of class type (Clause 9) 
539     //   having a non-trivial copy constructor, a non-trivial move constructor,
540     //   or a non-trivial destructor, with no corresponding parameter, 
541     //   is conditionally-supported with implementation-defined semantics.
542     bool TrivialEnough = false;
543     if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType())  {
544       if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
545         if (Record->hasTrivialCopyConstructor() &&
546             Record->hasTrivialMoveConstructor() &&
547             Record->hasTrivialDestructor())
548           TrivialEnough = true;
549       }
550     }
551
552     if (!TrivialEnough &&
553         getLangOptions().ObjCAutoRefCount &&
554         E->getType()->isObjCLifetimeType())
555       TrivialEnough = true;
556       
557     if (TrivialEnough) {
558       // Nothing to diagnose. This is okay.
559     } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
560                           PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
561                             << getLangOptions().CPlusPlus0x << E->getType() 
562                             << CT)) {
563       // Turn this into a trap.
564       CXXScopeSpec SS;
565       UnqualifiedId Name;
566       Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
567                          E->getLocStart());
568       ExprResult TrapFn = ActOnIdExpression(TUScope, SS, Name, true, false);
569       if (TrapFn.isInvalid())
570         return ExprError();
571
572       ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
573                                       MultiExprArg(), E->getLocEnd());
574       if (Call.isInvalid())
575         return ExprError();
576       
577       ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
578                                     Call.get(), E);
579       if (Comma.isInvalid())
580         return ExprError();      
581       E = Comma.get();
582     }
583   }
584   
585   return Owned(E);
586 }
587
588 /// \brief Converts an integer to complex float type.  Helper function of
589 /// UsualArithmeticConversions()
590 ///
591 /// \return false if the integer expression is an integer type and is
592 /// successfully converted to the complex type.
593 static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
594                                                   ExprResult &ComplexExpr,
595                                                   QualType IntTy,
596                                                   QualType ComplexTy,
597                                                   bool SkipCast) {
598   if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
599   if (SkipCast) return false;
600   if (IntTy->isIntegerType()) {
601     QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
602     IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
603     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
604                                   CK_FloatingRealToComplex);
605   } else {
606     assert(IntTy->isComplexIntegerType());
607     IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
608                                   CK_IntegralComplexToFloatingComplex);
609   }
610   return false;
611 }
612
613 /// \brief Takes two complex float types and converts them to the same type.
614 /// Helper function of UsualArithmeticConversions()
615 static QualType
616 handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
617                                             ExprResult &RHS, QualType LHSType,
618                                             QualType RHSType,
619                                             bool IsCompAssign) {
620   int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
621
622   if (order < 0) {
623     // _Complex float -> _Complex double
624     if (!IsCompAssign)
625       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
626     return RHSType;
627   }
628   if (order > 0)
629     // _Complex float -> _Complex double
630     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
631   return LHSType;
632 }
633
634 /// \brief Converts otherExpr to complex float and promotes complexExpr if
635 /// necessary.  Helper function of UsualArithmeticConversions()
636 static QualType handleOtherComplexFloatConversion(Sema &S,
637                                                   ExprResult &ComplexExpr,
638                                                   ExprResult &OtherExpr,
639                                                   QualType ComplexTy,
640                                                   QualType OtherTy,
641                                                   bool ConvertComplexExpr,
642                                                   bool ConvertOtherExpr) {
643   int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
644
645   // If just the complexExpr is complex, the otherExpr needs to be converted,
646   // and the complexExpr might need to be promoted.
647   if (order > 0) { // complexExpr is wider
648     // float -> _Complex double
649     if (ConvertOtherExpr) {
650       QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
651       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
652       OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
653                                       CK_FloatingRealToComplex);
654     }
655     return ComplexTy;
656   }
657
658   // otherTy is at least as wide.  Find its corresponding complex type.
659   QualType result = (order == 0 ? ComplexTy :
660                                   S.Context.getComplexType(OtherTy));
661
662   // double -> _Complex double
663   if (ConvertOtherExpr)
664     OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
665                                     CK_FloatingRealToComplex);
666
667   // _Complex float -> _Complex double
668   if (ConvertComplexExpr && order < 0)
669     ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
670                                       CK_FloatingComplexCast);
671
672   return result;
673 }
674
675 /// \brief Handle arithmetic conversion with complex types.  Helper function of
676 /// UsualArithmeticConversions()
677 static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
678                                              ExprResult &RHS, QualType LHSType,
679                                              QualType RHSType,
680                                              bool IsCompAssign) {
681   // if we have an integer operand, the result is the complex type.
682   if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
683                                              /*skipCast*/false))
684     return LHSType;
685   if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
686                                              /*skipCast*/IsCompAssign))
687     return RHSType;
688
689   // This handles complex/complex, complex/float, or float/complex.
690   // When both operands are complex, the shorter operand is converted to the
691   // type of the longer, and that is the type of the result. This corresponds
692   // to what is done when combining two real floating-point operands.
693   // The fun begins when size promotion occur across type domains.
694   // From H&S 6.3.4: When one operand is complex and the other is a real
695   // floating-point type, the less precise type is converted, within it's
696   // real or complex domain, to the precision of the other type. For example,
697   // when combining a "long double" with a "double _Complex", the
698   // "double _Complex" is promoted to "long double _Complex".
699
700   bool LHSComplexFloat = LHSType->isComplexType();
701   bool RHSComplexFloat = RHSType->isComplexType();
702
703   // If both are complex, just cast to the more precise type.
704   if (LHSComplexFloat && RHSComplexFloat)
705     return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
706                                                        LHSType, RHSType,
707                                                        IsCompAssign);
708
709   // If only one operand is complex, promote it if necessary and convert the
710   // other operand to complex.
711   if (LHSComplexFloat)
712     return handleOtherComplexFloatConversion(
713         S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
714         /*convertOtherExpr*/ true);
715
716   assert(RHSComplexFloat);
717   return handleOtherComplexFloatConversion(
718       S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
719       /*convertOtherExpr*/ !IsCompAssign);
720 }
721
722 /// \brief Hande arithmetic conversion from integer to float.  Helper function
723 /// of UsualArithmeticConversions()
724 static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
725                                            ExprResult &IntExpr,
726                                            QualType FloatTy, QualType IntTy,
727                                            bool ConvertFloat, bool ConvertInt) {
728   if (IntTy->isIntegerType()) {
729     if (ConvertInt)
730       // Convert intExpr to the lhs floating point type.
731       IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
732                                     CK_IntegralToFloating);
733     return FloatTy;
734   }
735      
736   // Convert both sides to the appropriate complex float.
737   assert(IntTy->isComplexIntegerType());
738   QualType result = S.Context.getComplexType(FloatTy);
739
740   // _Complex int -> _Complex float
741   if (ConvertInt)
742     IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
743                                   CK_IntegralComplexToFloatingComplex);
744
745   // float -> _Complex float
746   if (ConvertFloat)
747     FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
748                                     CK_FloatingRealToComplex);
749
750   return result;
751 }
752
753 /// \brief Handle arithmethic conversion with floating point types.  Helper
754 /// function of UsualArithmeticConversions()
755 static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
756                                       ExprResult &RHS, QualType LHSType,
757                                       QualType RHSType, bool IsCompAssign) {
758   bool LHSFloat = LHSType->isRealFloatingType();
759   bool RHSFloat = RHSType->isRealFloatingType();
760
761   // If we have two real floating types, convert the smaller operand
762   // to the bigger result.
763   if (LHSFloat && RHSFloat) {
764     int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
765     if (order > 0) {
766       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
767       return LHSType;
768     }
769
770     assert(order < 0 && "illegal float comparison");
771     if (!IsCompAssign)
772       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
773     return RHSType;
774   }
775
776   if (LHSFloat)
777     return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
778                                       /*convertFloat=*/!IsCompAssign,
779                                       /*convertInt=*/ true);
780   assert(RHSFloat);
781   return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
782                                     /*convertInt=*/ true,
783                                     /*convertFloat=*/!IsCompAssign);
784 }
785
786 /// \brief Handle conversions with GCC complex int extension.  Helper function
787 /// of UsualArithmeticConversions()
788 // FIXME: if the operands are (int, _Complex long), we currently
789 // don't promote the complex.  Also, signedness?
790 static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
791                                            ExprResult &RHS, QualType LHSType,
792                                            QualType RHSType,
793                                            bool IsCompAssign) {
794   const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
795   const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
796
797   if (LHSComplexInt && RHSComplexInt) {
798     int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
799                                               RHSComplexInt->getElementType());
800     assert(order && "inequal types with equal element ordering");
801     if (order > 0) {
802       // _Complex int -> _Complex long
803       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
804       return LHSType;
805     }
806
807     if (!IsCompAssign)
808       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
809     return RHSType;
810   }
811
812   if (LHSComplexInt) {
813     // int -> _Complex int
814     RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
815     return LHSType;
816   }
817
818   assert(RHSComplexInt);
819   // int -> _Complex int
820   if (!IsCompAssign)
821     LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
822   return RHSType;
823 }
824
825 /// \brief Handle integer arithmetic conversions.  Helper function of
826 /// UsualArithmeticConversions()
827 static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
828                                         ExprResult &RHS, QualType LHSType,
829                                         QualType RHSType, bool IsCompAssign) {
830   // The rules for this case are in C99 6.3.1.8
831   int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
832   bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
833   bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
834   if (LHSSigned == RHSSigned) {
835     // Same signedness; use the higher-ranked type
836     if (order >= 0) {
837       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
838       return LHSType;
839     } else if (!IsCompAssign)
840       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
841     return RHSType;
842   } else if (order != (LHSSigned ? 1 : -1)) {
843     // The unsigned type has greater than or equal rank to the
844     // signed type, so use the unsigned type
845     if (RHSSigned) {
846       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
847       return LHSType;
848     } else if (!IsCompAssign)
849       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
850     return RHSType;
851   } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
852     // The two types are different widths; if we are here, that
853     // means the signed type is larger than the unsigned type, so
854     // use the signed type.
855     if (LHSSigned) {
856       RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
857       return LHSType;
858     } else if (!IsCompAssign)
859       LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
860     return RHSType;
861   } else {
862     // The signed type is higher-ranked than the unsigned type,
863     // but isn't actually any bigger (like unsigned int and long
864     // on most 32-bit systems).  Use the unsigned type corresponding
865     // to the signed type.
866     QualType result =
867       S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
868     RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
869     if (!IsCompAssign)
870       LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
871     return result;
872   }
873 }
874
875 /// UsualArithmeticConversions - Performs various conversions that are common to
876 /// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
877 /// routine returns the first non-arithmetic type found. The client is
878 /// responsible for emitting appropriate error diagnostics.
879 /// FIXME: verify the conversion rules for "complex int" are consistent with
880 /// GCC.
881 QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
882                                           bool IsCompAssign) {
883   if (!IsCompAssign) {
884     LHS = UsualUnaryConversions(LHS.take());
885     if (LHS.isInvalid())
886       return QualType();
887   }
888
889   RHS = UsualUnaryConversions(RHS.take());
890   if (RHS.isInvalid())
891     return QualType();
892
893   // For conversion purposes, we ignore any qualifiers.
894   // For example, "const float" and "float" are equivalent.
895   QualType LHSType =
896     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
897   QualType RHSType =
898     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
899
900   // If both types are identical, no conversion is needed.
901   if (LHSType == RHSType)
902     return LHSType;
903
904   // If either side is a non-arithmetic type (e.g. a pointer), we are done.
905   // The caller can deal with this (e.g. pointer + int).
906   if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
907     return LHSType;
908
909   // Apply unary and bitfield promotions to the LHS's type.
910   QualType LHSUnpromotedType = LHSType;
911   if (LHSType->isPromotableIntegerType())
912     LHSType = Context.getPromotedIntegerType(LHSType);
913   QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
914   if (!LHSBitfieldPromoteTy.isNull())
915     LHSType = LHSBitfieldPromoteTy;
916   if (LHSType != LHSUnpromotedType && !IsCompAssign)
917     LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
918
919   // If both types are identical, no conversion is needed.
920   if (LHSType == RHSType)
921     return LHSType;
922
923   // At this point, we have two different arithmetic types.
924
925   // Handle complex types first (C99 6.3.1.8p1).
926   if (LHSType->isComplexType() || RHSType->isComplexType())
927     return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
928                                         IsCompAssign);
929
930   // Now handle "real" floating types (i.e. float, double, long double).
931   if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
932     return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
933                                  IsCompAssign);
934
935   // Handle GCC complex int extension.
936   if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
937     return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
938                                       IsCompAssign);
939
940   // Finally, we have two differing integer types.
941   return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
942                                  IsCompAssign);
943 }
944
945 //===----------------------------------------------------------------------===//
946 //  Semantic Analysis for various Expression Types
947 //===----------------------------------------------------------------------===//
948
949
950 ExprResult
951 Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
952                                 SourceLocation DefaultLoc,
953                                 SourceLocation RParenLoc,
954                                 Expr *ControllingExpr,
955                                 MultiTypeArg ArgTypes,
956                                 MultiExprArg ArgExprs) {
957   unsigned NumAssocs = ArgTypes.size();
958   assert(NumAssocs == ArgExprs.size());
959
960   ParsedType *ParsedTypes = ArgTypes.release();
961   Expr **Exprs = ArgExprs.release();
962
963   TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
964   for (unsigned i = 0; i < NumAssocs; ++i) {
965     if (ParsedTypes[i])
966       (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
967     else
968       Types[i] = 0;
969   }
970
971   ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
972                                              ControllingExpr, Types, Exprs,
973                                              NumAssocs);
974   delete [] Types;
975   return ER;
976 }
977
978 ExprResult
979 Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
980                                  SourceLocation DefaultLoc,
981                                  SourceLocation RParenLoc,
982                                  Expr *ControllingExpr,
983                                  TypeSourceInfo **Types,
984                                  Expr **Exprs,
985                                  unsigned NumAssocs) {
986   bool TypeErrorFound = false,
987        IsResultDependent = ControllingExpr->isTypeDependent(),
988        ContainsUnexpandedParameterPack
989          = ControllingExpr->containsUnexpandedParameterPack();
990
991   for (unsigned i = 0; i < NumAssocs; ++i) {
992     if (Exprs[i]->containsUnexpandedParameterPack())
993       ContainsUnexpandedParameterPack = true;
994
995     if (Types[i]) {
996       if (Types[i]->getType()->containsUnexpandedParameterPack())
997         ContainsUnexpandedParameterPack = true;
998
999       if (Types[i]->getType()->isDependentType()) {
1000         IsResultDependent = true;
1001       } else {
1002         // C1X 6.5.1.1p2 "The type name in a generic association shall specify a
1003         // complete object type other than a variably modified type."
1004         unsigned D = 0;
1005         if (Types[i]->getType()->isIncompleteType())
1006           D = diag::err_assoc_type_incomplete;
1007         else if (!Types[i]->getType()->isObjectType())
1008           D = diag::err_assoc_type_nonobject;
1009         else if (Types[i]->getType()->isVariablyModifiedType())
1010           D = diag::err_assoc_type_variably_modified;
1011
1012         if (D != 0) {
1013           Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1014             << Types[i]->getTypeLoc().getSourceRange()
1015             << Types[i]->getType();
1016           TypeErrorFound = true;
1017         }
1018
1019         // C1X 6.5.1.1p2 "No two generic associations in the same generic
1020         // selection shall specify compatible types."
1021         for (unsigned j = i+1; j < NumAssocs; ++j)
1022           if (Types[j] && !Types[j]->getType()->isDependentType() &&
1023               Context.typesAreCompatible(Types[i]->getType(),
1024                                          Types[j]->getType())) {
1025             Diag(Types[j]->getTypeLoc().getBeginLoc(),
1026                  diag::err_assoc_compatible_types)
1027               << Types[j]->getTypeLoc().getSourceRange()
1028               << Types[j]->getType()
1029               << Types[i]->getType();
1030             Diag(Types[i]->getTypeLoc().getBeginLoc(),
1031                  diag::note_compat_assoc)
1032               << Types[i]->getTypeLoc().getSourceRange()
1033               << Types[i]->getType();
1034             TypeErrorFound = true;
1035           }
1036       }
1037     }
1038   }
1039   if (TypeErrorFound)
1040     return ExprError();
1041
1042   // If we determined that the generic selection is result-dependent, don't
1043   // try to compute the result expression.
1044   if (IsResultDependent)
1045     return Owned(new (Context) GenericSelectionExpr(
1046                    Context, KeyLoc, ControllingExpr,
1047                    Types, Exprs, NumAssocs, DefaultLoc,
1048                    RParenLoc, ContainsUnexpandedParameterPack));
1049
1050   SmallVector<unsigned, 1> CompatIndices;
1051   unsigned DefaultIndex = -1U;
1052   for (unsigned i = 0; i < NumAssocs; ++i) {
1053     if (!Types[i])
1054       DefaultIndex = i;
1055     else if (Context.typesAreCompatible(ControllingExpr->getType(),
1056                                         Types[i]->getType()))
1057       CompatIndices.push_back(i);
1058   }
1059
1060   // C1X 6.5.1.1p2 "The controlling expression of a generic selection shall have
1061   // type compatible with at most one of the types named in its generic
1062   // association list."
1063   if (CompatIndices.size() > 1) {
1064     // We strip parens here because the controlling expression is typically
1065     // parenthesized in macro definitions.
1066     ControllingExpr = ControllingExpr->IgnoreParens();
1067     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1068       << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1069       << (unsigned) CompatIndices.size();
1070     for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
1071          E = CompatIndices.end(); I != E; ++I) {
1072       Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1073            diag::note_compat_assoc)
1074         << Types[*I]->getTypeLoc().getSourceRange()
1075         << Types[*I]->getType();
1076     }
1077     return ExprError();
1078   }
1079
1080   // C1X 6.5.1.1p2 "If a generic selection has no default generic association,
1081   // its controlling expression shall have type compatible with exactly one of
1082   // the types named in its generic association list."
1083   if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1084     // We strip parens here because the controlling expression is typically
1085     // parenthesized in macro definitions.
1086     ControllingExpr = ControllingExpr->IgnoreParens();
1087     Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1088       << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1089     return ExprError();
1090   }
1091
1092   // C1X 6.5.1.1p3 "If a generic selection has a generic association with a
1093   // type name that is compatible with the type of the controlling expression,
1094   // then the result expression of the generic selection is the expression
1095   // in that generic association. Otherwise, the result expression of the
1096   // generic selection is the expression in the default generic association."
1097   unsigned ResultIndex =
1098     CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1099
1100   return Owned(new (Context) GenericSelectionExpr(
1101                  Context, KeyLoc, ControllingExpr,
1102                  Types, Exprs, NumAssocs, DefaultLoc,
1103                  RParenLoc, ContainsUnexpandedParameterPack,
1104                  ResultIndex));
1105 }
1106
1107 /// ActOnStringLiteral - The specified tokens were lexed as pasted string
1108 /// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
1109 /// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1110 /// multiple tokens.  However, the common case is that StringToks points to one
1111 /// string.
1112 ///
1113 ExprResult
1114 Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
1115   assert(NumStringToks && "Must have at least one string!");
1116
1117   StringLiteralParser Literal(StringToks, NumStringToks, PP);
1118   if (Literal.hadError)
1119     return ExprError();
1120
1121   SmallVector<SourceLocation, 4> StringTokLocs;
1122   for (unsigned i = 0; i != NumStringToks; ++i)
1123     StringTokLocs.push_back(StringToks[i].getLocation());
1124
1125   QualType StrTy = Context.CharTy;
1126   if (Literal.isWide())
1127     StrTy = Context.getWCharType();
1128   else if (Literal.isUTF16())
1129     StrTy = Context.Char16Ty;
1130   else if (Literal.isUTF32())
1131     StrTy = Context.Char32Ty;
1132   else if (Literal.Pascal)
1133     StrTy = Context.UnsignedCharTy;
1134
1135   StringLiteral::StringKind Kind = StringLiteral::Ascii;
1136   if (Literal.isWide())
1137     Kind = StringLiteral::Wide;
1138   else if (Literal.isUTF8())
1139     Kind = StringLiteral::UTF8;
1140   else if (Literal.isUTF16())
1141     Kind = StringLiteral::UTF16;
1142   else if (Literal.isUTF32())
1143     Kind = StringLiteral::UTF32;
1144
1145   // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
1146   if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
1147     StrTy.addConst();
1148
1149   // Get an array type for the string, according to C99 6.4.5.  This includes
1150   // the nul terminator character as well as the string length for pascal
1151   // strings.
1152   StrTy = Context.getConstantArrayType(StrTy,
1153                                  llvm::APInt(32, Literal.GetNumStringChars()+1),
1154                                        ArrayType::Normal, 0);
1155
1156   // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
1157   return Owned(StringLiteral::Create(Context, Literal.GetString(),
1158                                      Kind, Literal.Pascal, StrTy,
1159                                      &StringTokLocs[0],
1160                                      StringTokLocs.size()));
1161 }
1162
1163 enum CaptureResult {
1164   /// No capture is required.
1165   CR_NoCapture,
1166
1167   /// A capture is required.
1168   CR_Capture,
1169
1170   /// A by-ref capture is required.
1171   CR_CaptureByRef,
1172
1173   /// An error occurred when trying to capture the given variable.
1174   CR_Error
1175 };
1176
1177 /// Diagnose an uncapturable value reference.
1178 ///
1179 /// \param var - the variable referenced
1180 /// \param DC - the context which we couldn't capture through
1181 static CaptureResult
1182 diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
1183                                    VarDecl *var, DeclContext *DC) {
1184   switch (S.ExprEvalContexts.back().Context) {
1185   case Sema::Unevaluated:
1186     // The argument will never be evaluated, so don't complain.
1187     return CR_NoCapture;
1188
1189   case Sema::PotentiallyEvaluated:
1190   case Sema::PotentiallyEvaluatedIfUsed:
1191     break;
1192
1193   case Sema::PotentiallyPotentiallyEvaluated:
1194     // FIXME: delay these!
1195     break;
1196   }
1197
1198   // Don't diagnose about capture if we're not actually in code right
1199   // now; in general, there are more appropriate places that will
1200   // diagnose this.
1201   if (!S.CurContext->isFunctionOrMethod()) return CR_NoCapture;
1202
1203   // Certain madnesses can happen with parameter declarations, which
1204   // we want to ignore.
1205   if (isa<ParmVarDecl>(var)) {
1206     // - If the parameter still belongs to the translation unit, then
1207     //   we're actually just using one parameter in the declaration of
1208     //   the next.  This is useful in e.g. VLAs.
1209     if (isa<TranslationUnitDecl>(var->getDeclContext()))
1210       return CR_NoCapture;
1211
1212     // - This particular madness can happen in ill-formed default
1213     //   arguments; claim it's okay and let downstream code handle it.
1214     if (S.CurContext == var->getDeclContext()->getParent())
1215       return CR_NoCapture;
1216   }
1217
1218   DeclarationName functionName;
1219   if (FunctionDecl *fn = dyn_cast<FunctionDecl>(var->getDeclContext()))
1220     functionName = fn->getDeclName();
1221   // FIXME: variable from enclosing block that we couldn't capture from!
1222
1223   S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
1224     << var->getIdentifier() << functionName;
1225   S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
1226     << var->getIdentifier();
1227
1228   return CR_Error;
1229 }
1230
1231 /// There is a well-formed capture at a particular scope level;
1232 /// propagate it through all the nested blocks.
1233 static CaptureResult propagateCapture(Sema &S, unsigned ValidScopeIndex,
1234                                       const BlockDecl::Capture &Capture) {
1235   VarDecl *var = Capture.getVariable();
1236
1237   // Update all the inner blocks with the capture information.
1238   for (unsigned i = ValidScopeIndex + 1, e = S.FunctionScopes.size();
1239          i != e; ++i) {
1240     BlockScopeInfo *innerBlock = cast<BlockScopeInfo>(S.FunctionScopes[i]);
1241     innerBlock->Captures.push_back(
1242       BlockDecl::Capture(Capture.getVariable(), Capture.isByRef(),
1243                          /*nested*/ true, Capture.getCopyExpr()));
1244     innerBlock->CaptureMap[var] = innerBlock->Captures.size(); // +1
1245   }
1246
1247   return Capture.isByRef() ? CR_CaptureByRef : CR_Capture;
1248 }
1249
1250 /// shouldCaptureValueReference - Determine if a reference to the
1251 /// given value in the current context requires a variable capture.
1252 ///
1253 /// This also keeps the captures set in the BlockScopeInfo records
1254 /// up-to-date.
1255 static CaptureResult shouldCaptureValueReference(Sema &S, SourceLocation loc,
1256                                                  ValueDecl *Value) {
1257   // Only variables ever require capture.
1258   VarDecl *var = dyn_cast<VarDecl>(Value);
1259   if (!var) return CR_NoCapture;
1260
1261   // Fast path: variables from the current context never require capture.
1262   DeclContext *DC = S.CurContext;
1263   if (var->getDeclContext() == DC) return CR_NoCapture;
1264
1265   // Only variables with local storage require capture.
1266   // FIXME: What about 'const' variables in C++?
1267   if (!var->hasLocalStorage()) return CR_NoCapture;
1268
1269   // Otherwise, we need to capture.
1270
1271   unsigned functionScopesIndex = S.FunctionScopes.size() - 1;
1272   do {
1273     // Only blocks (and eventually C++0x closures) can capture; other
1274     // scopes don't work.
1275     if (!isa<BlockDecl>(DC))
1276       return diagnoseUncapturableValueReference(S, loc, var, DC);
1277
1278     BlockScopeInfo *blockScope =
1279       cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1280     assert(blockScope->TheDecl == static_cast<BlockDecl*>(DC));
1281
1282     // Check whether we've already captured it in this block.  If so,
1283     // we're done.
1284     if (unsigned indexPlus1 = blockScope->CaptureMap[var])
1285       return propagateCapture(S, functionScopesIndex,
1286                               blockScope->Captures[indexPlus1 - 1]);
1287
1288     functionScopesIndex--;
1289     DC = cast<BlockDecl>(DC)->getDeclContext();
1290   } while (var->getDeclContext() != DC);
1291
1292   // Okay, we descended all the way to the block that defines the variable.
1293   // Actually try to capture it.
1294   QualType type = var->getType();
1295
1296   // Prohibit variably-modified types.
1297   if (type->isVariablyModifiedType()) {
1298     S.Diag(loc, diag::err_ref_vm_type);
1299     S.Diag(var->getLocation(), diag::note_declared_at);
1300     return CR_Error;
1301   }
1302
1303   // Prohibit arrays, even in __block variables, but not references to
1304   // them.
1305   if (type->isArrayType()) {
1306     S.Diag(loc, diag::err_ref_array_type);
1307     S.Diag(var->getLocation(), diag::note_declared_at);
1308     return CR_Error;
1309   }
1310
1311   S.MarkDeclarationReferenced(loc, var);
1312
1313   // The BlocksAttr indicates the variable is bound by-reference.
1314   bool byRef = var->hasAttr<BlocksAttr>();
1315
1316   // Build a copy expression.
1317   Expr *copyExpr = 0;
1318   const RecordType *rtype;
1319   if (!byRef && S.getLangOptions().CPlusPlus && !type->isDependentType() &&
1320       (rtype = type->getAs<RecordType>())) {
1321
1322     // The capture logic needs the destructor, so make sure we mark it.
1323     // Usually this is unnecessary because most local variables have
1324     // their destructors marked at declaration time, but parameters are
1325     // an exception because it's technically only the call site that
1326     // actually requires the destructor.
1327     if (isa<ParmVarDecl>(var))
1328       S.FinalizeVarWithDestructor(var, rtype);
1329
1330     // According to the blocks spec, the capture of a variable from
1331     // the stack requires a const copy constructor.  This is not true
1332     // of the copy/move done to move a __block variable to the heap.
1333     type.addConst();
1334
1335     Expr *declRef = new (S.Context) DeclRefExpr(var, type, VK_LValue, loc);
1336     ExprResult result =
1337       S.PerformCopyInitialization(
1338                       InitializedEntity::InitializeBlock(var->getLocation(),
1339                                                          type, false),
1340                                   loc, S.Owned(declRef));
1341
1342     // Build a full-expression copy expression if initialization
1343     // succeeded and used a non-trivial constructor.  Recover from
1344     // errors by pretending that the copy isn't necessary.
1345     if (!result.isInvalid() &&
1346         !cast<CXXConstructExpr>(result.get())->getConstructor()->isTrivial()) {
1347       result = S.MaybeCreateExprWithCleanups(result);
1348       copyExpr = result.take();
1349     }
1350   }
1351
1352   // We're currently at the declarer; go back to the closure.
1353   functionScopesIndex++;
1354   BlockScopeInfo *blockScope =
1355     cast<BlockScopeInfo>(S.FunctionScopes[functionScopesIndex]);
1356
1357   // Build a valid capture in this scope.
1358   blockScope->Captures.push_back(
1359                  BlockDecl::Capture(var, byRef, /*nested*/ false, copyExpr));
1360   blockScope->CaptureMap[var] = blockScope->Captures.size(); // +1
1361
1362   // Propagate that to inner captures if necessary.
1363   return propagateCapture(S, functionScopesIndex,
1364                           blockScope->Captures.back());
1365 }
1366
1367 static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
1368                                         const DeclarationNameInfo &NameInfo,
1369                                         bool ByRef) {
1370   assert(isa<VarDecl>(VD) && "capturing non-variable");
1371
1372   VarDecl *var = cast<VarDecl>(VD);
1373   assert(var->hasLocalStorage() && "capturing non-local");
1374   assert(ByRef == var->hasAttr<BlocksAttr>() && "byref set wrong");
1375
1376   QualType exprType = var->getType().getNonReferenceType();
1377
1378   BlockDeclRefExpr *BDRE;
1379   if (!ByRef) {
1380     // The variable will be bound by copy; make it const within the
1381     // closure, but record that this was done in the expression.
1382     bool constAdded = !exprType.isConstQualified();
1383     exprType.addConst();
1384
1385     BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1386                                             NameInfo.getLoc(), false,
1387                                             constAdded);
1388   } else {
1389     BDRE = new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
1390                                             NameInfo.getLoc(), true);
1391   }
1392
1393   return S.Owned(BDRE);
1394 }
1395
1396 ExprResult
1397 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1398                        SourceLocation Loc,
1399                        const CXXScopeSpec *SS) {
1400   DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
1401   return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
1402 }
1403
1404 /// BuildDeclRefExpr - Build an expression that references a
1405 /// declaration that does not require a closure capture.
1406 ExprResult
1407 Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
1408                        const DeclarationNameInfo &NameInfo,
1409                        const CXXScopeSpec *SS) {
1410   if (getLangOptions().CUDA)
1411     if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1412       if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1413         CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1414                            CalleeTarget = IdentifyCUDATarget(Callee);
1415         if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1416           Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1417             << CalleeTarget << D->getIdentifier() << CallerTarget;
1418           Diag(D->getLocation(), diag::note_previous_decl)
1419             << D->getIdentifier();
1420           return ExprError();
1421         }
1422       }
1423
1424   MarkDeclarationReferenced(NameInfo.getLoc(), D);
1425
1426   Expr *E = DeclRefExpr::Create(Context,
1427                                 SS? SS->getWithLocInContext(Context) 
1428                                   : NestedNameSpecifierLoc(),
1429                                 D, NameInfo, Ty, VK);
1430
1431   // Just in case we're building an illegal pointer-to-member.
1432   FieldDecl *FD = dyn_cast<FieldDecl>(D);
1433   if (FD && FD->isBitField())
1434     E->setObjectKind(OK_BitField);
1435
1436   return Owned(E);
1437 }
1438
1439 /// Decomposes the given name into a DeclarationNameInfo, its location, and
1440 /// possibly a list of template arguments.
1441 ///
1442 /// If this produces template arguments, it is permitted to call
1443 /// DecomposeTemplateName.
1444 ///
1445 /// This actually loses a lot of source location information for
1446 /// non-standard name kinds; we should consider preserving that in
1447 /// some way.
1448 void
1449 Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1450                              TemplateArgumentListInfo &Buffer,
1451                              DeclarationNameInfo &NameInfo,
1452                              const TemplateArgumentListInfo *&TemplateArgs) {
1453   if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1454     Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1455     Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1456
1457     ASTTemplateArgsPtr TemplateArgsPtr(*this,
1458                                        Id.TemplateId->getTemplateArgs(),
1459                                        Id.TemplateId->NumArgs);
1460     translateTemplateArguments(TemplateArgsPtr, Buffer);
1461     TemplateArgsPtr.release();
1462
1463     TemplateName TName = Id.TemplateId->Template.get();
1464     SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
1465     NameInfo = Context.getNameForTemplate(TName, TNameLoc);
1466     TemplateArgs = &Buffer;
1467   } else {
1468     NameInfo = GetNameFromUnqualifiedId(Id);
1469     TemplateArgs = 0;
1470   }
1471 }
1472
1473 /// Diagnose an empty lookup.
1474 ///
1475 /// \return false if new lookup candidates were found
1476 bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
1477                                CorrectTypoContext CTC,
1478                                TemplateArgumentListInfo *ExplicitTemplateArgs,
1479                                Expr **Args, unsigned NumArgs) {
1480   DeclarationName Name = R.getLookupName();
1481
1482   unsigned diagnostic = diag::err_undeclared_var_use;
1483   unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
1484   if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1485       Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
1486       Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
1487     diagnostic = diag::err_undeclared_use;
1488     diagnostic_suggest = diag::err_undeclared_use_suggest;
1489   }
1490
1491   // If the original lookup was an unqualified lookup, fake an
1492   // unqualified lookup.  This is useful when (for example) the
1493   // original lookup would not have found something because it was a
1494   // dependent name.
1495   for (DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1496        DC; DC = DC->getParent()) {
1497     if (isa<CXXRecordDecl>(DC)) {
1498       LookupQualifiedName(R, DC);
1499
1500       if (!R.empty()) {
1501         // Don't give errors about ambiguities in this lookup.
1502         R.suppressDiagnostics();
1503
1504         CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1505         bool isInstance = CurMethod &&
1506                           CurMethod->isInstance() &&
1507                           DC == CurMethod->getParent();
1508
1509         // Give a code modification hint to insert 'this->'.
1510         // TODO: fixit for inserting 'Base<T>::' in the other cases.
1511         // Actually quite difficult!
1512         if (isInstance) {
1513           UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1514               CallsUndergoingInstantiation.back()->getCallee());
1515           CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
1516               CurMethod->getInstantiatedFromMemberFunction());
1517           if (DepMethod) {
1518             if (getLangOptions().MicrosoftExt)
1519               diagnostic = diag::warn_found_via_dependent_bases_lookup;
1520             Diag(R.getNameLoc(), diagnostic) << Name
1521               << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1522             QualType DepThisType = DepMethod->getThisType(Context);
1523             CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1524                                        R.getNameLoc(), DepThisType, false);
1525             TemplateArgumentListInfo TList;
1526             if (ULE->hasExplicitTemplateArgs())
1527               ULE->copyTemplateArgumentsInto(TList);
1528             
1529             CXXScopeSpec SS;
1530             SS.Adopt(ULE->getQualifierLoc());
1531             CXXDependentScopeMemberExpr *DepExpr =
1532                 CXXDependentScopeMemberExpr::Create(
1533                     Context, DepThis, DepThisType, true, SourceLocation(),
1534                     SS.getWithLocInContext(Context), NULL,
1535                     R.getLookupNameInfo(),
1536                     ULE->hasExplicitTemplateArgs() ? &TList : 0);
1537             CallsUndergoingInstantiation.back()->setCallee(DepExpr);
1538           } else {
1539             // FIXME: we should be able to handle this case too. It is correct
1540             // to add this-> here. This is a workaround for PR7947.
1541             Diag(R.getNameLoc(), diagnostic) << Name;
1542           }
1543         } else {
1544           Diag(R.getNameLoc(), diagnostic) << Name;
1545         }
1546
1547         // Do we really want to note all of these?
1548         for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1549           Diag((*I)->getLocation(), diag::note_dependent_var_use);
1550
1551         // Tell the callee to try to recover.
1552         return false;
1553       }
1554
1555       R.clear();
1556     }
1557   }
1558
1559   // We didn't find anything, so try to correct for a typo.
1560   TypoCorrection Corrected;
1561   if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
1562                                     S, &SS, NULL, false, CTC))) {
1563     std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1564     std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1565     R.setLookupName(Corrected.getCorrection());
1566
1567     if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
1568       if (Corrected.isOverloaded()) {
1569         OverloadCandidateSet OCS(R.getNameLoc());
1570         OverloadCandidateSet::iterator Best;
1571         for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1572                                         CDEnd = Corrected.end();
1573              CD != CDEnd; ++CD) {
1574           if (FunctionTemplateDecl *FTD =
1575                    dyn_cast<FunctionTemplateDecl>(*CD))
1576             AddTemplateOverloadCandidate(
1577                 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
1578                 Args, NumArgs, OCS);
1579           else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1580             if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1581               AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
1582                                    Args, NumArgs, OCS);
1583         }
1584         switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1585           case OR_Success:
1586             ND = Best->Function;
1587             break;
1588           default:
1589             break;
1590         }
1591       }
1592       R.addDecl(ND);
1593       if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
1594         if (SS.isEmpty())
1595           Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1596             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1597         else
1598           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1599             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1600             << SS.getRange()
1601             << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1602         if (ND)
1603           Diag(ND->getLocation(), diag::note_previous_decl)
1604             << CorrectedQuotedStr;
1605
1606         // Tell the callee to try to recover.
1607         return false;
1608       }
1609
1610       if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
1611         // FIXME: If we ended up with a typo for a type name or
1612         // Objective-C class name, we're in trouble because the parser
1613         // is in the wrong place to recover. Suggest the typo
1614         // correction, but don't make it a fix-it since we're not going
1615         // to recover well anyway.
1616         if (SS.isEmpty())
1617           Diag(R.getNameLoc(), diagnostic_suggest)
1618             << Name << CorrectedQuotedStr;
1619         else
1620           Diag(R.getNameLoc(), diag::err_no_member_suggest)
1621             << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1622             << SS.getRange();
1623
1624         // Don't try to recover; it won't work.
1625         return true;
1626       }
1627     } else {
1628       // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
1629       // because we aren't able to recover.
1630       if (SS.isEmpty())
1631         Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
1632       else
1633         Diag(R.getNameLoc(), diag::err_no_member_suggest)
1634         << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
1635         << SS.getRange();
1636       return true;
1637     }
1638   }
1639   R.clear();
1640
1641   // Emit a special diagnostic for failed member lookups.
1642   // FIXME: computing the declaration context might fail here (?)
1643   if (!SS.isEmpty()) {
1644     Diag(R.getNameLoc(), diag::err_no_member)
1645       << Name << computeDeclContext(SS, false)
1646       << SS.getRange();
1647     return true;
1648   }
1649
1650   // Give up, we can't recover.
1651   Diag(R.getNameLoc(), diagnostic) << Name;
1652   return true;
1653 }
1654
1655 ExprResult Sema::ActOnIdExpression(Scope *S,
1656                                    CXXScopeSpec &SS,
1657                                    UnqualifiedId &Id,
1658                                    bool HasTrailingLParen,
1659                                    bool IsAddressOfOperand) {
1660   assert(!(IsAddressOfOperand && HasTrailingLParen) &&
1661          "cannot be direct & operand and have a trailing lparen");
1662
1663   if (SS.isInvalid())
1664     return ExprError();
1665
1666   TemplateArgumentListInfo TemplateArgsBuffer;
1667
1668   // Decompose the UnqualifiedId into the following data.
1669   DeclarationNameInfo NameInfo;
1670   const TemplateArgumentListInfo *TemplateArgs;
1671   DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
1672
1673   DeclarationName Name = NameInfo.getName();
1674   IdentifierInfo *II = Name.getAsIdentifierInfo();
1675   SourceLocation NameLoc = NameInfo.getLoc();
1676
1677   // C++ [temp.dep.expr]p3:
1678   //   An id-expression is type-dependent if it contains:
1679   //     -- an identifier that was declared with a dependent type,
1680   //        (note: handled after lookup)
1681   //     -- a template-id that is dependent,
1682   //        (note: handled in BuildTemplateIdExpr)
1683   //     -- a conversion-function-id that specifies a dependent type,
1684   //     -- a nested-name-specifier that contains a class-name that
1685   //        names a dependent type.
1686   // Determine whether this is a member of an unknown specialization;
1687   // we need to handle these differently.
1688   bool DependentID = false;
1689   if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1690       Name.getCXXNameType()->isDependentType()) {
1691     DependentID = true;
1692   } else if (SS.isSet()) {
1693     if (DeclContext *DC = computeDeclContext(SS, false)) {
1694       if (RequireCompleteDeclContext(SS, DC))
1695         return ExprError();
1696     } else {
1697       DependentID = true;
1698     }
1699   }
1700
1701   if (DependentID)
1702     return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1703                                       TemplateArgs);
1704
1705   bool IvarLookupFollowUp = false;
1706   // Perform the required lookup.
1707   LookupResult R(*this, NameInfo, 
1708                  (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam) 
1709                   ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
1710   if (TemplateArgs) {
1711     // Lookup the template name again to correctly establish the context in
1712     // which it was found. This is really unfortunate as we already did the
1713     // lookup to determine that it was a template name in the first place. If
1714     // this becomes a performance hit, we can work harder to preserve those
1715     // results until we get here but it's likely not worth it.
1716     bool MemberOfUnknownSpecialization;
1717     LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1718                        MemberOfUnknownSpecialization);
1719     
1720     if (MemberOfUnknownSpecialization ||
1721         (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
1722       return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1723                                         TemplateArgs);
1724   } else {
1725     IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1726     LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1727
1728     // If the result might be in a dependent base class, this is a dependent 
1729     // id-expression.
1730     if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
1731       return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1732                                         TemplateArgs);
1733       
1734     // If this reference is in an Objective-C method, then we need to do
1735     // some special Objective-C lookup, too.
1736     if (IvarLookupFollowUp) {
1737       ExprResult E(LookupInObjCMethod(R, S, II, true));
1738       if (E.isInvalid())
1739         return ExprError();
1740
1741       if (Expr *Ex = E.takeAs<Expr>())
1742         return Owned(Ex);
1743       
1744       // for further use, this must be set to false if in class method.
1745       IvarLookupFollowUp = getCurMethodDecl()->isInstanceMethod();
1746     }
1747   }
1748
1749   if (R.isAmbiguous())
1750     return ExprError();
1751
1752   // Determine whether this name might be a candidate for
1753   // argument-dependent lookup.
1754   bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1755
1756   if (R.empty() && !ADL) {
1757     // Otherwise, this could be an implicitly declared function reference (legal
1758     // in C90, extension in C99, forbidden in C++).
1759     if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1760       NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1761       if (D) R.addDecl(D);
1762     }
1763
1764     // If this name wasn't predeclared and if this is not a function
1765     // call, diagnose the problem.
1766     if (R.empty()) {
1767
1768       // In Microsoft mode, if we are inside a template class member function
1769       // and we can't resolve an identifier then assume the identifier is type
1770       // dependent. The goal is to postpone name lookup to instantiation time 
1771       // to be able to search into type dependent base classes.
1772       if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1773           isa<CXXMethodDecl>(CurContext))
1774         return ActOnDependentIdExpression(SS, NameInfo, IsAddressOfOperand,
1775                                           TemplateArgs);
1776
1777       if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1778         return ExprError();
1779
1780       assert(!R.empty() &&
1781              "DiagnoseEmptyLookup returned false but added no results");
1782
1783       // If we found an Objective-C instance variable, let
1784       // LookupInObjCMethod build the appropriate expression to
1785       // reference the ivar.
1786       if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1787         R.clear();
1788         ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1789         // In a hopelessly buggy code, Objective-C instance variable
1790         // lookup fails and no expression will be built to reference it.
1791         if (!E.isInvalid() && !E.get())
1792           return ExprError();
1793         return move(E);
1794       }
1795     }
1796   }
1797
1798   // This is guaranteed from this point on.
1799   assert(!R.empty() || ADL);
1800
1801   // Check whether this might be a C++ implicit instance member access.
1802   // C++ [class.mfct.non-static]p3:
1803   //   When an id-expression that is not part of a class member access
1804   //   syntax and not used to form a pointer to member is used in the
1805   //   body of a non-static member function of class X, if name lookup
1806   //   resolves the name in the id-expression to a non-static non-type
1807   //   member of some class C, the id-expression is transformed into a
1808   //   class member access expression using (*this) as the
1809   //   postfix-expression to the left of the . operator.
1810   //
1811   // But we don't actually need to do this for '&' operands if R
1812   // resolved to a function or overloaded function set, because the
1813   // expression is ill-formed if it actually works out to be a
1814   // non-static member function:
1815   //
1816   // C++ [expr.ref]p4:
1817   //   Otherwise, if E1.E2 refers to a non-static member function. . .
1818   //   [t]he expression can be used only as the left-hand operand of a
1819   //   member function call.
1820   //
1821   // There are other safeguards against such uses, but it's important
1822   // to get this right here so that we don't end up making a
1823   // spuriously dependent expression if we're inside a dependent
1824   // instance method.
1825   if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1826     bool MightBeImplicitMember;
1827     if (!IsAddressOfOperand)
1828       MightBeImplicitMember = true;
1829     else if (!SS.isEmpty())
1830       MightBeImplicitMember = false;
1831     else if (R.isOverloadedResult())
1832       MightBeImplicitMember = false;
1833     else if (R.isUnresolvableResult())
1834       MightBeImplicitMember = true;
1835     else
1836       MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1837                               isa<IndirectFieldDecl>(R.getFoundDecl());
1838
1839     if (MightBeImplicitMember)
1840       return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1841   }
1842
1843   if (TemplateArgs)
1844     return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1845
1846   return BuildDeclarationNameExpr(SS, R, ADL);
1847 }
1848
1849 /// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1850 /// declaration name, generally during template instantiation.
1851 /// There's a large number of things which don't need to be done along
1852 /// this path.
1853 ExprResult
1854 Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1855                                         const DeclarationNameInfo &NameInfo) {
1856   DeclContext *DC;
1857   if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1858     return BuildDependentDeclRefExpr(SS, NameInfo, 0);
1859
1860   if (RequireCompleteDeclContext(SS, DC))
1861     return ExprError();
1862
1863   LookupResult R(*this, NameInfo, LookupOrdinaryName);
1864   LookupQualifiedName(R, DC);
1865
1866   if (R.isAmbiguous())
1867     return ExprError();
1868
1869   if (R.empty()) {
1870     Diag(NameInfo.getLoc(), diag::err_no_member)
1871       << NameInfo.getName() << DC << SS.getRange();
1872     return ExprError();
1873   }
1874
1875   return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1876 }
1877
1878 /// LookupInObjCMethod - The parser has read a name in, and Sema has
1879 /// detected that we're currently inside an ObjC method.  Perform some
1880 /// additional lookup.
1881 ///
1882 /// Ideally, most of this would be done by lookup, but there's
1883 /// actually quite a lot of extra work involved.
1884 ///
1885 /// Returns a null sentinel to indicate trivial success.
1886 ExprResult
1887 Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1888                          IdentifierInfo *II, bool AllowBuiltinCreation) {
1889   SourceLocation Loc = Lookup.getNameLoc();
1890   ObjCMethodDecl *CurMethod = getCurMethodDecl();
1891
1892   // There are two cases to handle here.  1) scoped lookup could have failed,
1893   // in which case we should look for an ivar.  2) scoped lookup could have
1894   // found a decl, but that decl is outside the current instance method (i.e.
1895   // a global variable).  In these two cases, we do a lookup for an ivar with
1896   // this name, if the lookup sucedes, we replace it our current decl.
1897
1898   // If we're in a class method, we don't normally want to look for
1899   // ivars.  But if we don't find anything else, and there's an
1900   // ivar, that's an error.
1901   bool IsClassMethod = CurMethod->isClassMethod();
1902
1903   bool LookForIvars;
1904   if (Lookup.empty())
1905     LookForIvars = true;
1906   else if (IsClassMethod)
1907     LookForIvars = false;
1908   else
1909     LookForIvars = (Lookup.isSingleResult() &&
1910                     Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1911   ObjCInterfaceDecl *IFace = 0;
1912   if (LookForIvars) {
1913     IFace = CurMethod->getClassInterface();
1914     ObjCInterfaceDecl *ClassDeclared;
1915     if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1916       // Diagnose using an ivar in a class method.
1917       if (IsClassMethod)
1918         return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1919                          << IV->getDeclName());
1920
1921       // If we're referencing an invalid decl, just return this as a silent
1922       // error node.  The error diagnostic was already emitted on the decl.
1923       if (IV->isInvalidDecl())
1924         return ExprError();
1925
1926       // Check if referencing a field with __attribute__((deprecated)).
1927       if (DiagnoseUseOfDecl(IV, Loc))
1928         return ExprError();
1929
1930       // Diagnose the use of an ivar outside of the declaring class.
1931       if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1932           ClassDeclared != IFace)
1933         Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1934
1935       // FIXME: This should use a new expr for a direct reference, don't
1936       // turn this into Self->ivar, just return a BareIVarExpr or something.
1937       IdentifierInfo &II = Context.Idents.get("self");
1938       UnqualifiedId SelfName;
1939       SelfName.setIdentifier(&II, SourceLocation());
1940       SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
1941       CXXScopeSpec SelfScopeSpec;
1942       ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1943                                               SelfName, false, false);
1944       if (SelfExpr.isInvalid())
1945         return ExprError();
1946
1947       SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1948       if (SelfExpr.isInvalid())
1949         return ExprError();
1950
1951       MarkDeclarationReferenced(Loc, IV);
1952       return Owned(new (Context)
1953                    ObjCIvarRefExpr(IV, IV->getType(), Loc,
1954                                    SelfExpr.take(), true, true));
1955     }
1956   } else if (CurMethod->isInstanceMethod()) {
1957     // We should warn if a local variable hides an ivar.
1958     ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1959     ObjCInterfaceDecl *ClassDeclared;
1960     if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1961       if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1962           IFace == ClassDeclared)
1963         Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1964     }
1965   }
1966
1967   if (Lookup.empty() && II && AllowBuiltinCreation) {
1968     // FIXME. Consolidate this with similar code in LookupName.
1969     if (unsigned BuiltinID = II->getBuiltinID()) {
1970       if (!(getLangOptions().CPlusPlus &&
1971             Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1972         NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1973                                            S, Lookup.isForRedeclaration(),
1974                                            Lookup.getNameLoc());
1975         if (D) Lookup.addDecl(D);
1976       }
1977     }
1978   }
1979   // Sentinel value saying that we didn't do anything special.
1980   return Owned((Expr*) 0);
1981 }
1982
1983 /// \brief Cast a base object to a member's actual type.
1984 ///
1985 /// Logically this happens in three phases:
1986 ///
1987 /// * First we cast from the base type to the naming class.
1988 ///   The naming class is the class into which we were looking
1989 ///   when we found the member;  it's the qualifier type if a
1990 ///   qualifier was provided, and otherwise it's the base type.
1991 ///
1992 /// * Next we cast from the naming class to the declaring class.
1993 ///   If the member we found was brought into a class's scope by
1994 ///   a using declaration, this is that class;  otherwise it's
1995 ///   the class declaring the member.
1996 ///
1997 /// * Finally we cast from the declaring class to the "true"
1998 ///   declaring class of the member.  This conversion does not
1999 ///   obey access control.
2000 ExprResult
2001 Sema::PerformObjectMemberConversion(Expr *From,
2002                                     NestedNameSpecifier *Qualifier,
2003                                     NamedDecl *FoundDecl,
2004                                     NamedDecl *Member) {
2005   CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
2006   if (!RD)
2007     return Owned(From);
2008
2009   QualType DestRecordType;
2010   QualType DestType;
2011   QualType FromRecordType;
2012   QualType FromType = From->getType();
2013   bool PointerConversions = false;
2014   if (isa<FieldDecl>(Member)) {
2015     DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
2016
2017     if (FromType->getAs<PointerType>()) {
2018       DestType = Context.getPointerType(DestRecordType);
2019       FromRecordType = FromType->getPointeeType();
2020       PointerConversions = true;
2021     } else {
2022       DestType = DestRecordType;
2023       FromRecordType = FromType;
2024     }
2025   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
2026     if (Method->isStatic())
2027       return Owned(From);
2028
2029     DestType = Method->getThisType(Context);
2030     DestRecordType = DestType->getPointeeType();
2031
2032     if (FromType->getAs<PointerType>()) {
2033       FromRecordType = FromType->getPointeeType();
2034       PointerConversions = true;
2035     } else {
2036       FromRecordType = FromType;
2037       DestType = DestRecordType;
2038     }
2039   } else {
2040     // No conversion necessary.
2041     return Owned(From);
2042   }
2043
2044   if (DestType->isDependentType() || FromType->isDependentType())
2045     return Owned(From);
2046
2047   // If the unqualified types are the same, no conversion is necessary.
2048   if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2049     return Owned(From);
2050
2051   SourceRange FromRange = From->getSourceRange();
2052   SourceLocation FromLoc = FromRange.getBegin();
2053
2054   ExprValueKind VK = From->getValueKind();
2055
2056   // C++ [class.member.lookup]p8:
2057   //   [...] Ambiguities can often be resolved by qualifying a name with its
2058   //   class name.
2059   //
2060   // If the member was a qualified name and the qualified referred to a
2061   // specific base subobject type, we'll cast to that intermediate type
2062   // first and then to the object in which the member is declared. That allows
2063   // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2064   //
2065   //   class Base { public: int x; };
2066   //   class Derived1 : public Base { };
2067   //   class Derived2 : public Base { };
2068   //   class VeryDerived : public Derived1, public Derived2 { void f(); };
2069   //
2070   //   void VeryDerived::f() {
2071   //     x = 17; // error: ambiguous base subobjects
2072   //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
2073   //   }
2074   if (Qualifier) {
2075     QualType QType = QualType(Qualifier->getAsType(), 0);
2076     assert(!QType.isNull() && "lookup done with dependent qualifier?");
2077     assert(QType->isRecordType() && "lookup done with non-record type");
2078
2079     QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2080
2081     // In C++98, the qualifier type doesn't actually have to be a base
2082     // type of the object type, in which case we just ignore it.
2083     // Otherwise build the appropriate casts.
2084     if (IsDerivedFrom(FromRecordType, QRecordType)) {
2085       CXXCastPath BasePath;
2086       if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
2087                                        FromLoc, FromRange, &BasePath))
2088         return ExprError();
2089
2090       if (PointerConversions)
2091         QType = Context.getPointerType(QType);
2092       From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2093                                VK, &BasePath).take();
2094
2095       FromType = QType;
2096       FromRecordType = QRecordType;
2097
2098       // If the qualifier type was the same as the destination type,
2099       // we're done.
2100       if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
2101         return Owned(From);
2102     }
2103   }
2104
2105   bool IgnoreAccess = false;
2106
2107   // If we actually found the member through a using declaration, cast
2108   // down to the using declaration's type.
2109   //
2110   // Pointer equality is fine here because only one declaration of a
2111   // class ever has member declarations.
2112   if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2113     assert(isa<UsingShadowDecl>(FoundDecl));
2114     QualType URecordType = Context.getTypeDeclType(
2115                            cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2116
2117     // We only need to do this if the naming-class to declaring-class
2118     // conversion is non-trivial.
2119     if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2120       assert(IsDerivedFrom(FromRecordType, URecordType));
2121       CXXCastPath BasePath;
2122       if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
2123                                        FromLoc, FromRange, &BasePath))
2124         return ExprError();
2125
2126       QualType UType = URecordType;
2127       if (PointerConversions)
2128         UType = Context.getPointerType(UType);
2129       From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2130                                VK, &BasePath).take();
2131       FromType = UType;
2132       FromRecordType = URecordType;
2133     }
2134
2135     // We don't do access control for the conversion from the
2136     // declaring class to the true declaring class.
2137     IgnoreAccess = true;
2138   }
2139
2140   CXXCastPath BasePath;
2141   if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2142                                    FromLoc, FromRange, &BasePath,
2143                                    IgnoreAccess))
2144     return ExprError();
2145
2146   return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2147                            VK, &BasePath);
2148 }
2149
2150 bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
2151                                       const LookupResult &R,
2152                                       bool HasTrailingLParen) {
2153   // Only when used directly as the postfix-expression of a call.
2154   if (!HasTrailingLParen)
2155     return false;
2156
2157   // Never if a scope specifier was provided.
2158   if (SS.isSet())
2159     return false;
2160
2161   // Only in C++ or ObjC++.
2162   if (!getLangOptions().CPlusPlus)
2163     return false;
2164
2165   // Turn off ADL when we find certain kinds of declarations during
2166   // normal lookup:
2167   for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2168     NamedDecl *D = *I;
2169
2170     // C++0x [basic.lookup.argdep]p3:
2171     //     -- a declaration of a class member
2172     // Since using decls preserve this property, we check this on the
2173     // original decl.
2174     if (D->isCXXClassMember())
2175       return false;
2176
2177     // C++0x [basic.lookup.argdep]p3:
2178     //     -- a block-scope function declaration that is not a
2179     //        using-declaration
2180     // NOTE: we also trigger this for function templates (in fact, we
2181     // don't check the decl type at all, since all other decl types
2182     // turn off ADL anyway).
2183     if (isa<UsingShadowDecl>(D))
2184       D = cast<UsingShadowDecl>(D)->getTargetDecl();
2185     else if (D->getDeclContext()->isFunctionOrMethod())
2186       return false;
2187
2188     // C++0x [basic.lookup.argdep]p3:
2189     //     -- a declaration that is neither a function or a function
2190     //        template
2191     // And also for builtin functions.
2192     if (isa<FunctionDecl>(D)) {
2193       FunctionDecl *FDecl = cast<FunctionDecl>(D);
2194
2195       // But also builtin functions.
2196       if (FDecl->getBuiltinID() && FDecl->isImplicit())
2197         return false;
2198     } else if (!isa<FunctionTemplateDecl>(D))
2199       return false;
2200   }
2201
2202   return true;
2203 }
2204
2205
2206 /// Diagnoses obvious problems with the use of the given declaration
2207 /// as an expression.  This is only actually called for lookups that
2208 /// were not overloaded, and it doesn't promise that the declaration
2209 /// will in fact be used.
2210 static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
2211   if (isa<TypedefNameDecl>(D)) {
2212     S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2213     return true;
2214   }
2215
2216   if (isa<ObjCInterfaceDecl>(D)) {
2217     S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2218     return true;
2219   }
2220
2221   if (isa<NamespaceDecl>(D)) {
2222     S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2223     return true;
2224   }
2225
2226   return false;
2227 }
2228
2229 ExprResult
2230 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2231                                LookupResult &R,
2232                                bool NeedsADL) {
2233   // If this is a single, fully-resolved result and we don't need ADL,
2234   // just build an ordinary singleton decl ref.
2235   if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
2236     return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2237                                     R.getFoundDecl());
2238
2239   // We only need to check the declaration if there's exactly one
2240   // result, because in the overloaded case the results can only be
2241   // functions and function templates.
2242   if (R.isSingleResult() &&
2243       CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
2244     return ExprError();
2245
2246   // Otherwise, just build an unresolved lookup expression.  Suppress
2247   // any lookup-related diagnostics; we'll hash these out later, when
2248   // we've picked a target.
2249   R.suppressDiagnostics();
2250
2251   UnresolvedLookupExpr *ULE
2252     = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
2253                                    SS.getWithLocInContext(Context),
2254                                    R.getLookupNameInfo(),
2255                                    NeedsADL, R.isOverloadedResult(),
2256                                    R.begin(), R.end());
2257
2258   return Owned(ULE);
2259 }
2260
2261 /// \brief Complete semantic analysis for a reference to the given declaration.
2262 ExprResult
2263 Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
2264                                const DeclarationNameInfo &NameInfo,
2265                                NamedDecl *D) {
2266   assert(D && "Cannot refer to a NULL declaration");
2267   assert(!isa<FunctionTemplateDecl>(D) &&
2268          "Cannot refer unambiguously to a function template");
2269
2270   SourceLocation Loc = NameInfo.getLoc();
2271   if (CheckDeclInExpr(*this, Loc, D))
2272     return ExprError();
2273
2274   if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2275     // Specifically diagnose references to class templates that are missing
2276     // a template argument list.
2277     Diag(Loc, diag::err_template_decl_ref)
2278       << Template << SS.getRange();
2279     Diag(Template->getLocation(), diag::note_template_decl_here);
2280     return ExprError();
2281   }
2282
2283   // Make sure that we're referring to a value.
2284   ValueDecl *VD = dyn_cast<ValueDecl>(D);
2285   if (!VD) {
2286     Diag(Loc, diag::err_ref_non_value)
2287       << D << SS.getRange();
2288     Diag(D->getLocation(), diag::note_declared_at);
2289     return ExprError();
2290   }
2291
2292   // Check whether this declaration can be used. Note that we suppress
2293   // this check when we're going to perform argument-dependent lookup
2294   // on this function name, because this might not be the function
2295   // that overload resolution actually selects.
2296   if (DiagnoseUseOfDecl(VD, Loc))
2297     return ExprError();
2298
2299   // Only create DeclRefExpr's for valid Decl's.
2300   if (VD->isInvalidDecl())
2301     return ExprError();
2302
2303   // Handle members of anonymous structs and unions.  If we got here,
2304   // and the reference is to a class member indirect field, then this
2305   // must be the subject of a pointer-to-member expression.
2306   if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2307     if (!indirectField->isCXXClassMember())
2308       return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2309                                                       indirectField);
2310
2311   // If the identifier reference is inside a block, and it refers to a value
2312   // that is outside the block, create a BlockDeclRefExpr instead of a
2313   // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
2314   // the block is formed.
2315   //
2316   // We do not do this for things like enum constants, global variables, etc,
2317   // as they do not get snapshotted.
2318   //
2319   switch (shouldCaptureValueReference(*this, NameInfo.getLoc(), VD)) {
2320   case CR_Error:
2321     return ExprError();
2322
2323   case CR_Capture:
2324     assert(!SS.isSet() && "referenced local variable with scope specifier?");
2325     return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ false);
2326
2327   case CR_CaptureByRef:
2328     assert(!SS.isSet() && "referenced local variable with scope specifier?");
2329     return BuildBlockDeclRefExpr(*this, VD, NameInfo, /*byref*/ true);
2330
2331   case CR_NoCapture: {
2332     // If this reference is not in a block or if the referenced
2333     // variable is within the block, create a normal DeclRefExpr.
2334
2335     QualType type = VD->getType();
2336     ExprValueKind valueKind = VK_RValue;
2337
2338     switch (D->getKind()) {
2339     // Ignore all the non-ValueDecl kinds.
2340 #define ABSTRACT_DECL(kind)
2341 #define VALUE(type, base)
2342 #define DECL(type, base) \
2343     case Decl::type:
2344 #include "clang/AST/DeclNodes.inc"
2345       llvm_unreachable("invalid value decl kind");
2346       return ExprError();
2347
2348     // These shouldn't make it here.
2349     case Decl::ObjCAtDefsField:
2350     case Decl::ObjCIvar:
2351       llvm_unreachable("forming non-member reference to ivar?");
2352       return ExprError();
2353
2354     // Enum constants are always r-values and never references.
2355     // Unresolved using declarations are dependent.
2356     case Decl::EnumConstant:
2357     case Decl::UnresolvedUsingValue:
2358       valueKind = VK_RValue;
2359       break;
2360
2361     // Fields and indirect fields that got here must be for
2362     // pointer-to-member expressions; we just call them l-values for
2363     // internal consistency, because this subexpression doesn't really
2364     // exist in the high-level semantics.
2365     case Decl::Field:
2366     case Decl::IndirectField:
2367       assert(getLangOptions().CPlusPlus &&
2368              "building reference to field in C?");
2369
2370       // These can't have reference type in well-formed programs, but
2371       // for internal consistency we do this anyway.
2372       type = type.getNonReferenceType();
2373       valueKind = VK_LValue;
2374       break;
2375
2376     // Non-type template parameters are either l-values or r-values
2377     // depending on the type.
2378     case Decl::NonTypeTemplateParm: {
2379       if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2380         type = reftype->getPointeeType();
2381         valueKind = VK_LValue; // even if the parameter is an r-value reference
2382         break;
2383       }
2384
2385       // For non-references, we need to strip qualifiers just in case
2386       // the template parameter was declared as 'const int' or whatever.
2387       valueKind = VK_RValue;
2388       type = type.getUnqualifiedType();
2389       break;
2390     }
2391
2392     case Decl::Var:
2393       // In C, "extern void blah;" is valid and is an r-value.
2394       if (!getLangOptions().CPlusPlus &&
2395           !type.hasQualifiers() &&
2396           type->isVoidType()) {
2397         valueKind = VK_RValue;
2398         break;
2399       }
2400       // fallthrough
2401
2402     case Decl::ImplicitParam:
2403     case Decl::ParmVar:
2404       // These are always l-values.
2405       valueKind = VK_LValue;
2406       type = type.getNonReferenceType();
2407       break;
2408
2409     case Decl::Function: {
2410       const FunctionType *fty = type->castAs<FunctionType>();
2411
2412       // If we're referring to a function with an __unknown_anytype
2413       // result type, make the entire expression __unknown_anytype.
2414       if (fty->getResultType() == Context.UnknownAnyTy) {
2415         type = Context.UnknownAnyTy;
2416         valueKind = VK_RValue;
2417         break;
2418       }
2419
2420       // Functions are l-values in C++.
2421       if (getLangOptions().CPlusPlus) {
2422         valueKind = VK_LValue;
2423         break;
2424       }
2425       
2426       // C99 DR 316 says that, if a function type comes from a
2427       // function definition (without a prototype), that type is only
2428       // used for checking compatibility. Therefore, when referencing
2429       // the function, we pretend that we don't have the full function
2430       // type.
2431       if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2432           isa<FunctionProtoType>(fty))
2433         type = Context.getFunctionNoProtoType(fty->getResultType(),
2434                                               fty->getExtInfo());
2435
2436       // Functions are r-values in C.
2437       valueKind = VK_RValue;
2438       break;
2439     }
2440
2441     case Decl::CXXMethod:
2442       // If we're referring to a method with an __unknown_anytype
2443       // result type, make the entire expression __unknown_anytype.
2444       // This should only be possible with a type written directly.
2445       if (const FunctionProtoType *proto
2446             = dyn_cast<FunctionProtoType>(VD->getType()))
2447         if (proto->getResultType() == Context.UnknownAnyTy) {
2448           type = Context.UnknownAnyTy;
2449           valueKind = VK_RValue;
2450           break;
2451         }
2452
2453       // C++ methods are l-values if static, r-values if non-static.
2454       if (cast<CXXMethodDecl>(VD)->isStatic()) {
2455         valueKind = VK_LValue;
2456         break;
2457       }
2458       // fallthrough
2459
2460     case Decl::CXXConversion:
2461     case Decl::CXXDestructor:
2462     case Decl::CXXConstructor:
2463       valueKind = VK_RValue;
2464       break;
2465     }
2466
2467     return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2468   }
2469
2470   }
2471
2472   llvm_unreachable("unknown capture result");
2473   return ExprError();
2474 }
2475
2476 ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
2477   PredefinedExpr::IdentType IT;
2478
2479   switch (Kind) {
2480   default: llvm_unreachable("Unknown simple primary expr!");
2481   case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2482   case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2483   case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
2484   }
2485
2486   // Pre-defined identifiers are of type char[x], where x is the length of the
2487   // string.
2488
2489   Decl *currentDecl = getCurFunctionOrMethodDecl();
2490   if (!currentDecl && getCurBlock())
2491     currentDecl = getCurBlock()->TheDecl;
2492   if (!currentDecl) {
2493     Diag(Loc, diag::ext_predef_outside_function);
2494     currentDecl = Context.getTranslationUnitDecl();
2495   }
2496
2497   QualType ResTy;
2498   if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2499     ResTy = Context.DependentTy;
2500   } else {
2501     unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
2502
2503     llvm::APInt LengthI(32, Length + 1);
2504     ResTy = Context.CharTy.withConst();
2505     ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2506   }
2507   return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
2508 }
2509
2510 ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
2511   llvm::SmallString<16> CharBuffer;
2512   bool Invalid = false;
2513   StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
2514   if (Invalid)
2515     return ExprError();
2516
2517   CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
2518                             PP, Tok.getKind());
2519   if (Literal.hadError())
2520     return ExprError();
2521
2522   QualType Ty;
2523   if (!getLangOptions().CPlusPlus)
2524     Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
2525   else if (Literal.isWide())
2526     Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
2527   else if (Literal.isUTF16())
2528     Ty = Context.Char16Ty; // u'x' -> char16_t in C++0x.
2529   else if (Literal.isUTF32())
2530     Ty = Context.Char32Ty; // U'x' -> char32_t in C++0x.
2531   else if (Literal.isMultiChar())
2532     Ty = Context.IntTy;   // 'wxyz' -> int in C++.
2533   else
2534     Ty = Context.CharTy;  // 'x' -> char in C++
2535
2536   CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2537   if (Literal.isWide())
2538     Kind = CharacterLiteral::Wide;
2539   else if (Literal.isUTF16())
2540     Kind = CharacterLiteral::UTF16;
2541   else if (Literal.isUTF32())
2542     Kind = CharacterLiteral::UTF32;
2543
2544   return Owned(new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2545                                               Tok.getLocation()));
2546 }
2547
2548 ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
2549   // Fast path for a single digit (which is quite common).  A single digit
2550   // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2551   if (Tok.getLength() == 1) {
2552     const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
2553     unsigned IntSize = Context.getTargetInfo().getIntWidth();
2554     return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val-'0'),
2555                     Context.IntTy, Tok.getLocation()));
2556   }
2557
2558   llvm::SmallString<512> IntegerBuffer;
2559   // Add padding so that NumericLiteralParser can overread by one character.
2560   IntegerBuffer.resize(Tok.getLength()+1);
2561   const char *ThisTokBegin = &IntegerBuffer[0];
2562
2563   // Get the spelling of the token, which eliminates trigraphs, etc.
2564   bool Invalid = false;
2565   unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2566   if (Invalid)
2567     return ExprError();
2568
2569   NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
2570                                Tok.getLocation(), PP);
2571   if (Literal.hadError)
2572     return ExprError();
2573
2574   Expr *Res;
2575
2576   if (Literal.isFloatingLiteral()) {
2577     QualType Ty;
2578     if (Literal.isFloat)
2579       Ty = Context.FloatTy;
2580     else if (!Literal.isLong)
2581       Ty = Context.DoubleTy;
2582     else
2583       Ty = Context.LongDoubleTy;
2584
2585     const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2586
2587     using llvm::APFloat;
2588     APFloat Val(Format);
2589
2590     APFloat::opStatus result = Literal.GetFloatValue(Val);
2591
2592     // Overflow is always an error, but underflow is only an error if
2593     // we underflowed to zero (APFloat reports denormals as underflow).
2594     if ((result & APFloat::opOverflow) ||
2595         ((result & APFloat::opUnderflow) && Val.isZero())) {
2596       unsigned diagnostic;
2597       llvm::SmallString<20> buffer;
2598       if (result & APFloat::opOverflow) {
2599         diagnostic = diag::warn_float_overflow;
2600         APFloat::getLargest(Format).toString(buffer);
2601       } else {
2602         diagnostic = diag::warn_float_underflow;
2603         APFloat::getSmallest(Format).toString(buffer);
2604       }
2605
2606       Diag(Tok.getLocation(), diagnostic)
2607         << Ty
2608         << StringRef(buffer.data(), buffer.size());
2609     }
2610
2611     bool isExact = (result == APFloat::opOK);
2612     Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
2613
2614     if (Ty == Context.DoubleTy) {
2615       if (getLangOptions().SinglePrecisionConstants) {
2616         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2617       } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2618         Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
2619         Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
2620       }
2621     }
2622   } else if (!Literal.isIntegerLiteral()) {
2623     return ExprError();
2624   } else {
2625     QualType Ty;
2626
2627     // long long is a C99 feature.
2628     if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
2629         Literal.isLongLong)
2630       Diag(Tok.getLocation(), diag::ext_longlong);
2631
2632     // Get the value in the widest-possible width.
2633     llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
2634
2635     if (Literal.GetIntegerValue(ResultVal)) {
2636       // If this value didn't fit into uintmax_t, warn and force to ull.
2637       Diag(Tok.getLocation(), diag::warn_integer_too_large);
2638       Ty = Context.UnsignedLongLongTy;
2639       assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
2640              "long long is not intmax_t?");
2641     } else {
2642       // If this value fits into a ULL, try to figure out what else it fits into
2643       // according to the rules of C99 6.4.4.1p5.
2644
2645       // Octal, Hexadecimal, and integers with a U suffix are allowed to
2646       // be an unsigned int.
2647       bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2648
2649       // Check from smallest to largest, picking the smallest type we can.
2650       unsigned Width = 0;
2651       if (!Literal.isLong && !Literal.isLongLong) {
2652         // Are int/unsigned possibilities?
2653         unsigned IntSize = Context.getTargetInfo().getIntWidth();
2654
2655         // Does it fit in a unsigned int?
2656         if (ResultVal.isIntN(IntSize)) {
2657           // Does it fit in a signed int?
2658           if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
2659             Ty = Context.IntTy;
2660           else if (AllowUnsigned)
2661             Ty = Context.UnsignedIntTy;
2662           Width = IntSize;
2663         }
2664       }
2665
2666       // Are long/unsigned long possibilities?
2667       if (Ty.isNull() && !Literal.isLongLong) {
2668         unsigned LongSize = Context.getTargetInfo().getLongWidth();
2669
2670         // Does it fit in a unsigned long?
2671         if (ResultVal.isIntN(LongSize)) {
2672           // Does it fit in a signed long?
2673           if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
2674             Ty = Context.LongTy;
2675           else if (AllowUnsigned)
2676             Ty = Context.UnsignedLongTy;
2677           Width = LongSize;
2678         }
2679       }
2680
2681       // Finally, check long long if needed.
2682       if (Ty.isNull()) {
2683         unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
2684
2685         // Does it fit in a unsigned long long?
2686         if (ResultVal.isIntN(LongLongSize)) {
2687           // Does it fit in a signed long long?
2688           // To be compatible with MSVC, hex integer literals ending with the
2689           // LL or i64 suffix are always signed in Microsoft mode.
2690           if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
2691               (getLangOptions().MicrosoftExt && Literal.isLongLong)))
2692             Ty = Context.LongLongTy;
2693           else if (AllowUnsigned)
2694             Ty = Context.UnsignedLongLongTy;
2695           Width = LongLongSize;
2696         }
2697       }
2698
2699       // If we still couldn't decide a type, we probably have something that
2700       // does not fit in a signed long long, but has no U suffix.
2701       if (Ty.isNull()) {
2702         Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
2703         Ty = Context.UnsignedLongLongTy;
2704         Width = Context.getTargetInfo().getLongLongWidth();
2705       }
2706
2707       if (ResultVal.getBitWidth() != Width)
2708         ResultVal = ResultVal.trunc(Width);
2709     }
2710     Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
2711   }
2712
2713   // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2714   if (Literal.isImaginary)
2715     Res = new (Context) ImaginaryLiteral(Res,
2716                                         Context.getComplexType(Res->getType()));
2717
2718   return Owned(Res);
2719 }
2720
2721 ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
2722   assert((E != 0) && "ActOnParenExpr() missing expr");
2723   return Owned(new (Context) ParenExpr(L, R, E));
2724 }
2725
2726 static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2727                                          SourceLocation Loc,
2728                                          SourceRange ArgRange) {
2729   // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2730   // scalar or vector data type argument..."
2731   // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2732   // type (C99 6.2.5p18) or void.
2733   if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2734     S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2735       << T << ArgRange;
2736     return true;
2737   }
2738
2739   assert((T->isVoidType() || !T->isIncompleteType()) &&
2740          "Scalar types should always be complete");
2741   return false;
2742 }
2743
2744 static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2745                                            SourceLocation Loc,
2746                                            SourceRange ArgRange,
2747                                            UnaryExprOrTypeTrait TraitKind) {
2748   // C99 6.5.3.4p1:
2749   if (T->isFunctionType()) {
2750     // alignof(function) is allowed as an extension.
2751     if (TraitKind == UETT_SizeOf)
2752       S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2753     return false;
2754   }
2755
2756   // Allow sizeof(void)/alignof(void) as an extension.
2757   if (T->isVoidType()) {
2758     S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2759     return false;
2760   }
2761
2762   return true;
2763 }
2764
2765 static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2766                                              SourceLocation Loc,
2767                                              SourceRange ArgRange,
2768                                              UnaryExprOrTypeTrait TraitKind) {
2769   // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2770   if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2771     S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2772       << T << (TraitKind == UETT_SizeOf)
2773       << ArgRange;
2774     return true;
2775   }
2776
2777   return false;
2778 }
2779
2780 /// \brief Check the constrains on expression operands to unary type expression
2781 /// and type traits.
2782 ///
2783 /// Completes any types necessary and validates the constraints on the operand
2784 /// expression. The logic mostly mirrors the type-based overload, but may modify
2785 /// the expression as it completes the type for that expression through template
2786 /// instantiation, etc.
2787 bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
2788                                             UnaryExprOrTypeTrait ExprKind) {
2789   QualType ExprTy = E->getType();
2790
2791   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2792   //   the result is the size of the referenced type."
2793   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2794   //   result shall be the alignment of the referenced type."
2795   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2796     ExprTy = Ref->getPointeeType();
2797
2798   if (ExprKind == UETT_VecStep)
2799     return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2800                                         E->getSourceRange());
2801
2802   // Whitelist some types as extensions
2803   if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2804                                       E->getSourceRange(), ExprKind))
2805     return false;
2806
2807   if (RequireCompleteExprType(E,
2808                               PDiag(diag::err_sizeof_alignof_incomplete_type)
2809                               << ExprKind << E->getSourceRange(),
2810                               std::make_pair(SourceLocation(), PDiag(0))))
2811     return true;
2812
2813   // Completeing the expression's type may have changed it.
2814   ExprTy = E->getType();
2815   if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2816     ExprTy = Ref->getPointeeType();
2817
2818   if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2819                                        E->getSourceRange(), ExprKind))
2820     return true;
2821
2822   if (ExprKind == UETT_SizeOf) {
2823     if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
2824       if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2825         QualType OType = PVD->getOriginalType();
2826         QualType Type = PVD->getType();
2827         if (Type->isPointerType() && OType->isArrayType()) {
2828           Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
2829             << Type << OType;
2830           Diag(PVD->getLocation(), diag::note_declared_at);
2831         }
2832       }
2833     }
2834   }
2835
2836   return false;
2837 }
2838
2839 /// \brief Check the constraints on operands to unary expression and type
2840 /// traits.
2841 ///
2842 /// This will complete any types necessary, and validate the various constraints
2843 /// on those operands.
2844 ///
2845 /// The UsualUnaryConversions() function is *not* called by this routine.
2846 /// C99 6.3.2.1p[2-4] all state:
2847 ///   Except when it is the operand of the sizeof operator ...
2848 ///
2849 /// C++ [expr.sizeof]p4
2850 ///   The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2851 ///   standard conversions are not applied to the operand of sizeof.
2852 ///
2853 /// This policy is followed for all of the unary trait expressions.
2854 bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
2855                                             SourceLocation OpLoc,
2856                                             SourceRange ExprRange,
2857                                             UnaryExprOrTypeTrait ExprKind) {
2858   if (ExprType->isDependentType())
2859     return false;
2860
2861   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2862   //   the result is the size of the referenced type."
2863   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2864   //   result shall be the alignment of the referenced type."
2865   if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2866     ExprType = Ref->getPointeeType();
2867
2868   if (ExprKind == UETT_VecStep)
2869     return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
2870
2871   // Whitelist some types as extensions
2872   if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
2873                                       ExprKind))
2874     return false;
2875
2876   if (RequireCompleteType(OpLoc, ExprType,
2877                           PDiag(diag::err_sizeof_alignof_incomplete_type)
2878                           << ExprKind << ExprRange))
2879     return true;
2880
2881   if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
2882                                        ExprKind))
2883     return true;
2884
2885   return false;
2886 }
2887
2888 static bool CheckAlignOfExpr(Sema &S, Expr *E) {
2889   E = E->IgnoreParens();
2890
2891   // alignof decl is always ok.
2892   if (isa<DeclRefExpr>(E))
2893     return false;
2894
2895   // Cannot know anything else if the expression is dependent.
2896   if (E->isTypeDependent())
2897     return false;
2898
2899   if (E->getBitField()) {
2900     S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2901        << 1 << E->getSourceRange();
2902     return true;
2903   }
2904
2905   // Alignment of a field access is always okay, so long as it isn't a
2906   // bit-field.
2907   if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2908     if (isa<FieldDecl>(ME->getMemberDecl()))
2909       return false;
2910
2911   return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
2912 }
2913
2914 bool Sema::CheckVecStepExpr(Expr *E) {
2915   E = E->IgnoreParens();
2916
2917   // Cannot know anything else if the expression is dependent.
2918   if (E->isTypeDependent())
2919     return false;
2920
2921   return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
2922 }
2923
2924 /// \brief Build a sizeof or alignof expression given a type operand.
2925 ExprResult
2926 Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2927                                      SourceLocation OpLoc,
2928                                      UnaryExprOrTypeTrait ExprKind,
2929                                      SourceRange R) {
2930   if (!TInfo)
2931     return ExprError();
2932
2933   QualType T = TInfo->getType();
2934
2935   if (!T->isDependentType() &&
2936       CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
2937     return ExprError();
2938
2939   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2940   return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2941                                                       Context.getSizeType(),
2942                                                       OpLoc, R.getEnd()));
2943 }
2944
2945 /// \brief Build a sizeof or alignof expression given an expression
2946 /// operand.
2947 ExprResult
2948 Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2949                                      UnaryExprOrTypeTrait ExprKind) {
2950   ExprResult PE = CheckPlaceholderExpr(E);
2951   if (PE.isInvalid()) 
2952     return ExprError();
2953
2954   E = PE.get();
2955   
2956   // Verify that the operand is valid.
2957   bool isInvalid = false;
2958   if (E->isTypeDependent()) {
2959     // Delay type-checking for type-dependent expressions.
2960   } else if (ExprKind == UETT_AlignOf) {
2961     isInvalid = CheckAlignOfExpr(*this, E);
2962   } else if (ExprKind == UETT_VecStep) {
2963     isInvalid = CheckVecStepExpr(E);
2964   } else if (E->getBitField()) {  // C99 6.5.3.4p1.
2965     Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
2966     isInvalid = true;
2967   } else {
2968     isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
2969   }
2970
2971   if (isInvalid)
2972     return ExprError();
2973
2974   // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2975   return Owned(new (Context) UnaryExprOrTypeTraitExpr(
2976       ExprKind, E, Context.getSizeType(), OpLoc,
2977       E->getSourceRange().getEnd()));
2978 }
2979
2980 /// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2981 /// expr and the same for @c alignof and @c __alignof
2982 /// Note that the ArgRange is invalid if isType is false.
2983 ExprResult
2984 Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
2985                                     UnaryExprOrTypeTrait ExprKind, bool IsType,
2986                                     void *TyOrEx, const SourceRange &ArgRange) {
2987   // If error parsing type, ignore.
2988   if (TyOrEx == 0) return ExprError();
2989
2990   if (IsType) {
2991     TypeSourceInfo *TInfo;
2992     (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
2993     return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
2994   }
2995
2996   Expr *ArgEx = (Expr *)TyOrEx;
2997   ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
2998   return move(Result);
2999 }
3000
3001 static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
3002                                      bool IsReal) {
3003   if (V.get()->isTypeDependent())
3004     return S.Context.DependentTy;
3005
3006   // _Real and _Imag are only l-values for normal l-values.
3007   if (V.get()->getObjectKind() != OK_Ordinary) {
3008     V = S.DefaultLvalueConversion(V.take());
3009     if (V.isInvalid())
3010       return QualType();
3011   }
3012
3013   // These operators return the element type of a complex type.
3014   if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
3015     return CT->getElementType();
3016
3017   // Otherwise they pass through real integer and floating point types here.
3018   if (V.get()->getType()->isArithmeticType())
3019     return V.get()->getType();
3020
3021   // Test for placeholders.
3022   ExprResult PR = S.CheckPlaceholderExpr(V.get());
3023   if (PR.isInvalid()) return QualType();
3024   if (PR.get() != V.get()) {
3025     V = move(PR);
3026     return CheckRealImagOperand(S, V, Loc, IsReal);
3027   }
3028
3029   // Reject anything else.
3030   S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
3031     << (IsReal ? "__real" : "__imag");
3032   return QualType();
3033 }
3034
3035
3036
3037 ExprResult
3038 Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
3039                           tok::TokenKind Kind, Expr *Input) {
3040   UnaryOperatorKind Opc;
3041   switch (Kind) {
3042   default: llvm_unreachable("Unknown unary op!");
3043   case tok::plusplus:   Opc = UO_PostInc; break;
3044   case tok::minusminus: Opc = UO_PostDec; break;
3045   }
3046
3047   return BuildUnaryOp(S, OpLoc, Opc, Input);
3048 }
3049
3050 ExprResult
3051 Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3052                               Expr *Idx, SourceLocation RLoc) {
3053   // Since this might be a postfix expression, get rid of ParenListExprs.
3054   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
3055   if (Result.isInvalid()) return ExprError();
3056   Base = Result.take();
3057
3058   Expr *LHSExp = Base, *RHSExp = Idx;
3059
3060   if (getLangOptions().CPlusPlus &&
3061       (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
3062     return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3063                                                   Context.DependentTy,
3064                                                   VK_LValue, OK_Ordinary,
3065                                                   RLoc));
3066   }
3067
3068   if (getLangOptions().CPlusPlus &&
3069       (LHSExp->getType()->isRecordType() ||
3070        LHSExp->getType()->isEnumeralType() ||
3071        RHSExp->getType()->isRecordType() ||
3072        RHSExp->getType()->isEnumeralType())) {
3073     return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
3074   }
3075
3076   return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
3077 }
3078
3079
3080 ExprResult
3081 Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
3082                                       Expr *Idx, SourceLocation RLoc) {
3083   Expr *LHSExp = Base;
3084   Expr *RHSExp = Idx;
3085
3086   // Perform default conversions.
3087   if (!LHSExp->getType()->getAs<VectorType>()) {
3088     ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3089     if (Result.isInvalid())
3090       return ExprError();
3091     LHSExp = Result.take();
3092   }
3093   ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3094   if (Result.isInvalid())
3095     return ExprError();
3096   RHSExp = Result.take();
3097
3098   QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
3099   ExprValueKind VK = VK_LValue;
3100   ExprObjectKind OK = OK_Ordinary;
3101
3102   // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
3103   // to the expression *((e1)+(e2)). This means the array "Base" may actually be
3104   // in the subscript position. As a result, we need to derive the array base
3105   // and index from the expression types.
3106   Expr *BaseExpr, *IndexExpr;
3107   QualType ResultType;
3108   if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3109     BaseExpr = LHSExp;
3110     IndexExpr = RHSExp;
3111     ResultType = Context.DependentTy;
3112   } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
3113     BaseExpr = LHSExp;
3114     IndexExpr = RHSExp;
3115     ResultType = PTy->getPointeeType();
3116   } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3117      // Handle the uncommon case of "123[Ptr]".
3118     BaseExpr = RHSExp;
3119     IndexExpr = LHSExp;
3120     ResultType = PTy->getPointeeType();
3121   } else if (const ObjCObjectPointerType *PTy =
3122                LHSTy->getAs<ObjCObjectPointerType>()) {
3123     BaseExpr = LHSExp;
3124     IndexExpr = RHSExp;
3125     ResultType = PTy->getPointeeType();
3126   } else if (const ObjCObjectPointerType *PTy =
3127                RHSTy->getAs<ObjCObjectPointerType>()) {
3128      // Handle the uncommon case of "123[Ptr]".
3129     BaseExpr = RHSExp;
3130     IndexExpr = LHSExp;
3131     ResultType = PTy->getPointeeType();
3132   } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
3133     BaseExpr = LHSExp;    // vectors: V[123]
3134     IndexExpr = RHSExp;
3135     VK = LHSExp->getValueKind();
3136     if (VK != VK_RValue)
3137       OK = OK_VectorComponent;
3138
3139     // FIXME: need to deal with const...
3140     ResultType = VTy->getElementType();
3141   } else if (LHSTy->isArrayType()) {
3142     // If we see an array that wasn't promoted by
3143     // DefaultFunctionArrayLvalueConversion, it must be an array that
3144     // wasn't promoted because of the C90 rule that doesn't
3145     // allow promoting non-lvalue arrays.  Warn, then
3146     // force the promotion here.
3147     Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3148         LHSExp->getSourceRange();
3149     LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3150                                CK_ArrayToPointerDecay).take();
3151     LHSTy = LHSExp->getType();
3152
3153     BaseExpr = LHSExp;
3154     IndexExpr = RHSExp;
3155     ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
3156   } else if (RHSTy->isArrayType()) {
3157     // Same as previous, except for 123[f().a] case
3158     Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3159         RHSExp->getSourceRange();
3160     RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3161                                CK_ArrayToPointerDecay).take();
3162     RHSTy = RHSExp->getType();
3163
3164     BaseExpr = RHSExp;
3165     IndexExpr = LHSExp;
3166     ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
3167   } else {
3168     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3169        << LHSExp->getSourceRange() << RHSExp->getSourceRange());
3170   }
3171   // C99 6.5.2.1p1
3172   if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
3173     return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3174                      << IndexExpr->getSourceRange());
3175
3176   if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
3177        IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3178          && !IndexExpr->isTypeDependent())
3179     Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3180
3181   // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
3182   // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3183   // type. Note that Functions are not objects, and that (in C99 parlance)
3184   // incomplete types are not object types.
3185   if (ResultType->isFunctionType()) {
3186     Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3187       << ResultType << BaseExpr->getSourceRange();
3188     return ExprError();
3189   }
3190
3191   if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3192     // GNU extension: subscripting on pointer to void
3193     Diag(LLoc, diag::ext_gnu_subscript_void_type)
3194       << BaseExpr->getSourceRange();
3195
3196     // C forbids expressions of unqualified void type from being l-values.
3197     // See IsCForbiddenLValueType.
3198     if (!ResultType.hasQualifiers()) VK = VK_RValue;
3199   } else if (!ResultType->isDependentType() &&
3200       RequireCompleteType(LLoc, ResultType,
3201                           PDiag(diag::err_subscript_incomplete_type)
3202                             << BaseExpr->getSourceRange()))
3203     return ExprError();
3204
3205   // Diagnose bad cases where we step over interface counts.
3206   if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
3207     Diag(LLoc, diag::err_subscript_nonfragile_interface)
3208       << ResultType << BaseExpr->getSourceRange();
3209     return ExprError();
3210   }
3211
3212   assert(VK == VK_RValue || LangOpts.CPlusPlus ||
3213          !ResultType.isCForbiddenLValueType());
3214
3215   return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
3216                                                 ResultType, VK, OK, RLoc));
3217 }
3218
3219 ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3220                                         FunctionDecl *FD,
3221                                         ParmVarDecl *Param) {
3222   if (Param->hasUnparsedDefaultArg()) {
3223     Diag(CallLoc,
3224          diag::err_use_of_default_argument_to_function_declared_later) <<
3225       FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3226     Diag(UnparsedDefaultArgLocs[Param],
3227          diag::note_default_argument_declared_here);
3228     return ExprError();
3229   }
3230   
3231   if (Param->hasUninstantiatedDefaultArg()) {
3232     Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3233
3234     // Instantiate the expression.
3235     MultiLevelTemplateArgumentList ArgList
3236       = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3237
3238     std::pair<const TemplateArgument *, unsigned> Innermost
3239       = ArgList.getInnermost();
3240     InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3241                                Innermost.second);
3242
3243     ExprResult Result;
3244     {
3245       // C++ [dcl.fct.default]p5:
3246       //   The names in the [default argument] expression are bound, and
3247       //   the semantic constraints are checked, at the point where the
3248       //   default argument expression appears.
3249       ContextRAII SavedContext(*this, FD);
3250       Result = SubstExpr(UninstExpr, ArgList);
3251     }
3252     if (Result.isInvalid())
3253       return ExprError();
3254
3255     // Check the expression as an initializer for the parameter.
3256     InitializedEntity Entity
3257       = InitializedEntity::InitializeParameter(Context, Param);
3258     InitializationKind Kind
3259       = InitializationKind::CreateCopy(Param->getLocation(),
3260              /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3261     Expr *ResultE = Result.takeAs<Expr>();
3262
3263     InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3264     Result = InitSeq.Perform(*this, Entity, Kind,
3265                              MultiExprArg(*this, &ResultE, 1));
3266     if (Result.isInvalid())
3267       return ExprError();
3268
3269     // Build the default argument expression.
3270     return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3271                                            Result.takeAs<Expr>()));
3272   }
3273
3274   // If the default expression creates temporaries, we need to
3275   // push them to the current stack of expression temporaries so they'll
3276   // be properly destroyed.
3277   // FIXME: We should really be rebuilding the default argument with new
3278   // bound temporaries; see the comment in PR5810.
3279   for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i) {
3280     CXXTemporary *Temporary = Param->getDefaultArgTemporary(i);
3281     MarkDeclarationReferenced(Param->getDefaultArg()->getLocStart(), 
3282                     const_cast<CXXDestructorDecl*>(Temporary->getDestructor()));
3283     ExprTemporaries.push_back(Temporary);
3284     ExprNeedsCleanups = true;
3285   }
3286
3287   // We already type-checked the argument, so we know it works. 
3288   // Just mark all of the declarations in this potentially-evaluated expression
3289   // as being "referenced".
3290   MarkDeclarationsReferencedInExpr(Param->getDefaultArg());
3291   return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3292 }
3293
3294 /// ConvertArgumentsForCall - Converts the arguments specified in
3295 /// Args/NumArgs to the parameter types of the function FDecl with
3296 /// function prototype Proto. Call is the call expression itself, and
3297 /// Fn is the function expression. For a C++ member function, this
3298 /// routine does not attempt to convert the object argument. Returns
3299 /// true if the call is ill-formed.
3300 bool
3301 Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3302                               FunctionDecl *FDecl,
3303                               const FunctionProtoType *Proto,
3304                               Expr **Args, unsigned NumArgs,
3305                               SourceLocation RParenLoc,
3306                               bool IsExecConfig) {
3307   // Bail out early if calling a builtin with custom typechecking.
3308   // We don't need to do this in the 
3309   if (FDecl)
3310     if (unsigned ID = FDecl->getBuiltinID())
3311       if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3312         return false;
3313
3314   // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3315   // assignment, to the types of the corresponding parameter, ...
3316   unsigned NumArgsInProto = Proto->getNumArgs();
3317   bool Invalid = false;
3318   unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
3319   unsigned FnKind = Fn->getType()->isBlockPointerType()
3320                        ? 1 /* block */
3321                        : (IsExecConfig ? 3 /* kernel function (exec config) */
3322                                        : 0 /* function */);
3323
3324   // If too few arguments are available (and we don't have default
3325   // arguments for the remaining parameters), don't make the call.
3326   if (NumArgs < NumArgsInProto) {
3327     if (NumArgs < MinArgs) {
3328       Diag(RParenLoc, MinArgs == NumArgsInProto
3329                         ? diag::err_typecheck_call_too_few_args
3330                         : diag::err_typecheck_call_too_few_args_at_least)
3331         << FnKind
3332         << MinArgs << NumArgs << Fn->getSourceRange();
3333
3334       // Emit the location of the prototype.
3335       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3336         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3337           << FDecl;
3338
3339       return true;
3340     }
3341     Call->setNumArgs(Context, NumArgsInProto);
3342   }
3343
3344   // If too many are passed and not variadic, error on the extras and drop
3345   // them.
3346   if (NumArgs > NumArgsInProto) {
3347     if (!Proto->isVariadic()) {
3348       Diag(Args[NumArgsInProto]->getLocStart(),
3349            MinArgs == NumArgsInProto
3350              ? diag::err_typecheck_call_too_many_args
3351              : diag::err_typecheck_call_too_many_args_at_most)
3352         << FnKind
3353         << NumArgsInProto << NumArgs << Fn->getSourceRange()
3354         << SourceRange(Args[NumArgsInProto]->getLocStart(),
3355                        Args[NumArgs-1]->getLocEnd());
3356
3357       // Emit the location of the prototype.
3358       if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
3359         Diag(FDecl->getLocStart(), diag::note_callee_decl)
3360           << FDecl;
3361       
3362       // This deletes the extra arguments.
3363       Call->setNumArgs(Context, NumArgsInProto);
3364       return true;
3365     }
3366   }
3367   SmallVector<Expr *, 8> AllArgs;
3368   VariadicCallType CallType =
3369     Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3370   if (Fn->getType()->isBlockPointerType())
3371     CallType = VariadicBlock; // Block
3372   else if (isa<MemberExpr>(Fn))
3373     CallType = VariadicMethod;
3374   Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
3375                                    Proto, 0, Args, NumArgs, AllArgs, CallType);
3376   if (Invalid)
3377     return true;
3378   unsigned TotalNumArgs = AllArgs.size();
3379   for (unsigned i = 0; i < TotalNumArgs; ++i)
3380     Call->setArg(i, AllArgs[i]);
3381
3382   return false;
3383 }
3384
3385 bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3386                                   FunctionDecl *FDecl,
3387                                   const FunctionProtoType *Proto,
3388                                   unsigned FirstProtoArg,
3389                                   Expr **Args, unsigned NumArgs,
3390                                   SmallVector<Expr *, 8> &AllArgs,
3391                                   VariadicCallType CallType) {
3392   unsigned NumArgsInProto = Proto->getNumArgs();
3393   unsigned NumArgsToCheck = NumArgs;
3394   bool Invalid = false;
3395   if (NumArgs != NumArgsInProto)
3396     // Use default arguments for missing arguments
3397     NumArgsToCheck = NumArgsInProto;
3398   unsigned ArgIx = 0;
3399   // Continue to check argument types (even if we have too few/many args).
3400   for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3401     QualType ProtoArgType = Proto->getArgType(i);
3402
3403     Expr *Arg;
3404     if (ArgIx < NumArgs) {
3405       Arg = Args[ArgIx++];
3406
3407       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3408                               ProtoArgType,
3409                               PDiag(diag::err_call_incomplete_argument)
3410                               << Arg->getSourceRange()))
3411         return true;
3412
3413       // Pass the argument
3414       ParmVarDecl *Param = 0;
3415       if (FDecl && i < FDecl->getNumParams())
3416         Param = FDecl->getParamDecl(i);
3417
3418       InitializedEntity Entity =
3419         Param? InitializedEntity::InitializeParameter(Context, Param)
3420              : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3421                                                       Proto->isArgConsumed(i));
3422       ExprResult ArgE = PerformCopyInitialization(Entity,
3423                                                   SourceLocation(),
3424                                                   Owned(Arg));
3425       if (ArgE.isInvalid())
3426         return true;
3427
3428       Arg = ArgE.takeAs<Expr>();
3429     } else {
3430       ParmVarDecl *Param = FDecl->getParamDecl(i);
3431
3432       ExprResult ArgExpr =
3433         BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3434       if (ArgExpr.isInvalid())
3435         return true;
3436
3437       Arg = ArgExpr.takeAs<Expr>();
3438     }
3439
3440     // Check for array bounds violations for each argument to the call. This
3441     // check only triggers warnings when the argument isn't a more complex Expr
3442     // with its own checking, such as a BinaryOperator.
3443     CheckArrayAccess(Arg);
3444
3445     AllArgs.push_back(Arg);
3446   }
3447
3448   // If this is a variadic call, handle args passed through "...".
3449   if (CallType != VariadicDoesNotApply) {
3450
3451     // Assume that extern "C" functions with variadic arguments that
3452     // return __unknown_anytype aren't *really* variadic.
3453     if (Proto->getResultType() == Context.UnknownAnyTy &&
3454         FDecl && FDecl->isExternC()) {
3455       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3456         ExprResult arg;
3457         if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3458           arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3459         else
3460           arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3461         Invalid |= arg.isInvalid();
3462         AllArgs.push_back(arg.take());
3463       }
3464
3465     // Otherwise do argument promotion, (C99 6.5.2.2p7).
3466     } else {
3467       for (unsigned i = ArgIx; i != NumArgs; ++i) {
3468         ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3469                                                           FDecl);
3470         Invalid |= Arg.isInvalid();
3471         AllArgs.push_back(Arg.take());
3472       }
3473     }
3474
3475     // Check for array bounds violations.
3476     for (unsigned i = ArgIx; i != NumArgs; ++i)
3477       CheckArrayAccess(Args[i]);
3478   }
3479   return Invalid;
3480 }
3481
3482 /// Given a function expression of unknown-any type, try to rebuild it
3483 /// to have a function type.
3484 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3485
3486 /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3487 /// This provides the location of the left/right parens and a list of comma
3488 /// locations.
3489 ExprResult
3490 Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
3491                     MultiExprArg ArgExprs, SourceLocation RParenLoc,
3492                     Expr *ExecConfig, bool IsExecConfig) {
3493   unsigned NumArgs = ArgExprs.size();
3494
3495   // Since this might be a postfix expression, get rid of ParenListExprs.
3496   ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
3497   if (Result.isInvalid()) return ExprError();
3498   Fn = Result.take();
3499
3500   Expr **Args = ArgExprs.release();
3501
3502   if (getLangOptions().CPlusPlus) {
3503     // If this is a pseudo-destructor expression, build the call immediately.
3504     if (isa<CXXPseudoDestructorExpr>(Fn)) {
3505       if (NumArgs > 0) {
3506         // Pseudo-destructor calls should not have any arguments.
3507         Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3508           << FixItHint::CreateRemoval(
3509                                     SourceRange(Args[0]->getLocStart(),
3510                                                 Args[NumArgs-1]->getLocEnd()));
3511
3512         NumArgs = 0;
3513       }
3514
3515       return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3516                                           VK_RValue, RParenLoc));
3517     }
3518
3519     // Determine whether this is a dependent call inside a C++ template,
3520     // in which case we won't do any semantic analysis now.
3521     // FIXME: Will need to cache the results of name lookup (including ADL) in
3522     // Fn.
3523     bool Dependent = false;
3524     if (Fn->isTypeDependent())
3525       Dependent = true;
3526     else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3527       Dependent = true;
3528
3529     if (Dependent) {
3530       if (ExecConfig) {
3531         return Owned(new (Context) CUDAKernelCallExpr(
3532             Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3533             Context.DependentTy, VK_RValue, RParenLoc));
3534       } else {
3535         return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3536                                             Context.DependentTy, VK_RValue,
3537                                             RParenLoc));
3538       }
3539     }
3540
3541     // Determine whether this is a call to an object (C++ [over.call.object]).
3542     if (Fn->getType()->isRecordType())
3543       return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3544                                                 RParenLoc));
3545
3546     if (Fn->getType() == Context.UnknownAnyTy) {
3547       ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3548       if (result.isInvalid()) return ExprError();
3549       Fn = result.take();
3550     }
3551
3552     if (Fn->getType() == Context.BoundMemberTy) {
3553       return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3554                                        RParenLoc);
3555     }
3556   }
3557
3558   // Check for overloaded calls.  This can happen even in C due to extensions.
3559   if (Fn->getType() == Context.OverloadTy) {
3560     OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3561
3562     // We aren't supposed to apply this logic for if there's an '&' involved.
3563     if (!find.HasFormOfMemberPointer) {
3564       OverloadExpr *ovl = find.Expression;
3565       if (isa<UnresolvedLookupExpr>(ovl)) {
3566         UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3567         return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3568                                        RParenLoc, ExecConfig);
3569       } else {
3570         return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3571                                          RParenLoc);
3572       }
3573     }
3574   }
3575
3576   // If we're directly calling a function, get the appropriate declaration.
3577
3578   Expr *NakedFn = Fn->IgnoreParens();
3579
3580   NamedDecl *NDecl = 0;
3581   if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3582     if (UnOp->getOpcode() == UO_AddrOf)
3583       NakedFn = UnOp->getSubExpr()->IgnoreParens();
3584   
3585   if (isa<DeclRefExpr>(NakedFn))
3586     NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3587   else if (isa<MemberExpr>(NakedFn))
3588     NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
3589
3590   return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
3591                                ExecConfig, IsExecConfig);
3592 }
3593
3594 ExprResult
3595 Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
3596                               MultiExprArg ExecConfig, SourceLocation GGGLoc) {
3597   FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3598   if (!ConfigDecl)
3599     return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3600                           << "cudaConfigureCall");
3601   QualType ConfigQTy = ConfigDecl->getType();
3602
3603   DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3604       ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
3605
3606   return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3607                        /*IsExecConfig=*/true);
3608 }
3609
3610 /// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3611 ///
3612 /// __builtin_astype( value, dst type )
3613 ///
3614 ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
3615                                  SourceLocation BuiltinLoc,
3616                                  SourceLocation RParenLoc) {
3617   ExprValueKind VK = VK_RValue;
3618   ExprObjectKind OK = OK_Ordinary;
3619   QualType DstTy = GetTypeFromParser(ParsedDestTy);
3620   QualType SrcTy = E->getType();
3621   if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3622     return ExprError(Diag(BuiltinLoc,
3623                           diag::err_invalid_astype_of_different_size)
3624                      << DstTy
3625                      << SrcTy
3626                      << E->getSourceRange());
3627   return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
3628                RParenLoc));
3629 }
3630
3631 /// BuildResolvedCallExpr - Build a call to a resolved expression,
3632 /// i.e. an expression not of \p OverloadTy.  The expression should
3633 /// unary-convert to an expression of function-pointer or
3634 /// block-pointer type.
3635 ///
3636 /// \param NDecl the declaration being called, if available
3637 ExprResult
3638 Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3639                             SourceLocation LParenLoc,
3640                             Expr **Args, unsigned NumArgs,
3641                             SourceLocation RParenLoc,
3642                             Expr *Config, bool IsExecConfig) {
3643   FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3644
3645   // Promote the function operand.
3646   ExprResult Result = UsualUnaryConversions(Fn);
3647   if (Result.isInvalid())
3648     return ExprError();
3649   Fn = Result.take();
3650
3651   // Make the call expr early, before semantic checks.  This guarantees cleanup
3652   // of arguments and function on error.
3653   CallExpr *TheCall;
3654   if (Config) {
3655     TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3656                                                cast<CallExpr>(Config),
3657                                                Args, NumArgs,
3658                                                Context.BoolTy,
3659                                                VK_RValue,
3660                                                RParenLoc);
3661   } else {
3662     TheCall = new (Context) CallExpr(Context, Fn,
3663                                      Args, NumArgs,
3664                                      Context.BoolTy,
3665                                      VK_RValue,
3666                                      RParenLoc);
3667   }
3668
3669   unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3670
3671   // Bail out early if calling a builtin with custom typechecking.
3672   if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3673     return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3674
3675  retry:
3676   const FunctionType *FuncT;
3677   if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
3678     // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3679     // have type pointer to function".
3680     FuncT = PT->getPointeeType()->getAs<FunctionType>();
3681     if (FuncT == 0)
3682       return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3683                          << Fn->getType() << Fn->getSourceRange());
3684   } else if (const BlockPointerType *BPT =
3685                Fn->getType()->getAs<BlockPointerType>()) {
3686     FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3687   } else {
3688     // Handle calls to expressions of unknown-any type.
3689     if (Fn->getType() == Context.UnknownAnyTy) {
3690       ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
3691       if (rewrite.isInvalid()) return ExprError();
3692       Fn = rewrite.take();
3693       TheCall->setCallee(Fn);
3694       goto retry;
3695     }
3696
3697     return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3698       << Fn->getType() << Fn->getSourceRange());
3699   }
3700
3701   if (getLangOptions().CUDA) {
3702     if (Config) {
3703       // CUDA: Kernel calls must be to global functions
3704       if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3705         return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3706             << FDecl->getName() << Fn->getSourceRange());
3707
3708       // CUDA: Kernel function must have 'void' return type
3709       if (!FuncT->getResultType()->isVoidType())
3710         return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3711             << Fn->getType() << Fn->getSourceRange());
3712     } else {
3713       // CUDA: Calls to global functions must be configured
3714       if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3715         return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3716             << FDecl->getName() << Fn->getSourceRange());
3717     }
3718   }
3719
3720   // Check for a valid return type
3721   if (CheckCallReturnType(FuncT->getResultType(),
3722                           Fn->getSourceRange().getBegin(), TheCall,
3723                           FDecl))
3724     return ExprError();
3725
3726   // We know the result type of the call, set it.
3727   TheCall->setType(FuncT->getCallResultType(Context));
3728   TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
3729
3730   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
3731     if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
3732                                 RParenLoc, IsExecConfig))
3733       return ExprError();
3734   } else {
3735     assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3736
3737     if (FDecl) {
3738       // Check if we have too few/too many template arguments, based
3739       // on our knowledge of the function definition.
3740       const FunctionDecl *Def = 0;
3741       if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
3742         const FunctionProtoType *Proto 
3743           = Def->getType()->getAs<FunctionProtoType>();
3744         if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
3745           Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3746             << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3747       }
3748       
3749       // If the function we're calling isn't a function prototype, but we have
3750       // a function prototype from a prior declaratiom, use that prototype.
3751       if (!FDecl->hasPrototype())
3752         Proto = FDecl->getType()->getAs<FunctionProtoType>();
3753     }
3754
3755     // Promote the arguments (C99 6.5.2.2p6).
3756     for (unsigned i = 0; i != NumArgs; i++) {
3757       Expr *Arg = Args[i];
3758
3759       if (Proto && i < Proto->getNumArgs()) {
3760         InitializedEntity Entity
3761           = InitializedEntity::InitializeParameter(Context, 
3762                                                    Proto->getArgType(i),
3763                                                    Proto->isArgConsumed(i));
3764         ExprResult ArgE = PerformCopyInitialization(Entity,
3765                                                     SourceLocation(),
3766                                                     Owned(Arg));
3767         if (ArgE.isInvalid())
3768           return true;
3769         
3770         Arg = ArgE.takeAs<Expr>();
3771
3772       } else {
3773         ExprResult ArgE = DefaultArgumentPromotion(Arg);
3774
3775         if (ArgE.isInvalid())
3776           return true;
3777
3778         Arg = ArgE.takeAs<Expr>();
3779       }
3780       
3781       if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3782                               Arg->getType(),
3783                               PDiag(diag::err_call_incomplete_argument)
3784                                 << Arg->getSourceRange()))
3785         return ExprError();
3786
3787       TheCall->setArg(i, Arg);
3788     }
3789   }
3790
3791   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3792     if (!Method->isStatic())
3793       return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3794         << Fn->getSourceRange());
3795
3796   // Check for sentinels
3797   if (NDecl)
3798     DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3799
3800   // Do special checking on direct calls to functions.
3801   if (FDecl) {
3802     if (CheckFunctionCall(FDecl, TheCall))
3803       return ExprError();
3804
3805     if (BuiltinID)
3806       return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3807   } else if (NDecl) {
3808     if (CheckBlockCall(NDecl, TheCall))
3809       return ExprError();
3810   }
3811
3812   return MaybeBindToTemporary(TheCall);
3813 }
3814
3815 ExprResult
3816 Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
3817                            SourceLocation RParenLoc, Expr *InitExpr) {
3818   assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3819   // FIXME: put back this assert when initializers are worked out.
3820   //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3821
3822   TypeSourceInfo *TInfo;
3823   QualType literalType = GetTypeFromParser(Ty, &TInfo);
3824   if (!TInfo)
3825     TInfo = Context.getTrivialTypeSourceInfo(literalType);
3826
3827   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
3828 }
3829
3830 ExprResult
3831 Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3832                                SourceLocation RParenLoc, Expr *LiteralExpr) {
3833   QualType literalType = TInfo->getType();
3834
3835   if (literalType->isArrayType()) {
3836     if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3837              PDiag(diag::err_illegal_decl_array_incomplete_type)
3838                << SourceRange(LParenLoc,
3839                               LiteralExpr->getSourceRange().getEnd())))
3840       return ExprError();
3841     if (literalType->isVariableArrayType())
3842       return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3843         << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
3844   } else if (!literalType->isDependentType() &&
3845              RequireCompleteType(LParenLoc, literalType,
3846                       PDiag(diag::err_typecheck_decl_incomplete_type)
3847                         << SourceRange(LParenLoc,
3848                                        LiteralExpr->getSourceRange().getEnd())))
3849     return ExprError();
3850
3851   InitializedEntity Entity
3852     = InitializedEntity::InitializeTemporary(literalType);
3853   InitializationKind Kind
3854     = InitializationKind::CreateCStyleCast(LParenLoc, 
3855                                            SourceRange(LParenLoc, RParenLoc));
3856   InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
3857   ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3858                                        MultiExprArg(*this, &LiteralExpr, 1),
3859                                             &literalType);
3860   if (Result.isInvalid())
3861     return ExprError();
3862   LiteralExpr = Result.get();
3863
3864   bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3865   if (isFileScope) { // 6.5.2.5p3
3866     if (CheckForConstantInitializer(LiteralExpr, literalType))
3867       return ExprError();
3868   }
3869
3870   // In C, compound literals are l-values for some reason.
3871   ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3872
3873   return MaybeBindToTemporary(
3874            new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3875                                              VK, LiteralExpr, isFileScope));
3876 }
3877
3878 ExprResult
3879 Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
3880                     SourceLocation RBraceLoc) {
3881   unsigned NumInit = InitArgList.size();
3882   Expr **InitList = InitArgList.release();
3883
3884   // Semantic analysis for initializers is done by ActOnDeclarator() and
3885   // CheckInitializer() - it requires knowledge of the object being intialized.
3886
3887   InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3888                                                NumInit, RBraceLoc);
3889   E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3890   return Owned(E);
3891 }
3892
3893 /// Do an explicit extend of the given block pointer if we're in ARC.
3894 static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3895   assert(E.get()->getType()->isBlockPointerType());
3896   assert(E.get()->isRValue());
3897
3898   // Only do this in an r-value context.
3899   if (!S.getLangOptions().ObjCAutoRefCount) return;
3900
3901   E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
3902                                CK_ARCExtendBlockObject, E.get(),
3903                                /*base path*/ 0, VK_RValue);
3904   S.ExprNeedsCleanups = true;
3905 }
3906
3907 /// Prepare a conversion of the given expression to an ObjC object
3908 /// pointer type.
3909 CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3910   QualType type = E.get()->getType();
3911   if (type->isObjCObjectPointerType()) {
3912     return CK_BitCast;
3913   } else if (type->isBlockPointerType()) {
3914     maybeExtendBlockObject(*this, E);
3915     return CK_BlockPointerToObjCPointerCast;
3916   } else {
3917     assert(type->isPointerType());
3918     return CK_CPointerToObjCPointerCast;
3919   }
3920 }
3921
3922 /// Prepares for a scalar cast, performing all the necessary stages
3923 /// except the final cast and returning the kind required.
3924 CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
3925   // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3926   // Also, callers should have filtered out the invalid cases with
3927   // pointers.  Everything else should be possible.
3928
3929   QualType SrcTy = Src.get()->getType();
3930   if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
3931     return CK_NoOp;
3932
3933   switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
3934   case Type::STK_MemberPointer:
3935     llvm_unreachable("member pointer type in C");
3936
3937   case Type::STK_CPointer:
3938   case Type::STK_BlockPointer:
3939   case Type::STK_ObjCObjectPointer:
3940     switch (DestTy->getScalarTypeKind()) {
3941     case Type::STK_CPointer:
3942       return CK_BitCast;
3943     case Type::STK_BlockPointer:
3944       return (SrcKind == Type::STK_BlockPointer
3945                 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3946     case Type::STK_ObjCObjectPointer:
3947       if (SrcKind == Type::STK_ObjCObjectPointer)
3948         return CK_BitCast;
3949       else if (SrcKind == Type::STK_CPointer)
3950         return CK_CPointerToObjCPointerCast;
3951       else {
3952         maybeExtendBlockObject(*this, Src);
3953         return CK_BlockPointerToObjCPointerCast;
3954       }
3955     case Type::STK_Bool:
3956       return CK_PointerToBoolean;
3957     case Type::STK_Integral:
3958       return CK_PointerToIntegral;
3959     case Type::STK_Floating:
3960     case Type::STK_FloatingComplex:
3961     case Type::STK_IntegralComplex:
3962     case Type::STK_MemberPointer:
3963       llvm_unreachable("illegal cast from pointer");
3964     }
3965     break;
3966
3967   case Type::STK_Bool: // casting from bool is like casting from an integer
3968   case Type::STK_Integral:
3969     switch (DestTy->getScalarTypeKind()) {
3970     case Type::STK_CPointer:
3971     case Type::STK_ObjCObjectPointer:
3972     case Type::STK_BlockPointer:
3973       if (Src.get()->isNullPointerConstant(Context,
3974                                            Expr::NPC_ValueDependentIsNull))
3975         return CK_NullToPointer;
3976       return CK_IntegralToPointer;
3977     case Type::STK_Bool:
3978       return CK_IntegralToBoolean;
3979     case Type::STK_Integral:
3980       return CK_IntegralCast;
3981     case Type::STK_Floating:
3982       return CK_IntegralToFloating;
3983     case Type::STK_IntegralComplex:
3984       Src = ImpCastExprToType(Src.take(),
3985                               DestTy->castAs<ComplexType>()->getElementType(),
3986                               CK_IntegralCast);
3987       return CK_IntegralRealToComplex;
3988     case Type::STK_FloatingComplex:
3989       Src = ImpCastExprToType(Src.take(),
3990                               DestTy->castAs<ComplexType>()->getElementType(),
3991                               CK_IntegralToFloating);
3992       return CK_FloatingRealToComplex;
3993     case Type::STK_MemberPointer:
3994       llvm_unreachable("member pointer type in C");
3995     }
3996     break;
3997
3998   case Type::STK_Floating:
3999     switch (DestTy->getScalarTypeKind()) {
4000     case Type::STK_Floating:
4001       return CK_FloatingCast;
4002     case Type::STK_Bool:
4003       return CK_FloatingToBoolean;
4004     case Type::STK_Integral:
4005       return CK_FloatingToIntegral;
4006     case Type::STK_FloatingComplex:
4007       Src = ImpCastExprToType(Src.take(),
4008                               DestTy->castAs<ComplexType>()->getElementType(),
4009                               CK_FloatingCast);
4010       return CK_FloatingRealToComplex;
4011     case Type::STK_IntegralComplex:
4012       Src = ImpCastExprToType(Src.take(),
4013                               DestTy->castAs<ComplexType>()->getElementType(),
4014                               CK_FloatingToIntegral);
4015       return CK_IntegralRealToComplex;
4016     case Type::STK_CPointer:
4017     case Type::STK_ObjCObjectPointer:
4018     case Type::STK_BlockPointer:
4019       llvm_unreachable("valid float->pointer cast?");
4020     case Type::STK_MemberPointer:
4021       llvm_unreachable("member pointer type in C");
4022     }
4023     break;
4024
4025   case Type::STK_FloatingComplex:
4026     switch (DestTy->getScalarTypeKind()) {
4027     case Type::STK_FloatingComplex:
4028       return CK_FloatingComplexCast;
4029     case Type::STK_IntegralComplex:
4030       return CK_FloatingComplexToIntegralComplex;
4031     case Type::STK_Floating: {
4032       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4033       if (Context.hasSameType(ET, DestTy))
4034         return CK_FloatingComplexToReal;
4035       Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
4036       return CK_FloatingCast;
4037     }
4038     case Type::STK_Bool:
4039       return CK_FloatingComplexToBoolean;
4040     case Type::STK_Integral:
4041       Src = ImpCastExprToType(Src.take(),
4042                               SrcTy->castAs<ComplexType>()->getElementType(),
4043                               CK_FloatingComplexToReal);
4044       return CK_FloatingToIntegral;
4045     case Type::STK_CPointer:
4046     case Type::STK_ObjCObjectPointer:
4047     case Type::STK_BlockPointer:
4048       llvm_unreachable("valid complex float->pointer cast?");
4049     case Type::STK_MemberPointer:
4050       llvm_unreachable("member pointer type in C");
4051     }
4052     break;
4053
4054   case Type::STK_IntegralComplex:
4055     switch (DestTy->getScalarTypeKind()) {
4056     case Type::STK_FloatingComplex:
4057       return CK_IntegralComplexToFloatingComplex;
4058     case Type::STK_IntegralComplex:
4059       return CK_IntegralComplexCast;
4060     case Type::STK_Integral: {
4061       QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4062       if (Context.hasSameType(ET, DestTy))
4063         return CK_IntegralComplexToReal;
4064       Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
4065       return CK_IntegralCast;
4066     }
4067     case Type::STK_Bool:
4068       return CK_IntegralComplexToBoolean;
4069     case Type::STK_Floating:
4070       Src = ImpCastExprToType(Src.take(),
4071                               SrcTy->castAs<ComplexType>()->getElementType(),
4072                               CK_IntegralComplexToReal);
4073       return CK_IntegralToFloating;
4074     case Type::STK_CPointer:
4075     case Type::STK_ObjCObjectPointer:
4076     case Type::STK_BlockPointer:
4077       llvm_unreachable("valid complex int->pointer cast?");
4078     case Type::STK_MemberPointer:
4079       llvm_unreachable("member pointer type in C");
4080     }
4081     break;
4082   }
4083
4084   llvm_unreachable("Unhandled scalar cast");
4085 }
4086
4087 bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
4088                            CastKind &Kind) {
4089   assert(VectorTy->isVectorType() && "Not a vector type!");
4090
4091   if (Ty->isVectorType() || Ty->isIntegerType()) {
4092     if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
4093       return Diag(R.getBegin(),
4094                   Ty->isVectorType() ?
4095                   diag::err_invalid_conversion_between_vectors :
4096                   diag::err_invalid_conversion_between_vector_and_integer)
4097         << VectorTy << Ty << R;
4098   } else
4099     return Diag(R.getBegin(),
4100                 diag::err_invalid_conversion_between_vector_and_scalar)
4101       << VectorTy << Ty << R;
4102
4103   Kind = CK_BitCast;
4104   return false;
4105 }
4106
4107 ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4108                                     Expr *CastExpr, CastKind &Kind) {
4109   assert(DestTy->isExtVectorType() && "Not an extended vector type!");
4110
4111   QualType SrcTy = CastExpr->getType();
4112
4113   // If SrcTy is a VectorType, the total size must match to explicitly cast to
4114   // an ExtVectorType.
4115   // In OpenCL, casts between vectors of different types are not allowed.
4116   // (See OpenCL 6.2).
4117   if (SrcTy->isVectorType()) {
4118     if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4119         || (getLangOptions().OpenCL &&
4120             (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
4121       Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
4122         << DestTy << SrcTy << R;
4123       return ExprError();
4124     }
4125     Kind = CK_BitCast;
4126     return Owned(CastExpr);
4127   }
4128
4129   // All non-pointer scalars can be cast to ExtVector type.  The appropriate
4130   // conversion will take place first from scalar to elt type, and then
4131   // splat from elt type to vector.
4132   if (SrcTy->isPointerType())
4133     return Diag(R.getBegin(),
4134                 diag::err_invalid_conversion_between_vector_and_scalar)
4135       << DestTy << SrcTy << R;
4136
4137   QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
4138   ExprResult CastExprRes = Owned(CastExpr);
4139   CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
4140   if (CastExprRes.isInvalid())
4141     return ExprError();
4142   CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
4143
4144   Kind = CK_VectorSplat;
4145   return Owned(CastExpr);
4146 }
4147
4148 ExprResult
4149 Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4150                     Declarator &D, ParsedType &Ty,
4151                     SourceLocation RParenLoc, Expr *CastExpr) {
4152   assert(!D.isInvalidType() && (CastExpr != 0) &&
4153          "ActOnCastExpr(): missing type or expr");
4154
4155   TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
4156   if (D.isInvalidType())
4157     return ExprError();
4158
4159   if (getLangOptions().CPlusPlus) {
4160     // Check that there are no default arguments (C++ only).
4161     CheckExtraCXXDefaultArguments(D);
4162   }
4163
4164   checkUnusedDeclAttributes(D);
4165
4166   QualType castType = castTInfo->getType();
4167   Ty = CreateParsedType(castType, castTInfo);
4168
4169   bool isVectorLiteral = false;
4170
4171   // Check for an altivec or OpenCL literal,
4172   // i.e. all the elements are integer constants.
4173   ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4174   ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
4175   if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4176        && castType->isVectorType() && (PE || PLE)) {
4177     if (PLE && PLE->getNumExprs() == 0) {
4178       Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4179       return ExprError();
4180     }
4181     if (PE || PLE->getNumExprs() == 1) {
4182       Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4183       if (!E->getType()->isVectorType())
4184         isVectorLiteral = true;
4185     }
4186     else
4187       isVectorLiteral = true;
4188   }
4189
4190   // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4191   // then handle it as such.
4192   if (isVectorLiteral)
4193     return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
4194
4195   // If the Expr being casted is a ParenListExpr, handle it specially.
4196   // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4197   // sequence of BinOp comma operators.
4198   if (isa<ParenListExpr>(CastExpr)) {
4199     ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
4200     if (Result.isInvalid()) return ExprError();
4201     CastExpr = Result.take();
4202   }
4203
4204   return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
4205 }
4206
4207 ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4208                                     SourceLocation RParenLoc, Expr *E,
4209                                     TypeSourceInfo *TInfo) {
4210   assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4211          "Expected paren or paren list expression");
4212
4213   Expr **exprs;
4214   unsigned numExprs;
4215   Expr *subExpr;
4216   if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4217     exprs = PE->getExprs();
4218     numExprs = PE->getNumExprs();
4219   } else {
4220     subExpr = cast<ParenExpr>(E)->getSubExpr();
4221     exprs = &subExpr;
4222     numExprs = 1;
4223   }
4224
4225   QualType Ty = TInfo->getType();
4226   assert(Ty->isVectorType() && "Expected vector type");
4227
4228   SmallVector<Expr *, 8> initExprs;
4229   const VectorType *VTy = Ty->getAs<VectorType>();
4230   unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4231   
4232   // '(...)' form of vector initialization in AltiVec: the number of
4233   // initializers must be one or must match the size of the vector.
4234   // If a single value is specified in the initializer then it will be
4235   // replicated to all the components of the vector
4236   if (VTy->getVectorKind() == VectorType::AltiVecVector) {
4237     // The number of initializers must be one or must match the size of the
4238     // vector. If a single value is specified in the initializer then it will
4239     // be replicated to all the components of the vector
4240     if (numExprs == 1) {
4241       QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4242       ExprResult Literal = Owned(exprs[0]);
4243       Literal = ImpCastExprToType(Literal.take(), ElemTy,
4244                                   PrepareScalarCast(Literal, ElemTy));
4245       return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4246     }
4247     else if (numExprs < numElems) {
4248       Diag(E->getExprLoc(),
4249            diag::err_incorrect_number_of_vector_initializers);
4250       return ExprError();
4251     }
4252     else
4253       for (unsigned i = 0, e = numExprs; i != e; ++i)
4254         initExprs.push_back(exprs[i]);
4255   }
4256   else {
4257     // For OpenCL, when the number of initializers is a single value,
4258     // it will be replicated to all components of the vector.
4259     if (getLangOptions().OpenCL &&
4260         VTy->getVectorKind() == VectorType::GenericVector &&
4261         numExprs == 1) {
4262         QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
4263         ExprResult Literal = Owned(exprs[0]);
4264         Literal = ImpCastExprToType(Literal.take(), ElemTy,
4265                                     PrepareScalarCast(Literal, ElemTy));
4266         return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4267     }
4268     
4269     for (unsigned i = 0, e = numExprs; i != e; ++i)
4270       initExprs.push_back(exprs[i]);
4271   }
4272   // FIXME: This means that pretty-printing the final AST will produce curly
4273   // braces instead of the original commas.
4274   InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4275                                                    &initExprs[0],
4276                                                    initExprs.size(), RParenLoc);
4277   initE->setType(Ty);
4278   return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4279 }
4280
4281 /// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
4282 /// of comma binary operators.
4283 ExprResult
4284 Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4285   ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
4286   if (!E)
4287     return Owned(OrigExpr);
4288
4289   ExprResult Result(E->getExpr(0));
4290
4291   for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4292     Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4293                         E->getExpr(i));
4294
4295   if (Result.isInvalid()) return ExprError();
4296
4297   return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
4298 }
4299
4300 ExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
4301                                            SourceLocation R,
4302                                            MultiExprArg Val) {
4303   unsigned nexprs = Val.size();
4304   Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4305   assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4306   Expr *expr;
4307   if (nexprs == 1)
4308     expr = new (Context) ParenExpr(L, R, exprs[0]);
4309   else
4310     expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R,
4311                                        exprs[nexprs-1]->getType());
4312   return Owned(expr);
4313 }
4314
4315 /// \brief Emit a specialized diagnostic when one expression is a null pointer
4316 /// constant and the other is not a pointer.  Returns true if a diagnostic is
4317 /// emitted.
4318 bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
4319                                       SourceLocation QuestionLoc) {
4320   Expr *NullExpr = LHSExpr;
4321   Expr *NonPointerExpr = RHSExpr;
4322   Expr::NullPointerConstantKind NullKind =
4323       NullExpr->isNullPointerConstant(Context,
4324                                       Expr::NPC_ValueDependentIsNotNull);
4325
4326   if (NullKind == Expr::NPCK_NotNull) {
4327     NullExpr = RHSExpr;
4328     NonPointerExpr = LHSExpr;
4329     NullKind =
4330         NullExpr->isNullPointerConstant(Context,
4331                                         Expr::NPC_ValueDependentIsNotNull);
4332   }
4333
4334   if (NullKind == Expr::NPCK_NotNull)
4335     return false;
4336
4337   if (NullKind == Expr::NPCK_ZeroInteger) {
4338     // In this case, check to make sure that we got here from a "NULL"
4339     // string in the source code.
4340     NullExpr = NullExpr->IgnoreParenImpCasts();
4341     SourceLocation loc = NullExpr->getExprLoc();
4342     if (!findMacroSpelling(loc, "NULL"))
4343       return false;
4344   }
4345
4346   int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4347   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4348       << NonPointerExpr->getType() << DiagType
4349       << NonPointerExpr->getSourceRange();
4350   return true;
4351 }
4352
4353 /// \brief Return false if the condition expression is valid, true otherwise.
4354 static bool checkCondition(Sema &S, Expr *Cond) {
4355   QualType CondTy = Cond->getType();
4356
4357   // C99 6.5.15p2
4358   if (CondTy->isScalarType()) return false;
4359
4360   // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4361   if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4362     return false;
4363
4364   // Emit the proper error message.
4365   S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4366                               diag::err_typecheck_cond_expect_scalar :
4367                               diag::err_typecheck_cond_expect_scalar_or_vector)
4368     << CondTy;
4369   return true;
4370 }
4371
4372 /// \brief Return false if the two expressions can be converted to a vector,
4373 /// true otherwise
4374 static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4375                                                     ExprResult &RHS,
4376                                                     QualType CondTy) {
4377   // Both operands should be of scalar type.
4378   if (!LHS.get()->getType()->isScalarType()) {
4379     S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4380       << CondTy;
4381     return true;
4382   }
4383   if (!RHS.get()->getType()->isScalarType()) {
4384     S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4385       << CondTy;
4386     return true;
4387   }
4388
4389   // Implicity convert these scalars to the type of the condition.
4390   LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4391   RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4392   return false;
4393 }
4394
4395 /// \brief Handle when one or both operands are void type.
4396 static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4397                                          ExprResult &RHS) {
4398     Expr *LHSExpr = LHS.get();
4399     Expr *RHSExpr = RHS.get();
4400
4401     if (!LHSExpr->getType()->isVoidType())
4402       S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4403         << RHSExpr->getSourceRange();
4404     if (!RHSExpr->getType()->isVoidType())
4405       S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4406         << LHSExpr->getSourceRange();
4407     LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4408     RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4409     return S.Context.VoidTy;
4410 }
4411
4412 /// \brief Return false if the NullExpr can be promoted to PointerTy,
4413 /// true otherwise.
4414 static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4415                                         QualType PointerTy) {
4416   if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4417       !NullExpr.get()->isNullPointerConstant(S.Context,
4418                                             Expr::NPC_ValueDependentIsNull))
4419     return true;
4420
4421   NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4422   return false;
4423 }
4424
4425 /// \brief Checks compatibility between two pointers and return the resulting
4426 /// type.
4427 static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4428                                                      ExprResult &RHS,
4429                                                      SourceLocation Loc) {
4430   QualType LHSTy = LHS.get()->getType();
4431   QualType RHSTy = RHS.get()->getType();
4432
4433   if (S.Context.hasSameType(LHSTy, RHSTy)) {
4434     // Two identical pointers types are always compatible.
4435     return LHSTy;
4436   }
4437
4438   QualType lhptee, rhptee;
4439
4440   // Get the pointee types.
4441   if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4442     lhptee = LHSBTy->getPointeeType();
4443     rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
4444   } else {
4445     lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4446     rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
4447   }
4448
4449   if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4450                                     rhptee.getUnqualifiedType())) {
4451     S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4452       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4453       << RHS.get()->getSourceRange();
4454     // In this situation, we assume void* type. No especially good
4455     // reason, but this is what gcc does, and we do have to pick
4456     // to get a consistent AST.
4457     QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4458     LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4459     RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4460     return incompatTy;
4461   }
4462
4463   // The pointer types are compatible.
4464   // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4465   // differently qualified versions of compatible types, the result type is
4466   // a pointer to an appropriately qualified version of the *composite*
4467   // type.
4468   // FIXME: Need to calculate the composite type.
4469   // FIXME: Need to add qualifiers
4470
4471   LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4472   RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4473   return LHSTy;
4474 }
4475
4476 /// \brief Return the resulting type when the operands are both block pointers.
4477 static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4478                                                           ExprResult &LHS,
4479                                                           ExprResult &RHS,
4480                                                           SourceLocation Loc) {
4481   QualType LHSTy = LHS.get()->getType();
4482   QualType RHSTy = RHS.get()->getType();
4483
4484   if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4485     if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4486       QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4487       LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4488       RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4489       return destType;
4490     }
4491     S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4492       << LHSTy << RHSTy << LHS.get()->getSourceRange()
4493       << RHS.get()->getSourceRange();
4494     return QualType();
4495   }
4496
4497   // We have 2 block pointer types.
4498   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4499 }
4500
4501 /// \brief Return the resulting type when the operands are both pointers.
4502 static QualType
4503 checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4504                                             ExprResult &RHS,
4505                                             SourceLocation Loc) {
4506   // get the pointer types
4507   QualType LHSTy = LHS.get()->getType();
4508   QualType RHSTy = RHS.get()->getType();
4509
4510   // get the "pointed to" types
4511   QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4512   QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4513
4514   // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4515   if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4516     // Figure out necessary qualifiers (C99 6.5.15p6)
4517     QualType destPointee
4518       = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4519     QualType destType = S.Context.getPointerType(destPointee);
4520     // Add qualifiers if necessary.
4521     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4522     // Promote to void*.
4523     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4524     return destType;
4525   }
4526   if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4527     QualType destPointee
4528       = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4529     QualType destType = S.Context.getPointerType(destPointee);
4530     // Add qualifiers if necessary.
4531     RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4532     // Promote to void*.
4533     LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4534     return destType;
4535   }
4536
4537   return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4538 }
4539
4540 /// \brief Return false if the first expression is not an integer and the second
4541 /// expression is not a pointer, true otherwise.
4542 static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4543                                         Expr* PointerExpr, SourceLocation Loc,
4544                                         bool IsIntFirstExpr) {
4545   if (!PointerExpr->getType()->isPointerType() ||
4546       !Int.get()->getType()->isIntegerType())
4547     return false;
4548
4549   Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4550   Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
4551
4552   S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4553     << Expr1->getType() << Expr2->getType()
4554     << Expr1->getSourceRange() << Expr2->getSourceRange();
4555   Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4556                             CK_IntegralToPointer);
4557   return true;
4558 }
4559
4560 /// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4561 /// In that case, LHS = cond.
4562 /// C99 6.5.15
4563 QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4564                                         ExprResult &RHS, ExprValueKind &VK,
4565                                         ExprObjectKind &OK,
4566                                         SourceLocation QuestionLoc) {
4567
4568   ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4569   if (!LHSResult.isUsable()) return QualType();
4570   LHS = move(LHSResult);
4571
4572   ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4573   if (!RHSResult.isUsable()) return QualType();
4574   RHS = move(RHSResult);
4575
4576   // C++ is sufficiently different to merit its own checker.
4577   if (getLangOptions().CPlusPlus)
4578     return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
4579
4580   VK = VK_RValue;
4581   OK = OK_Ordinary;
4582
4583   Cond = UsualUnaryConversions(Cond.take());
4584   if (Cond.isInvalid())
4585     return QualType();
4586   LHS = UsualUnaryConversions(LHS.take());
4587   if (LHS.isInvalid())
4588     return QualType();
4589   RHS = UsualUnaryConversions(RHS.take());
4590   if (RHS.isInvalid())
4591     return QualType();
4592
4593   QualType CondTy = Cond.get()->getType();
4594   QualType LHSTy = LHS.get()->getType();
4595   QualType RHSTy = RHS.get()->getType();
4596
4597   // first, check the condition.
4598   if (checkCondition(*this, Cond.get()))
4599     return QualType();
4600
4601   // Now check the two expressions.
4602   if (LHSTy->isVectorType() || RHSTy->isVectorType())
4603     return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
4604
4605   // OpenCL: If the condition is a vector, and both operands are scalar,
4606   // attempt to implicity convert them to the vector type to act like the
4607   // built in select.
4608   if (getLangOptions().OpenCL && CondTy->isVectorType())
4609     if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
4610       return QualType();
4611   
4612   // If both operands have arithmetic type, do the usual arithmetic conversions
4613   // to find a common type: C99 6.5.15p3,5.
4614   if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4615     UsualArithmeticConversions(LHS, RHS);
4616     if (LHS.isInvalid() || RHS.isInvalid())
4617       return QualType();
4618     return LHS.get()->getType();
4619   }
4620
4621   // If both operands are the same structure or union type, the result is that
4622   // type.
4623   if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4624     if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4625       if (LHSRT->getDecl() == RHSRT->getDecl())
4626         // "If both the operands have structure or union type, the result has
4627         // that type."  This implies that CV qualifiers are dropped.
4628         return LHSTy.getUnqualifiedType();
4629     // FIXME: Type of conditional expression must be complete in C mode.
4630   }
4631
4632   // C99 6.5.15p5: "If both operands have void type, the result has void type."
4633   // The following || allows only one side to be void (a GCC-ism).
4634   if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4635     return checkConditionalVoidType(*this, LHS, RHS);
4636   }
4637
4638   // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4639   // the type of the other operand."
4640   if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4641   if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
4642
4643   // All objective-c pointer type analysis is done here.
4644   QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4645                                                         QuestionLoc);
4646   if (LHS.isInvalid() || RHS.isInvalid())
4647     return QualType();
4648   if (!compositeType.isNull())
4649     return compositeType;
4650
4651
4652   // Handle block pointer types.
4653   if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4654     return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4655                                                      QuestionLoc);
4656
4657   // Check constraints for C object pointers types (C99 6.5.15p3,6).
4658   if (LHSTy->isPointerType() && RHSTy->isPointerType())
4659     return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4660                                                        QuestionLoc);
4661
4662   // GCC compatibility: soften pointer/integer mismatch.  Note that
4663   // null pointers have been filtered out by this point.
4664   if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4665       /*isIntFirstExpr=*/true))
4666     return RHSTy;
4667   if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4668       /*isIntFirstExpr=*/false))
4669     return LHSTy;
4670
4671   // Emit a better diagnostic if one of the expressions is a null pointer
4672   // constant and the other is not a pointer type. In this case, the user most
4673   // likely forgot to take the address of the other expression.
4674   if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
4675     return QualType();
4676
4677   // Otherwise, the operands are not compatible.
4678   Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4679     << LHSTy << RHSTy << LHS.get()->getSourceRange()
4680     << RHS.get()->getSourceRange();
4681   return QualType();
4682 }
4683
4684 /// FindCompositeObjCPointerType - Helper method to find composite type of
4685 /// two objective-c pointer types of the two input expressions.
4686 QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
4687                                             SourceLocation QuestionLoc) {
4688   QualType LHSTy = LHS.get()->getType();
4689   QualType RHSTy = RHS.get()->getType();
4690
4691   // Handle things like Class and struct objc_class*.  Here we case the result
4692   // to the pseudo-builtin, because that will be implicitly cast back to the
4693   // redefinition type if an attempt is made to access its fields.
4694   if (LHSTy->isObjCClassType() &&
4695       (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
4696     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
4697     return LHSTy;
4698   }
4699   if (RHSTy->isObjCClassType() &&
4700       (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
4701     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
4702     return RHSTy;
4703   }
4704   // And the same for struct objc_object* / id
4705   if (LHSTy->isObjCIdType() &&
4706       (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
4707     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
4708     return LHSTy;
4709   }
4710   if (RHSTy->isObjCIdType() &&
4711       (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
4712     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
4713     return RHSTy;
4714   }
4715   // And the same for struct objc_selector* / SEL
4716   if (Context.isObjCSelType(LHSTy) &&
4717       (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
4718     RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4719     return LHSTy;
4720   }
4721   if (Context.isObjCSelType(RHSTy) &&
4722       (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
4723     LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
4724     return RHSTy;
4725   }
4726   // Check constraints for Objective-C object pointers types.
4727   if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4728
4729     if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4730       // Two identical object pointer types are always compatible.
4731       return LHSTy;
4732     }
4733     const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4734     const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
4735     QualType compositeType = LHSTy;
4736
4737     // If both operands are interfaces and either operand can be
4738     // assigned to the other, use that type as the composite
4739     // type. This allows
4740     //   xxx ? (A*) a : (B*) b
4741     // where B is a subclass of A.
4742     //
4743     // Additionally, as for assignment, if either type is 'id'
4744     // allow silent coercion. Finally, if the types are
4745     // incompatible then make sure to use 'id' as the composite
4746     // type so the result is acceptable for sending messages to.
4747
4748     // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4749     // It could return the composite type.
4750     if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4751       compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4752     } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4753       compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4754     } else if ((LHSTy->isObjCQualifiedIdType() ||
4755                 RHSTy->isObjCQualifiedIdType()) &&
4756                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4757       // Need to handle "id<xx>" explicitly.
4758       // GCC allows qualified id and any Objective-C type to devolve to
4759       // id. Currently localizing to here until clear this should be
4760       // part of ObjCQualifiedIdTypesAreCompatible.
4761       compositeType = Context.getObjCIdType();
4762     } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4763       compositeType = Context.getObjCIdType();
4764     } else if (!(compositeType =
4765                  Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4766       ;
4767     else {
4768       Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4769       << LHSTy << RHSTy
4770       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4771       QualType incompatTy = Context.getObjCIdType();
4772       LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4773       RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4774       return incompatTy;
4775     }
4776     // The object pointer types are compatible.
4777     LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4778     RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
4779     return compositeType;
4780   }
4781   // Check Objective-C object pointer types and 'void *'
4782   if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4783     QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4784     QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4785     QualType destPointee
4786     = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4787     QualType destType = Context.getPointerType(destPointee);
4788     // Add qualifiers if necessary.
4789     LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4790     // Promote to void*.
4791     RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4792     return destType;
4793   }
4794   if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4795     QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4796     QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4797     QualType destPointee
4798     = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4799     QualType destType = Context.getPointerType(destPointee);
4800     // Add qualifiers if necessary.
4801     RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4802     // Promote to void*.
4803     LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4804     return destType;
4805   }
4806   return QualType();
4807 }
4808
4809 /// SuggestParentheses - Emit a note with a fixit hint that wraps
4810 /// ParenRange in parentheses.
4811 static void SuggestParentheses(Sema &Self, SourceLocation Loc,
4812                                const PartialDiagnostic &Note,
4813                                SourceRange ParenRange) {
4814   SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4815   if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4816       EndLoc.isValid()) {
4817     Self.Diag(Loc, Note)
4818       << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4819       << FixItHint::CreateInsertion(EndLoc, ")");
4820   } else {
4821     // We can't display the parentheses, so just show the bare note.
4822     Self.Diag(Loc, Note) << ParenRange;
4823   }
4824 }
4825
4826 static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4827   return Opc >= BO_Mul && Opc <= BO_Shr;
4828 }
4829
4830 /// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4831 /// expression, either using a built-in or overloaded operator,
4832 /// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4833 /// expression.
4834 static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
4835                                    Expr **RHSExprs) {
4836   // Don't strip parenthesis: we should not warn if E is in parenthesis.
4837   E = E->IgnoreImpCasts();
4838   E = E->IgnoreConversionOperator();
4839   E = E->IgnoreImpCasts();
4840
4841   // Built-in binary operator.
4842   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4843     if (IsArithmeticOp(OP->getOpcode())) {
4844       *Opcode = OP->getOpcode();
4845       *RHSExprs = OP->getRHS();
4846       return true;
4847     }
4848   }
4849
4850   // Overloaded operator.
4851   if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4852     if (Call->getNumArgs() != 2)
4853       return false;
4854
4855     // Make sure this is really a binary operator that is safe to pass into
4856     // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4857     OverloadedOperatorKind OO = Call->getOperator();
4858     if (OO < OO_Plus || OO > OO_Arrow)
4859       return false;
4860
4861     BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4862     if (IsArithmeticOp(OpKind)) {
4863       *Opcode = OpKind;
4864       *RHSExprs = Call->getArg(1);
4865       return true;
4866     }
4867   }
4868
4869   return false;
4870 }
4871
4872 static bool IsLogicOp(BinaryOperatorKind Opc) {
4873   return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4874 }
4875
4876 /// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4877 /// or is a logical expression such as (x==y) which has int type, but is
4878 /// commonly interpreted as boolean.
4879 static bool ExprLooksBoolean(Expr *E) {
4880   E = E->IgnoreParenImpCasts();
4881
4882   if (E->getType()->isBooleanType())
4883     return true;
4884   if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4885     return IsLogicOp(OP->getOpcode());
4886   if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4887     return OP->getOpcode() == UO_LNot;
4888
4889   return false;
4890 }
4891
4892 /// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4893 /// and binary operator are mixed in a way that suggests the programmer assumed
4894 /// the conditional operator has higher precedence, for example:
4895 /// "int x = a + someBinaryCondition ? 1 : 2".
4896 static void DiagnoseConditionalPrecedence(Sema &Self,
4897                                           SourceLocation OpLoc,
4898                                           Expr *Condition,
4899                                           Expr *LHSExpr,
4900                                           Expr *RHSExpr) {
4901   BinaryOperatorKind CondOpcode;
4902   Expr *CondRHS;
4903
4904   if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
4905     return;
4906   if (!ExprLooksBoolean(CondRHS))
4907     return;
4908
4909   // The condition is an arithmetic binary expression, with a right-
4910   // hand side that looks boolean, so warn.
4911
4912   Self.Diag(OpLoc, diag::warn_precedence_conditional)
4913       << Condition->getSourceRange()
4914       << BinaryOperator::getOpcodeStr(CondOpcode);
4915
4916   SuggestParentheses(Self, OpLoc,
4917     Self.PDiag(diag::note_precedence_conditional_silence)
4918       << BinaryOperator::getOpcodeStr(CondOpcode),
4919     SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
4920
4921   SuggestParentheses(Self, OpLoc,
4922     Self.PDiag(diag::note_precedence_conditional_first),
4923     SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
4924 }
4925
4926 /// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4927 /// in the case of a the GNU conditional expr extension.
4928 ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4929                                     SourceLocation ColonLoc,
4930                                     Expr *CondExpr, Expr *LHSExpr,
4931                                     Expr *RHSExpr) {
4932   // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4933   // was the condition.
4934   OpaqueValueExpr *opaqueValue = 0;
4935   Expr *commonExpr = 0;
4936   if (LHSExpr == 0) {
4937     commonExpr = CondExpr;
4938
4939     // We usually want to apply unary conversions *before* saving, except
4940     // in the special case of a C++ l-value conditional.
4941     if (!(getLangOptions().CPlusPlus
4942           && !commonExpr->isTypeDependent()
4943           && commonExpr->getValueKind() == RHSExpr->getValueKind()
4944           && commonExpr->isGLValue()
4945           && commonExpr->isOrdinaryOrBitFieldObject()
4946           && RHSExpr->isOrdinaryOrBitFieldObject()
4947           && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
4948       ExprResult commonRes = UsualUnaryConversions(commonExpr);
4949       if (commonRes.isInvalid())
4950         return ExprError();
4951       commonExpr = commonRes.take();
4952     }
4953
4954     opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4955                                                 commonExpr->getType(),
4956                                                 commonExpr->getValueKind(),
4957                                                 commonExpr->getObjectKind());
4958     LHSExpr = CondExpr = opaqueValue;
4959   }
4960
4961   ExprValueKind VK = VK_RValue;
4962   ExprObjectKind OK = OK_Ordinary;
4963   ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4964   QualType result = CheckConditionalOperands(Cond, LHS, RHS, 
4965                                              VK, OK, QuestionLoc);
4966   if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4967       RHS.isInvalid())
4968     return ExprError();
4969
4970   DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4971                                 RHS.get());
4972
4973   if (!commonExpr)
4974     return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4975                                                    LHS.take(), ColonLoc, 
4976                                                    RHS.take(), result, VK, OK));
4977
4978   return Owned(new (Context)
4979     BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
4980                               RHS.take(), QuestionLoc, ColonLoc, result, VK,
4981                               OK));
4982 }
4983
4984 // checkPointerTypesForAssignment - This is a very tricky routine (despite
4985 // being closely modeled after the C99 spec:-). The odd characteristic of this
4986 // routine is it effectively iqnores the qualifiers on the top level pointee.
4987 // This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4988 // FIXME: add a couple examples in this comment.
4989 static Sema::AssignConvertType
4990 checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
4991   assert(LHSType.isCanonical() && "LHS not canonicalized!");
4992   assert(RHSType.isCanonical() && "RHS not canonicalized!");
4993
4994   // get the "pointed to" type (ignoring qualifiers at the top level)
4995   const Type *lhptee, *rhptee;
4996   Qualifiers lhq, rhq;
4997   llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
4998   llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
4999
5000   Sema::AssignConvertType ConvTy = Sema::Compatible;
5001
5002   // C99 6.5.16.1p1: This following citation is common to constraints
5003   // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5004   // qualifiers of the type *pointed to* by the right;
5005   Qualifiers lq;
5006
5007   // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5008   if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5009       lhq.compatiblyIncludesObjCLifetime(rhq)) {
5010     // Ignore lifetime for further calculation.
5011     lhq.removeObjCLifetime();
5012     rhq.removeObjCLifetime();
5013   }
5014
5015   if (!lhq.compatiblyIncludes(rhq)) {
5016     // Treat address-space mismatches as fatal.  TODO: address subspaces
5017     if (lhq.getAddressSpace() != rhq.getAddressSpace())
5018       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5019
5020     // It's okay to add or remove GC or lifetime qualifiers when converting to
5021     // and from void*.
5022     else if (lhq.withoutObjCGCAttr().withoutObjCGLifetime()
5023                         .compatiblyIncludes(
5024                                 rhq.withoutObjCGCAttr().withoutObjCGLifetime())
5025              && (lhptee->isVoidType() || rhptee->isVoidType()))
5026       ; // keep old
5027
5028     // Treat lifetime mismatches as fatal.
5029     else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5030       ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5031     
5032     // For GCC compatibility, other qualifier mismatches are treated
5033     // as still compatible in C.
5034     else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5035   }
5036
5037   // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5038   // incomplete type and the other is a pointer to a qualified or unqualified
5039   // version of void...
5040   if (lhptee->isVoidType()) {
5041     if (rhptee->isIncompleteOrObjectType())
5042       return ConvTy;
5043
5044     // As an extension, we allow cast to/from void* to function pointer.
5045     assert(rhptee->isFunctionType());
5046     return Sema::FunctionVoidPointer;
5047   }
5048
5049   if (rhptee->isVoidType()) {
5050     if (lhptee->isIncompleteOrObjectType())
5051       return ConvTy;
5052
5053     // As an extension, we allow cast to/from void* to function pointer.
5054     assert(lhptee->isFunctionType());
5055     return Sema::FunctionVoidPointer;
5056   }
5057
5058   // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
5059   // unqualified versions of compatible types, ...
5060   QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5061   if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
5062     // Check if the pointee types are compatible ignoring the sign.
5063     // We explicitly check for char so that we catch "char" vs
5064     // "unsigned char" on systems where "char" is unsigned.
5065     if (lhptee->isCharType())
5066       ltrans = S.Context.UnsignedCharTy;
5067     else if (lhptee->hasSignedIntegerRepresentation())
5068       ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
5069
5070     if (rhptee->isCharType())
5071       rtrans = S.Context.UnsignedCharTy;
5072     else if (rhptee->hasSignedIntegerRepresentation())
5073       rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
5074
5075     if (ltrans == rtrans) {
5076       // Types are compatible ignoring the sign. Qualifier incompatibility
5077       // takes priority over sign incompatibility because the sign
5078       // warning can be disabled.
5079       if (ConvTy != Sema::Compatible)
5080         return ConvTy;
5081
5082       return Sema::IncompatiblePointerSign;
5083     }
5084
5085     // If we are a multi-level pointer, it's possible that our issue is simply
5086     // one of qualification - e.g. char ** -> const char ** is not allowed. If
5087     // the eventual target type is the same and the pointers have the same
5088     // level of indirection, this must be the issue.
5089     if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
5090       do {
5091         lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5092         rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
5093       } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
5094
5095       if (lhptee == rhptee)
5096         return Sema::IncompatibleNestedPointerQualifiers;
5097     }
5098
5099     // General pointer incompatibility takes priority over qualifiers.
5100     return Sema::IncompatiblePointer;
5101   }
5102   if (!S.getLangOptions().CPlusPlus &&
5103       S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5104     return Sema::IncompatiblePointer;
5105   return ConvTy;
5106 }
5107
5108 /// checkBlockPointerTypesForAssignment - This routine determines whether two
5109 /// block pointer types are compatible or whether a block and normal pointer
5110 /// are compatible. It is more restrict than comparing two function pointer
5111 // types.
5112 static Sema::AssignConvertType
5113 checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5114                                     QualType RHSType) {
5115   assert(LHSType.isCanonical() && "LHS not canonicalized!");
5116   assert(RHSType.isCanonical() && "RHS not canonicalized!");
5117
5118   QualType lhptee, rhptee;
5119
5120   // get the "pointed to" type (ignoring qualifiers at the top level)
5121   lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5122   rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
5123
5124   // In C++, the types have to match exactly.
5125   if (S.getLangOptions().CPlusPlus)
5126     return Sema::IncompatibleBlockPointer;
5127
5128   Sema::AssignConvertType ConvTy = Sema::Compatible;
5129
5130   // For blocks we enforce that qualifiers are identical.
5131   if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5132     ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5133
5134   if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
5135     return Sema::IncompatibleBlockPointer;
5136
5137   return ConvTy;
5138 }
5139
5140 /// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
5141 /// for assignment compatibility.
5142 static Sema::AssignConvertType
5143 checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5144                                    QualType RHSType) {
5145   assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5146   assert(RHSType.isCanonical() && "RHS was not canonicalized!");
5147
5148   if (LHSType->isObjCBuiltinType()) {
5149     // Class is not compatible with ObjC object pointers.
5150     if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5151         !RHSType->isObjCQualifiedClassType())
5152       return Sema::IncompatiblePointer;
5153     return Sema::Compatible;
5154   }
5155   if (RHSType->isObjCBuiltinType()) {
5156     if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5157         !LHSType->isObjCQualifiedClassType())
5158       return Sema::IncompatiblePointer;
5159     return Sema::Compatible;
5160   }
5161   QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5162   QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5163
5164   if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
5165     return Sema::CompatiblePointerDiscardsQualifiers;
5166
5167   if (S.Context.typesAreCompatible(LHSType, RHSType))
5168     return Sema::Compatible;
5169   if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
5170     return Sema::IncompatibleObjCQualifiedId;
5171   return Sema::IncompatiblePointer;
5172 }
5173
5174 Sema::AssignConvertType
5175 Sema::CheckAssignmentConstraints(SourceLocation Loc,
5176                                  QualType LHSType, QualType RHSType) {
5177   // Fake up an opaque expression.  We don't actually care about what
5178   // cast operations are required, so if CheckAssignmentConstraints
5179   // adds casts to this they'll be wasted, but fortunately that doesn't
5180   // usually happen on valid code.
5181   OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5182   ExprResult RHSPtr = &RHSExpr;
5183   CastKind K = CK_Invalid;
5184
5185   return CheckAssignmentConstraints(LHSType, RHSPtr, K);
5186 }
5187
5188 /// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5189 /// has code to accommodate several GCC extensions when type checking
5190 /// pointers. Here are some objectionable examples that GCC considers warnings:
5191 ///
5192 ///  int a, *pint;
5193 ///  short *pshort;
5194 ///  struct foo *pfoo;
5195 ///
5196 ///  pint = pshort; // warning: assignment from incompatible pointer type
5197 ///  a = pint; // warning: assignment makes integer from pointer without a cast
5198 ///  pint = a; // warning: assignment makes pointer from integer without a cast
5199 ///  pint = pfoo; // warning: assignment from incompatible pointer type
5200 ///
5201 /// As a result, the code for dealing with pointers is more complex than the
5202 /// C99 spec dictates.
5203 ///
5204 /// Sets 'Kind' for any result kind except Incompatible.
5205 Sema::AssignConvertType
5206 Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5207                                  CastKind &Kind) {
5208   QualType RHSType = RHS.get()->getType();
5209   QualType OrigLHSType = LHSType;
5210
5211   // Get canonical types.  We're not formatting these types, just comparing
5212   // them.
5213   LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5214   RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
5215
5216   // We can't do assignment from/to atomics yet.
5217   if (LHSType->isAtomicType())
5218     return Incompatible;
5219
5220   // Common case: no conversion required.
5221   if (LHSType == RHSType) {
5222     Kind = CK_NoOp;
5223     return Compatible;
5224   }
5225
5226   // If the left-hand side is a reference type, then we are in a
5227   // (rare!) case where we've allowed the use of references in C,
5228   // e.g., as a parameter type in a built-in function. In this case,
5229   // just make sure that the type referenced is compatible with the
5230   // right-hand side type. The caller is responsible for adjusting
5231   // LHSType so that the resulting expression does not have reference
5232   // type.
5233   if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5234     if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
5235       Kind = CK_LValueBitCast;
5236       return Compatible;
5237     }
5238     return Incompatible;
5239   }
5240
5241   // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5242   // to the same ExtVector type.
5243   if (LHSType->isExtVectorType()) {
5244     if (RHSType->isExtVectorType())
5245       return Incompatible;
5246     if (RHSType->isArithmeticType()) {
5247       // CK_VectorSplat does T -> vector T, so first cast to the
5248       // element type.
5249       QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5250       if (elType != RHSType) {
5251         Kind = PrepareScalarCast(RHS, elType);
5252         RHS = ImpCastExprToType(RHS.take(), elType, Kind);
5253       }
5254       Kind = CK_VectorSplat;
5255       return Compatible;
5256     }
5257   }
5258
5259   // Conversions to or from vector type.
5260   if (LHSType->isVectorType() || RHSType->isVectorType()) {
5261     if (LHSType->isVectorType() && RHSType->isVectorType()) {
5262       // Allow assignments of an AltiVec vector type to an equivalent GCC
5263       // vector type and vice versa
5264       if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5265         Kind = CK_BitCast;
5266         return Compatible;
5267       }
5268
5269       // If we are allowing lax vector conversions, and LHS and RHS are both
5270       // vectors, the total size only needs to be the same. This is a bitcast;
5271       // no bits are changed but the result type is different.
5272       if (getLangOptions().LaxVectorConversions &&
5273           (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
5274         Kind = CK_BitCast;
5275         return IncompatibleVectors;
5276       }
5277     }
5278     return Incompatible;
5279   }
5280
5281   // Arithmetic conversions.
5282   if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5283       !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
5284     Kind = PrepareScalarCast(RHS, LHSType);
5285     return Compatible;
5286   }
5287
5288   // Conversions to normal pointers.
5289   if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
5290     // U* -> T*
5291     if (isa<PointerType>(RHSType)) {
5292       Kind = CK_BitCast;
5293       return checkPointerTypesForAssignment(*this, LHSType, RHSType);
5294     }
5295
5296     // int -> T*
5297     if (RHSType->isIntegerType()) {
5298       Kind = CK_IntegralToPointer; // FIXME: null?
5299       return IntToPointer;
5300     }
5301
5302     // C pointers are not compatible with ObjC object pointers,
5303     // with two exceptions:
5304     if (isa<ObjCObjectPointerType>(RHSType)) {
5305       //  - conversions to void*
5306       if (LHSPointer->getPointeeType()->isVoidType()) {
5307         Kind = CK_BitCast;
5308         return Compatible;
5309       }
5310
5311       //  - conversions from 'Class' to the redefinition type
5312       if (RHSType->isObjCClassType() &&
5313           Context.hasSameType(LHSType, 
5314                               Context.getObjCClassRedefinitionType())) {
5315         Kind = CK_BitCast;
5316         return Compatible;
5317       }
5318
5319       Kind = CK_BitCast;
5320       return IncompatiblePointer;
5321     }
5322
5323     // U^ -> void*
5324     if (RHSType->getAs<BlockPointerType>()) {
5325       if (LHSPointer->getPointeeType()->isVoidType()) {
5326         Kind = CK_BitCast;
5327         return Compatible;
5328       }
5329     }
5330
5331     return Incompatible;
5332   }
5333
5334   // Conversions to block pointers.
5335   if (isa<BlockPointerType>(LHSType)) {
5336     // U^ -> T^
5337     if (RHSType->isBlockPointerType()) {
5338       Kind = CK_BitCast;
5339       return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
5340     }
5341
5342     // int or null -> T^
5343     if (RHSType->isIntegerType()) {
5344       Kind = CK_IntegralToPointer; // FIXME: null
5345       return IntToBlockPointer;
5346     }
5347
5348     // id -> T^
5349     if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
5350       Kind = CK_AnyPointerToBlockPointerCast;
5351       return Compatible;
5352     }
5353
5354     // void* -> T^
5355     if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
5356       if (RHSPT->getPointeeType()->isVoidType()) {
5357         Kind = CK_AnyPointerToBlockPointerCast;
5358         return Compatible;
5359       }
5360
5361     return Incompatible;
5362   }
5363
5364   // Conversions to Objective-C pointers.
5365   if (isa<ObjCObjectPointerType>(LHSType)) {
5366     // A* -> B*
5367     if (RHSType->isObjCObjectPointerType()) {
5368       Kind = CK_BitCast;
5369       Sema::AssignConvertType result = 
5370         checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
5371       if (getLangOptions().ObjCAutoRefCount &&
5372           result == Compatible && 
5373           !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
5374         result = IncompatibleObjCWeakRef;
5375       return result;
5376     }
5377
5378     // int or null -> A*
5379     if (RHSType->isIntegerType()) {
5380       Kind = CK_IntegralToPointer; // FIXME: null
5381       return IntToPointer;
5382     }
5383
5384     // In general, C pointers are not compatible with ObjC object pointers,
5385     // with two exceptions:
5386     if (isa<PointerType>(RHSType)) {
5387       Kind = CK_CPointerToObjCPointerCast;
5388
5389       //  - conversions from 'void*'
5390       if (RHSType->isVoidPointerType()) {
5391         return Compatible;
5392       }
5393
5394       //  - conversions to 'Class' from its redefinition type
5395       if (LHSType->isObjCClassType() &&
5396           Context.hasSameType(RHSType, 
5397                               Context.getObjCClassRedefinitionType())) {
5398         return Compatible;
5399       }
5400
5401       return IncompatiblePointer;
5402     }
5403
5404     // T^ -> A*
5405     if (RHSType->isBlockPointerType()) {
5406       maybeExtendBlockObject(*this, RHS);
5407       Kind = CK_BlockPointerToObjCPointerCast;
5408       return Compatible;
5409     }
5410
5411     return Incompatible;
5412   }
5413
5414   // Conversions from pointers that are not covered by the above.
5415   if (isa<PointerType>(RHSType)) {
5416     // T* -> _Bool
5417     if (LHSType == Context.BoolTy) {
5418       Kind = CK_PointerToBoolean;
5419       return Compatible;
5420     }
5421
5422     // T* -> int
5423     if (LHSType->isIntegerType()) {
5424       Kind = CK_PointerToIntegral;
5425       return PointerToInt;
5426     }
5427
5428     return Incompatible;
5429   }
5430
5431   // Conversions from Objective-C pointers that are not covered by the above.
5432   if (isa<ObjCObjectPointerType>(RHSType)) {
5433     // T* -> _Bool
5434     if (LHSType == Context.BoolTy) {
5435       Kind = CK_PointerToBoolean;
5436       return Compatible;
5437     }
5438
5439     // T* -> int
5440     if (LHSType->isIntegerType()) {
5441       Kind = CK_PointerToIntegral;
5442       return PointerToInt;
5443     }
5444
5445     return Incompatible;
5446   }
5447
5448   // struct A -> struct B
5449   if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5450     if (Context.typesAreCompatible(LHSType, RHSType)) {
5451       Kind = CK_NoOp;
5452       return Compatible;
5453     }
5454   }
5455
5456   return Incompatible;
5457 }
5458
5459 /// \brief Constructs a transparent union from an expression that is
5460 /// used to initialize the transparent union.
5461 static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5462                                       ExprResult &EResult, QualType UnionType,
5463                                       FieldDecl *Field) {
5464   // Build an initializer list that designates the appropriate member
5465   // of the transparent union.
5466   Expr *E = EResult.take();
5467   InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
5468                                                    &E, 1,
5469                                                    SourceLocation());
5470   Initializer->setType(UnionType);
5471   Initializer->setInitializedFieldInUnion(Field);
5472
5473   // Build a compound literal constructing a value of the transparent
5474   // union type from this initializer list.
5475   TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
5476   EResult = S.Owned(
5477     new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5478                                 VK_RValue, Initializer, false));
5479 }
5480
5481 Sema::AssignConvertType
5482 Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
5483                                                ExprResult &RHS) {
5484   QualType RHSType = RHS.get()->getType();
5485
5486   // If the ArgType is a Union type, we want to handle a potential
5487   // transparent_union GCC extension.
5488   const RecordType *UT = ArgType->getAsUnionType();
5489   if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
5490     return Incompatible;
5491
5492   // The field to initialize within the transparent union.
5493   RecordDecl *UD = UT->getDecl();
5494   FieldDecl *InitField = 0;
5495   // It's compatible if the expression matches any of the fields.
5496   for (RecordDecl::field_iterator it = UD->field_begin(),
5497          itend = UD->field_end();
5498        it != itend; ++it) {
5499     if (it->getType()->isPointerType()) {
5500       // If the transparent union contains a pointer type, we allow:
5501       // 1) void pointer
5502       // 2) null pointer constant
5503       if (RHSType->isPointerType())
5504         if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
5505           RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
5506           InitField = *it;
5507           break;
5508         }
5509
5510       if (RHS.get()->isNullPointerConstant(Context,
5511                                            Expr::NPC_ValueDependentIsNull)) {
5512         RHS = ImpCastExprToType(RHS.take(), it->getType(),
5513                                 CK_NullToPointer);
5514         InitField = *it;
5515         break;
5516       }
5517     }
5518
5519     CastKind Kind = CK_Invalid;
5520     if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
5521           == Compatible) {
5522       RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
5523       InitField = *it;
5524       break;
5525     }
5526   }
5527
5528   if (!InitField)
5529     return Incompatible;
5530
5531   ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
5532   return Compatible;
5533 }
5534
5535 Sema::AssignConvertType
5536 Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5537                                        bool Diagnose) {
5538   if (getLangOptions().CPlusPlus) {
5539     if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
5540       // C++ 5.17p3: If the left operand is not of class type, the
5541       // expression is implicitly converted (C++ 4) to the
5542       // cv-unqualified type of the left operand.
5543       ExprResult Res = PerformImplicitConversion(RHS.get(),
5544                                                  LHSType.getUnqualifiedType(),
5545                                                  AA_Assigning, Diagnose);
5546       if (Res.isInvalid())
5547         return Incompatible;
5548       Sema::AssignConvertType result = Compatible;
5549       if (getLangOptions().ObjCAutoRefCount &&
5550           !CheckObjCARCUnavailableWeakConversion(LHSType,
5551                                                  RHS.get()->getType()))
5552         result = IncompatibleObjCWeakRef;
5553       RHS = move(Res);
5554       return result;
5555     }
5556
5557     // FIXME: Currently, we fall through and treat C++ classes like C
5558     // structures.
5559     // FIXME: We also fall through for atomics; not sure what should
5560     // happen there, though.
5561   }
5562
5563   // C99 6.5.16.1p1: the left operand is a pointer and the right is
5564   // a null pointer constant.
5565   if ((LHSType->isPointerType() ||
5566        LHSType->isObjCObjectPointerType() ||
5567        LHSType->isBlockPointerType())
5568       && RHS.get()->isNullPointerConstant(Context,
5569                                           Expr::NPC_ValueDependentIsNull)) {
5570     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
5571     return Compatible;
5572   }
5573
5574   // This check seems unnatural, however it is necessary to ensure the proper
5575   // conversion of functions/arrays. If the conversion were done for all
5576   // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
5577   // expressions that suppress this implicit conversion (&, sizeof).
5578   //
5579   // Suppress this for references: C++ 8.5.3p5.
5580   if (!LHSType->isReferenceType()) {
5581     RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5582     if (RHS.isInvalid())
5583       return Incompatible;
5584   }
5585
5586   CastKind Kind = CK_Invalid;
5587   Sema::AssignConvertType result =
5588     CheckAssignmentConstraints(LHSType, RHS, Kind);
5589
5590   // C99 6.5.16.1p2: The value of the right operand is converted to the
5591   // type of the assignment expression.
5592   // CheckAssignmentConstraints allows the left-hand side to be a reference,
5593   // so that we can use references in built-in functions even in C.
5594   // The getNonReferenceType() call makes sure that the resulting expression
5595   // does not have reference type.
5596   if (result != Incompatible && RHS.get()->getType() != LHSType)
5597     RHS = ImpCastExprToType(RHS.take(),
5598                             LHSType.getNonLValueExprType(Context), Kind);
5599   return result;
5600 }
5601
5602 QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5603                                ExprResult &RHS) {
5604   Diag(Loc, diag::err_typecheck_invalid_operands)
5605     << LHS.get()->getType() << RHS.get()->getType()
5606     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5607   return QualType();
5608 }
5609
5610 QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
5611                                    SourceLocation Loc, bool IsCompAssign) {
5612   // For conversion purposes, we ignore any qualifiers.
5613   // For example, "const float" and "float" are equivalent.
5614   QualType LHSType =
5615     Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5616   QualType RHSType =
5617     Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
5618
5619   // If the vector types are identical, return.
5620   if (LHSType == RHSType)
5621     return LHSType;
5622
5623   // Handle the case of equivalent AltiVec and GCC vector types
5624   if (LHSType->isVectorType() && RHSType->isVectorType() &&
5625       Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5626     if (LHSType->isExtVectorType()) {
5627       RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5628       return LHSType;
5629     }
5630
5631     if (!IsCompAssign)
5632       LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5633     return RHSType;
5634   }
5635
5636   if (getLangOptions().LaxVectorConversions &&
5637       Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
5638     // If we are allowing lax vector conversions, and LHS and RHS are both
5639     // vectors, the total size only needs to be the same. This is a
5640     // bitcast; no bits are changed but the result type is different.
5641     // FIXME: Should we really be allowing this?
5642     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5643     return LHSType;
5644   }
5645
5646   // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5647   // swap back (so that we don't reverse the inputs to a subtract, for instance.
5648   bool swapped = false;
5649   if (RHSType->isExtVectorType() && !IsCompAssign) {
5650     swapped = true;
5651     std::swap(RHS, LHS);
5652     std::swap(RHSType, LHSType);
5653   }
5654
5655   // Handle the case of an ext vector and scalar.
5656   if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
5657     QualType EltTy = LV->getElementType();
5658     if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5659       int order = Context.getIntegerTypeOrder(EltTy, RHSType);
5660       if (order > 0)
5661         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
5662       if (order >= 0) {
5663         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5664         if (swapped) std::swap(RHS, LHS);
5665         return LHSType;
5666       }
5667     }
5668     if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5669         RHSType->isRealFloatingType()) {
5670       int order = Context.getFloatingTypeOrder(EltTy, RHSType);
5671       if (order > 0)
5672         RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
5673       if (order >= 0) {
5674         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5675         if (swapped) std::swap(RHS, LHS);
5676         return LHSType;
5677       }
5678     }
5679   }
5680
5681   // Vectors of different size or scalar and non-ext-vector are errors.
5682   if (swapped) std::swap(RHS, LHS);
5683   Diag(Loc, diag::err_typecheck_vector_not_convertable)
5684     << LHS.get()->getType() << RHS.get()->getType()
5685     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5686   return QualType();
5687 }
5688
5689 // checkArithmeticNull - Detect when a NULL constant is used improperly in an
5690 // expression.  These are mainly cases where the null pointer is used as an
5691 // integer instead of a pointer.
5692 static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5693                                 SourceLocation Loc, bool IsCompare) {
5694   // The canonical way to check for a GNU null is with isNullPointerConstant,
5695   // but we use a bit of a hack here for speed; this is a relatively
5696   // hot path, and isNullPointerConstant is slow.
5697   bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5698   bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5699
5700   QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5701
5702   // Avoid analyzing cases where the result will either be invalid (and
5703   // diagnosed as such) or entirely valid and not something to warn about.
5704   if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5705       NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5706     return;
5707
5708   // Comparison operations would not make sense with a null pointer no matter
5709   // what the other expression is.
5710   if (!IsCompare) {
5711     S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5712         << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5713         << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5714     return;
5715   }
5716
5717   // The rest of the operations only make sense with a null pointer
5718   // if the other expression is a pointer.
5719   if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5720       NonNullType->canDecayToPointerType())
5721     return;
5722
5723   S.Diag(Loc, diag::warn_null_in_comparison_operation)
5724       << LHSNull /* LHS is NULL */ << NonNullType
5725       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5726 }
5727
5728 QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
5729                                            SourceLocation Loc,
5730                                            bool IsCompAssign, bool IsDiv) {
5731   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5732
5733   if (LHS.get()->getType()->isVectorType() ||
5734       RHS.get()->getType()->isVectorType())
5735     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
5736
5737   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
5738   if (LHS.isInvalid() || RHS.isInvalid())
5739     return QualType();
5740
5741   if (!LHS.get()->getType()->isArithmeticType() ||
5742       !RHS.get()->getType()->isArithmeticType())
5743     return InvalidOperands(Loc, LHS, RHS);
5744
5745   // Check for division by zero.
5746   if (IsDiv &&
5747       RHS.get()->isNullPointerConstant(Context,
5748                                        Expr::NPC_ValueDependentIsNotNull))
5749     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5750                                           << RHS.get()->getSourceRange());
5751
5752   return compType;
5753 }
5754
5755 QualType Sema::CheckRemainderOperands(
5756   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
5757   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5758
5759   if (LHS.get()->getType()->isVectorType() ||
5760       RHS.get()->getType()->isVectorType()) {
5761     if (LHS.get()->getType()->hasIntegerRepresentation() && 
5762         RHS.get()->getType()->hasIntegerRepresentation())
5763       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
5764     return InvalidOperands(Loc, LHS, RHS);
5765   }
5766
5767   QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
5768   if (LHS.isInvalid() || RHS.isInvalid())
5769     return QualType();
5770
5771   if (!LHS.get()->getType()->isIntegerType() ||
5772       !RHS.get()->getType()->isIntegerType())
5773     return InvalidOperands(Loc, LHS, RHS);
5774
5775   // Check for remainder by zero.
5776   if (RHS.get()->isNullPointerConstant(Context,
5777                                        Expr::NPC_ValueDependentIsNotNull))
5778     DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5779                                  << RHS.get()->getSourceRange());
5780
5781   return compType;
5782 }
5783
5784 /// \brief Diagnose invalid arithmetic on two void pointers.
5785 static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
5786                                                 Expr *LHSExpr, Expr *RHSExpr) {
5787   S.Diag(Loc, S.getLangOptions().CPlusPlus
5788                 ? diag::err_typecheck_pointer_arith_void_type
5789                 : diag::ext_gnu_void_ptr)
5790     << 1 /* two pointers */ << LHSExpr->getSourceRange()
5791                             << RHSExpr->getSourceRange();
5792 }
5793
5794 /// \brief Diagnose invalid arithmetic on a void pointer.
5795 static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5796                                             Expr *Pointer) {
5797   S.Diag(Loc, S.getLangOptions().CPlusPlus
5798                 ? diag::err_typecheck_pointer_arith_void_type
5799                 : diag::ext_gnu_void_ptr)
5800     << 0 /* one pointer */ << Pointer->getSourceRange();
5801 }
5802
5803 /// \brief Diagnose invalid arithmetic on two function pointers.
5804 static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5805                                                     Expr *LHS, Expr *RHS) {
5806   assert(LHS->getType()->isAnyPointerType());
5807   assert(RHS->getType()->isAnyPointerType());
5808   S.Diag(Loc, S.getLangOptions().CPlusPlus
5809                 ? diag::err_typecheck_pointer_arith_function_type
5810                 : diag::ext_gnu_ptr_func_arith)
5811     << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5812     // We only show the second type if it differs from the first.
5813     << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5814                                                    RHS->getType())
5815     << RHS->getType()->getPointeeType()
5816     << LHS->getSourceRange() << RHS->getSourceRange();
5817 }
5818
5819 /// \brief Diagnose invalid arithmetic on a function pointer.
5820 static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5821                                                 Expr *Pointer) {
5822   assert(Pointer->getType()->isAnyPointerType());
5823   S.Diag(Loc, S.getLangOptions().CPlusPlus
5824                 ? diag::err_typecheck_pointer_arith_function_type
5825                 : diag::ext_gnu_ptr_func_arith)
5826     << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5827     << 0 /* one pointer, so only one type */
5828     << Pointer->getSourceRange();
5829 }
5830
5831 /// \brief Emit error if Operand is incomplete pointer type
5832 ///
5833 /// \returns True if pointer has incomplete type
5834 static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5835                                                  Expr *Operand) {
5836   if ((Operand->getType()->isPointerType() &&
5837        !Operand->getType()->isDependentType()) ||
5838       Operand->getType()->isObjCObjectPointerType()) {
5839     QualType PointeeTy = Operand->getType()->getPointeeType();
5840     if (S.RequireCompleteType(
5841           Loc, PointeeTy,
5842           S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5843             << PointeeTy << Operand->getSourceRange()))
5844       return true;
5845   }
5846   return false;
5847 }
5848
5849 /// \brief Check the validity of an arithmetic pointer operand.
5850 ///
5851 /// If the operand has pointer type, this code will check for pointer types
5852 /// which are invalid in arithmetic operations. These will be diagnosed
5853 /// appropriately, including whether or not the use is supported as an
5854 /// extension.
5855 ///
5856 /// \returns True when the operand is valid to use (even if as an extension).
5857 static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5858                                             Expr *Operand) {
5859   if (!Operand->getType()->isAnyPointerType()) return true;
5860
5861   QualType PointeeTy = Operand->getType()->getPointeeType();
5862   if (PointeeTy->isVoidType()) {
5863     diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5864     return !S.getLangOptions().CPlusPlus;
5865   }
5866   if (PointeeTy->isFunctionType()) {
5867     diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5868     return !S.getLangOptions().CPlusPlus;
5869   }
5870
5871   if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
5872
5873   return true;
5874 }
5875
5876 /// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5877 /// operands.
5878 ///
5879 /// This routine will diagnose any invalid arithmetic on pointer operands much
5880 /// like \see checkArithmeticOpPointerOperand. However, it has special logic
5881 /// for emitting a single diagnostic even for operations where both LHS and RHS
5882 /// are (potentially problematic) pointers.
5883 ///
5884 /// \returns True when the operand is valid to use (even if as an extension).
5885 static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
5886                                                 Expr *LHSExpr, Expr *RHSExpr) {
5887   bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
5888   bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
5889   if (!isLHSPointer && !isRHSPointer) return true;
5890
5891   QualType LHSPointeeTy, RHSPointeeTy;
5892   if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
5893   if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
5894
5895   // Check for arithmetic on pointers to incomplete types.
5896   bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5897   bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5898   if (isLHSVoidPtr || isRHSVoidPtr) {
5899     if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
5900     else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
5901     else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
5902
5903     return !S.getLangOptions().CPlusPlus;
5904   }
5905
5906   bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5907   bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5908   if (isLHSFuncPtr || isRHSFuncPtr) {
5909     if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
5910     else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
5911                                                                 RHSExpr);
5912     else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
5913
5914     return !S.getLangOptions().CPlusPlus;
5915   }
5916
5917   if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
5918   if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
5919
5920   return true;
5921 }
5922
5923 /// \brief Check bad cases where we step over interface counts.
5924 static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
5925                                                    SourceLocation OpLoc,
5926                                                    Expr *Op) {
5927   assert(Op->getType()->isAnyPointerType());
5928   QualType PointeeTy = Op->getType()->getPointeeType();
5929   if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
5930     return true;
5931
5932   S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5933     << PointeeTy << Op->getSourceRange();
5934   return false;
5935 }
5936
5937 /// \brief Emit error when two pointers are incompatible.
5938 static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
5939                                            Expr *LHSExpr, Expr *RHSExpr) {
5940   assert(LHSExpr->getType()->isAnyPointerType());
5941   assert(RHSExpr->getType()->isAnyPointerType());
5942   S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5943     << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
5944     << RHSExpr->getSourceRange();
5945 }
5946
5947 QualType Sema::CheckAdditionOperands( // C99 6.5.6
5948   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy) {
5949   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5950
5951   if (LHS.get()->getType()->isVectorType() ||
5952       RHS.get()->getType()->isVectorType()) {
5953     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
5954     if (CompLHSTy) *CompLHSTy = compType;
5955     return compType;
5956   }
5957
5958   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
5959   if (LHS.isInvalid() || RHS.isInvalid())
5960     return QualType();
5961
5962   // handle the common case first (both operands are arithmetic).
5963   if (LHS.get()->getType()->isArithmeticType() &&
5964       RHS.get()->getType()->isArithmeticType()) {
5965     if (CompLHSTy) *CompLHSTy = compType;
5966     return compType;
5967   }
5968
5969   // Put any potential pointer into PExp
5970   Expr* PExp = LHS.get(), *IExp = RHS.get();
5971   if (IExp->getType()->isAnyPointerType())
5972     std::swap(PExp, IExp);
5973
5974   if (!PExp->getType()->isAnyPointerType())
5975     return InvalidOperands(Loc, LHS, RHS);
5976
5977   if (!IExp->getType()->isIntegerType())
5978     return InvalidOperands(Loc, LHS, RHS);
5979
5980   if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
5981     return QualType();
5982
5983   // Diagnose bad cases where we step over interface counts.
5984   if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
5985     return QualType();
5986
5987   // Check array bounds for pointer arithemtic
5988   CheckArrayAccess(PExp, IExp);
5989
5990   if (CompLHSTy) {
5991     QualType LHSTy = Context.isPromotableBitField(LHS.get());
5992     if (LHSTy.isNull()) {
5993       LHSTy = LHS.get()->getType();
5994       if (LHSTy->isPromotableIntegerType())
5995         LHSTy = Context.getPromotedIntegerType(LHSTy);
5996     }
5997     *CompLHSTy = LHSTy;
5998   }
5999
6000   return PExp->getType();
6001 }
6002
6003 // C99 6.5.6
6004 QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
6005                                         SourceLocation Loc,
6006                                         QualType* CompLHSTy) {
6007   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6008
6009   if (LHS.get()->getType()->isVectorType() ||
6010       RHS.get()->getType()->isVectorType()) {
6011     QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
6012     if (CompLHSTy) *CompLHSTy = compType;
6013     return compType;
6014   }
6015
6016   QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6017   if (LHS.isInvalid() || RHS.isInvalid())
6018     return QualType();
6019
6020   // Enforce type constraints: C99 6.5.6p3.
6021
6022   // Handle the common case first (both operands are arithmetic).
6023   if (LHS.get()->getType()->isArithmeticType() &&
6024       RHS.get()->getType()->isArithmeticType()) {
6025     if (CompLHSTy) *CompLHSTy = compType;
6026     return compType;
6027   }
6028
6029   // Either ptr - int   or   ptr - ptr.
6030   if (LHS.get()->getType()->isAnyPointerType()) {
6031     QualType lpointee = LHS.get()->getType()->getPointeeType();
6032
6033     // Diagnose bad cases where we step over interface counts.
6034     if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
6035       return QualType();
6036
6037     // The result type of a pointer-int computation is the pointer type.
6038     if (RHS.get()->getType()->isIntegerType()) {
6039       if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
6040         return QualType();
6041
6042       Expr *IExpr = RHS.get()->IgnoreParenCasts();
6043       UnaryOperator negRex(IExpr, UO_Minus, IExpr->getType(), VK_RValue,
6044                            OK_Ordinary, IExpr->getExprLoc());
6045       // Check array bounds for pointer arithemtic
6046       CheckArrayAccess(LHS.get()->IgnoreParenCasts(), &negRex);
6047
6048       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6049       return LHS.get()->getType();
6050     }
6051
6052     // Handle pointer-pointer subtractions.
6053     if (const PointerType *RHSPTy
6054           = RHS.get()->getType()->getAs<PointerType>()) {
6055       QualType rpointee = RHSPTy->getPointeeType();
6056
6057       if (getLangOptions().CPlusPlus) {
6058         // Pointee types must be the same: C++ [expr.add]
6059         if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
6060           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6061         }
6062       } else {
6063         // Pointee types must be compatible C99 6.5.6p3
6064         if (!Context.typesAreCompatible(
6065                 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6066                 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
6067           diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
6068           return QualType();
6069         }
6070       }
6071
6072       if (!checkArithmeticBinOpPointerOperands(*this, Loc,
6073                                                LHS.get(), RHS.get()))
6074         return QualType();
6075
6076       if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6077       return Context.getPointerDiffType();
6078     }
6079   }
6080
6081   return InvalidOperands(Loc, LHS, RHS);
6082 }
6083
6084 static bool isScopedEnumerationType(QualType T) {
6085   if (const EnumType *ET = dyn_cast<EnumType>(T))
6086     return ET->getDecl()->isScoped();
6087   return false;
6088 }
6089
6090 static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
6091                                    SourceLocation Loc, unsigned Opc,
6092                                    QualType LHSType) {
6093   llvm::APSInt Right;
6094   // Check right/shifter operand
6095   if (RHS.get()->isValueDependent() ||
6096       !RHS.get()->isIntegerConstantExpr(Right, S.Context))
6097     return;
6098
6099   if (Right.isNegative()) {
6100     S.DiagRuntimeBehavior(Loc, RHS.get(),
6101                           S.PDiag(diag::warn_shift_negative)
6102                             << RHS.get()->getSourceRange());
6103     return;
6104   }
6105   llvm::APInt LeftBits(Right.getBitWidth(),
6106                        S.Context.getTypeSize(LHS.get()->getType()));
6107   if (Right.uge(LeftBits)) {
6108     S.DiagRuntimeBehavior(Loc, RHS.get(),
6109                           S.PDiag(diag::warn_shift_gt_typewidth)
6110                             << RHS.get()->getSourceRange());
6111     return;
6112   }
6113   if (Opc != BO_Shl)
6114     return;
6115
6116   // When left shifting an ICE which is signed, we can check for overflow which
6117   // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6118   // integers have defined behavior modulo one more than the maximum value
6119   // representable in the result type, so never warn for those.
6120   llvm::APSInt Left;
6121   if (LHS.get()->isValueDependent() ||
6122       !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6123       LHSType->hasUnsignedIntegerRepresentation())
6124     return;
6125   llvm::APInt ResultBits =
6126       static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6127   if (LeftBits.uge(ResultBits))
6128     return;
6129   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6130   Result = Result.shl(Right);
6131
6132   // Print the bit representation of the signed integer as an unsigned
6133   // hexadecimal number.
6134   llvm::SmallString<40> HexResult;
6135   Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6136
6137   // If we are only missing a sign bit, this is less likely to result in actual
6138   // bugs -- if the result is cast back to an unsigned type, it will have the
6139   // expected value. Thus we place this behind a different warning that can be
6140   // turned off separately if needed.
6141   if (LeftBits == ResultBits - 1) {
6142     S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
6143         << HexResult.str() << LHSType
6144         << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6145     return;
6146   }
6147
6148   S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
6149     << HexResult.str() << Result.getMinSignedBits() << LHSType
6150     << Left.getBitWidth() << LHS.get()->getSourceRange()
6151     << RHS.get()->getSourceRange();
6152 }
6153
6154 // C99 6.5.7
6155 QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
6156                                   SourceLocation Loc, unsigned Opc,
6157                                   bool IsCompAssign) {
6158   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6159
6160   // C99 6.5.7p2: Each of the operands shall have integer type.
6161   if (!LHS.get()->getType()->hasIntegerRepresentation() || 
6162       !RHS.get()->getType()->hasIntegerRepresentation())
6163     return InvalidOperands(Loc, LHS, RHS);
6164
6165   // C++0x: Don't allow scoped enums. FIXME: Use something better than
6166   // hasIntegerRepresentation() above instead of this.
6167   if (isScopedEnumerationType(LHS.get()->getType()) ||
6168       isScopedEnumerationType(RHS.get()->getType())) {
6169     return InvalidOperands(Loc, LHS, RHS);
6170   }
6171
6172   // Vector shifts promote their scalar inputs to vector type.
6173   if (LHS.get()->getType()->isVectorType() ||
6174       RHS.get()->getType()->isVectorType())
6175     return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6176
6177   // Shifts don't perform usual arithmetic conversions, they just do integer
6178   // promotions on each operand. C99 6.5.7p3
6179
6180   // For the LHS, do usual unary conversions, but then reset them away
6181   // if this is a compound assignment.
6182   ExprResult OldLHS = LHS;
6183   LHS = UsualUnaryConversions(LHS.take());
6184   if (LHS.isInvalid())
6185     return QualType();
6186   QualType LHSType = LHS.get()->getType();
6187   if (IsCompAssign) LHS = OldLHS;
6188
6189   // The RHS is simpler.
6190   RHS = UsualUnaryConversions(RHS.take());
6191   if (RHS.isInvalid())
6192     return QualType();
6193
6194   // Sanity-check shift operands
6195   DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
6196
6197   // "The type of the result is that of the promoted left operand."
6198   return LHSType;
6199 }
6200
6201 static bool IsWithinTemplateSpecialization(Decl *D) {
6202   if (DeclContext *DC = D->getDeclContext()) {
6203     if (isa<ClassTemplateSpecializationDecl>(DC))
6204       return true;
6205     if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6206       return FD->isFunctionTemplateSpecialization();
6207   }
6208   return false;
6209 }
6210
6211 /// If two different enums are compared, raise a warning.
6212 static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6213                                 ExprResult &RHS) {
6214   QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6215   QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
6216
6217   const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6218   if (!LHSEnumType)
6219     return;
6220   const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6221   if (!RHSEnumType)
6222     return;
6223
6224   // Ignore anonymous enums.
6225   if (!LHSEnumType->getDecl()->getIdentifier())
6226     return;
6227   if (!RHSEnumType->getDecl()->getIdentifier())
6228     return;
6229
6230   if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6231     return;
6232
6233   S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6234       << LHSStrippedType << RHSStrippedType
6235       << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6236 }
6237
6238 /// \brief Diagnose bad pointer comparisons.
6239 static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
6240                                               ExprResult &LHS, ExprResult &RHS,
6241                                               bool IsError) {
6242   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
6243                       : diag::ext_typecheck_comparison_of_distinct_pointers)
6244     << LHS.get()->getType() << RHS.get()->getType()
6245     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6246 }
6247
6248 /// \brief Returns false if the pointers are converted to a composite type,
6249 /// true otherwise.
6250 static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
6251                                            ExprResult &LHS, ExprResult &RHS) {
6252   // C++ [expr.rel]p2:
6253   //   [...] Pointer conversions (4.10) and qualification
6254   //   conversions (4.4) are performed on pointer operands (or on
6255   //   a pointer operand and a null pointer constant) to bring
6256   //   them to their composite pointer type. [...]
6257   //
6258   // C++ [expr.eq]p1 uses the same notion for (in)equality
6259   // comparisons of pointers.
6260
6261   // C++ [expr.eq]p2:
6262   //   In addition, pointers to members can be compared, or a pointer to
6263   //   member and a null pointer constant. Pointer to member conversions
6264   //   (4.11) and qualification conversions (4.4) are performed to bring
6265   //   them to a common type. If one operand is a null pointer constant,
6266   //   the common type is the type of the other operand. Otherwise, the
6267   //   common type is a pointer to member type similar (4.4) to the type
6268   //   of one of the operands, with a cv-qualification signature (4.4)
6269   //   that is the union of the cv-qualification signatures of the operand
6270   //   types.
6271
6272   QualType LHSType = LHS.get()->getType();
6273   QualType RHSType = RHS.get()->getType();
6274   assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6275          (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
6276
6277   bool NonStandardCompositeType = false;
6278   bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
6279   QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
6280   if (T.isNull()) {
6281     diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
6282     return true;
6283   }
6284
6285   if (NonStandardCompositeType)
6286     S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
6287       << LHSType << RHSType << T << LHS.get()->getSourceRange()
6288       << RHS.get()->getSourceRange();
6289
6290   LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6291   RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
6292   return false;
6293 }
6294
6295 static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
6296                                                     ExprResult &LHS,
6297                                                     ExprResult &RHS,
6298                                                     bool IsError) {
6299   S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6300                       : diag::ext_typecheck_comparison_of_fptr_to_void)
6301     << LHS.get()->getType() << RHS.get()->getType()
6302     << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
6303 }
6304
6305 // C99 6.5.8, C++ [expr.rel]
6306 QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
6307                                     SourceLocation Loc, unsigned OpaqueOpc,
6308                                     bool IsRelational) {
6309   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6310
6311   BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
6312
6313   // Handle vector comparisons separately.
6314   if (LHS.get()->getType()->isVectorType() ||
6315       RHS.get()->getType()->isVectorType())
6316     return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
6317
6318   QualType LHSType = LHS.get()->getType();
6319   QualType RHSType = RHS.get()->getType();
6320
6321   Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6322   Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
6323
6324   checkEnumComparison(*this, Loc, LHS, RHS);
6325
6326   if (!LHSType->hasFloatingRepresentation() &&
6327       !(LHSType->isBlockPointerType() && IsRelational) &&
6328       !LHS.get()->getLocStart().isMacroID() &&
6329       !RHS.get()->getLocStart().isMacroID()) {
6330     // For non-floating point types, check for self-comparisons of the form
6331     // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6332     // often indicate logic errors in the program.
6333     //
6334     // NOTE: Don't warn about comparison expressions resulting from macro
6335     // expansion. Also don't warn about comparisons which are only self
6336     // comparisons within a template specialization. The warnings should catch
6337     // obvious cases in the definition of the template anyways. The idea is to
6338     // warn when the typed comparison operator will always evaluate to the same
6339     // result.
6340     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
6341       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
6342         if (DRL->getDecl() == DRR->getDecl() &&
6343             !IsWithinTemplateSpecialization(DRL->getDecl())) {
6344           DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6345                               << 0 // self-
6346                               << (Opc == BO_EQ
6347                                   || Opc == BO_LE
6348                                   || Opc == BO_GE));
6349         } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
6350                    !DRL->getDecl()->getType()->isReferenceType() &&
6351                    !DRR->getDecl()->getType()->isReferenceType()) {
6352             // what is it always going to eval to?
6353             char always_evals_to;
6354             switch(Opc) {
6355             case BO_EQ: // e.g. array1 == array2
6356               always_evals_to = 0; // false
6357               break;
6358             case BO_NE: // e.g. array1 != array2
6359               always_evals_to = 1; // true
6360               break;
6361             default:
6362               // best we can say is 'a constant'
6363               always_evals_to = 2; // e.g. array1 <= array2
6364               break;
6365             }
6366             DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
6367                                 << 1 // array
6368                                 << always_evals_to);
6369         }
6370       }
6371     }
6372
6373     if (isa<CastExpr>(LHSStripped))
6374       LHSStripped = LHSStripped->IgnoreParenCasts();
6375     if (isa<CastExpr>(RHSStripped))
6376       RHSStripped = RHSStripped->IgnoreParenCasts();
6377
6378     // Warn about comparisons against a string constant (unless the other
6379     // operand is null), the user probably wants strcmp.
6380     Expr *literalString = 0;
6381     Expr *literalStringStripped = 0;
6382     if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
6383         !RHSStripped->isNullPointerConstant(Context,
6384                                             Expr::NPC_ValueDependentIsNull)) {
6385       literalString = LHS.get();
6386       literalStringStripped = LHSStripped;
6387     } else if ((isa<StringLiteral>(RHSStripped) ||
6388                 isa<ObjCEncodeExpr>(RHSStripped)) &&
6389                !LHSStripped->isNullPointerConstant(Context,
6390                                             Expr::NPC_ValueDependentIsNull)) {
6391       literalString = RHS.get();
6392       literalStringStripped = RHSStripped;
6393     }
6394
6395     if (literalString) {
6396       std::string resultComparison;
6397       switch (Opc) {
6398       case BO_LT: resultComparison = ") < 0"; break;
6399       case BO_GT: resultComparison = ") > 0"; break;
6400       case BO_LE: resultComparison = ") <= 0"; break;
6401       case BO_GE: resultComparison = ") >= 0"; break;
6402       case BO_EQ: resultComparison = ") == 0"; break;
6403       case BO_NE: resultComparison = ") != 0"; break;
6404       default: llvm_unreachable("Invalid comparison operator");
6405       }
6406
6407       DiagRuntimeBehavior(Loc, 0,
6408         PDiag(diag::warn_stringcompare)
6409           << isa<ObjCEncodeExpr>(literalStringStripped)
6410           << literalString->getSourceRange());
6411     }
6412   }
6413
6414   // C99 6.5.8p3 / C99 6.5.9p4
6415   if (LHS.get()->getType()->isArithmeticType() &&
6416       RHS.get()->getType()->isArithmeticType()) {
6417     UsualArithmeticConversions(LHS, RHS);
6418     if (LHS.isInvalid() || RHS.isInvalid())
6419       return QualType();
6420   }
6421   else {
6422     LHS = UsualUnaryConversions(LHS.take());
6423     if (LHS.isInvalid())
6424       return QualType();
6425
6426     RHS = UsualUnaryConversions(RHS.take());
6427     if (RHS.isInvalid())
6428       return QualType();
6429   }
6430
6431   LHSType = LHS.get()->getType();
6432   RHSType = RHS.get()->getType();
6433
6434   // The result of comparisons is 'bool' in C++, 'int' in C.
6435   QualType ResultTy = Context.getLogicalOperationType();
6436
6437   if (IsRelational) {
6438     if (LHSType->isRealType() && RHSType->isRealType())
6439       return ResultTy;
6440   } else {
6441     // Check for comparisons of floating point operands using != and ==.
6442     if (LHSType->hasFloatingRepresentation())
6443       CheckFloatComparison(Loc, LHS.get(), RHS.get());
6444
6445     if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
6446       return ResultTy;
6447   }
6448
6449   bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
6450                                               Expr::NPC_ValueDependentIsNull);
6451   bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
6452                                               Expr::NPC_ValueDependentIsNull);
6453
6454   // All of the following pointer-related warnings are GCC extensions, except
6455   // when handling null pointer constants. 
6456   if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
6457     QualType LCanPointeeTy =
6458       LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
6459     QualType RCanPointeeTy =
6460       RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
6461
6462     if (getLangOptions().CPlusPlus) {
6463       if (LCanPointeeTy == RCanPointeeTy)
6464         return ResultTy;
6465       if (!IsRelational &&
6466           (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6467         // Valid unless comparison between non-null pointer and function pointer
6468         // This is a gcc extension compatibility comparison.
6469         // In a SFINAE context, we treat this as a hard error to maintain
6470         // conformance with the C++ standard.
6471         if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6472             && !LHSIsNull && !RHSIsNull) {
6473           diagnoseFunctionPointerToVoidComparison(
6474               *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
6475           
6476           if (isSFINAEContext())
6477             return QualType();
6478           
6479           RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6480           return ResultTy;
6481         }
6482       }
6483
6484       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
6485         return QualType();
6486       else
6487         return ResultTy;
6488     }
6489     // C99 6.5.9p2 and C99 6.5.8p2
6490     if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6491                                    RCanPointeeTy.getUnqualifiedType())) {
6492       // Valid unless a relational comparison of function pointers
6493       if (IsRelational && LCanPointeeTy->isFunctionType()) {
6494         Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
6495           << LHSType << RHSType << LHS.get()->getSourceRange()
6496           << RHS.get()->getSourceRange();
6497       }
6498     } else if (!IsRelational &&
6499                (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6500       // Valid unless comparison between non-null pointer and function pointer
6501       if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6502           && !LHSIsNull && !RHSIsNull)
6503         diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
6504                                                 /*isError*/false);
6505     } else {
6506       // Invalid
6507       diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
6508     }
6509     if (LCanPointeeTy != RCanPointeeTy) {
6510       if (LHSIsNull && !RHSIsNull)
6511         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6512       else
6513         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6514     }
6515     return ResultTy;
6516   }
6517
6518   if (getLangOptions().CPlusPlus) {
6519     // Comparison of nullptr_t with itself.
6520     if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
6521       return ResultTy;
6522     
6523     // Comparison of pointers with null pointer constants and equality
6524     // comparisons of member pointers to null pointer constants.
6525     if (RHSIsNull &&
6526         ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
6527          (!IsRelational && 
6528           (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6529       RHS = ImpCastExprToType(RHS.take(), LHSType, 
6530                         LHSType->isMemberPointerType()
6531                           ? CK_NullToMemberPointer
6532                           : CK_NullToPointer);
6533       return ResultTy;
6534     }
6535     if (LHSIsNull &&
6536         ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
6537          (!IsRelational && 
6538           (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6539       LHS = ImpCastExprToType(LHS.take(), RHSType, 
6540                         RHSType->isMemberPointerType()
6541                           ? CK_NullToMemberPointer
6542                           : CK_NullToPointer);
6543       return ResultTy;
6544     }
6545
6546     // Comparison of member pointers.
6547     if (!IsRelational &&
6548         LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6549       if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
6550         return QualType();
6551       else
6552         return ResultTy;
6553     }
6554
6555     // Handle scoped enumeration types specifically, since they don't promote
6556     // to integers.
6557     if (LHS.get()->getType()->isEnumeralType() &&
6558         Context.hasSameUnqualifiedType(LHS.get()->getType(),
6559                                        RHS.get()->getType()))
6560       return ResultTy;
6561   }
6562
6563   // Handle block pointer types.
6564   if (!IsRelational && LHSType->isBlockPointerType() &&
6565       RHSType->isBlockPointerType()) {
6566     QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6567     QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
6568
6569     if (!LHSIsNull && !RHSIsNull &&
6570         !Context.typesAreCompatible(lpointee, rpointee)) {
6571       Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6572         << LHSType << RHSType << LHS.get()->getSourceRange()
6573         << RHS.get()->getSourceRange();
6574     }
6575     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6576     return ResultTy;
6577   }
6578
6579   // Allow block pointers to be compared with null pointer constants.
6580   if (!IsRelational
6581       && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6582           || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
6583     if (!LHSIsNull && !RHSIsNull) {
6584       if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
6585              ->getPointeeType()->isVoidType())
6586             || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
6587                 ->getPointeeType()->isVoidType())))
6588         Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
6589           << LHSType << RHSType << LHS.get()->getSourceRange()
6590           << RHS.get()->getSourceRange();
6591     }
6592     if (LHSIsNull && !RHSIsNull)
6593       LHS = ImpCastExprToType(LHS.take(), RHSType,
6594                               RHSType->isPointerType() ? CK_BitCast
6595                                 : CK_AnyPointerToBlockPointerCast);
6596     else
6597       RHS = ImpCastExprToType(RHS.take(), LHSType,
6598                               LHSType->isPointerType() ? CK_BitCast
6599                                 : CK_AnyPointerToBlockPointerCast);
6600     return ResultTy;
6601   }
6602
6603   if (LHSType->isObjCObjectPointerType() ||
6604       RHSType->isObjCObjectPointerType()) {
6605     const PointerType *LPT = LHSType->getAs<PointerType>();
6606     const PointerType *RPT = RHSType->getAs<PointerType>();
6607     if (LPT || RPT) {
6608       bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6609       bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
6610
6611       if (!LPtrToVoid && !RPtrToVoid &&
6612           !Context.typesAreCompatible(LHSType, RHSType)) {
6613         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
6614                                           /*isError*/false);
6615       }
6616       if (LHSIsNull && !RHSIsNull)
6617         LHS = ImpCastExprToType(LHS.take(), RHSType,
6618                                 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
6619       else
6620         RHS = ImpCastExprToType(RHS.take(), LHSType,
6621                                 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
6622       return ResultTy;
6623     }
6624     if (LHSType->isObjCObjectPointerType() &&
6625         RHSType->isObjCObjectPointerType()) {
6626       if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6627         diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
6628                                           /*isError*/false);
6629       if (LHSIsNull && !RHSIsNull)
6630         LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
6631       else
6632         RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
6633       return ResultTy;
6634     }
6635   }
6636   if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6637       (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
6638     unsigned DiagID = 0;
6639     bool isError = false;
6640     if ((LHSIsNull && LHSType->isIntegerType()) ||
6641         (RHSIsNull && RHSType->isIntegerType())) {
6642       if (IsRelational && !getLangOptions().CPlusPlus)
6643         DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
6644     } else if (IsRelational && !getLangOptions().CPlusPlus)
6645       DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
6646     else if (getLangOptions().CPlusPlus) {
6647       DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6648       isError = true;
6649     } else
6650       DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
6651
6652     if (DiagID) {
6653       Diag(Loc, DiagID)
6654         << LHSType << RHSType << LHS.get()->getSourceRange()
6655         << RHS.get()->getSourceRange();
6656       if (isError)
6657         return QualType();
6658     }
6659     
6660     if (LHSType->isIntegerType())
6661       LHS = ImpCastExprToType(LHS.take(), RHSType,
6662                         LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6663     else
6664       RHS = ImpCastExprToType(RHS.take(), LHSType,
6665                         RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
6666     return ResultTy;
6667   }
6668   
6669   // Handle block pointers.
6670   if (!IsRelational && RHSIsNull
6671       && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6672     RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
6673     return ResultTy;
6674   }
6675   if (!IsRelational && LHSIsNull
6676       && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6677     LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
6678     return ResultTy;
6679   }
6680
6681   return InvalidOperands(Loc, LHS, RHS);
6682 }
6683
6684 /// CheckVectorCompareOperands - vector comparisons are a clang extension that
6685 /// operates on extended vector types.  Instead of producing an IntTy result,
6686 /// like a scalar comparison, a vector comparison produces a vector of integer
6687 /// types.
6688 QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
6689                                           SourceLocation Loc,
6690                                           bool IsRelational) {
6691   // Check to make sure we're operating on vectors of the same type and width,
6692   // Allowing one side to be a scalar of element type.
6693   QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
6694   if (vType.isNull())
6695     return vType;
6696
6697   QualType LHSType = LHS.get()->getType();
6698   QualType RHSType = RHS.get()->getType();
6699
6700   // If AltiVec, the comparison results in a numeric type, i.e.
6701   // bool for C++, int for C
6702   if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
6703     return Context.getLogicalOperationType();
6704
6705   // For non-floating point types, check for self-comparisons of the form
6706   // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
6707   // often indicate logic errors in the program.
6708   if (!LHSType->hasFloatingRepresentation()) {
6709     if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParens()))
6710       if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParens()))
6711         if (DRL->getDecl() == DRR->getDecl())
6712           DiagRuntimeBehavior(Loc, 0,
6713                               PDiag(diag::warn_comparison_always)
6714                                 << 0 // self-
6715                                 << 2 // "a constant"
6716                               );
6717   }
6718
6719   // Check for comparisons of floating point operands using != and ==.
6720   if (!IsRelational && LHSType->hasFloatingRepresentation()) {
6721     assert (RHSType->hasFloatingRepresentation());
6722     CheckFloatComparison(Loc, LHS.get(), RHS.get());
6723   }
6724
6725   // Return the type for the comparison, which is the same as vector type for
6726   // integer vectors, or an integer type of identical size and number of
6727   // elements for floating point vectors.
6728   if (LHSType->hasIntegerRepresentation())
6729     return LHSType;
6730
6731   const VectorType *VTy = LHSType->getAs<VectorType>();
6732   unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6733   if (TypeSize == Context.getTypeSize(Context.IntTy))
6734     return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6735   if (TypeSize == Context.getTypeSize(Context.LongTy))
6736     return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6737
6738   assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6739          "Unhandled vector element size in vector compare");
6740   return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6741 }
6742
6743 inline QualType Sema::CheckBitwiseOperands(
6744   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
6745   checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6746
6747   if (LHS.get()->getType()->isVectorType() ||
6748       RHS.get()->getType()->isVectorType()) {
6749     if (LHS.get()->getType()->hasIntegerRepresentation() &&
6750         RHS.get()->getType()->hasIntegerRepresentation())
6751       return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
6752     
6753     return InvalidOperands(Loc, LHS, RHS);
6754   }
6755
6756   ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6757   QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
6758                                                  IsCompAssign);
6759   if (LHSResult.isInvalid() || RHSResult.isInvalid())
6760     return QualType();
6761   LHS = LHSResult.take();
6762   RHS = RHSResult.take();
6763
6764   if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6765       RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
6766     return compType;
6767   return InvalidOperands(Loc, LHS, RHS);
6768 }
6769
6770 inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
6771   ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
6772   
6773   // Diagnose cases where the user write a logical and/or but probably meant a
6774   // bitwise one.  We do this when the LHS is a non-bool integer and the RHS
6775   // is a constant.
6776   if (LHS.get()->getType()->isIntegerType() &&
6777       !LHS.get()->getType()->isBooleanType() &&
6778       RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
6779       // Don't warn in macros or template instantiations.
6780       !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
6781     // If the RHS can be constant folded, and if it constant folds to something
6782     // that isn't 0 or 1 (which indicate a potential logical operation that
6783     // happened to fold to true/false) then warn.
6784     // Parens on the RHS are ignored.
6785     Expr::EvalResult Result;
6786     if (RHS.get()->Evaluate(Result, Context) && !Result.HasSideEffects)
6787       if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
6788           (Result.Val.getInt() != 0 && Result.Val.getInt() != 1)) {
6789         Diag(Loc, diag::warn_logical_instead_of_bitwise)
6790           << RHS.get()->getSourceRange()
6791           << (Opc == BO_LAnd ? "&&" : "||");
6792         // Suggest replacing the logical operator with the bitwise version
6793         Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6794             << (Opc == BO_LAnd ? "&" : "|")
6795             << FixItHint::CreateReplacement(SourceRange(
6796                 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6797                                                 getLangOptions())),
6798                                             Opc == BO_LAnd ? "&" : "|");
6799         if (Opc == BO_LAnd)
6800           // Suggest replacing "Foo() && kNonZero" with "Foo()"
6801           Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6802               << FixItHint::CreateRemoval(
6803                   SourceRange(
6804                       Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
6805                                                  0, getSourceManager(),
6806                                                  getLangOptions()),
6807                       RHS.get()->getLocEnd()));
6808       }
6809   }
6810   
6811   if (!Context.getLangOptions().CPlusPlus) {
6812     LHS = UsualUnaryConversions(LHS.take());
6813     if (LHS.isInvalid())
6814       return QualType();
6815
6816     RHS = UsualUnaryConversions(RHS.take());
6817     if (RHS.isInvalid())
6818       return QualType();
6819
6820     if (!LHS.get()->getType()->isScalarType() ||
6821         !RHS.get()->getType()->isScalarType())
6822       return InvalidOperands(Loc, LHS, RHS);
6823
6824     return Context.IntTy;
6825   }
6826
6827   // The following is safe because we only use this method for
6828   // non-overloadable operands.
6829
6830   // C++ [expr.log.and]p1
6831   // C++ [expr.log.or]p1
6832   // The operands are both contextually converted to type bool.
6833   ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6834   if (LHSRes.isInvalid())
6835     return InvalidOperands(Loc, LHS, RHS);
6836   LHS = move(LHSRes);
6837
6838   ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6839   if (RHSRes.isInvalid())
6840     return InvalidOperands(Loc, LHS, RHS);
6841   RHS = move(RHSRes);
6842
6843   // C++ [expr.log.and]p2
6844   // C++ [expr.log.or]p2
6845   // The result is a bool.
6846   return Context.BoolTy;
6847 }
6848
6849 /// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6850 /// is a read-only property; return true if so. A readonly property expression
6851 /// depends on various declarations and thus must be treated specially.
6852 ///
6853 static bool IsReadonlyProperty(Expr *E, Sema &S) {
6854   if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6855     const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6856     if (PropExpr->isImplicitProperty()) return false;
6857
6858     ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6859     QualType BaseType = PropExpr->isSuperReceiver() ? 
6860                             PropExpr->getSuperReceiverType() :  
6861                             PropExpr->getBase()->getType();
6862       
6863     if (const ObjCObjectPointerType *OPT =
6864           BaseType->getAsObjCInterfacePointerType())
6865       if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
6866         if (S.isPropertyReadonly(PDecl, IFace))
6867           return true;
6868   }
6869   return false;
6870 }
6871
6872 static bool IsConstProperty(Expr *E, Sema &S) {
6873   if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
6874     const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
6875     if (PropExpr->isImplicitProperty()) return false;
6876     
6877     ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6878     QualType T = PDecl->getType();
6879     if (T->isReferenceType())
6880       T = T->getAs<ReferenceType>()->getPointeeType();
6881     CanQualType CT = S.Context.getCanonicalType(T);
6882     return CT.isConstQualified();
6883   }
6884   return false;
6885 }
6886
6887 static bool IsReadonlyMessage(Expr *E, Sema &S) {
6888   if (E->getStmtClass() != Expr::MemberExprClass) 
6889     return false;
6890   const MemberExpr *ME = cast<MemberExpr>(E);
6891   NamedDecl *Member = ME->getMemberDecl();
6892   if (isa<FieldDecl>(Member)) {
6893     Expr *Base = ME->getBase()->IgnoreParenImpCasts();
6894     if (Base->getStmtClass() != Expr::ObjCMessageExprClass)
6895       return false;
6896     return cast<ObjCMessageExpr>(Base)->getMethodDecl() != 0;
6897   }
6898   return false;
6899 }
6900
6901 /// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
6902 /// emit an error and return true.  If so, return false.
6903 static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
6904   SourceLocation OrigLoc = Loc;
6905   Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
6906                                                               &Loc);
6907   if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
6908     IsLV = Expr::MLV_ReadonlyProperty;
6909   else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
6910     IsLV = Expr::MLV_Valid;
6911   else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
6912     IsLV = Expr::MLV_InvalidMessageExpression;
6913   if (IsLV == Expr::MLV_Valid)
6914     return false;
6915
6916   unsigned Diag = 0;
6917   bool NeedType = false;
6918   switch (IsLV) { // C99 6.5.16p2
6919   case Expr::MLV_ConstQualified:
6920     Diag = diag::err_typecheck_assign_const;
6921
6922     // In ARC, use some specialized diagnostics for occasions where we
6923     // infer 'const'.  These are always pseudo-strong variables.
6924     if (S.getLangOptions().ObjCAutoRefCount) {
6925       DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
6926       if (declRef && isa<VarDecl>(declRef->getDecl())) {
6927         VarDecl *var = cast<VarDecl>(declRef->getDecl());
6928
6929         // Use the normal diagnostic if it's pseudo-__strong but the
6930         // user actually wrote 'const'.
6931         if (var->isARCPseudoStrong() &&
6932             (!var->getTypeSourceInfo() ||
6933              !var->getTypeSourceInfo()->getType().isConstQualified())) {
6934           // There are two pseudo-strong cases:
6935           //  - self
6936           ObjCMethodDecl *method = S.getCurMethodDecl();
6937           if (method && var == method->getSelfDecl())
6938             Diag = diag::err_typecheck_arr_assign_self;
6939
6940           //  - fast enumeration variables
6941           else
6942             Diag = diag::err_typecheck_arr_assign_enumeration;
6943
6944           SourceRange Assign;
6945           if (Loc != OrigLoc)
6946             Assign = SourceRange(OrigLoc, OrigLoc);
6947           S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
6948           // We need to preserve the AST regardless, so migration tool 
6949           // can do its job.
6950           return false;
6951         }
6952       }
6953     }
6954
6955     break;
6956   case Expr::MLV_ArrayType:
6957     Diag = diag::err_typecheck_array_not_modifiable_lvalue;
6958     NeedType = true;
6959     break;
6960   case Expr::MLV_NotObjectType:
6961     Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
6962     NeedType = true;
6963     break;
6964   case Expr::MLV_LValueCast:
6965     Diag = diag::err_typecheck_lvalue_casts_not_supported;
6966     break;
6967   case Expr::MLV_Valid:
6968     llvm_unreachable("did not take early return for MLV_Valid");
6969   case Expr::MLV_InvalidExpression:
6970   case Expr::MLV_MemberFunction:
6971   case Expr::MLV_ClassTemporary:
6972     Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
6973     break;
6974   case Expr::MLV_IncompleteType:
6975   case Expr::MLV_IncompleteVoidType:
6976     return S.RequireCompleteType(Loc, E->getType(),
6977               S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
6978                   << E->getSourceRange());
6979   case Expr::MLV_DuplicateVectorComponents:
6980     Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
6981     break;
6982   case Expr::MLV_NotBlockQualified:
6983     Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
6984     break;
6985   case Expr::MLV_ReadonlyProperty:
6986     Diag = diag::error_readonly_property_assignment;
6987     break;
6988   case Expr::MLV_NoSetterProperty:
6989     Diag = diag::error_nosetter_property_assignment;
6990     break;
6991   case Expr::MLV_InvalidMessageExpression:
6992     Diag = diag::error_readonly_message_assignment;
6993     break;
6994   case Expr::MLV_SubObjCPropertySetting:
6995     Diag = diag::error_no_subobject_property_setting;
6996     break;
6997   }
6998
6999   SourceRange Assign;
7000   if (Loc != OrigLoc)
7001     Assign = SourceRange(OrigLoc, OrigLoc);
7002   if (NeedType)
7003     S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
7004   else
7005     S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7006   return true;
7007 }
7008
7009
7010
7011 // C99 6.5.16.1
7012 QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
7013                                        SourceLocation Loc,
7014                                        QualType CompoundType) {
7015   // Verify that LHS is a modifiable lvalue, and emit error if not.
7016   if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
7017     return QualType();
7018
7019   QualType LHSType = LHSExpr->getType();
7020   QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7021                                              CompoundType;
7022   AssignConvertType ConvTy;
7023   if (CompoundType.isNull()) {
7024     QualType LHSTy(LHSType);
7025     // Simple assignment "x = y".
7026     if (LHSExpr->getObjectKind() == OK_ObjCProperty) {
7027       ExprResult LHSResult = Owned(LHSExpr);
7028       ConvertPropertyForLValue(LHSResult, RHS, LHSTy);
7029       if (LHSResult.isInvalid())
7030         return QualType();
7031       LHSExpr = LHSResult.take();
7032     }
7033     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
7034     if (RHS.isInvalid())
7035       return QualType();
7036     // Special case of NSObject attributes on c-style pointer types.
7037     if (ConvTy == IncompatiblePointer &&
7038         ((Context.isObjCNSObjectType(LHSType) &&
7039           RHSType->isObjCObjectPointerType()) ||
7040          (Context.isObjCNSObjectType(RHSType) &&
7041           LHSType->isObjCObjectPointerType())))
7042       ConvTy = Compatible;
7043
7044     if (ConvTy == Compatible &&
7045         getLangOptions().ObjCNonFragileABI &&
7046         LHSType->isObjCObjectType())
7047       Diag(Loc, diag::err_assignment_requires_nonfragile_object)
7048         << LHSType;
7049
7050     // If the RHS is a unary plus or minus, check to see if they = and + are
7051     // right next to each other.  If so, the user may have typo'd "x =+ 4"
7052     // instead of "x += 4".
7053     Expr *RHSCheck = RHS.get();
7054     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7055       RHSCheck = ICE->getSubExpr();
7056     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
7057       if ((UO->getOpcode() == UO_Plus ||
7058            UO->getOpcode() == UO_Minus) &&
7059           Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
7060           // Only if the two operators are exactly adjacent.
7061           Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
7062           // And there is a space or other character before the subexpr of the
7063           // unary +/-.  We don't want to warn on "x=-1".
7064           Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
7065           UO->getSubExpr()->getLocStart().isFileID()) {
7066         Diag(Loc, diag::warn_not_compound_assign)
7067           << (UO->getOpcode() == UO_Plus ? "+" : "-")
7068           << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
7069       }
7070     }
7071
7072     if (ConvTy == Compatible) {
7073       if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
7074         checkRetainCycles(LHSExpr, RHS.get());
7075       else if (getLangOptions().ObjCAutoRefCount)
7076         checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
7077     }
7078   } else {
7079     // Compound assignment "x += y"
7080     ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
7081   }
7082
7083   if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
7084                                RHS.get(), AA_Assigning))
7085     return QualType();
7086
7087   CheckForNullPointerDereference(*this, LHSExpr);
7088
7089   // C99 6.5.16p3: The type of an assignment expression is the type of the
7090   // left operand unless the left operand has qualified type, in which case
7091   // it is the unqualified version of the type of the left operand.
7092   // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7093   // is converted to the type of the assignment expression (above).
7094   // C++ 5.17p1: the type of the assignment expression is that of its left
7095   // operand.
7096   return (getLangOptions().CPlusPlus
7097           ? LHSType : LHSType.getUnqualifiedType());
7098 }
7099
7100 // C99 6.5.17
7101 static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
7102                                    SourceLocation Loc) {
7103   S.DiagnoseUnusedExprResult(LHS.get());
7104
7105   LHS = S.CheckPlaceholderExpr(LHS.take());
7106   RHS = S.CheckPlaceholderExpr(RHS.take());
7107   if (LHS.isInvalid() || RHS.isInvalid())
7108     return QualType();
7109
7110   // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7111   // operands, but not unary promotions.
7112   // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
7113
7114   // So we treat the LHS as a ignored value, and in C++ we allow the
7115   // containing site to determine what should be done with the RHS.
7116   LHS = S.IgnoredValueConversions(LHS.take());
7117   if (LHS.isInvalid())
7118     return QualType();
7119
7120   if (!S.getLangOptions().CPlusPlus) {
7121     RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7122     if (RHS.isInvalid())
7123       return QualType();
7124     if (!RHS.get()->getType()->isVoidType())
7125       S.RequireCompleteType(Loc, RHS.get()->getType(),
7126                             diag::err_incomplete_type);
7127   }
7128
7129   return RHS.get()->getType();
7130 }
7131
7132 /// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7133 /// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
7134 static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7135                                                ExprValueKind &VK,
7136                                                SourceLocation OpLoc,
7137                                                bool IsInc, bool IsPrefix) {
7138   if (Op->isTypeDependent())
7139     return S.Context.DependentTy;
7140
7141   QualType ResType = Op->getType();
7142   assert(!ResType.isNull() && "no type for increment/decrement expression");
7143
7144   if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
7145     // Decrement of bool is not allowed.
7146     if (!IsInc) {
7147       S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
7148       return QualType();
7149     }
7150     // Increment of bool sets it to true, but is deprecated.
7151     S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
7152   } else if (ResType->isRealType()) {
7153     // OK!
7154   } else if (ResType->isAnyPointerType()) {
7155     // C99 6.5.2.4p2, 6.5.6p2
7156     if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
7157       return QualType();
7158
7159     // Diagnose bad cases where we step over interface counts.
7160     else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
7161       return QualType();
7162   } else if (ResType->isAnyComplexType()) {
7163     // C99 does not support ++/-- on complex types, we allow as an extension.
7164     S.Diag(OpLoc, diag::ext_integer_increment_complex)
7165       << ResType << Op->getSourceRange();
7166   } else if (ResType->isPlaceholderType()) {
7167     ExprResult PR = S.CheckPlaceholderExpr(Op);
7168     if (PR.isInvalid()) return QualType();
7169     return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
7170                                           IsInc, IsPrefix);
7171   } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7172     // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
7173   } else {
7174     S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
7175       << ResType << int(IsInc) << Op->getSourceRange();
7176     return QualType();
7177   }
7178   // At this point, we know we have a real, complex or pointer type.
7179   // Now make sure the operand is a modifiable lvalue.
7180   if (CheckForModifiableLvalue(Op, OpLoc, S))
7181     return QualType();
7182   // In C++, a prefix increment is the same type as the operand. Otherwise
7183   // (in C or with postfix), the increment is the unqualified type of the
7184   // operand.
7185   if (IsPrefix && S.getLangOptions().CPlusPlus) {
7186     VK = VK_LValue;
7187     return ResType;
7188   } else {
7189     VK = VK_RValue;
7190     return ResType.getUnqualifiedType();
7191   }
7192 }
7193
7194 ExprResult Sema::ConvertPropertyForRValue(Expr *E) {
7195   assert(E->getValueKind() == VK_LValue &&
7196          E->getObjectKind() == OK_ObjCProperty);
7197   const ObjCPropertyRefExpr *PRE = E->getObjCProperty();
7198
7199   QualType T = E->getType();
7200   QualType ReceiverType;
7201   if (PRE->isObjectReceiver())
7202     ReceiverType = PRE->getBase()->getType();
7203   else if (PRE->isSuperReceiver())
7204     ReceiverType = PRE->getSuperReceiverType();
7205   else
7206     ReceiverType = Context.getObjCInterfaceType(PRE->getClassReceiver());
7207     
7208   ExprValueKind VK = VK_RValue;
7209   if (PRE->isImplicitProperty()) {
7210     if (ObjCMethodDecl *GetterMethod = 
7211           PRE->getImplicitPropertyGetter()) {
7212       T = getMessageSendResultType(ReceiverType, GetterMethod, 
7213                                    PRE->isClassReceiver(), 
7214                                    PRE->isSuperReceiver());
7215       VK = Expr::getValueKindForType(GetterMethod->getResultType());
7216     }
7217     else {
7218       Diag(PRE->getLocation(), diag::err_getter_not_found)
7219             << PRE->getBase()->getType();
7220     }
7221   }
7222   else {
7223     // lvalue-ness of an explicit property is determined by
7224     // getter type.
7225     QualType ResT = PRE->getGetterResultType();
7226     VK = Expr::getValueKindForType(ResT);
7227   }
7228     
7229   E = ImplicitCastExpr::Create(Context, T, CK_GetObjCProperty,
7230                                E, 0, VK);
7231   
7232   ExprResult Result = MaybeBindToTemporary(E);
7233   if (!Result.isInvalid())
7234     E = Result.take();
7235
7236   return Owned(E);
7237 }
7238
7239 void Sema::ConvertPropertyForLValue(ExprResult &LHS, ExprResult &RHS,
7240                                     QualType &LHSTy) {
7241   assert(LHS.get()->getValueKind() == VK_LValue &&
7242          LHS.get()->getObjectKind() == OK_ObjCProperty);
7243   const ObjCPropertyRefExpr *PropRef = LHS.get()->getObjCProperty();
7244
7245   bool Consumed = false;
7246
7247   if (PropRef->isImplicitProperty()) {
7248     // If using property-dot syntax notation for assignment, and there is a
7249     // setter, RHS expression is being passed to the setter argument. So,
7250     // type conversion (and comparison) is RHS to setter's argument type.
7251     if (const ObjCMethodDecl *SetterMD = PropRef->getImplicitPropertySetter()) {
7252       ObjCMethodDecl::param_const_iterator P = SetterMD->param_begin();
7253       LHSTy = (*P)->getType();
7254       Consumed = (getLangOptions().ObjCAutoRefCount &&
7255                   (*P)->hasAttr<NSConsumedAttr>());
7256
7257     // Otherwise, if the getter returns an l-value, just call that.
7258     } else {
7259       QualType Result = PropRef->getImplicitPropertyGetter()->getResultType();
7260       ExprValueKind VK = Expr::getValueKindForType(Result);
7261       if (VK == VK_LValue) {
7262         LHS = ImplicitCastExpr::Create(Context, LHS.get()->getType(),
7263                                         CK_GetObjCProperty, LHS.take(), 0, VK);
7264         return;
7265       }
7266     }
7267   } else if (getLangOptions().ObjCAutoRefCount) {
7268     const ObjCMethodDecl *setter
7269       = PropRef->getExplicitProperty()->getSetterMethodDecl();
7270     if (setter) {
7271       ObjCMethodDecl::param_const_iterator P = setter->param_begin();
7272       LHSTy = (*P)->getType();
7273       Consumed = (*P)->hasAttr<NSConsumedAttr>();
7274     }
7275   }
7276
7277   if ((getLangOptions().CPlusPlus && LHSTy->isRecordType()) ||
7278       getLangOptions().ObjCAutoRefCount) {
7279     InitializedEntity Entity = 
7280       InitializedEntity::InitializeParameter(Context, LHSTy, Consumed);
7281     ExprResult ArgE = PerformCopyInitialization(Entity, SourceLocation(), RHS);
7282     if (!ArgE.isInvalid()) {
7283       RHS = ArgE;
7284       if (getLangOptions().ObjCAutoRefCount && !PropRef->isSuperReceiver())
7285         checkRetainCycles(const_cast<Expr*>(PropRef->getBase()), RHS.get());
7286     }
7287   }
7288 }
7289   
7290
7291 /// getPrimaryDecl - Helper function for CheckAddressOfOperand().
7292 /// This routine allows us to typecheck complex/recursive expressions
7293 /// where the declaration is needed for type checking. We only need to
7294 /// handle cases when the expression references a function designator
7295 /// or is an lvalue. Here are some examples:
7296 ///  - &(x) => x
7297 ///  - &*****f => f for f a function designator.
7298 ///  - &s.xx => s
7299 ///  - &s.zz[1].yy -> s, if zz is an array
7300 ///  - *(x + 1) -> x, if x is an array
7301 ///  - &"123"[2] -> 0
7302 ///  - & __real__ x -> x
7303 static ValueDecl *getPrimaryDecl(Expr *E) {
7304   switch (E->getStmtClass()) {
7305   case Stmt::DeclRefExprClass:
7306     return cast<DeclRefExpr>(E)->getDecl();
7307   case Stmt::MemberExprClass:
7308     // If this is an arrow operator, the address is an offset from
7309     // the base's value, so the object the base refers to is
7310     // irrelevant.
7311     if (cast<MemberExpr>(E)->isArrow())
7312       return 0;
7313     // Otherwise, the expression refers to a part of the base
7314     return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
7315   case Stmt::ArraySubscriptExprClass: {
7316     // FIXME: This code shouldn't be necessary!  We should catch the implicit
7317     // promotion of register arrays earlier.
7318     Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7319     if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7320       if (ICE->getSubExpr()->getType()->isArrayType())
7321         return getPrimaryDecl(ICE->getSubExpr());
7322     }
7323     return 0;
7324   }
7325   case Stmt::UnaryOperatorClass: {
7326     UnaryOperator *UO = cast<UnaryOperator>(E);
7327
7328     switch(UO->getOpcode()) {
7329     case UO_Real:
7330     case UO_Imag:
7331     case UO_Extension:
7332       return getPrimaryDecl(UO->getSubExpr());
7333     default:
7334       return 0;
7335     }
7336   }
7337   case Stmt::ParenExprClass:
7338     return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
7339   case Stmt::ImplicitCastExprClass:
7340     // If the result of an implicit cast is an l-value, we care about
7341     // the sub-expression; otherwise, the result here doesn't matter.
7342     return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
7343   default:
7344     return 0;
7345   }
7346 }
7347
7348 namespace {
7349   enum {
7350     AO_Bit_Field = 0,
7351     AO_Vector_Element = 1,
7352     AO_Property_Expansion = 2,
7353     AO_Register_Variable = 3,
7354     AO_No_Error = 4
7355   };
7356 }
7357 /// \brief Diagnose invalid operand for address of operations.
7358 ///
7359 /// \param Type The type of operand which cannot have its address taken.
7360 static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7361                                          Expr *E, unsigned Type) {
7362   S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7363 }
7364
7365 /// CheckAddressOfOperand - The operand of & must be either a function
7366 /// designator or an lvalue designating an object. If it is an lvalue, the
7367 /// object cannot be declared with storage class register or be a bit field.
7368 /// Note: The usual conversions are *not* applied to the operand of the &
7369 /// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
7370 /// In C++, the operand might be an overloaded function name, in which case
7371 /// we allow the '&' but retain the overloaded-function type.
7372 static QualType CheckAddressOfOperand(Sema &S, Expr *OrigOp,
7373                                       SourceLocation OpLoc) {
7374   if (OrigOp->isTypeDependent())
7375     return S.Context.DependentTy;
7376   if (OrigOp->getType() == S.Context.OverloadTy) {
7377     if (!isa<OverloadExpr>(OrigOp->IgnoreParens())) {
7378       S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7379         << OrigOp->getSourceRange();
7380       return QualType();
7381     }
7382                   
7383     return S.Context.OverloadTy;
7384   }
7385   if (OrigOp->getType() == S.Context.UnknownAnyTy)
7386     return S.Context.UnknownAnyTy;
7387   if (OrigOp->getType() == S.Context.BoundMemberTy) {
7388     S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7389       << OrigOp->getSourceRange();
7390     return QualType();
7391   }
7392
7393   assert(!OrigOp->getType()->isPlaceholderType());
7394
7395   // Make sure to ignore parentheses in subsequent checks
7396   Expr *op = OrigOp->IgnoreParens();
7397
7398   if (S.getLangOptions().C99) {
7399     // Implement C99-only parts of addressof rules.
7400     if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
7401       if (uOp->getOpcode() == UO_Deref)
7402         // Per C99 6.5.3.2, the address of a deref always returns a valid result
7403         // (assuming the deref expression is valid).
7404         return uOp->getSubExpr()->getType();
7405     }
7406     // Technically, there should be a check for array subscript
7407     // expressions here, but the result of one is always an lvalue anyway.
7408   }
7409   ValueDecl *dcl = getPrimaryDecl(op);
7410   Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
7411   unsigned AddressOfError = AO_No_Error;
7412
7413   if (lval == Expr::LV_ClassTemporary) { 
7414     bool sfinae = S.isSFINAEContext();
7415     S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7416                          : diag::ext_typecheck_addrof_class_temporary)
7417       << op->getType() << op->getSourceRange();
7418     if (sfinae)
7419       return QualType();
7420   } else if (isa<ObjCSelectorExpr>(op)) {
7421     return S.Context.getPointerType(op->getType());
7422   } else if (lval == Expr::LV_MemberFunction) {
7423     // If it's an instance method, make a member pointer.
7424     // The expression must have exactly the form &A::foo.
7425
7426     // If the underlying expression isn't a decl ref, give up.
7427     if (!isa<DeclRefExpr>(op)) {
7428       S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7429         << OrigOp->getSourceRange();
7430       return QualType();
7431     }
7432     DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7433     CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7434
7435     // The id-expression was parenthesized.
7436     if (OrigOp != DRE) {
7437       S.Diag(OpLoc, diag::err_parens_pointer_member_function)
7438         << OrigOp->getSourceRange();
7439
7440     // The method was named without a qualifier.
7441     } else if (!DRE->getQualifier()) {
7442       S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
7443         << op->getSourceRange();
7444     }
7445
7446     return S.Context.getMemberPointerType(op->getType(),
7447               S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
7448   } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
7449     // C99 6.5.3.2p1
7450     // The operand must be either an l-value or a function designator
7451     if (!op->getType()->isFunctionType()) {
7452       // FIXME: emit more specific diag...
7453       S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7454         << op->getSourceRange();
7455       return QualType();
7456     }
7457   } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
7458     // The operand cannot be a bit-field
7459     AddressOfError = AO_Bit_Field;
7460   } else if (op->getObjectKind() == OK_VectorComponent) {
7461     // The operand cannot be an element of a vector
7462     AddressOfError = AO_Vector_Element;
7463   } else if (op->getObjectKind() == OK_ObjCProperty) {
7464     // cannot take address of a property expression.
7465     AddressOfError = AO_Property_Expansion;
7466   } else if (dcl) { // C99 6.5.3.2p1
7467     // We have an lvalue with a decl. Make sure the decl is not declared
7468     // with the register storage-class specifier.
7469     if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
7470       // in C++ it is not error to take address of a register
7471       // variable (c++03 7.1.1P3)
7472       if (vd->getStorageClass() == SC_Register &&
7473           !S.getLangOptions().CPlusPlus) {
7474         AddressOfError = AO_Register_Variable;
7475       }
7476     } else if (isa<FunctionTemplateDecl>(dcl)) {
7477       return S.Context.OverloadTy;
7478     } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
7479       // Okay: we can take the address of a field.
7480       // Could be a pointer to member, though, if there is an explicit
7481       // scope qualifier for the class.
7482       if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
7483         DeclContext *Ctx = dcl->getDeclContext();
7484         if (Ctx && Ctx->isRecord()) {
7485           if (dcl->getType()->isReferenceType()) {
7486             S.Diag(OpLoc,
7487                    diag::err_cannot_form_pointer_to_member_of_reference_type)
7488               << dcl->getDeclName() << dcl->getType();
7489             return QualType();
7490           }
7491
7492           while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7493             Ctx = Ctx->getParent();
7494           return S.Context.getMemberPointerType(op->getType(),
7495                 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
7496         }
7497       }
7498     } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
7499       llvm_unreachable("Unknown/unexpected decl type");
7500   }
7501
7502   if (AddressOfError != AO_No_Error) {
7503     diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7504     return QualType();
7505   }
7506
7507   if (lval == Expr::LV_IncompleteVoidType) {
7508     // Taking the address of a void variable is technically illegal, but we
7509     // allow it in cases which are otherwise valid.
7510     // Example: "extern void x; void* y = &x;".
7511     S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
7512   }
7513
7514   // If the operand has type "type", the result has type "pointer to type".
7515   if (op->getType()->isObjCObjectType())
7516     return S.Context.getObjCObjectPointerType(op->getType());
7517   return S.Context.getPointerType(op->getType());
7518 }
7519
7520 /// CheckIndirectionOperand - Type check unary indirection (prefix '*').
7521 static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7522                                         SourceLocation OpLoc) {
7523   if (Op->isTypeDependent())
7524     return S.Context.DependentTy;
7525
7526   ExprResult ConvResult = S.UsualUnaryConversions(Op);
7527   if (ConvResult.isInvalid())
7528     return QualType();
7529   Op = ConvResult.take();
7530   QualType OpTy = Op->getType();
7531   QualType Result;
7532
7533   if (isa<CXXReinterpretCastExpr>(Op)) {
7534     QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7535     S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7536                                      Op->getSourceRange());
7537   }
7538
7539   // Note that per both C89 and C99, indirection is always legal, even if OpTy
7540   // is an incomplete type or void.  It would be possible to warn about
7541   // dereferencing a void pointer, but it's completely well-defined, and such a
7542   // warning is unlikely to catch any mistakes.
7543   if (const PointerType *PT = OpTy->getAs<PointerType>())
7544     Result = PT->getPointeeType();
7545   else if (const ObjCObjectPointerType *OPT =
7546              OpTy->getAs<ObjCObjectPointerType>())
7547     Result = OPT->getPointeeType();
7548   else {
7549     ExprResult PR = S.CheckPlaceholderExpr(Op);
7550     if (PR.isInvalid()) return QualType();
7551     if (PR.take() != Op)
7552       return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
7553   }
7554
7555   if (Result.isNull()) {
7556     S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
7557       << OpTy << Op->getSourceRange();
7558     return QualType();
7559   }
7560
7561   // Dereferences are usually l-values...
7562   VK = VK_LValue;
7563
7564   // ...except that certain expressions are never l-values in C.
7565   if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
7566     VK = VK_RValue;
7567   
7568   return Result;
7569 }
7570
7571 static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
7572   tok::TokenKind Kind) {
7573   BinaryOperatorKind Opc;
7574   switch (Kind) {
7575   default: llvm_unreachable("Unknown binop!");
7576   case tok::periodstar:           Opc = BO_PtrMemD; break;
7577   case tok::arrowstar:            Opc = BO_PtrMemI; break;
7578   case tok::star:                 Opc = BO_Mul; break;
7579   case tok::slash:                Opc = BO_Div; break;
7580   case tok::percent:              Opc = BO_Rem; break;
7581   case tok::plus:                 Opc = BO_Add; break;
7582   case tok::minus:                Opc = BO_Sub; break;
7583   case tok::lessless:             Opc = BO_Shl; break;
7584   case tok::greatergreater:       Opc = BO_Shr; break;
7585   case tok::lessequal:            Opc = BO_LE; break;
7586   case tok::less:                 Opc = BO_LT; break;
7587   case tok::greaterequal:         Opc = BO_GE; break;
7588   case tok::greater:              Opc = BO_GT; break;
7589   case tok::exclaimequal:         Opc = BO_NE; break;
7590   case tok::equalequal:           Opc = BO_EQ; break;
7591   case tok::amp:                  Opc = BO_And; break;
7592   case tok::caret:                Opc = BO_Xor; break;
7593   case tok::pipe:                 Opc = BO_Or; break;
7594   case tok::ampamp:               Opc = BO_LAnd; break;
7595   case tok::pipepipe:             Opc = BO_LOr; break;
7596   case tok::equal:                Opc = BO_Assign; break;
7597   case tok::starequal:            Opc = BO_MulAssign; break;
7598   case tok::slashequal:           Opc = BO_DivAssign; break;
7599   case tok::percentequal:         Opc = BO_RemAssign; break;
7600   case tok::plusequal:            Opc = BO_AddAssign; break;
7601   case tok::minusequal:           Opc = BO_SubAssign; break;
7602   case tok::lesslessequal:        Opc = BO_ShlAssign; break;
7603   case tok::greatergreaterequal:  Opc = BO_ShrAssign; break;
7604   case tok::ampequal:             Opc = BO_AndAssign; break;
7605   case tok::caretequal:           Opc = BO_XorAssign; break;
7606   case tok::pipeequal:            Opc = BO_OrAssign; break;
7607   case tok::comma:                Opc = BO_Comma; break;
7608   }
7609   return Opc;
7610 }
7611
7612 static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
7613   tok::TokenKind Kind) {
7614   UnaryOperatorKind Opc;
7615   switch (Kind) {
7616   default: llvm_unreachable("Unknown unary op!");
7617   case tok::plusplus:     Opc = UO_PreInc; break;
7618   case tok::minusminus:   Opc = UO_PreDec; break;
7619   case tok::amp:          Opc = UO_AddrOf; break;
7620   case tok::star:         Opc = UO_Deref; break;
7621   case tok::plus:         Opc = UO_Plus; break;
7622   case tok::minus:        Opc = UO_Minus; break;
7623   case tok::tilde:        Opc = UO_Not; break;
7624   case tok::exclaim:      Opc = UO_LNot; break;
7625   case tok::kw___real:    Opc = UO_Real; break;
7626   case tok::kw___imag:    Opc = UO_Imag; break;
7627   case tok::kw___extension__: Opc = UO_Extension; break;
7628   }
7629   return Opc;
7630 }
7631
7632 /// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7633 /// This warning is only emitted for builtin assignment operations. It is also
7634 /// suppressed in the event of macro expansions.
7635 static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
7636                                    SourceLocation OpLoc) {
7637   if (!S.ActiveTemplateInstantiations.empty())
7638     return;
7639   if (OpLoc.isInvalid() || OpLoc.isMacroID())
7640     return;
7641   LHSExpr = LHSExpr->IgnoreParenImpCasts();
7642   RHSExpr = RHSExpr->IgnoreParenImpCasts();
7643   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7644   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7645   if (!LHSDeclRef || !RHSDeclRef ||
7646       LHSDeclRef->getLocation().isMacroID() ||
7647       RHSDeclRef->getLocation().isMacroID())
7648     return;
7649   const ValueDecl *LHSDecl =
7650     cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7651   const ValueDecl *RHSDecl =
7652     cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7653   if (LHSDecl != RHSDecl)
7654     return;
7655   if (LHSDecl->getType().isVolatileQualified())
7656     return;
7657   if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
7658     if (RefTy->getPointeeType().isVolatileQualified())
7659       return;
7660
7661   S.Diag(OpLoc, diag::warn_self_assignment)
7662       << LHSDeclRef->getType()
7663       << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
7664 }
7665
7666 /// CreateBuiltinBinOp - Creates a new built-in binary operation with
7667 /// operator @p Opc at location @c TokLoc. This routine only supports
7668 /// built-in operations; ActOnBinOp handles overloaded operators.
7669 ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
7670                                     BinaryOperatorKind Opc,
7671                                     Expr *LHSExpr, Expr *RHSExpr) {
7672   ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
7673   QualType ResultTy;     // Result type of the binary operator.
7674   // The following two variables are used for compound assignment operators
7675   QualType CompLHSTy;    // Type of LHS after promotions for computation
7676   QualType CompResultTy; // Type of computation result
7677   ExprValueKind VK = VK_RValue;
7678   ExprObjectKind OK = OK_Ordinary;
7679
7680   // Check if a 'foo<int>' involved in a binary op, identifies a single 
7681   // function unambiguously (i.e. an lvalue ala 13.4)
7682   // But since an assignment can trigger target based overload, exclude it in 
7683   // our blind search. i.e:
7684   // template<class T> void f(); template<class T, class U> void f(U);
7685   // f<int> == 0;  // resolve f<int> blindly
7686   // void (*p)(int); p = f<int>;  // resolve f<int> using target
7687   if (Opc != BO_Assign) { 
7688     ExprResult resolvedLHS = CheckPlaceholderExpr(LHS.get());
7689     if (!resolvedLHS.isUsable()) return ExprError();
7690     LHS = move(resolvedLHS);
7691
7692     ExprResult resolvedRHS = CheckPlaceholderExpr(RHS.get());
7693     if (!resolvedRHS.isUsable()) return ExprError();
7694     RHS = move(resolvedRHS);
7695   }
7696
7697   switch (Opc) {
7698   case BO_Assign:
7699     ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
7700     if (getLangOptions().CPlusPlus &&
7701         LHS.get()->getObjectKind() != OK_ObjCProperty) {
7702       VK = LHS.get()->getValueKind();
7703       OK = LHS.get()->getObjectKind();
7704     }
7705     if (!ResultTy.isNull())
7706       DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
7707     break;
7708   case BO_PtrMemD:
7709   case BO_PtrMemI:
7710     ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
7711                                             Opc == BO_PtrMemI);
7712     break;
7713   case BO_Mul:
7714   case BO_Div:
7715     ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
7716                                            Opc == BO_Div);
7717     break;
7718   case BO_Rem:
7719     ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
7720     break;
7721   case BO_Add:
7722     ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc);
7723     break;
7724   case BO_Sub:
7725     ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
7726     break;
7727   case BO_Shl:
7728   case BO_Shr:
7729     ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
7730     break;
7731   case BO_LE:
7732   case BO_LT:
7733   case BO_GE:
7734   case BO_GT:
7735     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
7736     break;
7737   case BO_EQ:
7738   case BO_NE:
7739     ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
7740     break;
7741   case BO_And:
7742   case BO_Xor:
7743   case BO_Or:
7744     ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
7745     break;
7746   case BO_LAnd:
7747   case BO_LOr:
7748     ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
7749     break;
7750   case BO_MulAssign:
7751   case BO_DivAssign:
7752     CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
7753                                                Opc == BO_DivAssign);
7754     CompLHSTy = CompResultTy;
7755     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7756       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7757     break;
7758   case BO_RemAssign:
7759     CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
7760     CompLHSTy = CompResultTy;
7761     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7762       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7763     break;
7764   case BO_AddAssign:
7765     CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7766     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7767       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7768     break;
7769   case BO_SubAssign:
7770     CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7771     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7772       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7773     break;
7774   case BO_ShlAssign:
7775   case BO_ShrAssign:
7776     CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
7777     CompLHSTy = CompResultTy;
7778     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7779       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7780     break;
7781   case BO_AndAssign:
7782   case BO_XorAssign:
7783   case BO_OrAssign:
7784     CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
7785     CompLHSTy = CompResultTy;
7786     if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7787       ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
7788     break;
7789   case BO_Comma:
7790     ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7791     if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7792       VK = RHS.get()->getValueKind();
7793       OK = RHS.get()->getObjectKind();
7794     }
7795     break;
7796   }
7797   if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
7798     return ExprError();
7799
7800   // Check for array bounds violations for both sides of the BinaryOperator
7801   CheckArrayAccess(LHS.get());
7802   CheckArrayAccess(RHS.get());
7803
7804   if (CompResultTy.isNull())
7805     return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
7806                                               ResultTy, VK, OK, OpLoc));
7807   if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
7808       OK_ObjCProperty) {
7809     VK = VK_LValue;
7810     OK = LHS.get()->getObjectKind();
7811   }
7812   return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
7813                                                     ResultTy, VK, OK, CompLHSTy,
7814                                                     CompResultTy, OpLoc));
7815 }
7816
7817 /// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7818 /// operators are mixed in a way that suggests that the programmer forgot that
7819 /// comparison operators have higher precedence. The most typical example of
7820 /// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
7821 static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
7822                                       SourceLocation OpLoc, Expr *LHSExpr,
7823                                       Expr *RHSExpr) {
7824   typedef BinaryOperator BinOp;
7825   BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7826                 RHSopc = static_cast<BinOp::Opcode>(-1);
7827   if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7828     LHSopc = BO->getOpcode();
7829   if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7830     RHSopc = BO->getOpcode();
7831
7832   // Subs are not binary operators.
7833   if (LHSopc == -1 && RHSopc == -1)
7834     return;
7835
7836   // Bitwise operations are sometimes used as eager logical ops.
7837   // Don't diagnose this.
7838   if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7839       (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
7840     return;
7841
7842   bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7843   bool isRightComp = BinOp::isComparisonOp(RHSopc);
7844   if (!isLeftComp && !isRightComp) return;
7845
7846   SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7847                                                    OpLoc)
7848                                      : SourceRange(OpLoc, RHSExpr->getLocEnd());
7849   std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7850                                  : BinOp::getOpcodeStr(RHSopc);
7851   SourceRange ParensRange = isLeftComp ?
7852       SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7853                   RHSExpr->getLocEnd())
7854     : SourceRange(LHSExpr->getLocStart(),
7855                   cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
7856
7857   Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7858     << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7859   SuggestParentheses(Self, OpLoc,
7860     Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
7861     RHSExpr->getSourceRange());
7862   SuggestParentheses(Self, OpLoc,
7863     Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7864     ParensRange);
7865 }
7866
7867 /// \brief It accepts a '&' expr that is inside a '|' one.
7868 /// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7869 /// in parentheses.
7870 static void
7871 EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7872                                        BinaryOperator *Bop) {
7873   assert(Bop->getOpcode() == BO_And);
7874   Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7875       << Bop->getSourceRange() << OpLoc;
7876   SuggestParentheses(Self, Bop->getOperatorLoc(),
7877     Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7878     Bop->getSourceRange());
7879 }
7880
7881 /// \brief It accepts a '&&' expr that is inside a '||' one.
7882 /// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7883 /// in parentheses.
7884 static void
7885 EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
7886                                        BinaryOperator *Bop) {
7887   assert(Bop->getOpcode() == BO_LAnd);
7888   Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7889       << Bop->getSourceRange() << OpLoc;
7890   SuggestParentheses(Self, Bop->getOperatorLoc(),
7891     Self.PDiag(diag::note_logical_and_in_logical_or_silence),
7892     Bop->getSourceRange());
7893 }
7894
7895 /// \brief Returns true if the given expression can be evaluated as a constant
7896 /// 'true'.
7897 static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7898   bool Res;
7899   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7900 }
7901
7902 /// \brief Returns true if the given expression can be evaluated as a constant
7903 /// 'false'.
7904 static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7905   bool Res;
7906   return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7907 }
7908
7909 /// \brief Look for '&&' in the left hand of a '||' expr.
7910 static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
7911                                              Expr *LHSExpr, Expr *RHSExpr) {
7912   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
7913     if (Bop->getOpcode() == BO_LAnd) {
7914       // If it's "a && b || 0" don't warn since the precedence doesn't matter.
7915       if (EvaluatesAsFalse(S, RHSExpr))
7916         return;
7917       // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7918       if (!EvaluatesAsTrue(S, Bop->getLHS()))
7919         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7920     } else if (Bop->getOpcode() == BO_LOr) {
7921       if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7922         // If it's "a || b && 1 || c" we didn't warn earlier for
7923         // "a || b && 1", but warn now.
7924         if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7925           return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7926       }
7927     }
7928   }
7929 }
7930
7931 /// \brief Look for '&&' in the right hand of a '||' expr.
7932 static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
7933                                              Expr *LHSExpr, Expr *RHSExpr) {
7934   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
7935     if (Bop->getOpcode() == BO_LAnd) {
7936       // If it's "0 || a && b" don't warn since the precedence doesn't matter.
7937       if (EvaluatesAsFalse(S, LHSExpr))
7938         return;
7939       // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7940       if (!EvaluatesAsTrue(S, Bop->getRHS()))
7941         return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7942     }
7943   }
7944 }
7945
7946 /// \brief Look for '&' in the left or right hand of a '|' expr.
7947 static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7948                                              Expr *OrArg) {
7949   if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7950     if (Bop->getOpcode() == BO_And)
7951       return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7952   }
7953 }
7954
7955 /// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
7956 /// precedence.
7957 static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
7958                                     SourceLocation OpLoc, Expr *LHSExpr,
7959                                     Expr *RHSExpr){
7960   // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
7961   if (BinaryOperator::isBitwiseOp(Opc))
7962     DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
7963
7964   // Diagnose "arg1 & arg2 | arg3"
7965   if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7966     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
7967     DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
7968   }
7969
7970   // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
7971   // We don't warn for 'assert(a || b && "bad")' since this is safe.
7972   if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
7973     DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
7974     DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
7975   }
7976 }
7977
7978 // Binary Operators.  'Tok' is the token for the operator.
7979 ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
7980                             tok::TokenKind Kind,
7981                             Expr *LHSExpr, Expr *RHSExpr) {
7982   BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
7983   assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
7984   assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
7985
7986   // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
7987   DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
7988
7989   return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
7990 }
7991
7992 ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
7993                             BinaryOperatorKind Opc,
7994                             Expr *LHSExpr, Expr *RHSExpr) {
7995   if (getLangOptions().CPlusPlus) {
7996     bool UseBuiltinOperator;
7997
7998     if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent()) {
7999       UseBuiltinOperator = false;
8000     } else if (Opc == BO_Assign &&
8001                LHSExpr->getObjectKind() == OK_ObjCProperty) {
8002       UseBuiltinOperator = true;
8003     } else {
8004       UseBuiltinOperator = !LHSExpr->getType()->isOverloadableType() &&
8005                            !RHSExpr->getType()->isOverloadableType();
8006     }
8007
8008     if (!UseBuiltinOperator) {
8009       // Find all of the overloaded operators visible from this
8010       // point. We perform both an operator-name lookup from the local
8011       // scope and an argument-dependent lookup based on the types of
8012       // the arguments.
8013       UnresolvedSet<16> Functions;
8014       OverloadedOperatorKind OverOp
8015         = BinaryOperator::getOverloadedOperator(Opc);
8016       if (S && OverOp != OO_None)
8017         LookupOverloadedOperatorName(OverOp, S, LHSExpr->getType(),
8018                                      RHSExpr->getType(), Functions);
8019
8020       // Build the (potentially-overloaded, potentially-dependent)
8021       // binary operation.
8022       return CreateOverloadedBinOp(OpLoc, Opc, Functions, LHSExpr, RHSExpr);
8023     }
8024   }
8025
8026   // Build a built-in binary operation.
8027   return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
8028 }
8029
8030 ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
8031                                       UnaryOperatorKind Opc,
8032                                       Expr *InputExpr) {
8033   ExprResult Input = Owned(InputExpr);
8034   ExprValueKind VK = VK_RValue;
8035   ExprObjectKind OK = OK_Ordinary;
8036   QualType resultType;
8037   switch (Opc) {
8038   case UO_PreInc:
8039   case UO_PreDec:
8040   case UO_PostInc:
8041   case UO_PostDec:
8042     resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
8043                                                 Opc == UO_PreInc ||
8044                                                 Opc == UO_PostInc,
8045                                                 Opc == UO_PreInc ||
8046                                                 Opc == UO_PreDec);
8047     break;
8048   case UO_AddrOf:
8049     resultType = CheckAddressOfOperand(*this, Input.get(), OpLoc);
8050     break;
8051   case UO_Deref: {
8052     ExprResult resolved = CheckPlaceholderExpr(Input.get());
8053     if (!resolved.isUsable()) return ExprError();
8054     Input = move(resolved);
8055     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8056     resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
8057     break;
8058   }
8059   case UO_Plus:
8060   case UO_Minus:
8061     Input = UsualUnaryConversions(Input.take());
8062     if (Input.isInvalid()) return ExprError();
8063     resultType = Input.get()->getType();
8064     if (resultType->isDependentType())
8065       break;
8066     if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8067         resultType->isVectorType()) 
8068       break;
8069     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8070              resultType->isEnumeralType())
8071       break;
8072     else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
8073              Opc == UO_Plus &&
8074              resultType->isPointerType())
8075       break;
8076     else if (resultType->isPlaceholderType()) {
8077       Input = CheckPlaceholderExpr(Input.take());
8078       if (Input.isInvalid()) return ExprError();
8079       return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
8080     }
8081
8082     return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8083       << resultType << Input.get()->getSourceRange());
8084
8085   case UO_Not: // bitwise complement
8086     Input = UsualUnaryConversions(Input.take());
8087     if (Input.isInvalid()) return ExprError();
8088     resultType = Input.get()->getType();
8089     if (resultType->isDependentType())
8090       break;
8091     // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8092     if (resultType->isComplexType() || resultType->isComplexIntegerType())
8093       // C99 does not support '~' for complex conjugation.
8094       Diag(OpLoc, diag::ext_integer_complement_complex)
8095         << resultType << Input.get()->getSourceRange();
8096     else if (resultType->hasIntegerRepresentation())
8097       break;
8098     else if (resultType->isPlaceholderType()) {
8099       Input = CheckPlaceholderExpr(Input.take());
8100       if (Input.isInvalid()) return ExprError();
8101       return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
8102     } else {
8103       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8104         << resultType << Input.get()->getSourceRange());
8105     }
8106     break;
8107
8108   case UO_LNot: // logical negation
8109     // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
8110     Input = DefaultFunctionArrayLvalueConversion(Input.take());
8111     if (Input.isInvalid()) return ExprError();
8112     resultType = Input.get()->getType();
8113
8114     // Though we still have to promote half FP to float...
8115     if (resultType->isHalfType()) {
8116       Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8117       resultType = Context.FloatTy;
8118     }
8119
8120     if (resultType->isDependentType())
8121       break;
8122     if (resultType->isScalarType()) {
8123       // C99 6.5.3.3p1: ok, fallthrough;
8124       if (Context.getLangOptions().CPlusPlus) {
8125         // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8126         // operand contextually converted to bool.
8127         Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8128                                   ScalarTypeToBooleanCastKind(resultType));
8129       }
8130     } else if (resultType->isPlaceholderType()) {
8131       Input = CheckPlaceholderExpr(Input.take());
8132       if (Input.isInvalid()) return ExprError();
8133       return CreateBuiltinUnaryOp(OpLoc, Opc, Input.take());
8134     } else {
8135       return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
8136         << resultType << Input.get()->getSourceRange());
8137     }
8138     
8139     // LNot always has type int. C99 6.5.3.3p5.
8140     // In C++, it's bool. C++ 5.3.1p8
8141     resultType = Context.getLogicalOperationType();
8142     break;
8143   case UO_Real:
8144   case UO_Imag:
8145     resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
8146     // _Real and _Imag map ordinary l-values into ordinary l-values.
8147     if (Input.isInvalid()) return ExprError();
8148     if (Input.get()->getValueKind() != VK_RValue &&
8149         Input.get()->getObjectKind() == OK_Ordinary)
8150       VK = Input.get()->getValueKind();
8151     break;
8152   case UO_Extension:
8153     resultType = Input.get()->getType();
8154     VK = Input.get()->getValueKind();
8155     OK = Input.get()->getObjectKind();
8156     break;
8157   }
8158   if (resultType.isNull() || Input.isInvalid())
8159     return ExprError();
8160
8161   // Check for array bounds violations in the operand of the UnaryOperator,
8162   // except for the '*' and '&' operators that have to be handled specially
8163   // by CheckArrayAccess (as there are special cases like &array[arraysize]
8164   // that are explicitly defined as valid by the standard).
8165   if (Opc != UO_AddrOf && Opc != UO_Deref)
8166     CheckArrayAccess(Input.get());
8167
8168   return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
8169                                            VK, OK, OpLoc));
8170 }
8171
8172 ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
8173                               UnaryOperatorKind Opc, Expr *Input) {
8174   if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
8175       UnaryOperator::getOverloadedOperator(Opc) != OO_None) {
8176     // Find all of the overloaded operators visible from this
8177     // point. We perform both an operator-name lookup from the local
8178     // scope and an argument-dependent lookup based on the types of
8179     // the arguments.
8180     UnresolvedSet<16> Functions;
8181     OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
8182     if (S && OverOp != OO_None)
8183       LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8184                                    Functions);
8185
8186     return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
8187   }
8188
8189   return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8190 }
8191
8192 // Unary Operators.  'Tok' is the token for the operator.
8193 ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
8194                               tok::TokenKind Op, Expr *Input) {
8195   return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
8196 }
8197
8198 /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
8199 ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
8200                                 LabelDecl *TheDecl) {
8201   TheDecl->setUsed();
8202   // Create the AST node.  The address of a label always has type 'void*'.
8203   return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
8204                                        Context.getPointerType(Context.VoidTy)));
8205 }
8206
8207 /// Given the last statement in a statement-expression, check whether
8208 /// the result is a producing expression (like a call to an
8209 /// ns_returns_retained function) and, if so, rebuild it to hoist the
8210 /// release out of the full-expression.  Otherwise, return null.
8211 /// Cannot fail.
8212 static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
8213   // Should always be wrapped with one of these.
8214   ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
8215   if (!cleanups) return 0;
8216
8217   ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
8218   if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
8219     return 0;
8220
8221   // Splice out the cast.  This shouldn't modify any interesting
8222   // features of the statement.
8223   Expr *producer = cast->getSubExpr();
8224   assert(producer->getType() == cast->getType());
8225   assert(producer->getValueKind() == cast->getValueKind());
8226   cleanups->setSubExpr(producer);
8227   return cleanups;
8228 }
8229
8230 ExprResult
8231 Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
8232                     SourceLocation RPLoc) { // "({..})"
8233   assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8234   CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8235
8236   bool isFileScope
8237     = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
8238   if (isFileScope)
8239     return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
8240
8241   // FIXME: there are a variety of strange constraints to enforce here, for
8242   // example, it is not possible to goto into a stmt expression apparently.
8243   // More semantic analysis is needed.
8244
8245   // If there are sub stmts in the compound stmt, take the type of the last one
8246   // as the type of the stmtexpr.
8247   QualType Ty = Context.VoidTy;
8248   bool StmtExprMayBindToTemp = false;
8249   if (!Compound->body_empty()) {
8250     Stmt *LastStmt = Compound->body_back();
8251     LabelStmt *LastLabelStmt = 0;
8252     // If LastStmt is a label, skip down through into the body.
8253     while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8254       LastLabelStmt = Label;
8255       LastStmt = Label->getSubStmt();
8256     }
8257
8258     if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
8259       // Do function/array conversion on the last expression, but not
8260       // lvalue-to-rvalue.  However, initialize an unqualified type.
8261       ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8262       if (LastExpr.isInvalid())
8263         return ExprError();
8264       Ty = LastExpr.get()->getType().getUnqualifiedType();
8265
8266       if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
8267         // In ARC, if the final expression ends in a consume, splice
8268         // the consume out and bind it later.  In the alternate case
8269         // (when dealing with a retainable type), the result
8270         // initialization will create a produce.  In both cases the
8271         // result will be +1, and we'll need to balance that out with
8272         // a bind.
8273         if (Expr *rebuiltLastStmt
8274               = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8275           LastExpr = rebuiltLastStmt;
8276         } else {
8277           LastExpr = PerformCopyInitialization(
8278                             InitializedEntity::InitializeResult(LPLoc, 
8279                                                                 Ty,
8280                                                                 false),
8281                                                    SourceLocation(),
8282                                                LastExpr);
8283         }
8284
8285         if (LastExpr.isInvalid())
8286           return ExprError();
8287         if (LastExpr.get() != 0) {
8288           if (!LastLabelStmt)
8289             Compound->setLastStmt(LastExpr.take());
8290           else
8291             LastLabelStmt->setSubStmt(LastExpr.take());
8292           StmtExprMayBindToTemp = true;
8293         }
8294       }
8295     }
8296   }
8297
8298   // FIXME: Check that expression type is complete/non-abstract; statement
8299   // expressions are not lvalues.
8300   Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8301   if (StmtExprMayBindToTemp)
8302     return MaybeBindToTemporary(ResStmtExpr);
8303   return Owned(ResStmtExpr);
8304 }
8305
8306 ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
8307                                       TypeSourceInfo *TInfo,
8308                                       OffsetOfComponent *CompPtr,
8309                                       unsigned NumComponents,
8310                                       SourceLocation RParenLoc) {
8311   QualType ArgTy = TInfo->getType();
8312   bool Dependent = ArgTy->isDependentType();
8313   SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
8314   
8315   // We must have at least one component that refers to the type, and the first
8316   // one is known to be a field designator.  Verify that the ArgTy represents
8317   // a struct/union/class.
8318   if (!Dependent && !ArgTy->isRecordType())
8319     return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type) 
8320                        << ArgTy << TypeRange);
8321   
8322   // Type must be complete per C99 7.17p3 because a declaring a variable
8323   // with an incomplete type would be ill-formed.
8324   if (!Dependent 
8325       && RequireCompleteType(BuiltinLoc, ArgTy,
8326                              PDiag(diag::err_offsetof_incomplete_type)
8327                                << TypeRange))
8328     return ExprError();
8329   
8330   // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8331   // GCC extension, diagnose them.
8332   // FIXME: This diagnostic isn't actually visible because the location is in
8333   // a system header!
8334   if (NumComponents != 1)
8335     Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8336       << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
8337   
8338   bool DidWarnAboutNonPOD = false;
8339   QualType CurrentType = ArgTy;
8340   typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
8341   SmallVector<OffsetOfNode, 4> Comps;
8342   SmallVector<Expr*, 4> Exprs;
8343   for (unsigned i = 0; i != NumComponents; ++i) {
8344     const OffsetOfComponent &OC = CompPtr[i];
8345     if (OC.isBrackets) {
8346       // Offset of an array sub-field.  TODO: Should we allow vector elements?
8347       if (!CurrentType->isDependentType()) {
8348         const ArrayType *AT = Context.getAsArrayType(CurrentType);
8349         if(!AT)
8350           return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8351                            << CurrentType);
8352         CurrentType = AT->getElementType();
8353       } else
8354         CurrentType = Context.DependentTy;
8355       
8356       // The expression must be an integral expression.
8357       // FIXME: An integral constant expression?
8358       Expr *Idx = static_cast<Expr*>(OC.U.E);
8359       if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8360           !Idx->getType()->isIntegerType())
8361         return ExprError(Diag(Idx->getLocStart(),
8362                               diag::err_typecheck_subscript_not_integer)
8363                          << Idx->getSourceRange());
8364       
8365       // Record this array index.
8366       Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
8367       Exprs.push_back(Idx);
8368       continue;
8369     }
8370     
8371     // Offset of a field.
8372     if (CurrentType->isDependentType()) {
8373       // We have the offset of a field, but we can't look into the dependent
8374       // type. Just record the identifier of the field.
8375       Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8376       CurrentType = Context.DependentTy;
8377       continue;
8378     }
8379     
8380     // We need to have a complete type to look into.
8381     if (RequireCompleteType(OC.LocStart, CurrentType,
8382                             diag::err_offsetof_incomplete_type))
8383       return ExprError();
8384     
8385     // Look for the designated field.
8386     const RecordType *RC = CurrentType->getAs<RecordType>();
8387     if (!RC) 
8388       return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8389                        << CurrentType);
8390     RecordDecl *RD = RC->getDecl();
8391     
8392     // C++ [lib.support.types]p5:
8393     //   The macro offsetof accepts a restricted set of type arguments in this
8394     //   International Standard. type shall be a POD structure or a POD union
8395     //   (clause 9).
8396     if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8397       if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
8398           DiagRuntimeBehavior(BuiltinLoc, 0,
8399                               PDiag(diag::warn_offsetof_non_pod_type)
8400                               << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8401                               << CurrentType))
8402         DidWarnAboutNonPOD = true;
8403     }
8404     
8405     // Look for the field.
8406     LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8407     LookupQualifiedName(R, RD);
8408     FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
8409     IndirectFieldDecl *IndirectMemberDecl = 0;
8410     if (!MemberDecl) {
8411       if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
8412         MemberDecl = IndirectMemberDecl->getAnonField();
8413     }
8414
8415     if (!MemberDecl)
8416       return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8417                        << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, 
8418                                                               OC.LocEnd));
8419     
8420     // C99 7.17p3:
8421     //   (If the specified member is a bit-field, the behavior is undefined.)
8422     //
8423     // We diagnose this as an error.
8424     if (MemberDecl->isBitField()) {
8425       Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8426         << MemberDecl->getDeclName()
8427         << SourceRange(BuiltinLoc, RParenLoc);
8428       Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8429       return ExprError();
8430     }
8431
8432     RecordDecl *Parent = MemberDecl->getParent();
8433     if (IndirectMemberDecl)
8434       Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
8435
8436     // If the member was found in a base class, introduce OffsetOfNodes for
8437     // the base class indirections.
8438     CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8439                        /*DetectVirtual=*/false);
8440     if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
8441       CXXBasePath &Path = Paths.front();
8442       for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8443            B != BEnd; ++B)
8444         Comps.push_back(OffsetOfNode(B->Base));
8445     }
8446
8447     if (IndirectMemberDecl) {
8448       for (IndirectFieldDecl::chain_iterator FI =
8449            IndirectMemberDecl->chain_begin(),
8450            FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8451         assert(isa<FieldDecl>(*FI));
8452         Comps.push_back(OffsetOfNode(OC.LocStart,
8453                                      cast<FieldDecl>(*FI), OC.LocEnd));
8454       }
8455     } else
8456       Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
8457
8458     CurrentType = MemberDecl->getType().getNonReferenceType(); 
8459   }
8460   
8461   return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc, 
8462                                     TInfo, Comps.data(), Comps.size(),
8463                                     Exprs.data(), Exprs.size(), RParenLoc));  
8464 }
8465
8466 ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
8467                                       SourceLocation BuiltinLoc,
8468                                       SourceLocation TypeLoc,
8469                                       ParsedType ParsedArgTy,
8470                                       OffsetOfComponent *CompPtr,
8471                                       unsigned NumComponents,
8472                                       SourceLocation RParenLoc) {
8473   
8474   TypeSourceInfo *ArgTInfo;
8475   QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
8476   if (ArgTy.isNull())
8477     return ExprError();
8478
8479   if (!ArgTInfo)
8480     ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8481
8482   return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents, 
8483                               RParenLoc);
8484 }
8485
8486
8487 ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
8488                                  Expr *CondExpr,
8489                                  Expr *LHSExpr, Expr *RHSExpr,
8490                                  SourceLocation RPLoc) {
8491   assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8492
8493   ExprValueKind VK = VK_RValue;
8494   ExprObjectKind OK = OK_Ordinary;
8495   QualType resType;
8496   bool ValueDependent = false;
8497   if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
8498     resType = Context.DependentTy;
8499     ValueDependent = true;
8500   } else {
8501     // The conditional expression is required to be a constant expression.
8502     llvm::APSInt condEval(32);
8503     SourceLocation ExpLoc;
8504     if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
8505       return ExprError(Diag(ExpLoc,
8506                        diag::err_typecheck_choose_expr_requires_constant)
8507         << CondExpr->getSourceRange());
8508
8509     // If the condition is > zero, then the AST type is the same as the LSHExpr.
8510     Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8511
8512     resType = ActiveExpr->getType();
8513     ValueDependent = ActiveExpr->isValueDependent();
8514     VK = ActiveExpr->getValueKind();
8515     OK = ActiveExpr->getObjectKind();
8516   }
8517
8518   return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
8519                                         resType, VK, OK, RPLoc,
8520                                         resType->isDependentType(),
8521                                         ValueDependent));
8522 }
8523
8524 //===----------------------------------------------------------------------===//
8525 // Clang Extensions.
8526 //===----------------------------------------------------------------------===//
8527
8528 /// ActOnBlockStart - This callback is invoked when a block literal is started.
8529 void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
8530   BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
8531   PushBlockScope(CurScope, Block);
8532   CurContext->addDecl(Block);
8533   if (CurScope)
8534     PushDeclContext(CurScope, Block);
8535   else
8536     CurContext = Block;
8537 }
8538
8539 void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
8540   assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
8541   assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
8542   BlockScopeInfo *CurBlock = getCurBlock();
8543
8544   TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
8545   QualType T = Sig->getType();
8546
8547   // GetTypeForDeclarator always produces a function type for a block
8548   // literal signature.  Furthermore, it is always a FunctionProtoType
8549   // unless the function was written with a typedef.
8550   assert(T->isFunctionType() &&
8551          "GetTypeForDeclarator made a non-function block signature");
8552
8553   // Look for an explicit signature in that function type.
8554   FunctionProtoTypeLoc ExplicitSignature;
8555
8556   TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8557   if (isa<FunctionProtoTypeLoc>(tmp)) {
8558     ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8559
8560     // Check whether that explicit signature was synthesized by
8561     // GetTypeForDeclarator.  If so, don't save that as part of the
8562     // written signature.
8563     if (ExplicitSignature.getLocalRangeBegin() ==
8564         ExplicitSignature.getLocalRangeEnd()) {
8565       // This would be much cheaper if we stored TypeLocs instead of
8566       // TypeSourceInfos.
8567       TypeLoc Result = ExplicitSignature.getResultLoc();
8568       unsigned Size = Result.getFullDataSize();
8569       Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8570       Sig->getTypeLoc().initializeFullCopy(Result, Size);
8571
8572       ExplicitSignature = FunctionProtoTypeLoc();
8573     }
8574   }
8575
8576   CurBlock->TheDecl->setSignatureAsWritten(Sig);
8577   CurBlock->FunctionType = T;
8578
8579   const FunctionType *Fn = T->getAs<FunctionType>();
8580   QualType RetTy = Fn->getResultType();
8581   bool isVariadic =
8582     (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8583
8584   CurBlock->TheDecl->setIsVariadic(isVariadic);
8585
8586   // Don't allow returning a objc interface by value.
8587   if (RetTy->isObjCObjectType()) {
8588     Diag(ParamInfo.getSourceRange().getBegin(),
8589          diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8590     return;
8591   }
8592
8593   // Context.DependentTy is used as a placeholder for a missing block
8594   // return type.  TODO:  what should we do with declarators like:
8595   //   ^ * { ... }
8596   // If the answer is "apply template argument deduction"....
8597   if (RetTy != Context.DependentTy)
8598     CurBlock->ReturnType = RetTy;
8599
8600   // Push block parameters from the declarator if we had them.
8601   SmallVector<ParmVarDecl*, 8> Params;
8602   if (ExplicitSignature) {
8603     for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8604       ParmVarDecl *Param = ExplicitSignature.getArg(I);
8605       if (Param->getIdentifier() == 0 &&
8606           !Param->isImplicit() &&
8607           !Param->isInvalidDecl() &&
8608           !getLangOptions().CPlusPlus)
8609         Diag(Param->getLocation(), diag::err_parameter_name_omitted);
8610       Params.push_back(Param);
8611     }
8612
8613   // Fake up parameter variables if we have a typedef, like
8614   //   ^ fntype { ... }
8615   } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8616     for (FunctionProtoType::arg_type_iterator
8617            I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8618       ParmVarDecl *Param =
8619         BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8620                                    ParamInfo.getSourceRange().getBegin(),
8621                                    *I);
8622       Params.push_back(Param);
8623     }
8624   }
8625
8626   // Set the parameters on the block decl.
8627   if (!Params.empty()) {
8628     CurBlock->TheDecl->setParams(Params);
8629     CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8630                              CurBlock->TheDecl->param_end(),
8631                              /*CheckParameterNames=*/false);
8632   }
8633   
8634   // Finally we can process decl attributes.
8635   ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
8636
8637   if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
8638     Diag(ParamInfo.getAttributes()->getLoc(),
8639          diag::warn_attribute_sentinel_not_variadic) << 1;
8640     // FIXME: remove the attribute.
8641   }
8642
8643   // Put the parameter variables in scope.  We can bail out immediately
8644   // if we don't have any.
8645   if (Params.empty())
8646     return;
8647
8648   for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
8649          E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8650     (*AI)->setOwningFunction(CurBlock->TheDecl);
8651
8652     // If this has an identifier, add it to the scope stack.
8653     if ((*AI)->getIdentifier()) {
8654       CheckShadow(CurBlock->TheScope, *AI);
8655
8656       PushOnScopeChains(*AI, CurBlock->TheScope);
8657     }
8658   }
8659 }
8660
8661 /// ActOnBlockError - If there is an error parsing a block, this callback
8662 /// is invoked to pop the information about the block from the action impl.
8663 void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
8664   // Pop off CurBlock, handle nested blocks.
8665   PopDeclContext();
8666   PopFunctionOrBlockScope();
8667 }
8668
8669 /// ActOnBlockStmtExpr - This is called when the body of a block statement
8670 /// literal was successfully completed.  ^(int x){...}
8671 ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
8672                                     Stmt *Body, Scope *CurScope) {
8673   // If blocks are disabled, emit an error.
8674   if (!LangOpts.Blocks)
8675     Diag(CaretLoc, diag::err_blocks_disable);
8676
8677   BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
8678   
8679   PopDeclContext();
8680
8681   QualType RetTy = Context.VoidTy;
8682   if (!BSI->ReturnType.isNull())
8683     RetTy = BSI->ReturnType;
8684
8685   bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
8686   QualType BlockTy;
8687
8688   // Set the captured variables on the block.
8689   BSI->TheDecl->setCaptures(Context, BSI->Captures.begin(), BSI->Captures.end(),
8690                             BSI->CapturesCXXThis);
8691
8692   // If the user wrote a function type in some form, try to use that.
8693   if (!BSI->FunctionType.isNull()) {
8694     const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8695
8696     FunctionType::ExtInfo Ext = FTy->getExtInfo();
8697     if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8698     
8699     // Turn protoless block types into nullary block types.
8700     if (isa<FunctionNoProtoType>(FTy)) {
8701       FunctionProtoType::ExtProtoInfo EPI;
8702       EPI.ExtInfo = Ext;
8703       BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8704
8705     // Otherwise, if we don't need to change anything about the function type,
8706     // preserve its sugar structure.
8707     } else if (FTy->getResultType() == RetTy &&
8708                (!NoReturn || FTy->getNoReturnAttr())) {
8709       BlockTy = BSI->FunctionType;
8710
8711     // Otherwise, make the minimal modifications to the function type.
8712     } else {
8713       const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
8714       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8715       EPI.TypeQuals = 0; // FIXME: silently?
8716       EPI.ExtInfo = Ext;
8717       BlockTy = Context.getFunctionType(RetTy,
8718                                         FPT->arg_type_begin(),
8719                                         FPT->getNumArgs(),
8720                                         EPI);
8721     }
8722
8723   // If we don't have a function type, just build one from nothing.
8724   } else {
8725     FunctionProtoType::ExtProtoInfo EPI;
8726     EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
8727     BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
8728   }
8729
8730   DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8731                            BSI->TheDecl->param_end());
8732   BlockTy = Context.getBlockPointerType(BlockTy);
8733
8734   // If needed, diagnose invalid gotos and switches in the block.
8735   if (getCurFunction()->NeedsScopeChecking() &&
8736       !hasAnyUnrecoverableErrorsInThisFunction())
8737     DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
8738
8739   BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
8740
8741   for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8742        ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8743     const VarDecl *variable = ci->getVariable();
8744     QualType T = variable->getType();
8745     QualType::DestructionKind destructKind = T.isDestructedType();
8746     if (destructKind != QualType::DK_none)
8747       getCurFunction()->setHasBranchProtectedScope();
8748   }
8749
8750   computeNRVO(Body, getCurBlock());
8751   
8752   BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8753   const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
8754   PopFunctionOrBlockScope(&WP, Result->getBlockDecl(), Result);
8755
8756   return Owned(Result);
8757 }
8758
8759 ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
8760                                         Expr *E, ParsedType Ty,
8761                                         SourceLocation RPLoc) {
8762   TypeSourceInfo *TInfo;
8763   GetTypeFromParser(Ty, &TInfo);
8764   return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
8765 }
8766
8767 ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
8768                                 Expr *E, TypeSourceInfo *TInfo,
8769                                 SourceLocation RPLoc) {
8770   Expr *OrigExpr = E;
8771
8772   // Get the va_list type
8773   QualType VaListType = Context.getBuiltinVaListType();
8774   if (VaListType->isArrayType()) {
8775     // Deal with implicit array decay; for example, on x86-64,
8776     // va_list is an array, but it's supposed to decay to
8777     // a pointer for va_arg.
8778     VaListType = Context.getArrayDecayedType(VaListType);
8779     // Make sure the input expression also decays appropriately.
8780     ExprResult Result = UsualUnaryConversions(E);
8781     if (Result.isInvalid())
8782       return ExprError();
8783     E = Result.take();
8784   } else {
8785     // Otherwise, the va_list argument must be an l-value because
8786     // it is modified by va_arg.
8787     if (!E->isTypeDependent() &&
8788         CheckForModifiableLvalue(E, BuiltinLoc, *this))
8789       return ExprError();
8790   }
8791
8792   if (!E->isTypeDependent() &&
8793       !Context.hasSameType(VaListType, E->getType())) {
8794     return ExprError(Diag(E->getLocStart(),
8795                          diag::err_first_argument_to_va_arg_not_of_type_va_list)
8796       << OrigExpr->getType() << E->getSourceRange());
8797   }
8798
8799   if (!TInfo->getType()->isDependentType()) {
8800     if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
8801           PDiag(diag::err_second_parameter_to_va_arg_incomplete)
8802           << TInfo->getTypeLoc().getSourceRange()))
8803       return ExprError();
8804
8805     if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
8806           TInfo->getType(),
8807           PDiag(diag::err_second_parameter_to_va_arg_abstract)
8808           << TInfo->getTypeLoc().getSourceRange()))
8809       return ExprError();
8810
8811     if (!TInfo->getType().isPODType(Context)) {
8812       Diag(TInfo->getTypeLoc().getBeginLoc(),
8813            TInfo->getType()->isObjCLifetimeType()
8814              ? diag::warn_second_parameter_to_va_arg_ownership_qualified
8815              : diag::warn_second_parameter_to_va_arg_not_pod)
8816         << TInfo->getType()
8817         << TInfo->getTypeLoc().getSourceRange();
8818     }
8819
8820     // Check for va_arg where arguments of the given type will be promoted
8821     // (i.e. this va_arg is guaranteed to have undefined behavior).
8822     QualType PromoteType;
8823     if (TInfo->getType()->isPromotableIntegerType()) {
8824       PromoteType = Context.getPromotedIntegerType(TInfo->getType());
8825       if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
8826         PromoteType = QualType();
8827     }
8828     if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
8829       PromoteType = Context.DoubleTy;
8830     if (!PromoteType.isNull())
8831       Diag(TInfo->getTypeLoc().getBeginLoc(),
8832           diag::warn_second_parameter_to_va_arg_never_compatible)
8833         << TInfo->getType()
8834         << PromoteType
8835         << TInfo->getTypeLoc().getSourceRange();
8836   }
8837
8838   QualType T = TInfo->getType().getNonLValueExprType(Context);
8839   return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
8840 }
8841
8842 ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
8843   // The type of __null will be int or long, depending on the size of
8844   // pointers on the target.
8845   QualType Ty;
8846   unsigned pw = Context.getTargetInfo().getPointerWidth(0);
8847   if (pw == Context.getTargetInfo().getIntWidth())
8848     Ty = Context.IntTy;
8849   else if (pw == Context.getTargetInfo().getLongWidth())
8850     Ty = Context.LongTy;
8851   else if (pw == Context.getTargetInfo().getLongLongWidth())
8852     Ty = Context.LongLongTy;
8853   else {
8854     llvm_unreachable("I don't know size of pointer!");
8855   }
8856
8857   return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
8858 }
8859
8860 static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
8861                                            Expr *SrcExpr, FixItHint &Hint) {
8862   if (!SemaRef.getLangOptions().ObjC1)
8863     return;
8864
8865   const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
8866   if (!PT)
8867     return;
8868
8869   // Check if the destination is of type 'id'.
8870   if (!PT->isObjCIdType()) {
8871     // Check if the destination is the 'NSString' interface.
8872     const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
8873     if (!ID || !ID->getIdentifier()->isStr("NSString"))
8874       return;
8875   }
8876
8877   // Strip off any parens and casts.
8878   StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
8879   if (!SL || !SL->isAscii())
8880     return;
8881
8882   Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
8883 }
8884
8885 bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
8886                                     SourceLocation Loc,
8887                                     QualType DstType, QualType SrcType,
8888                                     Expr *SrcExpr, AssignmentAction Action,
8889                                     bool *Complained) {
8890   if (Complained)
8891     *Complained = false;
8892
8893   // Decode the result (notice that AST's are still created for extensions).
8894   bool CheckInferredResultType = false;
8895   bool isInvalid = false;
8896   unsigned DiagKind;
8897   FixItHint Hint;
8898   ConversionFixItGenerator ConvHints;
8899   bool MayHaveConvFixit = false;
8900
8901   switch (ConvTy) {
8902   default: llvm_unreachable("Unknown conversion type");
8903   case Compatible: return false;
8904   case PointerToInt:
8905     DiagKind = diag::ext_typecheck_convert_pointer_int;
8906     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8907     MayHaveConvFixit = true;
8908     break;
8909   case IntToPointer:
8910     DiagKind = diag::ext_typecheck_convert_int_pointer;
8911     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8912     MayHaveConvFixit = true;
8913     break;
8914   case IncompatiblePointer:
8915     MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
8916     DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
8917     CheckInferredResultType = DstType->isObjCObjectPointerType() &&
8918       SrcType->isObjCObjectPointerType();
8919     if (Hint.isNull() && !CheckInferredResultType) {
8920       ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8921     }
8922     MayHaveConvFixit = true;
8923     break;
8924   case IncompatiblePointerSign:
8925     DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
8926     break;
8927   case FunctionVoidPointer:
8928     DiagKind = diag::ext_typecheck_convert_pointer_void_func;
8929     break;
8930   case IncompatiblePointerDiscardsQualifiers: {
8931     // Perform array-to-pointer decay if necessary.
8932     if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
8933
8934     Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
8935     Qualifiers rhq = DstType->getPointeeType().getQualifiers();
8936     if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
8937       DiagKind = diag::err_typecheck_incompatible_address_space;
8938       break;
8939
8940
8941     } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
8942       DiagKind = diag::err_typecheck_incompatible_ownership;
8943       break;
8944     }
8945
8946     llvm_unreachable("unknown error case for discarding qualifiers!");
8947     // fallthrough
8948   }
8949   case CompatiblePointerDiscardsQualifiers:
8950     // If the qualifiers lost were because we were applying the
8951     // (deprecated) C++ conversion from a string literal to a char*
8952     // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
8953     // Ideally, this check would be performed in
8954     // checkPointerTypesForAssignment. However, that would require a
8955     // bit of refactoring (so that the second argument is an
8956     // expression, rather than a type), which should be done as part
8957     // of a larger effort to fix checkPointerTypesForAssignment for
8958     // C++ semantics.
8959     if (getLangOptions().CPlusPlus &&
8960         IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
8961       return false;
8962     DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
8963     break;
8964   case IncompatibleNestedPointerQualifiers:
8965     DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
8966     break;
8967   case IntToBlockPointer:
8968     DiagKind = diag::err_int_to_block_pointer;
8969     break;
8970   case IncompatibleBlockPointer:
8971     DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
8972     break;
8973   case IncompatibleObjCQualifiedId:
8974     // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
8975     // it can give a more specific diagnostic.
8976     DiagKind = diag::warn_incompatible_qualified_id;
8977     break;
8978   case IncompatibleVectors:
8979     DiagKind = diag::warn_incompatible_vectors;
8980     break;
8981   case IncompatibleObjCWeakRef:
8982     DiagKind = diag::err_arc_weak_unavailable_assign;
8983     break;
8984   case Incompatible:
8985     DiagKind = diag::err_typecheck_convert_incompatible;
8986     ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
8987     MayHaveConvFixit = true;
8988     isInvalid = true;
8989     break;
8990   }
8991
8992   QualType FirstType, SecondType;
8993   switch (Action) {
8994   case AA_Assigning:
8995   case AA_Initializing:
8996     // The destination type comes first.
8997     FirstType = DstType;
8998     SecondType = SrcType;
8999     break;
9000
9001   case AA_Returning:
9002   case AA_Passing:
9003   case AA_Converting:
9004   case AA_Sending:
9005   case AA_Casting:
9006     // The source type comes first.
9007     FirstType = SrcType;
9008     SecondType = DstType;
9009     break;
9010   }
9011
9012   PartialDiagnostic FDiag = PDiag(DiagKind);
9013   FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9014
9015   // If we can fix the conversion, suggest the FixIts.
9016   assert(ConvHints.isNull() || Hint.isNull());
9017   if (!ConvHints.isNull()) {
9018     for (llvm::SmallVector<FixItHint, 1>::iterator
9019         HI = ConvHints.Hints.begin(), HE = ConvHints.Hints.end();
9020         HI != HE; ++HI)
9021       FDiag << *HI;
9022   } else {
9023     FDiag << Hint;
9024   }
9025   if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9026
9027   Diag(Loc, FDiag);
9028
9029   if (CheckInferredResultType)
9030     EmitRelatedResultTypeNote(SrcExpr);
9031   
9032   if (Complained)
9033     *Complained = true;
9034   return isInvalid;
9035 }
9036
9037 bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
9038   llvm::APSInt ICEResult;
9039   if (E->isIntegerConstantExpr(ICEResult, Context)) {
9040     if (Result)
9041       *Result = ICEResult;
9042     return false;
9043   }
9044
9045   Expr::EvalResult EvalResult;
9046
9047   if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
9048       EvalResult.HasSideEffects) {
9049     Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
9050
9051     if (EvalResult.Diag) {
9052       // We only show the note if it's not the usual "invalid subexpression"
9053       // or if it's actually in a subexpression.
9054       if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
9055           E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
9056         Diag(EvalResult.DiagLoc, EvalResult.Diag);
9057     }
9058
9059     return true;
9060   }
9061
9062   Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
9063     E->getSourceRange();
9064
9065   if (EvalResult.Diag &&
9066       Diags.getDiagnosticLevel(diag::ext_expr_not_ice, EvalResult.DiagLoc)
9067           != DiagnosticsEngine::Ignored)
9068     Diag(EvalResult.DiagLoc, EvalResult.Diag);
9069
9070   if (Result)
9071     *Result = EvalResult.Val.getInt();
9072   return false;
9073 }
9074
9075 void
9076 Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
9077   ExprEvalContexts.push_back(
9078              ExpressionEvaluationContextRecord(NewContext,
9079                                                ExprTemporaries.size(),
9080                                                ExprNeedsCleanups));
9081   ExprNeedsCleanups = false;
9082 }
9083
9084 void Sema::PopExpressionEvaluationContext() {
9085   // Pop the current expression evaluation context off the stack.
9086   ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
9087   ExprEvalContexts.pop_back();
9088
9089   if (Rec.Context == PotentiallyPotentiallyEvaluated) {
9090     if (Rec.PotentiallyReferenced) {
9091       // Mark any remaining declarations in the current position of the stack
9092       // as "referenced". If they were not meant to be referenced, semantic
9093       // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
9094       for (PotentiallyReferencedDecls::iterator
9095              I = Rec.PotentiallyReferenced->begin(),
9096              IEnd = Rec.PotentiallyReferenced->end();
9097            I != IEnd; ++I)
9098         MarkDeclarationReferenced(I->first, I->second);
9099     }
9100
9101     if (Rec.PotentiallyDiagnosed) {
9102       // Emit any pending diagnostics.
9103       for (PotentiallyEmittedDiagnostics::iterator
9104                 I = Rec.PotentiallyDiagnosed->begin(),
9105              IEnd = Rec.PotentiallyDiagnosed->end();
9106            I != IEnd; ++I)
9107         Diag(I->first, I->second);
9108     }
9109   }
9110
9111   // When are coming out of an unevaluated context, clear out any
9112   // temporaries that we may have created as part of the evaluation of
9113   // the expression in that context: they aren't relevant because they
9114   // will never be constructed.
9115   if (Rec.Context == Unevaluated) {
9116     ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
9117                           ExprTemporaries.end());
9118     ExprNeedsCleanups = Rec.ParentNeedsCleanups;
9119
9120   // Otherwise, merge the contexts together.
9121   } else {
9122     ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
9123   }
9124
9125   // Destroy the popped expression evaluation record.
9126   Rec.Destroy();
9127 }
9128
9129 void Sema::DiscardCleanupsInEvaluationContext() {
9130   ExprTemporaries.erase(
9131               ExprTemporaries.begin() + ExprEvalContexts.back().NumTemporaries,
9132               ExprTemporaries.end());
9133   ExprNeedsCleanups = false;
9134 }
9135
9136 /// \brief Note that the given declaration was referenced in the source code.
9137 ///
9138 /// This routine should be invoke whenever a given declaration is referenced
9139 /// in the source code, and where that reference occurred. If this declaration
9140 /// reference means that the the declaration is used (C++ [basic.def.odr]p2,
9141 /// C99 6.9p3), then the declaration will be marked as used.
9142 ///
9143 /// \param Loc the location where the declaration was referenced.
9144 ///
9145 /// \param D the declaration that has been referenced by the source code.
9146 void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
9147   assert(D && "No declaration?");
9148
9149   D->setReferenced();
9150
9151   if (D->isUsed(false))
9152     return;
9153
9154   // Mark a parameter or variable declaration "used", regardless of whether
9155   // we're in a template or not. The reason for this is that unevaluated
9156   // expressions (e.g. (void)sizeof()) constitute a use for warning purposes
9157   // (-Wunused-variables and -Wunused-parameters)
9158   if (isa<ParmVarDecl>(D) ||
9159       (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
9160     D->setUsed();
9161     return;
9162   }
9163
9164   if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
9165     return;
9166
9167   // Do not mark anything as "used" within a dependent context; wait for
9168   // an instantiation.
9169   if (CurContext->isDependentContext())
9170     return;
9171
9172   switch (ExprEvalContexts.back().Context) {
9173     case Unevaluated:
9174       // We are in an expression that is not potentially evaluated; do nothing.
9175       return;
9176
9177     case PotentiallyEvaluated:
9178       // We are in a potentially-evaluated expression, so this declaration is
9179       // "used"; handle this below.
9180       break;
9181
9182     case PotentiallyPotentiallyEvaluated:
9183       // We are in an expression that may be potentially evaluated; queue this
9184       // declaration reference until we know whether the expression is
9185       // potentially evaluated.
9186       ExprEvalContexts.back().addReferencedDecl(Loc, D);
9187       return;
9188       
9189     case PotentiallyEvaluatedIfUsed:
9190       // Referenced declarations will only be used if the construct in the
9191       // containing expression is used.
9192       return;
9193   }
9194
9195   // Note that this declaration has been used.
9196   if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
9197     if (Constructor->isDefaulted()) {
9198       if (Constructor->isDefaultConstructor()) {
9199         if (Constructor->isTrivial())
9200           return;
9201         if (!Constructor->isUsed(false))
9202           DefineImplicitDefaultConstructor(Loc, Constructor);
9203       } else if (Constructor->isCopyConstructor()) {
9204         if (!Constructor->isUsed(false))
9205           DefineImplicitCopyConstructor(Loc, Constructor);
9206       } else if (Constructor->isMoveConstructor()) {
9207         if (!Constructor->isUsed(false))
9208           DefineImplicitMoveConstructor(Loc, Constructor);
9209       }
9210     }
9211
9212     MarkVTableUsed(Loc, Constructor->getParent());
9213   } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
9214     if (Destructor->isDefaulted() && !Destructor->isUsed(false))
9215       DefineImplicitDestructor(Loc, Destructor);
9216     if (Destructor->isVirtual())
9217       MarkVTableUsed(Loc, Destructor->getParent());
9218   } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
9219     if (MethodDecl->isDefaulted() && MethodDecl->isOverloadedOperator() &&
9220         MethodDecl->getOverloadedOperator() == OO_Equal) {
9221       if (!MethodDecl->isUsed(false)) {
9222         if (MethodDecl->isCopyAssignmentOperator())
9223           DefineImplicitCopyAssignment(Loc, MethodDecl);
9224         else
9225           DefineImplicitMoveAssignment(Loc, MethodDecl);
9226       }
9227     } else if (MethodDecl->isVirtual())
9228       MarkVTableUsed(Loc, MethodDecl->getParent());
9229   }
9230   if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
9231     // Recursive functions should be marked when used from another function.
9232     if (CurContext == Function) return;
9233
9234     // Implicit instantiation of function templates and member functions of
9235     // class templates.
9236     if (Function->isImplicitlyInstantiable()) {
9237       bool AlreadyInstantiated = false;
9238       if (FunctionTemplateSpecializationInfo *SpecInfo
9239                                 = Function->getTemplateSpecializationInfo()) {
9240         if (SpecInfo->getPointOfInstantiation().isInvalid())
9241           SpecInfo->setPointOfInstantiation(Loc);
9242         else if (SpecInfo->getTemplateSpecializationKind()
9243                    == TSK_ImplicitInstantiation)
9244           AlreadyInstantiated = true;
9245       } else if (MemberSpecializationInfo *MSInfo
9246                                   = Function->getMemberSpecializationInfo()) {
9247         if (MSInfo->getPointOfInstantiation().isInvalid())
9248           MSInfo->setPointOfInstantiation(Loc);
9249         else if (MSInfo->getTemplateSpecializationKind()
9250                    == TSK_ImplicitInstantiation)
9251           AlreadyInstantiated = true;
9252       }
9253
9254       if (!AlreadyInstantiated) {
9255         if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
9256             cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
9257           PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
9258                                                                       Loc));
9259         else
9260           PendingInstantiations.push_back(std::make_pair(Function, Loc));
9261       }
9262     } else {
9263       // Walk redefinitions, as some of them may be instantiable.
9264       for (FunctionDecl::redecl_iterator i(Function->redecls_begin()),
9265            e(Function->redecls_end()); i != e; ++i) {
9266         if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9267           MarkDeclarationReferenced(Loc, *i);
9268       }
9269     }
9270
9271     // Keep track of used but undefined functions.
9272     if (!Function->isPure() && !Function->hasBody() &&
9273         Function->getLinkage() != ExternalLinkage) {
9274       SourceLocation &old = UndefinedInternals[Function->getCanonicalDecl()];
9275       if (old.isInvalid()) old = Loc;
9276     }
9277
9278     Function->setUsed(true);
9279     return;
9280   }
9281
9282   if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
9283     // Implicit instantiation of static data members of class templates.
9284     if (Var->isStaticDataMember() &&
9285         Var->getInstantiatedFromStaticDataMember()) {
9286       MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
9287       assert(MSInfo && "Missing member specialization information?");
9288       if (MSInfo->getPointOfInstantiation().isInvalid() &&
9289           MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
9290         MSInfo->setPointOfInstantiation(Loc);
9291         // This is a modification of an existing AST node. Notify listeners.
9292         if (ASTMutationListener *L = getASTMutationListener())
9293           L->StaticDataMemberInstantiated(Var);
9294         PendingInstantiations.push_back(std::make_pair(Var, Loc));
9295       }
9296     }
9297
9298     // Keep track of used but undefined variables.  We make a hole in
9299     // the warning for static const data members with in-line
9300     // initializers.
9301     if (Var->hasDefinition() == VarDecl::DeclarationOnly
9302         && Var->getLinkage() != ExternalLinkage
9303         && !(Var->isStaticDataMember() && Var->hasInit())) {
9304       SourceLocation &old = UndefinedInternals[Var->getCanonicalDecl()];
9305       if (old.isInvalid()) old = Loc;
9306     }
9307
9308     D->setUsed(true);
9309     return;
9310   }
9311 }
9312
9313 namespace {
9314   // Mark all of the declarations referenced
9315   // FIXME: Not fully implemented yet! We need to have a better understanding
9316   // of when we're entering
9317   class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
9318     Sema &S;
9319     SourceLocation Loc;
9320
9321   public:
9322     typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
9323
9324     MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
9325
9326     bool TraverseTemplateArgument(const TemplateArgument &Arg);
9327     bool TraverseRecordType(RecordType *T);
9328   };
9329 }
9330
9331 bool MarkReferencedDecls::TraverseTemplateArgument(
9332   const TemplateArgument &Arg) {
9333   if (Arg.getKind() == TemplateArgument::Declaration) {
9334     S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
9335   }
9336
9337   return Inherited::TraverseTemplateArgument(Arg);
9338 }
9339
9340 bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
9341   if (ClassTemplateSpecializationDecl *Spec
9342                   = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
9343     const TemplateArgumentList &Args = Spec->getTemplateArgs();
9344     return TraverseTemplateArguments(Args.data(), Args.size());
9345   }
9346
9347   return true;
9348 }
9349
9350 void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
9351   MarkReferencedDecls Marker(*this, Loc);
9352   Marker.TraverseType(Context.getCanonicalType(T));
9353 }
9354
9355 namespace {
9356   /// \brief Helper class that marks all of the declarations referenced by
9357   /// potentially-evaluated subexpressions as "referenced".
9358   class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
9359     Sema &S;
9360     
9361   public:
9362     typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
9363     
9364     explicit EvaluatedExprMarker(Sema &S) : Inherited(S.Context), S(S) { }
9365     
9366     void VisitDeclRefExpr(DeclRefExpr *E) {
9367       S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9368     }
9369     
9370     void VisitMemberExpr(MemberExpr *E) {
9371       S.MarkDeclarationReferenced(E->getMemberLoc(), E->getMemberDecl());
9372       Inherited::VisitMemberExpr(E);
9373     }
9374     
9375     void VisitCXXNewExpr(CXXNewExpr *E) {
9376       if (E->getConstructor())
9377         S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9378       if (E->getOperatorNew())
9379         S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorNew());
9380       if (E->getOperatorDelete())
9381         S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9382       Inherited::VisitCXXNewExpr(E);
9383     }
9384     
9385     void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
9386       if (E->getOperatorDelete())
9387         S.MarkDeclarationReferenced(E->getLocStart(), E->getOperatorDelete());
9388       QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
9389       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
9390         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
9391         S.MarkDeclarationReferenced(E->getLocStart(), 
9392                                     S.LookupDestructor(Record));
9393       }
9394       
9395       Inherited::VisitCXXDeleteExpr(E);
9396     }
9397     
9398     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9399       S.MarkDeclarationReferenced(E->getLocStart(), E->getConstructor());
9400       Inherited::VisitCXXConstructExpr(E);
9401     }
9402     
9403     void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
9404       S.MarkDeclarationReferenced(E->getLocation(), E->getDecl());
9405     }
9406     
9407     void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
9408       Visit(E->getExpr());
9409     }
9410   };
9411 }
9412
9413 /// \brief Mark any declarations that appear within this expression or any
9414 /// potentially-evaluated subexpressions as "referenced".
9415 void Sema::MarkDeclarationsReferencedInExpr(Expr *E) {
9416   EvaluatedExprMarker(*this).Visit(E);
9417 }
9418
9419 /// \brief Emit a diagnostic that describes an effect on the run-time behavior
9420 /// of the program being compiled.
9421 ///
9422 /// This routine emits the given diagnostic when the code currently being
9423 /// type-checked is "potentially evaluated", meaning that there is a
9424 /// possibility that the code will actually be executable. Code in sizeof()
9425 /// expressions, code used only during overload resolution, etc., are not
9426 /// potentially evaluated. This routine will suppress such diagnostics or,
9427 /// in the absolutely nutty case of potentially potentially evaluated
9428 /// expressions (C++ typeid), queue the diagnostic to potentially emit it
9429 /// later.
9430 ///
9431 /// This routine should be used for all diagnostics that describe the run-time
9432 /// behavior of a program, such as passing a non-POD value through an ellipsis.
9433 /// Failure to do so will likely result in spurious diagnostics or failures
9434 /// during overload resolution or within sizeof/alignof/typeof/typeid.
9435 bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
9436                                const PartialDiagnostic &PD) {
9437   switch (ExprEvalContexts.back().Context) {
9438   case Unevaluated:
9439     // The argument will never be evaluated, so don't complain.
9440     break;
9441
9442   case PotentiallyEvaluated:
9443   case PotentiallyEvaluatedIfUsed:
9444     if (Statement && getCurFunctionOrMethodDecl()) {
9445       FunctionScopes.back()->PossiblyUnreachableDiags.
9446         push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
9447     }
9448     else
9449       Diag(Loc, PD);
9450       
9451     return true;
9452
9453   case PotentiallyPotentiallyEvaluated:
9454     ExprEvalContexts.back().addDiagnostic(Loc, PD);
9455     break;
9456   }
9457
9458   return false;
9459 }
9460
9461 bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
9462                                CallExpr *CE, FunctionDecl *FD) {
9463   if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
9464     return false;
9465
9466   PartialDiagnostic Note =
9467     FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
9468     << FD->getDeclName() : PDiag();
9469   SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
9470
9471   if (RequireCompleteType(Loc, ReturnType,
9472                           FD ?
9473                           PDiag(diag::err_call_function_incomplete_return)
9474                             << CE->getSourceRange() << FD->getDeclName() :
9475                           PDiag(diag::err_call_incomplete_return)
9476                             << CE->getSourceRange(),
9477                           std::make_pair(NoteLoc, Note)))
9478     return true;
9479
9480   return false;
9481 }
9482
9483 // Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
9484 // will prevent this condition from triggering, which is what we want.
9485 void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
9486   SourceLocation Loc;
9487
9488   unsigned diagnostic = diag::warn_condition_is_assignment;
9489   bool IsOrAssign = false;
9490
9491   if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
9492     if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
9493       return;
9494
9495     IsOrAssign = Op->getOpcode() == BO_OrAssign;
9496
9497     // Greylist some idioms by putting them into a warning subcategory.
9498     if (ObjCMessageExpr *ME
9499           = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
9500       Selector Sel = ME->getSelector();
9501
9502       // self = [<foo> init...]
9503       if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
9504         diagnostic = diag::warn_condition_is_idiomatic_assignment;
9505
9506       // <foo> = [<bar> nextObject]
9507       else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
9508         diagnostic = diag::warn_condition_is_idiomatic_assignment;
9509     }
9510
9511     Loc = Op->getOperatorLoc();
9512   } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
9513     if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
9514       return;
9515
9516     IsOrAssign = Op->getOperator() == OO_PipeEqual;
9517     Loc = Op->getOperatorLoc();
9518   } else {
9519     // Not an assignment.
9520     return;
9521   }
9522
9523   Diag(Loc, diagnostic) << E->getSourceRange();
9524
9525   SourceLocation Open = E->getSourceRange().getBegin();
9526   SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
9527   Diag(Loc, diag::note_condition_assign_silence)
9528         << FixItHint::CreateInsertion(Open, "(")
9529         << FixItHint::CreateInsertion(Close, ")");
9530
9531   if (IsOrAssign)
9532     Diag(Loc, diag::note_condition_or_assign_to_comparison)
9533       << FixItHint::CreateReplacement(Loc, "!=");
9534   else
9535     Diag(Loc, diag::note_condition_assign_to_comparison)
9536       << FixItHint::CreateReplacement(Loc, "==");
9537 }
9538
9539 /// \brief Redundant parentheses over an equality comparison can indicate
9540 /// that the user intended an assignment used as condition.
9541 void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
9542   // Don't warn if the parens came from a macro.
9543   SourceLocation parenLoc = ParenE->getLocStart();
9544   if (parenLoc.isInvalid() || parenLoc.isMacroID())
9545     return;
9546   // Don't warn for dependent expressions.
9547   if (ParenE->isTypeDependent())
9548     return;
9549
9550   Expr *E = ParenE->IgnoreParens();
9551
9552   if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
9553     if (opE->getOpcode() == BO_EQ &&
9554         opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
9555                                                            == Expr::MLV_Valid) {
9556       SourceLocation Loc = opE->getOperatorLoc();
9557       
9558       Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
9559       Diag(Loc, diag::note_equality_comparison_silence)
9560         << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
9561         << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
9562       Diag(Loc, diag::note_equality_comparison_to_assign)
9563         << FixItHint::CreateReplacement(Loc, "=");
9564     }
9565 }
9566
9567 ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
9568   DiagnoseAssignmentAsCondition(E);
9569   if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
9570     DiagnoseEqualityWithExtraParens(parenE);
9571
9572   ExprResult result = CheckPlaceholderExpr(E);
9573   if (result.isInvalid()) return ExprError();
9574   E = result.take();
9575
9576   if (!E->isTypeDependent()) {
9577     if (getLangOptions().CPlusPlus)
9578       return CheckCXXBooleanCondition(E); // C++ 6.4p4
9579
9580     ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
9581     if (ERes.isInvalid())
9582       return ExprError();
9583     E = ERes.take();
9584
9585     QualType T = E->getType();
9586     if (!T->isScalarType()) { // C99 6.8.4.1p1
9587       Diag(Loc, diag::err_typecheck_statement_requires_scalar)
9588         << T << E->getSourceRange();
9589       return ExprError();
9590     }
9591   }
9592
9593   return Owned(E);
9594 }
9595
9596 ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
9597                                        Expr *SubExpr) {
9598   if (!SubExpr)
9599     return ExprError();
9600
9601   return CheckBooleanCondition(SubExpr, Loc);
9602 }
9603
9604 namespace {
9605   /// A visitor for rebuilding a call to an __unknown_any expression
9606   /// to have an appropriate type.
9607   struct RebuildUnknownAnyFunction
9608     : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
9609
9610     Sema &S;
9611
9612     RebuildUnknownAnyFunction(Sema &S) : S(S) {}
9613
9614     ExprResult VisitStmt(Stmt *S) {
9615       llvm_unreachable("unexpected statement!");
9616       return ExprError();
9617     }
9618
9619     ExprResult VisitExpr(Expr *E) {
9620       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
9621         << E->getSourceRange();
9622       return ExprError();
9623     }
9624
9625     /// Rebuild an expression which simply semantically wraps another
9626     /// expression which it shares the type and value kind of.
9627     template <class T> ExprResult rebuildSugarExpr(T *E) {
9628       ExprResult SubResult = Visit(E->getSubExpr());
9629       if (SubResult.isInvalid()) return ExprError();
9630
9631       Expr *SubExpr = SubResult.take();
9632       E->setSubExpr(SubExpr);
9633       E->setType(SubExpr->getType());
9634       E->setValueKind(SubExpr->getValueKind());
9635       assert(E->getObjectKind() == OK_Ordinary);
9636       return E;
9637     }
9638
9639     ExprResult VisitParenExpr(ParenExpr *E) {
9640       return rebuildSugarExpr(E);
9641     }
9642
9643     ExprResult VisitUnaryExtension(UnaryOperator *E) {
9644       return rebuildSugarExpr(E);
9645     }
9646
9647     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9648       ExprResult SubResult = Visit(E->getSubExpr());
9649       if (SubResult.isInvalid()) return ExprError();
9650
9651       Expr *SubExpr = SubResult.take();
9652       E->setSubExpr(SubExpr);
9653       E->setType(S.Context.getPointerType(SubExpr->getType()));
9654       assert(E->getValueKind() == VK_RValue);
9655       assert(E->getObjectKind() == OK_Ordinary);
9656       return E;
9657     }
9658
9659     ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
9660       if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
9661
9662       E->setType(VD->getType());
9663
9664       assert(E->getValueKind() == VK_RValue);
9665       if (S.getLangOptions().CPlusPlus &&
9666           !(isa<CXXMethodDecl>(VD) &&
9667             cast<CXXMethodDecl>(VD)->isInstance()))
9668         E->setValueKind(VK_LValue);
9669
9670       return E;
9671     }
9672
9673     ExprResult VisitMemberExpr(MemberExpr *E) {
9674       return resolveDecl(E, E->getMemberDecl());
9675     }
9676
9677     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9678       return resolveDecl(E, E->getDecl());
9679     }
9680   };
9681 }
9682
9683 /// Given a function expression of unknown-any type, try to rebuild it
9684 /// to have a function type.
9685 static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
9686   ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
9687   if (Result.isInvalid()) return ExprError();
9688   return S.DefaultFunctionArrayConversion(Result.take());
9689 }
9690
9691 namespace {
9692   /// A visitor for rebuilding an expression of type __unknown_anytype
9693   /// into one which resolves the type directly on the referring
9694   /// expression.  Strict preservation of the original source
9695   /// structure is not a goal.
9696   struct RebuildUnknownAnyExpr
9697     : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
9698
9699     Sema &S;
9700
9701     /// The current destination type.
9702     QualType DestType;
9703
9704     RebuildUnknownAnyExpr(Sema &S, QualType CastType)
9705       : S(S), DestType(CastType) {}
9706
9707     ExprResult VisitStmt(Stmt *S) {
9708       llvm_unreachable("unexpected statement!");
9709       return ExprError();
9710     }
9711
9712     ExprResult VisitExpr(Expr *E) {
9713       S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9714         << E->getSourceRange();
9715       return ExprError();
9716     }
9717
9718     ExprResult VisitCallExpr(CallExpr *E);
9719     ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
9720
9721     /// Rebuild an expression which simply semantically wraps another
9722     /// expression which it shares the type and value kind of.
9723     template <class T> ExprResult rebuildSugarExpr(T *E) {
9724       ExprResult SubResult = Visit(E->getSubExpr());
9725       if (SubResult.isInvalid()) return ExprError();
9726       Expr *SubExpr = SubResult.take();
9727       E->setSubExpr(SubExpr);
9728       E->setType(SubExpr->getType());
9729       E->setValueKind(SubExpr->getValueKind());
9730       assert(E->getObjectKind() == OK_Ordinary);
9731       return E;
9732     }
9733
9734     ExprResult VisitParenExpr(ParenExpr *E) {
9735       return rebuildSugarExpr(E);
9736     }
9737
9738     ExprResult VisitUnaryExtension(UnaryOperator *E) {
9739       return rebuildSugarExpr(E);
9740     }
9741
9742     ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
9743       const PointerType *Ptr = DestType->getAs<PointerType>();
9744       if (!Ptr) {
9745         S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
9746           << E->getSourceRange();
9747         return ExprError();
9748       }
9749       assert(E->getValueKind() == VK_RValue);
9750       assert(E->getObjectKind() == OK_Ordinary);
9751       E->setType(DestType);
9752
9753       // Build the sub-expression as if it were an object of the pointee type.
9754       DestType = Ptr->getPointeeType();
9755       ExprResult SubResult = Visit(E->getSubExpr());
9756       if (SubResult.isInvalid()) return ExprError();
9757       E->setSubExpr(SubResult.take());
9758       return E;
9759     }
9760
9761     ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
9762
9763     ExprResult resolveDecl(Expr *E, ValueDecl *VD);
9764
9765     ExprResult VisitMemberExpr(MemberExpr *E) {
9766       return resolveDecl(E, E->getMemberDecl());
9767     }
9768
9769     ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
9770       return resolveDecl(E, E->getDecl());
9771     }
9772   };
9773 }
9774
9775 /// Rebuilds a call expression which yielded __unknown_anytype.
9776 ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
9777   Expr *CalleeExpr = E->getCallee();
9778
9779   enum FnKind {
9780     FK_MemberFunction,
9781     FK_FunctionPointer,
9782     FK_BlockPointer
9783   };
9784
9785   FnKind Kind;
9786   QualType CalleeType = CalleeExpr->getType();
9787   if (CalleeType == S.Context.BoundMemberTy) {
9788     assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
9789     Kind = FK_MemberFunction;
9790     CalleeType = Expr::findBoundMemberType(CalleeExpr);
9791   } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
9792     CalleeType = Ptr->getPointeeType();
9793     Kind = FK_FunctionPointer;
9794   } else {
9795     CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
9796     Kind = FK_BlockPointer;
9797   }
9798   const FunctionType *FnType = CalleeType->castAs<FunctionType>();
9799
9800   // Verify that this is a legal result type of a function.
9801   if (DestType->isArrayType() || DestType->isFunctionType()) {
9802     unsigned diagID = diag::err_func_returning_array_function;
9803     if (Kind == FK_BlockPointer)
9804       diagID = diag::err_block_returning_array_function;
9805
9806     S.Diag(E->getExprLoc(), diagID)
9807       << DestType->isFunctionType() << DestType;
9808     return ExprError();
9809   }
9810
9811   // Otherwise, go ahead and set DestType as the call's result.
9812   E->setType(DestType.getNonLValueExprType(S.Context));
9813   E->setValueKind(Expr::getValueKindForType(DestType));
9814   assert(E->getObjectKind() == OK_Ordinary);
9815
9816   // Rebuild the function type, replacing the result type with DestType.
9817   if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
9818     DestType = S.Context.getFunctionType(DestType,
9819                                          Proto->arg_type_begin(),
9820                                          Proto->getNumArgs(),
9821                                          Proto->getExtProtoInfo());
9822   else
9823     DestType = S.Context.getFunctionNoProtoType(DestType,
9824                                                 FnType->getExtInfo());
9825
9826   // Rebuild the appropriate pointer-to-function type.
9827   switch (Kind) { 
9828   case FK_MemberFunction:
9829     // Nothing to do.
9830     break;
9831
9832   case FK_FunctionPointer:
9833     DestType = S.Context.getPointerType(DestType);
9834     break;
9835
9836   case FK_BlockPointer:
9837     DestType = S.Context.getBlockPointerType(DestType);
9838     break;
9839   }
9840
9841   // Finally, we can recurse.
9842   ExprResult CalleeResult = Visit(CalleeExpr);
9843   if (!CalleeResult.isUsable()) return ExprError();
9844   E->setCallee(CalleeResult.take());
9845
9846   // Bind a temporary if necessary.
9847   return S.MaybeBindToTemporary(E);
9848 }
9849
9850 ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
9851   // Verify that this is a legal result type of a call.
9852   if (DestType->isArrayType() || DestType->isFunctionType()) {
9853     S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
9854       << DestType->isFunctionType() << DestType;
9855     return ExprError();
9856   }
9857
9858   // Rewrite the method result type if available.
9859   if (ObjCMethodDecl *Method = E->getMethodDecl()) {
9860     assert(Method->getResultType() == S.Context.UnknownAnyTy);
9861     Method->setResultType(DestType);
9862   }
9863
9864   // Change the type of the message.
9865   E->setType(DestType.getNonReferenceType());
9866   E->setValueKind(Expr::getValueKindForType(DestType));
9867
9868   return S.MaybeBindToTemporary(E);
9869 }
9870
9871 ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
9872   // The only case we should ever see here is a function-to-pointer decay.
9873   assert(E->getCastKind() == CK_FunctionToPointerDecay);
9874   assert(E->getValueKind() == VK_RValue);
9875   assert(E->getObjectKind() == OK_Ordinary);
9876
9877   E->setType(DestType);
9878
9879   // Rebuild the sub-expression as the pointee (function) type.
9880   DestType = DestType->castAs<PointerType>()->getPointeeType();
9881
9882   ExprResult Result = Visit(E->getSubExpr());
9883   if (!Result.isUsable()) return ExprError();
9884
9885   E->setSubExpr(Result.take());
9886   return S.Owned(E);
9887 }
9888
9889 ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
9890   ExprValueKind ValueKind = VK_LValue;
9891   QualType Type = DestType;
9892
9893   // We know how to make this work for certain kinds of decls:
9894
9895   //  - functions
9896   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
9897     if (const PointerType *Ptr = Type->getAs<PointerType>()) {
9898       DestType = Ptr->getPointeeType();
9899       ExprResult Result = resolveDecl(E, VD);
9900       if (Result.isInvalid()) return ExprError();
9901       return S.ImpCastExprToType(Result.take(), Type,
9902                                  CK_FunctionToPointerDecay, VK_RValue);
9903     }
9904
9905     if (!Type->isFunctionType()) {
9906       S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
9907         << VD << E->getSourceRange();
9908       return ExprError();
9909     }
9910
9911     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
9912       if (MD->isInstance()) {
9913         ValueKind = VK_RValue;
9914         Type = S.Context.BoundMemberTy;
9915       }
9916
9917     // Function references aren't l-values in C.
9918     if (!S.getLangOptions().CPlusPlus)
9919       ValueKind = VK_RValue;
9920
9921   //  - variables
9922   } else if (isa<VarDecl>(VD)) {
9923     if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
9924       Type = RefTy->getPointeeType();
9925     } else if (Type->isFunctionType()) {
9926       S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
9927         << VD << E->getSourceRange();
9928       return ExprError();
9929     }
9930
9931   //  - nothing else
9932   } else {
9933     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
9934       << VD << E->getSourceRange();
9935     return ExprError();
9936   }
9937
9938   VD->setType(DestType);
9939   E->setType(Type);
9940   E->setValueKind(ValueKind);
9941   return S.Owned(E);
9942 }
9943
9944 /// Check a cast of an unknown-any type.  We intentionally only
9945 /// trigger this for C-style casts.
9946 ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
9947                                      Expr *CastExpr, CastKind &CastKind,
9948                                      ExprValueKind &VK, CXXCastPath &Path) {
9949   // Rewrite the casted expression from scratch.
9950   ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
9951   if (!result.isUsable()) return ExprError();
9952
9953   CastExpr = result.take();
9954   VK = CastExpr->getValueKind();
9955   CastKind = CK_NoOp;
9956
9957   return CastExpr;
9958 }
9959
9960 static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
9961   Expr *orig = E;
9962   unsigned diagID = diag::err_uncasted_use_of_unknown_any;
9963   while (true) {
9964     E = E->IgnoreParenImpCasts();
9965     if (CallExpr *call = dyn_cast<CallExpr>(E)) {
9966       E = call->getCallee();
9967       diagID = diag::err_uncasted_call_of_unknown_any;
9968     } else {
9969       break;
9970     }
9971   }
9972
9973   SourceLocation loc;
9974   NamedDecl *d;
9975   if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
9976     loc = ref->getLocation();
9977     d = ref->getDecl();
9978   } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
9979     loc = mem->getMemberLoc();
9980     d = mem->getMemberDecl();
9981   } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
9982     diagID = diag::err_uncasted_call_of_unknown_any;
9983     loc = msg->getSelectorStartLoc();
9984     d = msg->getMethodDecl();
9985     if (!d) {
9986       S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
9987         << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
9988         << orig->getSourceRange();
9989       return ExprError();
9990     }
9991   } else {
9992     S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
9993       << E->getSourceRange();
9994     return ExprError();
9995   }
9996
9997   S.Diag(loc, diagID) << d << orig->getSourceRange();
9998
9999   // Never recoverable.
10000   return ExprError();
10001 }
10002
10003 /// Check for operands with placeholder types and complain if found.
10004 /// Returns true if there was an error and no recovery was possible.
10005 ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
10006   // Placeholder types are always *exactly* the appropriate builtin type.
10007   QualType type = E->getType();
10008
10009   // Overloaded expressions.
10010   if (type == Context.OverloadTy) {
10011     // Try to resolve a single function template specialization.
10012     // This is obligatory.
10013     ExprResult result = Owned(E);
10014     if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
10015       return result;
10016
10017     // If that failed, try to recover with a call.
10018     } else {
10019       tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
10020                            /*complain*/ true);
10021       return result;
10022     }
10023   }
10024
10025   // Bound member functions.
10026   if (type == Context.BoundMemberTy) {
10027     ExprResult result = Owned(E);
10028     tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
10029                          /*complain*/ true);
10030     return result;
10031   }    
10032
10033   // Expressions of unknown type.
10034   if (type == Context.UnknownAnyTy)
10035     return diagnoseUnknownAnyExpr(*this, E);
10036
10037   assert(!type->isPlaceholderType());
10038   return Owned(E);
10039 }
10040
10041 bool Sema::CheckCaseExpression(Expr *E) {
10042   if (E->isTypeDependent())
10043     return true;
10044   if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
10045     return E->getType()->isIntegralOrEnumerationType();
10046   return false;
10047 }