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