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