SemaExpr.cpp revision 4fdcdda2862ac8c818184ca593ef43ff11469eac
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 "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/Lex/Preprocessor.h"
21#include "clang/Lex/LiteralSupport.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Designator.h"
26#include "clang/Parse/Scope.h"
27using namespace clang;
28
29
30/// \brief Determine whether the use of this declaration is valid, and
31/// emit any corresponding diagnostics.
32///
33/// This routine diagnoses various problems with referencing
34/// declarations that can occur when using a declaration. For example,
35/// it might warn if a deprecated or unavailable declaration is being
36/// used, or produce an error (and return true) if a C++0x deleted
37/// function is being used.
38///
39/// \returns true if there was an error (this declaration cannot be
40/// referenced), false otherwise.
41bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
42  // See if the decl is deprecated.
43  if (D->getAttr<DeprecatedAttr>()) {
44    // Implementing deprecated stuff requires referencing deprecated
45    // stuff. Don't warn if we are implementing a deprecated
46    // construct.
47    bool isSilenced = false;
48
49    if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
50      // If this reference happens *in* a deprecated function or method, don't
51      // warn.
52      isSilenced = ND->getAttr<DeprecatedAttr>();
53
54      // If this is an Objective-C method implementation, check to see if the
55      // method was deprecated on the declaration, not the definition.
56      if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
57        // The semantic decl context of a ObjCMethodDecl is the
58        // ObjCImplementationDecl.
59        if (ObjCImplementationDecl *Impl
60              = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
61
62          MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
63                                                    MD->isInstanceMethod());
64          isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
65        }
66      }
67    }
68
69    if (!isSilenced)
70      Diag(Loc, diag::warn_deprecated) << D->getDeclName();
71  }
72
73  // See if this is a deleted function.
74  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
75    if (FD->isDeleted()) {
76      Diag(Loc, diag::err_deleted_function_use);
77      Diag(D->getLocation(), diag::note_unavailable_here) << true;
78      return true;
79    }
80  }
81
82  // See if the decl is unavailable
83  if (D->getAttr<UnavailableAttr>()) {
84    Diag(Loc, diag::warn_unavailable) << D->getDeclName();
85    Diag(D->getLocation(), diag::note_unavailable_here) << 0;
86  }
87
88  return false;
89}
90
91/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
92/// (and other functions in future), which have been declared with sentinel
93/// attribute. It warns if call does not have the sentinel argument.
94///
95void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
96                                 Expr **Args, unsigned NumArgs)
97{
98  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
99  if (!attr)
100    return;
101  int sentinelPos = attr->getSentinel();
102  int nullPos = attr->getNullPos();
103
104  // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105  // base class. Then we won't be needing two versions of the same code.
106  unsigned int i = 0;
107  bool warnNotEnoughArgs = false;
108  int isMethod = 0;
109  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110    // skip over named parameters.
111    ObjCMethodDecl::param_iterator P, E = MD->param_end();
112    for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113      if (nullPos)
114        --nullPos;
115      else
116        ++i;
117    }
118    warnNotEnoughArgs = (P != E || i >= NumArgs);
119    isMethod = 1;
120  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
121    // skip over named parameters.
122    ObjCMethodDecl::param_iterator P, E = FD->param_end();
123    for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124      if (nullPos)
125        --nullPos;
126      else
127        ++i;
128    }
129    warnNotEnoughArgs = (P != E || i >= NumArgs);
130  } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
131    // block or function pointer call.
132    QualType Ty = V->getType();
133    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134      const FunctionType *FT = Ty->isFunctionPointerType()
135      ? Ty->getAs<PointerType>()->getPointeeType()->getAsFunctionType()
136      : Ty->getAs<BlockPointerType>()->getPointeeType()->getAsFunctionType();
137      if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138        unsigned NumArgsInProto = Proto->getNumArgs();
139        unsigned k;
140        for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141          if (nullPos)
142            --nullPos;
143          else
144            ++i;
145        }
146        warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147      }
148      if (Ty->isBlockPointerType())
149        isMethod = 2;
150    } else
151      return;
152  } else
153    return;
154
155  if (warnNotEnoughArgs) {
156    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
157    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
158    return;
159  }
160  int sentinel = i;
161  while (sentinelPos > 0 && i < NumArgs-1) {
162    --sentinelPos;
163    ++i;
164  }
165  if (sentinelPos > 0) {
166    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
167    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
168    return;
169  }
170  while (i < NumArgs-1) {
171    ++i;
172    ++sentinel;
173  }
174  Expr *sentinelExpr = Args[sentinel];
175  if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176                       !sentinelExpr->isNullPointerConstant(Context))) {
177    Diag(Loc, diag::warn_missing_sentinel) << isMethod;
178    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
179  }
180  return;
181}
182
183SourceRange Sema::getExprRange(ExprTy *E) const {
184  Expr *Ex = (Expr *)E;
185  return Ex? Ex->getSourceRange() : SourceRange();
186}
187
188//===----------------------------------------------------------------------===//
189//  Standard Promotions and Conversions
190//===----------------------------------------------------------------------===//
191
192/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
193void Sema::DefaultFunctionArrayConversion(Expr *&E) {
194  QualType Ty = E->getType();
195  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
196
197  if (Ty->isFunctionType())
198    ImpCastExprToType(E, Context.getPointerType(Ty));
199  else if (Ty->isArrayType()) {
200    // In C90 mode, arrays only promote to pointers if the array expression is
201    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
202    // type 'array of type' is converted to an expression that has type 'pointer
203    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
204    // that has type 'array of type' ...".  The relevant change is "an lvalue"
205    // (C90) to "an expression" (C99).
206    //
207    // C++ 4.2p1:
208    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
209    // T" can be converted to an rvalue of type "pointer to T".
210    //
211    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
212        E->isLvalue(Context) == Expr::LV_Valid)
213      ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
214                        CastExpr::CK_ArrayToPointerDecay);
215  }
216}
217
218/// UsualUnaryConversions - Performs various conversions that are common to most
219/// operators (C99 6.3). The conversions of array and function types are
220/// sometimes surpressed. For example, the array->pointer conversion doesn't
221/// apply if the array is an argument to the sizeof or address (&) operators.
222/// In these instances, this routine should *not* be called.
223Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
224  QualType Ty = Expr->getType();
225  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
226
227  // C99 6.3.1.1p2:
228  //
229  //   The following may be used in an expression wherever an int or
230  //   unsigned int may be used:
231  //     - an object or expression with an integer type whose integer
232  //       conversion rank is less than or equal to the rank of int
233  //       and unsigned int.
234  //     - A bit-field of type _Bool, int, signed int, or unsigned int.
235  //
236  //   If an int can represent all values of the original type, the
237  //   value is converted to an int; otherwise, it is converted to an
238  //   unsigned int. These are called the integer promotions. All
239  //   other types are unchanged by the integer promotions.
240  QualType PTy = Context.isPromotableBitField(Expr);
241  if (!PTy.isNull()) {
242    ImpCastExprToType(Expr, PTy);
243    return Expr;
244  }
245  if (Ty->isPromotableIntegerType()) {
246    QualType PT = Context.getPromotedIntegerType(Ty);
247    ImpCastExprToType(Expr, PT);
248    return Expr;
249  }
250
251  DefaultFunctionArrayConversion(Expr);
252  return Expr;
253}
254
255/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
256/// do not have a prototype. Arguments that have type float are promoted to
257/// double. All other argument types are converted by UsualUnaryConversions().
258void Sema::DefaultArgumentPromotion(Expr *&Expr) {
259  QualType Ty = Expr->getType();
260  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
261
262  // If this is a 'float' (CVR qualified or typedef) promote to double.
263  if (const BuiltinType *BT = Ty->getAsBuiltinType())
264    if (BT->getKind() == BuiltinType::Float)
265      return ImpCastExprToType(Expr, Context.DoubleTy);
266
267  UsualUnaryConversions(Expr);
268}
269
270/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
271/// will warn if the resulting type is not a POD type, and rejects ObjC
272/// interfaces passed by value.  This returns true if the argument type is
273/// completely illegal.
274bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
275  DefaultArgumentPromotion(Expr);
276
277  if (Expr->getType()->isObjCInterfaceType()) {
278    Diag(Expr->getLocStart(),
279         diag::err_cannot_pass_objc_interface_to_vararg)
280      << Expr->getType() << CT;
281    return true;
282  }
283
284  if (!Expr->getType()->isPODType())
285    Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
286      << Expr->getType() << CT;
287
288  return false;
289}
290
291
292/// UsualArithmeticConversions - Performs various conversions that are common to
293/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
294/// routine returns the first non-arithmetic type found. The client is
295/// responsible for emitting appropriate error diagnostics.
296/// FIXME: verify the conversion rules for "complex int" are consistent with
297/// GCC.
298QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
299                                          bool isCompAssign) {
300  if (!isCompAssign)
301    UsualUnaryConversions(lhsExpr);
302
303  UsualUnaryConversions(rhsExpr);
304
305  // For conversion purposes, we ignore any qualifiers.
306  // For example, "const float" and "float" are equivalent.
307  QualType lhs =
308    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
309  QualType rhs =
310    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
311
312  // If both types are identical, no conversion is needed.
313  if (lhs == rhs)
314    return lhs;
315
316  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
317  // The caller can deal with this (e.g. pointer + int).
318  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
319    return lhs;
320
321  // Perform bitfield promotions.
322  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
323  if (!LHSBitfieldPromoteTy.isNull())
324    lhs = LHSBitfieldPromoteTy;
325  QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
326  if (!RHSBitfieldPromoteTy.isNull())
327    rhs = RHSBitfieldPromoteTy;
328
329  QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
330  if (!isCompAssign)
331    ImpCastExprToType(lhsExpr, destType);
332  ImpCastExprToType(rhsExpr, destType);
333  return destType;
334}
335
336//===----------------------------------------------------------------------===//
337//  Semantic Analysis for various Expression Types
338//===----------------------------------------------------------------------===//
339
340
341/// ActOnStringLiteral - The specified tokens were lexed as pasted string
342/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
343/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
344/// multiple tokens.  However, the common case is that StringToks points to one
345/// string.
346///
347Action::OwningExprResult
348Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
349  assert(NumStringToks && "Must have at least one string!");
350
351  StringLiteralParser Literal(StringToks, NumStringToks, PP);
352  if (Literal.hadError)
353    return ExprError();
354
355  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
356  for (unsigned i = 0; i != NumStringToks; ++i)
357    StringTokLocs.push_back(StringToks[i].getLocation());
358
359  QualType StrTy = Context.CharTy;
360  if (Literal.AnyWide) StrTy = Context.getWCharType();
361  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
362
363  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
364  if (getLangOptions().CPlusPlus)
365    StrTy.addConst();
366
367  // Get an array type for the string, according to C99 6.4.5.  This includes
368  // the nul terminator character as well as the string length for pascal
369  // strings.
370  StrTy = Context.getConstantArrayType(StrTy,
371                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
372                                       ArrayType::Normal, 0);
373
374  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
375  return Owned(StringLiteral::Create(Context, Literal.GetString(),
376                                     Literal.GetStringLength(),
377                                     Literal.AnyWide, StrTy,
378                                     &StringTokLocs[0],
379                                     StringTokLocs.size()));
380}
381
382/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
383/// CurBlock to VD should cause it to be snapshotted (as we do for auto
384/// variables defined outside the block) or false if this is not needed (e.g.
385/// for values inside the block or for globals).
386///
387/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
388/// up-to-date.
389///
390static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
391                                              ValueDecl *VD) {
392  // If the value is defined inside the block, we couldn't snapshot it even if
393  // we wanted to.
394  if (CurBlock->TheDecl == VD->getDeclContext())
395    return false;
396
397  // If this is an enum constant or function, it is constant, don't snapshot.
398  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
399    return false;
400
401  // If this is a reference to an extern, static, or global variable, no need to
402  // snapshot it.
403  // FIXME: What about 'const' variables in C++?
404  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
405    if (!Var->hasLocalStorage())
406      return false;
407
408  // Blocks that have these can't be constant.
409  CurBlock->hasBlockDeclRefExprs = true;
410
411  // If we have nested blocks, the decl may be declared in an outer block (in
412  // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
413  // be defined outside all of the current blocks (in which case the blocks do
414  // all get the bit).  Walk the nesting chain.
415  for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
416       NextBlock = NextBlock->PrevBlockInfo) {
417    // If we found the defining block for the variable, don't mark the block as
418    // having a reference outside it.
419    if (NextBlock->TheDecl == VD->getDeclContext())
420      break;
421
422    // Otherwise, the DeclRef from the inner block causes the outer one to need
423    // a snapshot as well.
424    NextBlock->hasBlockDeclRefExprs = true;
425  }
426
427  return true;
428}
429
430
431
432/// ActOnIdentifierExpr - The parser read an identifier in expression context,
433/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
434/// identifier is used in a function call context.
435/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
436/// class or namespace that the identifier must be a member of.
437Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
438                                                 IdentifierInfo &II,
439                                                 bool HasTrailingLParen,
440                                                 const CXXScopeSpec *SS,
441                                                 bool isAddressOfOperand) {
442  return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
443                                  isAddressOfOperand);
444}
445
446/// BuildDeclRefExpr - Build either a DeclRefExpr or a
447/// QualifiedDeclRefExpr based on whether or not SS is a
448/// nested-name-specifier.
449Sema::OwningExprResult
450Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
451                       bool TypeDependent, bool ValueDependent,
452                       const CXXScopeSpec *SS) {
453  if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
454    Diag(Loc,
455         diag::err_auto_variable_cannot_appear_in_own_initializer)
456      << D->getDeclName();
457    return ExprError();
458  }
459
460  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
461    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
462      if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
463        if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
464          Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
465            << D->getIdentifier() << FD->getDeclName();
466          Diag(D->getLocation(), diag::note_local_variable_declared_here)
467            << D->getIdentifier();
468          return ExprError();
469        }
470      }
471    }
472  }
473
474  MarkDeclarationReferenced(Loc, D);
475
476  Expr *E;
477  if (SS && !SS->isEmpty()) {
478    E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
479                                          ValueDependent, SS->getRange(),
480                  static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
481  } else
482    E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
483
484  return Owned(E);
485}
486
487/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
488/// variable corresponding to the anonymous union or struct whose type
489/// is Record.
490static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
491                                             RecordDecl *Record) {
492  assert(Record->isAnonymousStructOrUnion() &&
493         "Record must be an anonymous struct or union!");
494
495  // FIXME: Once Decls are directly linked together, this will be an O(1)
496  // operation rather than a slow walk through DeclContext's vector (which
497  // itself will be eliminated). DeclGroups might make this even better.
498  DeclContext *Ctx = Record->getDeclContext();
499  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
500                               DEnd = Ctx->decls_end();
501       D != DEnd; ++D) {
502    if (*D == Record) {
503      // The object for the anonymous struct/union directly
504      // follows its type in the list of declarations.
505      ++D;
506      assert(D != DEnd && "Missing object for anonymous record");
507      assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
508      return *D;
509    }
510  }
511
512  assert(false && "Missing object for anonymous record");
513  return 0;
514}
515
516/// \brief Given a field that represents a member of an anonymous
517/// struct/union, build the path from that field's context to the
518/// actual member.
519///
520/// Construct the sequence of field member references we'll have to
521/// perform to get to the field in the anonymous union/struct. The
522/// list of members is built from the field outward, so traverse it
523/// backwards to go from an object in the current context to the field
524/// we found.
525///
526/// \returns The variable from which the field access should begin,
527/// for an anonymous struct/union that is not a member of another
528/// class. Otherwise, returns NULL.
529VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
530                                   llvm::SmallVectorImpl<FieldDecl *> &Path) {
531  assert(Field->getDeclContext()->isRecord() &&
532         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
533         && "Field must be stored inside an anonymous struct or union");
534
535  Path.push_back(Field);
536  VarDecl *BaseObject = 0;
537  DeclContext *Ctx = Field->getDeclContext();
538  do {
539    RecordDecl *Record = cast<RecordDecl>(Ctx);
540    Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
541    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
542      Path.push_back(AnonField);
543    else {
544      BaseObject = cast<VarDecl>(AnonObject);
545      break;
546    }
547    Ctx = Ctx->getParent();
548  } while (Ctx->isRecord() &&
549           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
550
551  return BaseObject;
552}
553
554Sema::OwningExprResult
555Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
556                                               FieldDecl *Field,
557                                               Expr *BaseObjectExpr,
558                                               SourceLocation OpLoc) {
559  llvm::SmallVector<FieldDecl *, 4> AnonFields;
560  VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
561                                                            AnonFields);
562
563  // Build the expression that refers to the base object, from
564  // which we will build a sequence of member references to each
565  // of the anonymous union objects and, eventually, the field we
566  // found via name lookup.
567  bool BaseObjectIsPointer = false;
568  unsigned ExtraQuals = 0;
569  if (BaseObject) {
570    // BaseObject is an anonymous struct/union variable (and is,
571    // therefore, not part of another non-anonymous record).
572    if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
573    MarkDeclarationReferenced(Loc, BaseObject);
574    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
575                                               SourceLocation());
576    ExtraQuals
577      = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
578  } else if (BaseObjectExpr) {
579    // The caller provided the base object expression. Determine
580    // whether its a pointer and whether it adds any qualifiers to the
581    // anonymous struct/union fields we're looking into.
582    QualType ObjectType = BaseObjectExpr->getType();
583    if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
584      BaseObjectIsPointer = true;
585      ObjectType = ObjectPtr->getPointeeType();
586    }
587    ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
588  } else {
589    // We've found a member of an anonymous struct/union that is
590    // inside a non-anonymous struct/union, so in a well-formed
591    // program our base object expression is "this".
592    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
593      if (!MD->isStatic()) {
594        QualType AnonFieldType
595          = Context.getTagDeclType(
596                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
597        QualType ThisType = Context.getTagDeclType(MD->getParent());
598        if ((Context.getCanonicalType(AnonFieldType)
599               == Context.getCanonicalType(ThisType)) ||
600            IsDerivedFrom(ThisType, AnonFieldType)) {
601          // Our base object expression is "this".
602          BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
603                                                     MD->getThisType(Context));
604          BaseObjectIsPointer = true;
605        }
606      } else {
607        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
608          << Field->getDeclName());
609      }
610      ExtraQuals = MD->getTypeQualifiers();
611    }
612
613    if (!BaseObjectExpr)
614      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
615        << Field->getDeclName());
616  }
617
618  // Build the implicit member references to the field of the
619  // anonymous struct/union.
620  Expr *Result = BaseObjectExpr;
621  unsigned BaseAddrSpace = BaseObjectExpr->getType().getAddressSpace();
622  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
623         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
624       FI != FIEnd; ++FI) {
625    QualType MemberType = (*FI)->getType();
626    if (!(*FI)->isMutable()) {
627      unsigned combinedQualifiers
628        = MemberType.getCVRQualifiers() | ExtraQuals;
629      MemberType = MemberType.getQualifiedType(combinedQualifiers);
630    }
631    if (BaseAddrSpace != MemberType.getAddressSpace())
632      MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
633    MarkDeclarationReferenced(Loc, *FI);
634    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
635                                      OpLoc, MemberType);
636    BaseObjectIsPointer = false;
637    ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
638  }
639
640  return Owned(Result);
641}
642
643/// ActOnDeclarationNameExpr - The parser has read some kind of name
644/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
645/// performs lookup on that name and returns an expression that refers
646/// to that name. This routine isn't directly called from the parser,
647/// because the parser doesn't know about DeclarationName. Rather,
648/// this routine is called by ActOnIdentifierExpr,
649/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
650/// which form the DeclarationName from the corresponding syntactic
651/// forms.
652///
653/// HasTrailingLParen indicates whether this identifier is used in a
654/// function call context.  LookupCtx is only used for a C++
655/// qualified-id (foo::bar) to indicate the class or namespace that
656/// the identifier must be a member of.
657///
658/// isAddressOfOperand means that this expression is the direct operand
659/// of an address-of operator. This matters because this is the only
660/// situation where a qualified name referencing a non-static member may
661/// appear outside a member function of this class.
662Sema::OwningExprResult
663Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
664                               DeclarationName Name, bool HasTrailingLParen,
665                               const CXXScopeSpec *SS,
666                               bool isAddressOfOperand) {
667  // Could be enum-constant, value decl, instance variable, etc.
668  if (SS && SS->isInvalid())
669    return ExprError();
670
671  // C++ [temp.dep.expr]p3:
672  //   An id-expression is type-dependent if it contains:
673  //     -- a nested-name-specifier that contains a class-name that
674  //        names a dependent type.
675  // FIXME: Member of the current instantiation.
676  if (SS && isDependentScopeSpecifier(*SS)) {
677    return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
678                                                     Loc, SS->getRange(),
679                static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
680                                                     isAddressOfOperand));
681  }
682
683  LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName,
684                                         false, true, Loc);
685
686  if (Lookup.isAmbiguous()) {
687    DiagnoseAmbiguousLookup(Lookup, Name, Loc,
688                            SS && SS->isSet() ? SS->getRange()
689                                              : SourceRange());
690    return ExprError();
691  }
692
693  NamedDecl *D = Lookup.getAsDecl();
694
695  // If this reference is in an Objective-C method, then ivar lookup happens as
696  // well.
697  IdentifierInfo *II = Name.getAsIdentifierInfo();
698  if (II && getCurMethodDecl()) {
699    // There are two cases to handle here.  1) scoped lookup could have failed,
700    // in which case we should look for an ivar.  2) scoped lookup could have
701    // found a decl, but that decl is outside the current instance method (i.e.
702    // a global variable).  In these two cases, we do a lookup for an ivar with
703    // this name, if the lookup sucedes, we replace it our current decl.
704    if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
705      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
706      ObjCInterfaceDecl *ClassDeclared;
707      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
708        // Check if referencing a field with __attribute__((deprecated)).
709        if (DiagnoseUseOfDecl(IV, Loc))
710          return ExprError();
711
712        // If we're referencing an invalid decl, just return this as a silent
713        // error node.  The error diagnostic was already emitted on the decl.
714        if (IV->isInvalidDecl())
715          return ExprError();
716
717        bool IsClsMethod = getCurMethodDecl()->isClassMethod();
718        // If a class method attemps to use a free standing ivar, this is
719        // an error.
720        if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
721           return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
722                           << IV->getDeclName());
723        // If a class method uses a global variable, even if an ivar with
724        // same name exists, use the global.
725        if (!IsClsMethod) {
726          if (IV->getAccessControl() == ObjCIvarDecl::Private &&
727              ClassDeclared != IFace)
728           Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
729          // FIXME: This should use a new expr for a direct reference, don't
730          // turn this into Self->ivar, just return a BareIVarExpr or something.
731          IdentifierInfo &II = Context.Idents.get("self");
732          OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
733                                                          II, false);
734          MarkDeclarationReferenced(Loc, IV);
735          return Owned(new (Context)
736                       ObjCIvarRefExpr(IV, IV->getType(), Loc,
737                                       SelfExpr.takeAs<Expr>(), true, true));
738        }
739      }
740    } else if (getCurMethodDecl()->isInstanceMethod()) {
741      // We should warn if a local variable hides an ivar.
742      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
743      ObjCInterfaceDecl *ClassDeclared;
744      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
745        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
746            IFace == ClassDeclared)
747          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
748      }
749    }
750    // Needed to implement property "super.method" notation.
751    if (D == 0 && II->isStr("super")) {
752      QualType T;
753
754      if (getCurMethodDecl()->isInstanceMethod())
755        T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
756                                      getCurMethodDecl()->getClassInterface()));
757      else
758        T = Context.getObjCClassType();
759      return Owned(new (Context) ObjCSuperExpr(Loc, T));
760    }
761  }
762
763  // Determine whether this name might be a candidate for
764  // argument-dependent lookup.
765  bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
766             HasTrailingLParen;
767
768  if (ADL && D == 0) {
769    // We've seen something of the form
770    //
771    //   identifier(
772    //
773    // and we did not find any entity by the name
774    // "identifier". However, this identifier is still subject to
775    // argument-dependent lookup, so keep track of the name.
776    return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
777                                                          Context.OverloadTy,
778                                                          Loc));
779  }
780
781  if (D == 0) {
782    // Otherwise, this could be an implicitly declared function reference (legal
783    // in C90, extension in C99).
784    if (HasTrailingLParen && II &&
785        !getLangOptions().CPlusPlus) // Not in C++.
786      D = ImplicitlyDefineFunction(Loc, *II, S);
787    else {
788      // If this name wasn't predeclared and if this is not a function call,
789      // diagnose the problem.
790      if (SS && !SS->isEmpty())
791        return ExprError(Diag(Loc, diag::err_typecheck_no_member)
792          << Name << SS->getRange());
793      else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
794               Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
795        return ExprError(Diag(Loc, diag::err_undeclared_use)
796          << Name.getAsString());
797      else
798        return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
799    }
800  }
801
802  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
803    // Warn about constructs like:
804    //   if (void *X = foo()) { ... } else { X }.
805    // In the else block, the pointer is always false.
806
807    // FIXME: In a template instantiation, we don't have scope
808    // information to check this property.
809    if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
810      Scope *CheckS = S;
811      while (CheckS) {
812        if (CheckS->isWithinElse() &&
813            CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
814          if (Var->getType()->isBooleanType())
815            ExprError(Diag(Loc, diag::warn_value_always_false)
816                      << Var->getDeclName());
817          else
818            ExprError(Diag(Loc, diag::warn_value_always_zero)
819                      << Var->getDeclName());
820          break;
821        }
822
823        // Move up one more control parent to check again.
824        CheckS = CheckS->getControlParent();
825        if (CheckS)
826          CheckS = CheckS->getParent();
827      }
828    }
829  } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
830    if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
831      // C99 DR 316 says that, if a function type comes from a
832      // function definition (without a prototype), that type is only
833      // used for checking compatibility. Therefore, when referencing
834      // the function, we pretend that we don't have the full function
835      // type.
836      if (DiagnoseUseOfDecl(Func, Loc))
837        return ExprError();
838
839      QualType T = Func->getType();
840      QualType NoProtoType = T;
841      if (const FunctionProtoType *Proto = T->getAsFunctionProtoType())
842        NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
843      return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
844    }
845  }
846
847  return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
848}
849/// \brief Cast member's object to its own class if necessary.
850bool
851Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
852  if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
853    if (CXXRecordDecl *RD =
854        dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
855      QualType DestType =
856        Context.getCanonicalType(Context.getTypeDeclType(RD));
857      if (DestType->isDependentType() || From->getType()->isDependentType())
858        return false;
859      QualType FromRecordType = From->getType();
860      QualType DestRecordType = DestType;
861      if (FromRecordType->getAs<PointerType>()) {
862        DestType = Context.getPointerType(DestType);
863        FromRecordType = FromRecordType->getPointeeType();
864      }
865      if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
866          CheckDerivedToBaseConversion(FromRecordType,
867                                       DestRecordType,
868                                       From->getSourceRange().getBegin(),
869                                       From->getSourceRange()))
870        return true;
871      ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
872                        /*isLvalue=*/true);
873    }
874  return false;
875}
876
877/// \brief Complete semantic analysis for a reference to the given declaration.
878Sema::OwningExprResult
879Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
880                               bool HasTrailingLParen,
881                               const CXXScopeSpec *SS,
882                               bool isAddressOfOperand) {
883  assert(D && "Cannot refer to a NULL declaration");
884  DeclarationName Name = D->getDeclName();
885
886  // If this is an expression of the form &Class::member, don't build an
887  // implicit member ref, because we want a pointer to the member in general,
888  // not any specific instance's member.
889  if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
890    DeclContext *DC = computeDeclContext(*SS);
891    if (D && isa<CXXRecordDecl>(DC)) {
892      QualType DType;
893      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
894        DType = FD->getType().getNonReferenceType();
895      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
896        DType = Method->getType();
897      } else if (isa<OverloadedFunctionDecl>(D)) {
898        DType = Context.OverloadTy;
899      }
900      // Could be an inner type. That's diagnosed below, so ignore it here.
901      if (!DType.isNull()) {
902        // The pointer is type- and value-dependent if it points into something
903        // dependent.
904        bool Dependent = DC->isDependentContext();
905        return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
906      }
907    }
908  }
909
910  // We may have found a field within an anonymous union or struct
911  // (C++ [class.union]).
912  if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
913    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
914      return BuildAnonymousStructUnionMemberReference(Loc, FD);
915
916  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
917    if (!MD->isStatic()) {
918      // C++ [class.mfct.nonstatic]p2:
919      //   [...] if name lookup (3.4.1) resolves the name in the
920      //   id-expression to a nonstatic nontype member of class X or of
921      //   a base class of X, the id-expression is transformed into a
922      //   class member access expression (5.2.5) using (*this) (9.3.2)
923      //   as the postfix-expression to the left of the '.' operator.
924      DeclContext *Ctx = 0;
925      QualType MemberType;
926      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
927        Ctx = FD->getDeclContext();
928        MemberType = FD->getType();
929
930        if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
931          MemberType = RefType->getPointeeType();
932        else if (!FD->isMutable()) {
933          unsigned combinedQualifiers
934            = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
935          MemberType = MemberType.getQualifiedType(combinedQualifiers);
936        }
937      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
938        if (!Method->isStatic()) {
939          Ctx = Method->getParent();
940          MemberType = Method->getType();
941        }
942      } else if (FunctionTemplateDecl *FunTmpl
943                   = dyn_cast<FunctionTemplateDecl>(D)) {
944        if (CXXMethodDecl *Method
945              = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
946          if (!Method->isStatic()) {
947            Ctx = Method->getParent();
948            MemberType = Context.OverloadTy;
949          }
950        }
951      } else if (OverloadedFunctionDecl *Ovl
952                   = dyn_cast<OverloadedFunctionDecl>(D)) {
953        // FIXME: We need an abstraction for iterating over one or more function
954        // templates or functions. This code is far too repetitive!
955        for (OverloadedFunctionDecl::function_iterator
956               Func = Ovl->function_begin(),
957               FuncEnd = Ovl->function_end();
958             Func != FuncEnd; ++Func) {
959          CXXMethodDecl *DMethod = 0;
960          if (FunctionTemplateDecl *FunTmpl
961                = dyn_cast<FunctionTemplateDecl>(*Func))
962            DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
963          else
964            DMethod = dyn_cast<CXXMethodDecl>(*Func);
965
966          if (DMethod && !DMethod->isStatic()) {
967            Ctx = DMethod->getDeclContext();
968            MemberType = Context.OverloadTy;
969            break;
970          }
971        }
972      }
973
974      if (Ctx && Ctx->isRecord()) {
975        QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
976        QualType ThisType = Context.getTagDeclType(MD->getParent());
977        if ((Context.getCanonicalType(CtxType)
978               == Context.getCanonicalType(ThisType)) ||
979            IsDerivedFrom(ThisType, CtxType)) {
980          // Build the implicit member access expression.
981          Expr *This = new (Context) CXXThisExpr(SourceLocation(),
982                                                 MD->getThisType(Context));
983          MarkDeclarationReferenced(Loc, D);
984          if (PerformObjectMemberConversion(This, D))
985            return ExprError();
986          if (DiagnoseUseOfDecl(D, Loc))
987            return ExprError();
988          return Owned(new (Context) MemberExpr(This, true, D,
989                                                Loc, MemberType));
990        }
991      }
992    }
993  }
994
995  if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
996    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
997      if (MD->isStatic())
998        // "invalid use of member 'x' in static member function"
999        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1000          << FD->getDeclName());
1001    }
1002
1003    // Any other ways we could have found the field in a well-formed
1004    // program would have been turned into implicit member expressions
1005    // above.
1006    return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1007      << FD->getDeclName());
1008  }
1009
1010  if (isa<TypedefDecl>(D))
1011    return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
1012  if (isa<ObjCInterfaceDecl>(D))
1013    return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
1014  if (isa<NamespaceDecl>(D))
1015    return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
1016
1017  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
1018  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
1019    return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1020                           false, false, SS);
1021  else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1022    return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1023                            false, false, SS);
1024  ValueDecl *VD = cast<ValueDecl>(D);
1025
1026  // Check whether this declaration can be used. Note that we suppress
1027  // this check when we're going to perform argument-dependent lookup
1028  // on this function name, because this might not be the function
1029  // that overload resolution actually selects.
1030  bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1031             HasTrailingLParen;
1032  if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1033    return ExprError();
1034
1035  // Only create DeclRefExpr's for valid Decl's.
1036  if (VD->isInvalidDecl())
1037    return ExprError();
1038
1039  // If the identifier reference is inside a block, and it refers to a value
1040  // that is outside the block, create a BlockDeclRefExpr instead of a
1041  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
1042  // the block is formed.
1043  //
1044  // We do not do this for things like enum constants, global variables, etc,
1045  // as they do not get snapshotted.
1046  //
1047  if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
1048    MarkDeclarationReferenced(Loc, VD);
1049    QualType ExprTy = VD->getType().getNonReferenceType();
1050    // The BlocksAttr indicates the variable is bound by-reference.
1051    if (VD->getAttr<BlocksAttr>())
1052      return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1053    // This is to record that a 'const' was actually synthesize and added.
1054    bool constAdded = !ExprTy.isConstQualified();
1055    // Variable will be bound by-copy, make it const within the closure.
1056
1057    ExprTy.addConst();
1058    return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1059                                                constAdded));
1060  }
1061  // If this reference is not in a block or if the referenced variable is
1062  // within the block, create a normal DeclRefExpr.
1063
1064  bool TypeDependent = false;
1065  bool ValueDependent = false;
1066  if (getLangOptions().CPlusPlus) {
1067    // C++ [temp.dep.expr]p3:
1068    //   An id-expression is type-dependent if it contains:
1069    //     - an identifier that was declared with a dependent type,
1070    if (VD->getType()->isDependentType())
1071      TypeDependent = true;
1072    //     - FIXME: a template-id that is dependent,
1073    //     - a conversion-function-id that specifies a dependent type,
1074    else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1075             Name.getCXXNameType()->isDependentType())
1076      TypeDependent = true;
1077    //     - a nested-name-specifier that contains a class-name that
1078    //       names a dependent type.
1079    else if (SS && !SS->isEmpty()) {
1080      for (DeclContext *DC = computeDeclContext(*SS);
1081           DC; DC = DC->getParent()) {
1082        // FIXME: could stop early at namespace scope.
1083        if (DC->isRecord()) {
1084          CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1085          if (Context.getTypeDeclType(Record)->isDependentType()) {
1086            TypeDependent = true;
1087            break;
1088          }
1089        }
1090      }
1091    }
1092
1093    // C++ [temp.dep.constexpr]p2:
1094    //
1095    //   An identifier is value-dependent if it is:
1096    //     - a name declared with a dependent type,
1097    if (TypeDependent)
1098      ValueDependent = true;
1099    //     - the name of a non-type template parameter,
1100    else if (isa<NonTypeTemplateParmDecl>(VD))
1101      ValueDependent = true;
1102    //    - a constant with integral or enumeration type and is
1103    //      initialized with an expression that is value-dependent
1104    else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1105      if (Dcl->getType().getCVRQualifiers() == QualType::Const &&
1106          Dcl->getInit()) {
1107        ValueDependent = Dcl->getInit()->isValueDependent();
1108      }
1109    }
1110  }
1111
1112  return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1113                          TypeDependent, ValueDependent, SS);
1114}
1115
1116Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1117                                                 tok::TokenKind Kind) {
1118  PredefinedExpr::IdentType IT;
1119
1120  switch (Kind) {
1121  default: assert(0 && "Unknown simple primary expr!");
1122  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1123  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1124  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1125  }
1126
1127  // Pre-defined identifiers are of type char[x], where x is the length of the
1128  // string.
1129  unsigned Length;
1130  if (FunctionDecl *FD = getCurFunctionDecl())
1131    Length = FD->getIdentifier()->getLength();
1132  else if (ObjCMethodDecl *MD = getCurMethodDecl())
1133    Length = MD->getSynthesizedMethodSize();
1134  else {
1135    Diag(Loc, diag::ext_predef_outside_function);
1136    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
1137    Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
1138  }
1139
1140
1141  llvm::APInt LengthI(32, Length + 1);
1142  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
1143  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1144  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1145}
1146
1147Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1148  llvm::SmallString<16> CharBuffer;
1149  CharBuffer.resize(Tok.getLength());
1150  const char *ThisTokBegin = &CharBuffer[0];
1151  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1152
1153  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1154                            Tok.getLocation(), PP);
1155  if (Literal.hadError())
1156    return ExprError();
1157
1158  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1159
1160  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1161                                              Literal.isWide(),
1162                                              type, Tok.getLocation()));
1163}
1164
1165Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1166  // Fast path for a single digit (which is quite common).  A single digit
1167  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1168  if (Tok.getLength() == 1) {
1169    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1170    unsigned IntSize = Context.Target.getIntWidth();
1171    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1172                    Context.IntTy, Tok.getLocation()));
1173  }
1174
1175  llvm::SmallString<512> IntegerBuffer;
1176  // Add padding so that NumericLiteralParser can overread by one character.
1177  IntegerBuffer.resize(Tok.getLength()+1);
1178  const char *ThisTokBegin = &IntegerBuffer[0];
1179
1180  // Get the spelling of the token, which eliminates trigraphs, etc.
1181  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1182
1183  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1184                               Tok.getLocation(), PP);
1185  if (Literal.hadError)
1186    return ExprError();
1187
1188  Expr *Res;
1189
1190  if (Literal.isFloatingLiteral()) {
1191    QualType Ty;
1192    if (Literal.isFloat)
1193      Ty = Context.FloatTy;
1194    else if (!Literal.isLong)
1195      Ty = Context.DoubleTy;
1196    else
1197      Ty = Context.LongDoubleTy;
1198
1199    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1200
1201    // isExact will be set by GetFloatValue().
1202    bool isExact = false;
1203    llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1204    Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1205
1206  } else if (!Literal.isIntegerLiteral()) {
1207    return ExprError();
1208  } else {
1209    QualType Ty;
1210
1211    // long long is a C99 feature.
1212    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1213        Literal.isLongLong)
1214      Diag(Tok.getLocation(), diag::ext_longlong);
1215
1216    // Get the value in the widest-possible width.
1217    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1218
1219    if (Literal.GetIntegerValue(ResultVal)) {
1220      // If this value didn't fit into uintmax_t, warn and force to ull.
1221      Diag(Tok.getLocation(), diag::warn_integer_too_large);
1222      Ty = Context.UnsignedLongLongTy;
1223      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1224             "long long is not intmax_t?");
1225    } else {
1226      // If this value fits into a ULL, try to figure out what else it fits into
1227      // according to the rules of C99 6.4.4.1p5.
1228
1229      // Octal, Hexadecimal, and integers with a U suffix are allowed to
1230      // be an unsigned int.
1231      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1232
1233      // Check from smallest to largest, picking the smallest type we can.
1234      unsigned Width = 0;
1235      if (!Literal.isLong && !Literal.isLongLong) {
1236        // Are int/unsigned possibilities?
1237        unsigned IntSize = Context.Target.getIntWidth();
1238
1239        // Does it fit in a unsigned int?
1240        if (ResultVal.isIntN(IntSize)) {
1241          // Does it fit in a signed int?
1242          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1243            Ty = Context.IntTy;
1244          else if (AllowUnsigned)
1245            Ty = Context.UnsignedIntTy;
1246          Width = IntSize;
1247        }
1248      }
1249
1250      // Are long/unsigned long possibilities?
1251      if (Ty.isNull() && !Literal.isLongLong) {
1252        unsigned LongSize = Context.Target.getLongWidth();
1253
1254        // Does it fit in a unsigned long?
1255        if (ResultVal.isIntN(LongSize)) {
1256          // Does it fit in a signed long?
1257          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1258            Ty = Context.LongTy;
1259          else if (AllowUnsigned)
1260            Ty = Context.UnsignedLongTy;
1261          Width = LongSize;
1262        }
1263      }
1264
1265      // Finally, check long long if needed.
1266      if (Ty.isNull()) {
1267        unsigned LongLongSize = Context.Target.getLongLongWidth();
1268
1269        // Does it fit in a unsigned long long?
1270        if (ResultVal.isIntN(LongLongSize)) {
1271          // Does it fit in a signed long long?
1272          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1273            Ty = Context.LongLongTy;
1274          else if (AllowUnsigned)
1275            Ty = Context.UnsignedLongLongTy;
1276          Width = LongLongSize;
1277        }
1278      }
1279
1280      // If we still couldn't decide a type, we probably have something that
1281      // does not fit in a signed long long, but has no U suffix.
1282      if (Ty.isNull()) {
1283        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1284        Ty = Context.UnsignedLongLongTy;
1285        Width = Context.Target.getLongLongWidth();
1286      }
1287
1288      if (ResultVal.getBitWidth() != Width)
1289        ResultVal.trunc(Width);
1290    }
1291    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1292  }
1293
1294  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1295  if (Literal.isImaginary)
1296    Res = new (Context) ImaginaryLiteral(Res,
1297                                        Context.getComplexType(Res->getType()));
1298
1299  return Owned(Res);
1300}
1301
1302Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1303                                              SourceLocation R, ExprArg Val) {
1304  Expr *E = Val.takeAs<Expr>();
1305  assert((E != 0) && "ActOnParenExpr() missing expr");
1306  return Owned(new (Context) ParenExpr(L, R, E));
1307}
1308
1309/// The UsualUnaryConversions() function is *not* called by this routine.
1310/// See C99 6.3.2.1p[2-4] for more details.
1311bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1312                                     SourceLocation OpLoc,
1313                                     const SourceRange &ExprRange,
1314                                     bool isSizeof) {
1315  if (exprType->isDependentType())
1316    return false;
1317
1318  // C99 6.5.3.4p1:
1319  if (isa<FunctionType>(exprType)) {
1320    // alignof(function) is allowed as an extension.
1321    if (isSizeof)
1322      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1323    return false;
1324  }
1325
1326  // Allow sizeof(void)/alignof(void) as an extension.
1327  if (exprType->isVoidType()) {
1328    Diag(OpLoc, diag::ext_sizeof_void_type)
1329      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1330    return false;
1331  }
1332
1333  if (RequireCompleteType(OpLoc, exprType,
1334                          isSizeof ? diag::err_sizeof_incomplete_type :
1335                          diag::err_alignof_incomplete_type,
1336                          ExprRange))
1337    return true;
1338
1339  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
1340  if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
1341    Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
1342      << exprType << isSizeof << ExprRange;
1343    return true;
1344  }
1345
1346  return false;
1347}
1348
1349bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1350                            const SourceRange &ExprRange) {
1351  E = E->IgnoreParens();
1352
1353  // alignof decl is always ok.
1354  if (isa<DeclRefExpr>(E))
1355    return false;
1356
1357  // Cannot know anything else if the expression is dependent.
1358  if (E->isTypeDependent())
1359    return false;
1360
1361  if (E->getBitField()) {
1362    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1363    return true;
1364  }
1365
1366  // Alignment of a field access is always okay, so long as it isn't a
1367  // bit-field.
1368  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1369    if (isa<FieldDecl>(ME->getMemberDecl()))
1370      return false;
1371
1372  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1373}
1374
1375/// \brief Build a sizeof or alignof expression given a type operand.
1376Action::OwningExprResult
1377Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1378                              bool isSizeOf, SourceRange R) {
1379  if (T.isNull())
1380    return ExprError();
1381
1382  if (!T->isDependentType() &&
1383      CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1384    return ExprError();
1385
1386  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1387  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1388                                               Context.getSizeType(), OpLoc,
1389                                               R.getEnd()));
1390}
1391
1392/// \brief Build a sizeof or alignof expression given an expression
1393/// operand.
1394Action::OwningExprResult
1395Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1396                              bool isSizeOf, SourceRange R) {
1397  // Verify that the operand is valid.
1398  bool isInvalid = false;
1399  if (E->isTypeDependent()) {
1400    // Delay type-checking for type-dependent expressions.
1401  } else if (!isSizeOf) {
1402    isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1403  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
1404    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1405    isInvalid = true;
1406  } else {
1407    isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1408  }
1409
1410  if (isInvalid)
1411    return ExprError();
1412
1413  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1414  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1415                                               Context.getSizeType(), OpLoc,
1416                                               R.getEnd()));
1417}
1418
1419/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1420/// the same for @c alignof and @c __alignof
1421/// Note that the ArgRange is invalid if isType is false.
1422Action::OwningExprResult
1423Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1424                             void *TyOrEx, const SourceRange &ArgRange) {
1425  // If error parsing type, ignore.
1426  if (TyOrEx == 0) return ExprError();
1427
1428  if (isType) {
1429    // FIXME: Preserve type source info.
1430    QualType ArgTy = GetTypeFromParser(TyOrEx);
1431    return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1432  }
1433
1434  // Get the end location.
1435  Expr *ArgEx = (Expr *)TyOrEx;
1436  Action::OwningExprResult Result
1437    = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1438
1439  if (Result.isInvalid())
1440    DeleteExpr(ArgEx);
1441
1442  return move(Result);
1443}
1444
1445QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1446  if (V->isTypeDependent())
1447    return Context.DependentTy;
1448
1449  // These operators return the element type of a complex type.
1450  if (const ComplexType *CT = V->getType()->getAsComplexType())
1451    return CT->getElementType();
1452
1453  // Otherwise they pass through real integer and floating point types here.
1454  if (V->getType()->isArithmeticType())
1455    return V->getType();
1456
1457  // Reject anything else.
1458  Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1459    << (isReal ? "__real" : "__imag");
1460  return QualType();
1461}
1462
1463
1464
1465Action::OwningExprResult
1466Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1467                          tok::TokenKind Kind, ExprArg Input) {
1468  // Since this might be a postfix expression, get rid of ParenListExprs.
1469  Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
1470  Expr *Arg = (Expr *)Input.get();
1471
1472  UnaryOperator::Opcode Opc;
1473  switch (Kind) {
1474  default: assert(0 && "Unknown unary op!");
1475  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1476  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1477  }
1478
1479  if (getLangOptions().CPlusPlus &&
1480      (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1481    // Which overloaded operator?
1482    OverloadedOperatorKind OverOp =
1483      (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1484
1485    // C++ [over.inc]p1:
1486    //
1487    //     [...] If the function is a member function with one
1488    //     parameter (which shall be of type int) or a non-member
1489    //     function with two parameters (the second of which shall be
1490    //     of type int), it defines the postfix increment operator ++
1491    //     for objects of that type. When the postfix increment is
1492    //     called as a result of using the ++ operator, the int
1493    //     argument will have value zero.
1494    Expr *Args[2] = {
1495      Arg,
1496      new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1497                          /*isSigned=*/true), Context.IntTy, SourceLocation())
1498    };
1499
1500    // Build the candidate set for overloading
1501    OverloadCandidateSet CandidateSet;
1502    AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
1503
1504    // Perform overload resolution.
1505    OverloadCandidateSet::iterator Best;
1506    switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
1507    case OR_Success: {
1508      // We found a built-in operator or an overloaded operator.
1509      FunctionDecl *FnDecl = Best->Function;
1510
1511      if (FnDecl) {
1512        // We matched an overloaded operator. Build a call to that
1513        // operator.
1514
1515        // Convert the arguments.
1516        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1517          if (PerformObjectArgumentInitialization(Arg, Method))
1518            return ExprError();
1519        } else {
1520          // Convert the arguments.
1521          if (PerformCopyInitialization(Arg,
1522                                        FnDecl->getParamDecl(0)->getType(),
1523                                        "passing"))
1524            return ExprError();
1525        }
1526
1527        // Determine the result type
1528        QualType ResultTy
1529          = FnDecl->getType()->getAsFunctionType()->getResultType();
1530        ResultTy = ResultTy.getNonReferenceType();
1531
1532        // Build the actual expression node.
1533        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1534                                                 SourceLocation());
1535        UsualUnaryConversions(FnExpr);
1536
1537        Input.release();
1538        Args[0] = Arg;
1539        return Owned(new (Context) CXXOperatorCallExpr(Context, OverOp, FnExpr,
1540                                                       Args, 2, ResultTy,
1541                                                       OpLoc));
1542      } else {
1543        // We matched a built-in operator. Convert the arguments, then
1544        // break out so that we will build the appropriate built-in
1545        // operator node.
1546        if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1547                                      "passing"))
1548          return ExprError();
1549
1550        break;
1551      }
1552    }
1553
1554    case OR_No_Viable_Function:
1555      // No viable function; fall through to handling this as a
1556      // built-in operator, which will produce an error message for us.
1557      break;
1558
1559    case OR_Ambiguous:
1560      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1561          << UnaryOperator::getOpcodeStr(Opc)
1562          << Arg->getSourceRange();
1563      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1564      return ExprError();
1565
1566    case OR_Deleted:
1567      Diag(OpLoc, diag::err_ovl_deleted_oper)
1568        << Best->Function->isDeleted()
1569        << UnaryOperator::getOpcodeStr(Opc)
1570        << Arg->getSourceRange();
1571      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1572      return ExprError();
1573    }
1574
1575    // Either we found no viable overloaded operator or we matched a
1576    // built-in operator. In either case, fall through to trying to
1577    // build a built-in operation.
1578  }
1579
1580  Input.release();
1581  Input = Arg;
1582  return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1583}
1584
1585Action::OwningExprResult
1586Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1587                              ExprArg Idx, SourceLocation RLoc) {
1588  // Since this might be a postfix expression, get rid of ParenListExprs.
1589  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1590
1591  Expr *LHSExp = static_cast<Expr*>(Base.get()),
1592       *RHSExp = static_cast<Expr*>(Idx.get());
1593
1594  if (getLangOptions().CPlusPlus &&
1595      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1596    Base.release();
1597    Idx.release();
1598    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1599                                                  Context.DependentTy, RLoc));
1600  }
1601
1602  if (getLangOptions().CPlusPlus &&
1603      (LHSExp->getType()->isRecordType() ||
1604       LHSExp->getType()->isEnumeralType() ||
1605       RHSExp->getType()->isRecordType() ||
1606       RHSExp->getType()->isEnumeralType())) {
1607    // Add the appropriate overloaded operators (C++ [over.match.oper])
1608    // to the candidate set.
1609    OverloadCandidateSet CandidateSet;
1610    Expr *Args[2] = { LHSExp, RHSExp };
1611    AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1612                          SourceRange(LLoc, RLoc));
1613
1614    // Perform overload resolution.
1615    OverloadCandidateSet::iterator Best;
1616    switch (BestViableFunction(CandidateSet, LLoc, Best)) {
1617    case OR_Success: {
1618      // We found a built-in operator or an overloaded operator.
1619      FunctionDecl *FnDecl = Best->Function;
1620
1621      if (FnDecl) {
1622        // We matched an overloaded operator. Build a call to that
1623        // operator.
1624
1625        // Convert the arguments.
1626        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1627          if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1628              PerformCopyInitialization(RHSExp,
1629                                        FnDecl->getParamDecl(0)->getType(),
1630                                        "passing"))
1631            return ExprError();
1632        } else {
1633          // Convert the arguments.
1634          if (PerformCopyInitialization(LHSExp,
1635                                        FnDecl->getParamDecl(0)->getType(),
1636                                        "passing") ||
1637              PerformCopyInitialization(RHSExp,
1638                                        FnDecl->getParamDecl(1)->getType(),
1639                                        "passing"))
1640            return ExprError();
1641        }
1642
1643        // Determine the result type
1644        QualType ResultTy
1645          = FnDecl->getType()->getAsFunctionType()->getResultType();
1646        ResultTy = ResultTy.getNonReferenceType();
1647
1648        // Build the actual expression node.
1649        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1650                                                 SourceLocation());
1651        UsualUnaryConversions(FnExpr);
1652
1653        Base.release();
1654        Idx.release();
1655        Args[0] = LHSExp;
1656        Args[1] = RHSExp;
1657        return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1658                                                       FnExpr, Args, 2,
1659                                                       ResultTy, LLoc));
1660      } else {
1661        // We matched a built-in operator. Convert the arguments, then
1662        // break out so that we will build the appropriate built-in
1663        // operator node.
1664        if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1665                                      "passing") ||
1666            PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1667                                      "passing"))
1668          return ExprError();
1669
1670        break;
1671      }
1672    }
1673
1674    case OR_No_Viable_Function:
1675      // No viable function; fall through to handling this as a
1676      // built-in operator, which will produce an error message for us.
1677      break;
1678
1679    case OR_Ambiguous:
1680      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
1681          << "[]"
1682          << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1683      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1684      return ExprError();
1685
1686    case OR_Deleted:
1687      Diag(LLoc, diag::err_ovl_deleted_oper)
1688        << Best->Function->isDeleted()
1689        << "[]"
1690        << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1691      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1692      return ExprError();
1693    }
1694
1695    // Either we found no viable overloaded operator or we matched a
1696    // built-in operator. In either case, fall through to trying to
1697    // build a built-in operation.
1698  }
1699
1700  // Perform default conversions.
1701  DefaultFunctionArrayConversion(LHSExp);
1702  DefaultFunctionArrayConversion(RHSExp);
1703
1704  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1705
1706  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1707  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1708  // in the subscript position. As a result, we need to derive the array base
1709  // and index from the expression types.
1710  Expr *BaseExpr, *IndexExpr;
1711  QualType ResultType;
1712  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1713    BaseExpr = LHSExp;
1714    IndexExpr = RHSExp;
1715    ResultType = Context.DependentTy;
1716  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
1717    BaseExpr = LHSExp;
1718    IndexExpr = RHSExp;
1719    ResultType = PTy->getPointeeType();
1720  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
1721     // Handle the uncommon case of "123[Ptr]".
1722    BaseExpr = RHSExp;
1723    IndexExpr = LHSExp;
1724    ResultType = PTy->getPointeeType();
1725  } else if (const ObjCObjectPointerType *PTy =
1726               LHSTy->getAsObjCObjectPointerType()) {
1727    BaseExpr = LHSExp;
1728    IndexExpr = RHSExp;
1729    ResultType = PTy->getPointeeType();
1730  } else if (const ObjCObjectPointerType *PTy =
1731               RHSTy->getAsObjCObjectPointerType()) {
1732     // Handle the uncommon case of "123[Ptr]".
1733    BaseExpr = RHSExp;
1734    IndexExpr = LHSExp;
1735    ResultType = PTy->getPointeeType();
1736  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1737    BaseExpr = LHSExp;    // vectors: V[123]
1738    IndexExpr = RHSExp;
1739
1740    // FIXME: need to deal with const...
1741    ResultType = VTy->getElementType();
1742  } else if (LHSTy->isArrayType()) {
1743    // If we see an array that wasn't promoted by
1744    // DefaultFunctionArrayConversion, it must be an array that
1745    // wasn't promoted because of the C90 rule that doesn't
1746    // allow promoting non-lvalue arrays.  Warn, then
1747    // force the promotion here.
1748    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1749        LHSExp->getSourceRange();
1750    ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1751    LHSTy = LHSExp->getType();
1752
1753    BaseExpr = LHSExp;
1754    IndexExpr = RHSExp;
1755    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
1756  } else if (RHSTy->isArrayType()) {
1757    // Same as previous, except for 123[f().a] case
1758    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1759        RHSExp->getSourceRange();
1760    ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1761    RHSTy = RHSExp->getType();
1762
1763    BaseExpr = RHSExp;
1764    IndexExpr = LHSExp;
1765    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
1766  } else {
1767    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1768       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
1769  }
1770  // C99 6.5.2.1p1
1771  if (!(IndexExpr->getType()->isIntegerType() &&
1772        IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
1773    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1774                     << IndexExpr->getSourceRange());
1775
1776  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1777  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1778  // type. Note that Functions are not objects, and that (in C99 parlance)
1779  // incomplete types are not object types.
1780  if (ResultType->isFunctionType()) {
1781    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1782      << ResultType << BaseExpr->getSourceRange();
1783    return ExprError();
1784  }
1785
1786  if (!ResultType->isDependentType() &&
1787      RequireCompleteType(LLoc, ResultType, diag::err_subscript_incomplete_type,
1788                          BaseExpr->getSourceRange()))
1789    return ExprError();
1790
1791  // Diagnose bad cases where we step over interface counts.
1792  if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1793    Diag(LLoc, diag::err_subscript_nonfragile_interface)
1794      << ResultType << BaseExpr->getSourceRange();
1795    return ExprError();
1796  }
1797
1798  Base.release();
1799  Idx.release();
1800  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1801                                                ResultType, RLoc));
1802}
1803
1804QualType Sema::
1805CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1806                        IdentifierInfo &CompName, SourceLocation CompLoc) {
1807  const ExtVectorType *vecType = baseType->getAsExtVectorType();
1808
1809  // The vector accessor can't exceed the number of elements.
1810  const char *compStr = CompName.getName();
1811
1812  // This flag determines whether or not the component is one of the four
1813  // special names that indicate a subset of exactly half the elements are
1814  // to be selected.
1815  bool HalvingSwizzle = false;
1816
1817  // This flag determines whether or not CompName has an 's' char prefix,
1818  // indicating that it is a string of hex values to be used as vector indices.
1819  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
1820
1821  // Check that we've found one of the special components, or that the component
1822  // names must come from the same set.
1823  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1824      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1825    HalvingSwizzle = true;
1826  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1827    do
1828      compStr++;
1829    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1830  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1831    do
1832      compStr++;
1833    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1834  }
1835
1836  if (!HalvingSwizzle && *compStr) {
1837    // We didn't get to the end of the string. This means the component names
1838    // didn't come from the same set *or* we encountered an illegal name.
1839    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1840      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1841    return QualType();
1842  }
1843
1844  // Ensure no component accessor exceeds the width of the vector type it
1845  // operates on.
1846  if (!HalvingSwizzle) {
1847    compStr = CompName.getName();
1848
1849    if (HexSwizzle)
1850      compStr++;
1851
1852    while (*compStr) {
1853      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1854        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1855          << baseType << SourceRange(CompLoc);
1856        return QualType();
1857      }
1858    }
1859  }
1860
1861  // If this is a halving swizzle, verify that the base type has an even
1862  // number of elements.
1863  if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1864    Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1865      << baseType << SourceRange(CompLoc);
1866    return QualType();
1867  }
1868
1869  // The component accessor looks fine - now we need to compute the actual type.
1870  // The vector type is implied by the component accessor. For example,
1871  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1872  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1873  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1874  unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1875                                     : CompName.getLength();
1876  if (HexSwizzle)
1877    CompSize--;
1878
1879  if (CompSize == 1)
1880    return vecType->getElementType();
1881
1882  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1883  // Now look up the TypeDefDecl from the vector type. Without this,
1884  // diagostics look bad. We want extended vector types to appear built-in.
1885  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1886    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1887      return Context.getTypedefType(ExtVectorDecls[i]);
1888  }
1889  return VT; // should never get here (a typedef type should always be found).
1890}
1891
1892static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1893                                                IdentifierInfo &Member,
1894                                                const Selector &Sel,
1895                                                ASTContext &Context) {
1896
1897  if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(&Member))
1898    return PD;
1899  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1900    return OMD;
1901
1902  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1903       E = PDecl->protocol_end(); I != E; ++I) {
1904    if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1905                                                     Context))
1906      return D;
1907  }
1908  return 0;
1909}
1910
1911static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
1912                                IdentifierInfo &Member,
1913                                const Selector &Sel,
1914                                ASTContext &Context) {
1915  // Check protocols on qualified interfaces.
1916  Decl *GDecl = 0;
1917  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1918       E = QIdTy->qual_end(); I != E; ++I) {
1919    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1920      GDecl = PD;
1921      break;
1922    }
1923    // Also must look for a getter name which uses property syntax.
1924    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1925      GDecl = OMD;
1926      break;
1927    }
1928  }
1929  if (!GDecl) {
1930    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1931         E = QIdTy->qual_end(); I != E; ++I) {
1932      // Search in the protocol-qualifier list of current protocol.
1933      GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
1934      if (GDecl)
1935        return GDecl;
1936    }
1937  }
1938  return GDecl;
1939}
1940
1941/// FindMethodInNestedImplementations - Look up a method in current and
1942/// all base class implementations.
1943///
1944ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1945                                              const ObjCInterfaceDecl *IFace,
1946                                              const Selector &Sel) {
1947  ObjCMethodDecl *Method = 0;
1948  if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
1949    Method = ImpDecl->getInstanceMethod(Sel);
1950
1951  if (!Method && IFace->getSuperClass())
1952    return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1953  return Method;
1954}
1955
1956Action::OwningExprResult
1957Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1958                               tok::TokenKind OpKind, SourceLocation MemberLoc,
1959                               IdentifierInfo &Member,
1960                               DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
1961  // FIXME: handle the CXXScopeSpec for proper lookup of qualified-ids
1962  if (SS && SS->isInvalid())
1963    return ExprError();
1964
1965  // Since this might be a postfix expression, get rid of ParenListExprs.
1966  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1967
1968  Expr *BaseExpr = Base.takeAs<Expr>();
1969  assert(BaseExpr && "no record expression");
1970
1971  // Perform default conversions.
1972  DefaultFunctionArrayConversion(BaseExpr);
1973
1974  QualType BaseType = BaseExpr->getType();
1975  // If this is an Objective-C pseudo-builtin and a definition is provided then
1976  // use that.
1977  if (BaseType->isObjCIdType()) {
1978    // We have an 'id' type. Rather than fall through, we check if this
1979    // is a reference to 'isa'.
1980    if (BaseType != Context.ObjCIdRedefinitionType) {
1981      BaseType = Context.ObjCIdRedefinitionType;
1982      ImpCastExprToType(BaseExpr, BaseType);
1983    }
1984  } else if (BaseType->isObjCClassType() &&
1985      BaseType != Context.ObjCClassRedefinitionType) {
1986    BaseType = Context.ObjCClassRedefinitionType;
1987    ImpCastExprToType(BaseExpr, BaseType);
1988  }
1989  assert(!BaseType.isNull() && "no type for member expression");
1990
1991  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
1992  // must have pointer type, and the accessed type is the pointee.
1993  if (OpKind == tok::arrow) {
1994    if (BaseType->isDependentType())
1995      return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
1996                                                         BaseExpr, true,
1997                                                         OpLoc,
1998                                                     DeclarationName(&Member),
1999                                                         MemberLoc));
2000    else if (const PointerType *PT = BaseType->getAs<PointerType>())
2001      BaseType = PT->getPointeeType();
2002    else if (BaseType->isObjCObjectPointerType())
2003      ;
2004    else
2005      return ExprError(Diag(MemberLoc,
2006                            diag::err_typecheck_member_reference_arrow)
2007        << BaseType << BaseExpr->getSourceRange());
2008  } else {
2009    if (BaseType->isDependentType()) {
2010      // Require that the base type isn't a pointer type
2011      // (so we'll report an error for)
2012      // T* t;
2013      // t.f;
2014      //
2015      // In Obj-C++, however, the above expression is valid, since it could be
2016      // accessing the 'f' property if T is an Obj-C interface. The extra check
2017      // allows this, while still reporting an error if T is a struct pointer.
2018      const PointerType *PT = BaseType->getAs<PointerType>();
2019
2020      if (!PT || (getLangOptions().ObjC1 &&
2021                  !PT->getPointeeType()->isRecordType()))
2022        return Owned(new (Context) CXXUnresolvedMemberExpr(Context,
2023                                                           BaseExpr, false,
2024                                                           OpLoc,
2025                                                     DeclarationName(&Member),
2026                                                           MemberLoc));
2027    }
2028  }
2029
2030  // Handle field access to simple records.  This also handles access to fields
2031  // of the ObjC 'id' struct.
2032  if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
2033    RecordDecl *RDecl = RTy->getDecl();
2034    if (RequireCompleteType(OpLoc, BaseType,
2035                               diag::err_typecheck_incomplete_tag,
2036                               BaseExpr->getSourceRange()))
2037      return ExprError();
2038
2039    DeclContext *DC = RDecl;
2040    if (SS && SS->isSet()) {
2041      // If the member name was a qualified-id, look into the
2042      // nested-name-specifier.
2043      DC = computeDeclContext(*SS, false);
2044
2045      // FIXME: If DC is not computable, we should build a
2046      // CXXUnresolvedMemberExpr.
2047      assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2048    }
2049
2050    // The record definition is complete, now make sure the member is valid.
2051    LookupResult Result
2052      = LookupQualifiedName(DC, DeclarationName(&Member),
2053                            LookupMemberName, false);
2054
2055    if (SS && SS->isSet()) {
2056      QualType BaseTypeCanon
2057        = Context.getCanonicalType(BaseType).getUnqualifiedType();
2058      QualType MemberTypeCanon
2059        = Context.getCanonicalType(
2060            Context.getTypeDeclType(
2061                     dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2062
2063      if (BaseTypeCanon != MemberTypeCanon &&
2064          !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2065        return ExprError(Diag(SS->getBeginLoc(),
2066                              diag::err_not_direct_base_or_virtual)
2067                         << MemberTypeCanon << BaseTypeCanon);
2068    }
2069
2070    if (!Result)
2071      return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2072               << &Member << BaseExpr->getSourceRange());
2073    if (Result.isAmbiguous()) {
2074      DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
2075                              MemberLoc, BaseExpr->getSourceRange());
2076      return ExprError();
2077    }
2078
2079    NamedDecl *MemberDecl = Result;
2080
2081    // If the decl being referenced had an error, return an error for this
2082    // sub-expr without emitting another error, in order to avoid cascading
2083    // error cases.
2084    if (MemberDecl->isInvalidDecl())
2085      return ExprError();
2086
2087    // Check the use of this field
2088    if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2089      return ExprError();
2090
2091    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2092      // We may have found a field within an anonymous union or struct
2093      // (C++ [class.union]).
2094      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2095        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2096                                                        BaseExpr, OpLoc);
2097
2098      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2099      QualType MemberType = FD->getType();
2100      if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2101        MemberType = Ref->getPointeeType();
2102      else {
2103        unsigned BaseAddrSpace = BaseType.getAddressSpace();
2104        unsigned combinedQualifiers =
2105          MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
2106        if (FD->isMutable())
2107          combinedQualifiers &= ~QualType::Const;
2108        MemberType = MemberType.getQualifiedType(combinedQualifiers);
2109        if (BaseAddrSpace != MemberType.getAddressSpace())
2110           MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
2111      }
2112
2113      MarkDeclarationReferenced(MemberLoc, FD);
2114      if (PerformObjectMemberConversion(BaseExpr, FD))
2115        return ExprError();
2116      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2117                                            MemberLoc, MemberType));
2118    }
2119
2120    if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2121      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2122      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2123                                            Var, MemberLoc,
2124                                         Var->getType().getNonReferenceType()));
2125    }
2126    if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2127      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2128      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2129                                            MemberFn, MemberLoc,
2130                                            MemberFn->getType()));
2131    }
2132    if (FunctionTemplateDecl *FunTmpl
2133          = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2134      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2135      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2136                                            FunTmpl, MemberLoc,
2137                                            Context.OverloadTy));
2138    }
2139    if (OverloadedFunctionDecl *Ovl
2140          = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
2141      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
2142                                            MemberLoc, Context.OverloadTy));
2143    if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2144      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2145      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2146                                            Enum, MemberLoc, Enum->getType()));
2147    }
2148    if (isa<TypeDecl>(MemberDecl))
2149      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2150        << DeclarationName(&Member) << int(OpKind == tok::arrow));
2151
2152    // We found a declaration kind that we didn't expect. This is a
2153    // generic error message that tells the user that she can't refer
2154    // to this member with '.' or '->'.
2155    return ExprError(Diag(MemberLoc,
2156                          diag::err_typecheck_member_reference_unknown)
2157      << DeclarationName(&Member) << int(OpKind == tok::arrow));
2158  }
2159
2160  // Handle properties on ObjC 'Class' types.
2161  if (OpKind == tok::period && BaseType->isObjCClassType()) {
2162    // Also must look for a getter name which uses property syntax.
2163    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2164    if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2165      ObjCInterfaceDecl *IFace = MD->getClassInterface();
2166      ObjCMethodDecl *Getter;
2167      // FIXME: need to also look locally in the implementation.
2168      if ((Getter = IFace->lookupClassMethod(Sel))) {
2169        // Check the use of this method.
2170        if (DiagnoseUseOfDecl(Getter, MemberLoc))
2171          return ExprError();
2172      }
2173      // If we found a getter then this may be a valid dot-reference, we
2174      // will look for the matching setter, in case it is needed.
2175      Selector SetterSel =
2176        SelectorTable::constructSetterName(PP.getIdentifierTable(),
2177                                           PP.getSelectorTable(), &Member);
2178      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2179      if (!Setter) {
2180        // If this reference is in an @implementation, also check for 'private'
2181        // methods.
2182        Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2183      }
2184      // Look through local category implementations associated with the class.
2185      if (!Setter)
2186        Setter = IFace->getCategoryClassMethod(SetterSel);
2187
2188      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2189        return ExprError();
2190
2191      if (Getter || Setter) {
2192        QualType PType;
2193
2194        if (Getter)
2195          PType = Getter->getResultType();
2196        else
2197          // Get the expression type from Setter's incoming parameter.
2198          PType = (*(Setter->param_end() -1))->getType();
2199        // FIXME: we must check that the setter has property type.
2200        return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
2201                                        Setter, MemberLoc, BaseExpr));
2202      }
2203      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2204        << &Member << BaseType);
2205    }
2206  }
2207  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2208  // (*Obj).ivar.
2209  if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2210      (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2211    const ObjCObjectPointerType *OPT = BaseType->getAsObjCObjectPointerType();
2212    const ObjCInterfaceType *IFaceT =
2213      OPT ? OPT->getInterfaceType() : BaseType->getAsObjCInterfaceType();
2214    if (IFaceT) {
2215      ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2216      ObjCInterfaceDecl *ClassDeclared;
2217      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(&Member, ClassDeclared);
2218
2219      if (IV) {
2220        // If the decl being referenced had an error, return an error for this
2221        // sub-expr without emitting another error, in order to avoid cascading
2222        // error cases.
2223        if (IV->isInvalidDecl())
2224          return ExprError();
2225
2226        // Check whether we can reference this field.
2227        if (DiagnoseUseOfDecl(IV, MemberLoc))
2228          return ExprError();
2229        if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2230            IV->getAccessControl() != ObjCIvarDecl::Package) {
2231          ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2232          if (ObjCMethodDecl *MD = getCurMethodDecl())
2233            ClassOfMethodDecl =  MD->getClassInterface();
2234          else if (ObjCImpDecl && getCurFunctionDecl()) {
2235            // Case of a c-function declared inside an objc implementation.
2236            // FIXME: For a c-style function nested inside an objc implementation
2237            // class, there is no implementation context available, so we pass
2238            // down the context as argument to this routine. Ideally, this context
2239            // need be passed down in the AST node and somehow calculated from the
2240            // AST for a function decl.
2241            Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2242            if (ObjCImplementationDecl *IMPD =
2243                dyn_cast<ObjCImplementationDecl>(ImplDecl))
2244              ClassOfMethodDecl = IMPD->getClassInterface();
2245            else if (ObjCCategoryImplDecl* CatImplClass =
2246                        dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2247              ClassOfMethodDecl = CatImplClass->getClassInterface();
2248          }
2249
2250          if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2251            if (ClassDeclared != IDecl ||
2252                ClassOfMethodDecl != ClassDeclared)
2253              Diag(MemberLoc, diag::error_private_ivar_access)
2254                << IV->getDeclName();
2255          } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2256            // @protected
2257            Diag(MemberLoc, diag::error_protected_ivar_access)
2258              << IV->getDeclName();
2259        }
2260
2261        return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2262                                                   MemberLoc, BaseExpr,
2263                                                   OpKind == tok::arrow));
2264      }
2265      return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2266                         << IDecl->getDeclName() << &Member
2267                         << BaseExpr->getSourceRange());
2268    }
2269  }
2270  // Handle properties on 'id' and qualified "id".
2271  if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2272                                BaseType->isObjCQualifiedIdType())) {
2273    const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
2274
2275    // Check protocols on qualified interfaces.
2276    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2277    if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2278      if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2279        // Check the use of this declaration
2280        if (DiagnoseUseOfDecl(PD, MemberLoc))
2281          return ExprError();
2282
2283        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2284                                                       MemberLoc, BaseExpr));
2285      }
2286      if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2287        // Check the use of this method.
2288        if (DiagnoseUseOfDecl(OMD, MemberLoc))
2289          return ExprError();
2290
2291        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2292                                                   OMD->getResultType(),
2293                                                   OMD, OpLoc, MemberLoc,
2294                                                   NULL, 0));
2295      }
2296    }
2297
2298    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2299                       << &Member << BaseType);
2300  }
2301  // Handle Objective-C property access, which is "Obj.property" where Obj is a
2302  // pointer to a (potentially qualified) interface type.
2303  const ObjCObjectPointerType *OPT;
2304  if (OpKind == tok::period &&
2305      (OPT = BaseType->getAsObjCInterfacePointerType())) {
2306    const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2307    ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2308
2309    // Search for a declared property first.
2310    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
2311      // Check whether we can reference this property.
2312      if (DiagnoseUseOfDecl(PD, MemberLoc))
2313        return ExprError();
2314      QualType ResTy = PD->getType();
2315      Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2316      ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2317      if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2318        ResTy = Getter->getResultType();
2319      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
2320                                                     MemberLoc, BaseExpr));
2321    }
2322    // Check protocols on qualified interfaces.
2323    for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2324         E = OPT->qual_end(); I != E; ++I)
2325      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2326        // Check whether we can reference this property.
2327        if (DiagnoseUseOfDecl(PD, MemberLoc))
2328          return ExprError();
2329
2330        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2331                                                       MemberLoc, BaseExpr));
2332      }
2333    for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2334         E = OPT->qual_end(); I != E; ++I)
2335      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
2336        // Check whether we can reference this property.
2337        if (DiagnoseUseOfDecl(PD, MemberLoc))
2338          return ExprError();
2339
2340        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2341                                                       MemberLoc, BaseExpr));
2342      }
2343    // If that failed, look for an "implicit" property by seeing if the nullary
2344    // selector is implemented.
2345
2346    // FIXME: The logic for looking up nullary and unary selectors should be
2347    // shared with the code in ActOnInstanceMessage.
2348
2349    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
2350    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2351
2352    // If this reference is in an @implementation, check for 'private' methods.
2353    if (!Getter)
2354      Getter = FindMethodInNestedImplementations(IFace, Sel);
2355
2356    // Look through local category implementations associated with the class.
2357    if (!Getter)
2358      Getter = IFace->getCategoryInstanceMethod(Sel);
2359    if (Getter) {
2360      // Check if we can reference this property.
2361      if (DiagnoseUseOfDecl(Getter, MemberLoc))
2362        return ExprError();
2363    }
2364    // If we found a getter then this may be a valid dot-reference, we
2365    // will look for the matching setter, in case it is needed.
2366    Selector SetterSel =
2367      SelectorTable::constructSetterName(PP.getIdentifierTable(),
2368                                         PP.getSelectorTable(), &Member);
2369    ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2370    if (!Setter) {
2371      // If this reference is in an @implementation, also check for 'private'
2372      // methods.
2373      Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2374    }
2375    // Look through local category implementations associated with the class.
2376    if (!Setter)
2377      Setter = IFace->getCategoryInstanceMethod(SetterSel);
2378
2379    if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2380      return ExprError();
2381
2382    if (Getter || Setter) {
2383      QualType PType;
2384
2385      if (Getter)
2386        PType = Getter->getResultType();
2387      else
2388        // Get the expression type from Setter's incoming parameter.
2389        PType = (*(Setter->param_end() -1))->getType();
2390      // FIXME: we must check that the setter has property type.
2391      return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
2392                                      Setter, MemberLoc, BaseExpr));
2393    }
2394    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2395      << &Member << BaseType);
2396  }
2397
2398  // Handle the following exceptional case (*Obj).isa.
2399  if (OpKind == tok::period &&
2400      BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2401      Member.isStr("isa"))
2402    return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2403                                           Context.getObjCIdType()));
2404
2405  // Handle 'field access' to vectors, such as 'V.xx'.
2406  if (BaseType->isExtVectorType()) {
2407    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2408    if (ret.isNull())
2409      return ExprError();
2410    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
2411                                                    MemberLoc));
2412  }
2413
2414  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2415    << BaseType << BaseExpr->getSourceRange();
2416
2417  // If the user is trying to apply -> or . to a function or function
2418  // pointer, it's probably because they forgot parentheses to call
2419  // the function. Suggest the addition of those parentheses.
2420  if (BaseType == Context.OverloadTy ||
2421      BaseType->isFunctionType() ||
2422      (BaseType->isPointerType() &&
2423       BaseType->getAs<PointerType>()->isFunctionType())) {
2424    SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2425    Diag(Loc, diag::note_member_reference_needs_call)
2426      << CodeModificationHint::CreateInsertion(Loc, "()");
2427  }
2428
2429  return ExprError();
2430}
2431
2432/// ConvertArgumentsForCall - Converts the arguments specified in
2433/// Args/NumArgs to the parameter types of the function FDecl with
2434/// function prototype Proto. Call is the call expression itself, and
2435/// Fn is the function expression. For a C++ member function, this
2436/// routine does not attempt to convert the object argument. Returns
2437/// true if the call is ill-formed.
2438bool
2439Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2440                              FunctionDecl *FDecl,
2441                              const FunctionProtoType *Proto,
2442                              Expr **Args, unsigned NumArgs,
2443                              SourceLocation RParenLoc) {
2444  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2445  // assignment, to the types of the corresponding parameter, ...
2446  unsigned NumArgsInProto = Proto->getNumArgs();
2447  unsigned NumArgsToCheck = NumArgs;
2448  bool Invalid = false;
2449
2450  // If too few arguments are available (and we don't have default
2451  // arguments for the remaining parameters), don't make the call.
2452  if (NumArgs < NumArgsInProto) {
2453    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2454      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2455        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2456    // Use default arguments for missing arguments
2457    NumArgsToCheck = NumArgsInProto;
2458    Call->setNumArgs(Context, NumArgsInProto);
2459  }
2460
2461  // If too many are passed and not variadic, error on the extras and drop
2462  // them.
2463  if (NumArgs > NumArgsInProto) {
2464    if (!Proto->isVariadic()) {
2465      Diag(Args[NumArgsInProto]->getLocStart(),
2466           diag::err_typecheck_call_too_many_args)
2467        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2468        << SourceRange(Args[NumArgsInProto]->getLocStart(),
2469                       Args[NumArgs-1]->getLocEnd());
2470      // This deletes the extra arguments.
2471      Call->setNumArgs(Context, NumArgsInProto);
2472      Invalid = true;
2473    }
2474    NumArgsToCheck = NumArgsInProto;
2475  }
2476
2477  // Continue to check argument types (even if we have too few/many args).
2478  for (unsigned i = 0; i != NumArgsToCheck; i++) {
2479    QualType ProtoArgType = Proto->getArgType(i);
2480
2481    Expr *Arg;
2482    if (i < NumArgs) {
2483      Arg = Args[i];
2484
2485      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2486                              ProtoArgType,
2487                              diag::err_call_incomplete_argument,
2488                              Arg->getSourceRange()))
2489        return true;
2490
2491      // Pass the argument.
2492      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2493        return true;
2494    } else {
2495      if (FDecl->getParamDecl(i)->hasUnparsedDefaultArg()) {
2496        Diag (Call->getSourceRange().getBegin(),
2497              diag::err_use_of_default_argument_to_function_declared_later) <<
2498        FDecl << cast<CXXRecordDecl>(FDecl->getDeclContext())->getDeclName();
2499        Diag(UnparsedDefaultArgLocs[FDecl->getParamDecl(i)],
2500              diag::note_default_argument_declared_here);
2501      } else {
2502        Expr *DefaultExpr = FDecl->getParamDecl(i)->getDefaultArg();
2503
2504        // If the default expression creates temporaries, we need to
2505        // push them to the current stack of expression temporaries so they'll
2506        // be properly destroyed.
2507        if (CXXExprWithTemporaries *E
2508              = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2509          assert(!E->shouldDestroyTemporaries() &&
2510                 "Can't destroy temporaries in a default argument expr!");
2511          for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2512            ExprTemporaries.push_back(E->getTemporary(I));
2513        }
2514      }
2515
2516      // We already type-checked the argument, so we know it works.
2517      Arg = CXXDefaultArgExpr::Create(Context, FDecl->getParamDecl(i));
2518    }
2519
2520    QualType ArgType = Arg->getType();
2521
2522    Call->setArg(i, Arg);
2523  }
2524
2525  // If this is a variadic call, handle args passed through "...".
2526  if (Proto->isVariadic()) {
2527    VariadicCallType CallType = VariadicFunction;
2528    if (Fn->getType()->isBlockPointerType())
2529      CallType = VariadicBlock; // Block
2530    else if (isa<MemberExpr>(Fn))
2531      CallType = VariadicMethod;
2532
2533    // Promote the arguments (C99 6.5.2.2p7).
2534    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2535      Expr *Arg = Args[i];
2536      Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
2537      Call->setArg(i, Arg);
2538    }
2539  }
2540
2541  return Invalid;
2542}
2543
2544/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2545/// This provides the location of the left/right parens and a list of comma
2546/// locations.
2547Action::OwningExprResult
2548Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2549                    MultiExprArg args,
2550                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2551  unsigned NumArgs = args.size();
2552
2553  // Since this might be a postfix expression, get rid of ParenListExprs.
2554  fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2555
2556  Expr *Fn = fn.takeAs<Expr>();
2557  Expr **Args = reinterpret_cast<Expr**>(args.release());
2558  assert(Fn && "no function call expression");
2559  FunctionDecl *FDecl = NULL;
2560  NamedDecl *NDecl = NULL;
2561  DeclarationName UnqualifiedName;
2562
2563  if (getLangOptions().CPlusPlus) {
2564    // Determine whether this is a dependent call inside a C++ template,
2565    // in which case we won't do any semantic analysis now.
2566    // FIXME: Will need to cache the results of name lookup (including ADL) in
2567    // Fn.
2568    bool Dependent = false;
2569    if (Fn->isTypeDependent())
2570      Dependent = true;
2571    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2572      Dependent = true;
2573
2574    if (Dependent)
2575      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2576                                          Context.DependentTy, RParenLoc));
2577
2578    // Determine whether this is a call to an object (C++ [over.call.object]).
2579    if (Fn->getType()->isRecordType())
2580      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2581                                                CommaLocs, RParenLoc));
2582
2583    // Determine whether this is a call to a member function.
2584    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2585      NamedDecl *MemDecl = MemExpr->getMemberDecl();
2586      if (isa<OverloadedFunctionDecl>(MemDecl) ||
2587          isa<CXXMethodDecl>(MemDecl) ||
2588          (isa<FunctionTemplateDecl>(MemDecl) &&
2589           isa<CXXMethodDecl>(
2590                cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
2591        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2592                                               CommaLocs, RParenLoc));
2593    }
2594  }
2595
2596  // If we're directly calling a function, get the appropriate declaration.
2597  // Also, in C++, keep track of whether we should perform argument-dependent
2598  // lookup and whether there were any explicitly-specified template arguments.
2599  Expr *FnExpr = Fn;
2600  bool ADL = true;
2601  bool HasExplicitTemplateArgs = 0;
2602  const TemplateArgument *ExplicitTemplateArgs = 0;
2603  unsigned NumExplicitTemplateArgs = 0;
2604  while (true) {
2605    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2606      FnExpr = IcExpr->getSubExpr();
2607    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2608      // Parentheses around a function disable ADL
2609      // (C++0x [basic.lookup.argdep]p1).
2610      ADL = false;
2611      FnExpr = PExpr->getSubExpr();
2612    } else if (isa<UnaryOperator>(FnExpr) &&
2613               cast<UnaryOperator>(FnExpr)->getOpcode()
2614                 == UnaryOperator::AddrOf) {
2615      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2616    } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2617      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2618      ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2619      NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
2620      break;
2621    } else if (UnresolvedFunctionNameExpr *DepName
2622                 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2623      UnqualifiedName = DepName->getName();
2624      break;
2625    } else if (TemplateIdRefExpr *TemplateIdRef
2626                 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2627      NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2628      if (!NDecl)
2629        NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2630      HasExplicitTemplateArgs = true;
2631      ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2632      NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2633
2634      // C++ [temp.arg.explicit]p6:
2635      //   [Note: For simple function names, argument dependent lookup (3.4.2)
2636      //   applies even when the function name is not visible within the
2637      //   scope of the call. This is because the call still has the syntactic
2638      //   form of a function call (3.4.1). But when a function template with
2639      //   explicit template arguments is used, the call does not have the
2640      //   correct syntactic form unless there is a function template with
2641      //   that name visible at the point of the call. If no such name is
2642      //   visible, the call is not syntactically well-formed and
2643      //   argument-dependent lookup does not apply. If some such name is
2644      //   visible, argument dependent lookup applies and additional function
2645      //   templates may be found in other namespaces.
2646      //
2647      // The summary of this paragraph is that, if we get to this point and the
2648      // template-id was not a qualified name, then argument-dependent lookup
2649      // is still possible.
2650      if (TemplateIdRef->getQualifier())
2651        ADL = false;
2652      break;
2653    } else {
2654      // Any kind of name that does not refer to a declaration (or
2655      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2656      ADL = false;
2657      break;
2658    }
2659  }
2660
2661  OverloadedFunctionDecl *Ovl = 0;
2662  FunctionTemplateDecl *FunctionTemplate = 0;
2663  if (NDecl) {
2664    FDecl = dyn_cast<FunctionDecl>(NDecl);
2665    if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
2666      FDecl = FunctionTemplate->getTemplatedDecl();
2667    else
2668      FDecl = dyn_cast<FunctionDecl>(NDecl);
2669    Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
2670  }
2671
2672  if (Ovl || FunctionTemplate ||
2673      (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2674    // We don't perform ADL for implicit declarations of builtins.
2675    if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
2676      ADL = false;
2677
2678    // We don't perform ADL in C.
2679    if (!getLangOptions().CPlusPlus)
2680      ADL = false;
2681
2682    if (Ovl || FunctionTemplate || ADL) {
2683      FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2684                                      HasExplicitTemplateArgs,
2685                                      ExplicitTemplateArgs,
2686                                      NumExplicitTemplateArgs,
2687                                      LParenLoc, Args, NumArgs, CommaLocs,
2688                                      RParenLoc, ADL);
2689      if (!FDecl)
2690        return ExprError();
2691
2692      // Update Fn to refer to the actual function selected.
2693      Expr *NewFn = 0;
2694      if (QualifiedDeclRefExpr *QDRExpr
2695            = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
2696        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2697                                                   QDRExpr->getLocation(),
2698                                                   false, false,
2699                                                 QDRExpr->getQualifierRange(),
2700                                                   QDRExpr->getQualifier());
2701      else
2702        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2703                                          Fn->getSourceRange().getBegin());
2704      Fn->Destroy(Context);
2705      Fn = NewFn;
2706    }
2707  }
2708
2709  // Promote the function operand.
2710  UsualUnaryConversions(Fn);
2711
2712  // Make the call expr early, before semantic checks.  This guarantees cleanup
2713  // of arguments and function on error.
2714  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2715                                                               Args, NumArgs,
2716                                                               Context.BoolTy,
2717                                                               RParenLoc));
2718
2719  const FunctionType *FuncT;
2720  if (!Fn->getType()->isBlockPointerType()) {
2721    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2722    // have type pointer to function".
2723    const PointerType *PT = Fn->getType()->getAs<PointerType>();
2724    if (PT == 0)
2725      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2726        << Fn->getType() << Fn->getSourceRange());
2727    FuncT = PT->getPointeeType()->getAsFunctionType();
2728  } else { // This is a block call.
2729    FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
2730                getAsFunctionType();
2731  }
2732  if (FuncT == 0)
2733    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2734      << Fn->getType() << Fn->getSourceRange());
2735
2736  // Check for a valid return type
2737  if (!FuncT->getResultType()->isVoidType() &&
2738      RequireCompleteType(Fn->getSourceRange().getBegin(),
2739                          FuncT->getResultType(),
2740                          diag::err_call_incomplete_return,
2741                          TheCall->getSourceRange()))
2742    return ExprError();
2743
2744  // We know the result type of the call, set it.
2745  TheCall->setType(FuncT->getResultType().getNonReferenceType());
2746
2747  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2748    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2749                                RParenLoc))
2750      return ExprError();
2751  } else {
2752    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2753
2754    if (FDecl) {
2755      // Check if we have too few/too many template arguments, based
2756      // on our knowledge of the function definition.
2757      const FunctionDecl *Def = 0;
2758      if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
2759        const FunctionProtoType *Proto =
2760            Def->getType()->getAsFunctionProtoType();
2761        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2762          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2763            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2764        }
2765      }
2766    }
2767
2768    // Promote the arguments (C99 6.5.2.2p6).
2769    for (unsigned i = 0; i != NumArgs; i++) {
2770      Expr *Arg = Args[i];
2771      DefaultArgumentPromotion(Arg);
2772      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2773                              Arg->getType(),
2774                              diag::err_call_incomplete_argument,
2775                              Arg->getSourceRange()))
2776        return ExprError();
2777      TheCall->setArg(i, Arg);
2778    }
2779  }
2780
2781  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2782    if (!Method->isStatic())
2783      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2784        << Fn->getSourceRange());
2785
2786  // Check for sentinels
2787  if (NDecl)
2788    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
2789
2790  // Do special checking on direct calls to functions.
2791  if (FDecl) {
2792    if (CheckFunctionCall(FDecl, TheCall.get()))
2793      return ExprError();
2794
2795    if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2796      return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2797  } else if (NDecl) {
2798    if (CheckBlockCall(NDecl, TheCall.get()))
2799      return ExprError();
2800  }
2801
2802  return MaybeBindToTemporary(TheCall.take());
2803}
2804
2805Action::OwningExprResult
2806Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2807                           SourceLocation RParenLoc, ExprArg InitExpr) {
2808  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
2809  //FIXME: Preserve type source info.
2810  QualType literalType = GetTypeFromParser(Ty);
2811  // FIXME: put back this assert when initializers are worked out.
2812  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
2813  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
2814
2815  if (literalType->isArrayType()) {
2816    if (literalType->isVariableArrayType())
2817      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2818        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
2819  } else if (!literalType->isDependentType() &&
2820             RequireCompleteType(LParenLoc, literalType,
2821                                 diag::err_typecheck_decl_incomplete_type,
2822                SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
2823    return ExprError();
2824
2825  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
2826                            DeclarationName(), /*FIXME:DirectInit=*/false))
2827    return ExprError();
2828
2829  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
2830  if (isFileScope) { // 6.5.2.5p3
2831    if (CheckForConstantInitializer(literalExpr, literalType))
2832      return ExprError();
2833  }
2834  InitExpr.release();
2835  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2836                                                 literalExpr, isFileScope));
2837}
2838
2839Action::OwningExprResult
2840Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2841                    SourceLocation RBraceLoc) {
2842  unsigned NumInit = initlist.size();
2843  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
2844
2845  // Semantic analysis for initializers is done by ActOnDeclarator() and
2846  // CheckInitializer() - it requires knowledge of the object being intialized.
2847
2848  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
2849                                               RBraceLoc);
2850  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
2851  return Owned(E);
2852}
2853
2854/// CheckCastTypes - Check type constraints for casting between types.
2855bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
2856                          CastExpr::CastKind& Kind, bool FunctionalStyle) {
2857  if (getLangOptions().CPlusPlus)
2858    return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle);
2859
2860  DefaultFunctionArrayConversion(castExpr);
2861
2862  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2863  // type needs to be scalar.
2864  if (castType->isVoidType()) {
2865    // Cast to void allows any expr type.
2866  } else if (!castType->isScalarType() && !castType->isVectorType()) {
2867    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2868        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2869        (castType->isStructureType() || castType->isUnionType())) {
2870      // GCC struct/union extension: allow cast to self.
2871      // FIXME: Check that the cast destination type is complete.
2872      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2873        << castType << castExpr->getSourceRange();
2874      Kind = CastExpr::CK_NoOp;
2875    } else if (castType->isUnionType()) {
2876      // GCC cast to union extension
2877      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
2878      RecordDecl::field_iterator Field, FieldEnd;
2879      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2880           Field != FieldEnd; ++Field) {
2881        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2882            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2883          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2884            << castExpr->getSourceRange();
2885          break;
2886        }
2887      }
2888      if (Field == FieldEnd)
2889        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2890          << castExpr->getType() << castExpr->getSourceRange();
2891      Kind = CastExpr::CK_ToUnion;
2892    } else {
2893      // Reject any other conversions to non-scalar types.
2894      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
2895        << castType << castExpr->getSourceRange();
2896    }
2897  } else if (!castExpr->getType()->isScalarType() &&
2898             !castExpr->getType()->isVectorType()) {
2899    return Diag(castExpr->getLocStart(),
2900                diag::err_typecheck_expect_scalar_operand)
2901      << castExpr->getType() << castExpr->getSourceRange();
2902  } else if (castType->isExtVectorType()) {
2903    if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
2904      return true;
2905  } else if (castType->isVectorType()) {
2906    if (CheckVectorCast(TyR, castType, castExpr->getType()))
2907      return true;
2908  } else if (castExpr->getType()->isVectorType()) {
2909    if (CheckVectorCast(TyR, castExpr->getType(), castType))
2910      return true;
2911  } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
2912    return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
2913  } else if (!castType->isArithmeticType()) {
2914    QualType castExprType = castExpr->getType();
2915    if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2916      return Diag(castExpr->getLocStart(),
2917                  diag::err_cast_pointer_from_non_pointer_int)
2918        << castExprType << castExpr->getSourceRange();
2919  } else if (!castExpr->getType()->isArithmeticType()) {
2920    if (!castType->isIntegralType() && castType->isArithmeticType())
2921      return Diag(castExpr->getLocStart(),
2922                  diag::err_cast_pointer_to_non_pointer_int)
2923        << castType << castExpr->getSourceRange();
2924  }
2925  if (isa<ObjCSelectorExpr>(castExpr))
2926    return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
2927  return false;
2928}
2929
2930bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
2931  assert(VectorTy->isVectorType() && "Not a vector type!");
2932
2933  if (Ty->isVectorType() || Ty->isIntegerType()) {
2934    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
2935      return Diag(R.getBegin(),
2936                  Ty->isVectorType() ?
2937                  diag::err_invalid_conversion_between_vectors :
2938                  diag::err_invalid_conversion_between_vector_and_integer)
2939        << VectorTy << Ty << R;
2940  } else
2941    return Diag(R.getBegin(),
2942                diag::err_invalid_conversion_between_vector_and_scalar)
2943      << VectorTy << Ty << R;
2944
2945  return false;
2946}
2947
2948bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
2949  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
2950
2951  // If SrcTy is a VectorType, the total size must match to explicitly cast to
2952  // an ExtVectorType.
2953  if (SrcTy->isVectorType()) {
2954    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
2955      return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
2956        << DestTy << SrcTy << R;
2957    return false;
2958  }
2959
2960  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
2961  // conversion will take place first from scalar to elt type, and then
2962  // splat from elt type to vector.
2963  if (SrcTy->isPointerType())
2964    return Diag(R.getBegin(),
2965                diag::err_invalid_conversion_between_vector_and_scalar)
2966      << DestTy << SrcTy << R;
2967  return false;
2968}
2969
2970Action::OwningExprResult
2971Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
2972                    SourceLocation RParenLoc, ExprArg Op) {
2973  CastExpr::CastKind Kind = CastExpr::CK_Unknown;
2974
2975  assert((Ty != 0) && (Op.get() != 0) &&
2976         "ActOnCastExpr(): missing type or expr");
2977
2978  Expr *castExpr = (Expr *)Op.get();
2979  //FIXME: Preserve type source info.
2980  QualType castType = GetTypeFromParser(Ty);
2981
2982  // If the Expr being casted is a ParenListExpr, handle it specially.
2983  if (isa<ParenListExpr>(castExpr))
2984    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
2985
2986  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
2987                     Kind))
2988    return ExprError();
2989
2990  Op.release();
2991  return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
2992                                            Kind, castExpr, castType,
2993                                            LParenLoc, RParenLoc));
2994}
2995
2996/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
2997/// of comma binary operators.
2998Action::OwningExprResult
2999Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3000  Expr *expr = EA.takeAs<Expr>();
3001  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3002  if (!E)
3003    return Owned(expr);
3004
3005  OwningExprResult Result(*this, E->getExpr(0));
3006
3007  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3008    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3009                        Owned(E->getExpr(i)));
3010
3011  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3012}
3013
3014Action::OwningExprResult
3015Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3016                               SourceLocation RParenLoc, ExprArg Op,
3017                               QualType Ty) {
3018  ParenListExpr *PE = (ParenListExpr *)Op.get();
3019
3020  // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3021  // then handle it as such.
3022  if (getLangOptions().AltiVec && Ty->isVectorType()) {
3023    if (PE->getNumExprs() == 0) {
3024      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3025      return ExprError();
3026    }
3027
3028    llvm::SmallVector<Expr *, 8> initExprs;
3029    for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3030      initExprs.push_back(PE->getExpr(i));
3031
3032    // FIXME: This means that pretty-printing the final AST will produce curly
3033    // braces instead of the original commas.
3034    Op.release();
3035    InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3036                                                 initExprs.size(), RParenLoc);
3037    E->setType(Ty);
3038    return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3039                                Owned(E));
3040  } else {
3041    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3042    // sequence of BinOp comma operators.
3043    Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3044    return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3045  }
3046}
3047
3048Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3049                                                  SourceLocation R,
3050                                                  MultiExprArg Val) {
3051  unsigned nexprs = Val.size();
3052  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3053  assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3054  Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3055  return Owned(expr);
3056}
3057
3058/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3059/// In that case, lhs = cond.
3060/// C99 6.5.15
3061QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3062                                        SourceLocation QuestionLoc) {
3063  // C++ is sufficiently different to merit its own checker.
3064  if (getLangOptions().CPlusPlus)
3065    return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3066
3067  UsualUnaryConversions(Cond);
3068  UsualUnaryConversions(LHS);
3069  UsualUnaryConversions(RHS);
3070  QualType CondTy = Cond->getType();
3071  QualType LHSTy = LHS->getType();
3072  QualType RHSTy = RHS->getType();
3073
3074  // first, check the condition.
3075  if (!CondTy->isScalarType()) { // C99 6.5.15p2
3076    Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3077      << CondTy;
3078    return QualType();
3079  }
3080
3081  // Now check the two expressions.
3082  if (LHSTy->isVectorType() || RHSTy->isVectorType())
3083    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3084
3085  // If both operands have arithmetic type, do the usual arithmetic conversions
3086  // to find a common type: C99 6.5.15p3,5.
3087  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3088    UsualArithmeticConversions(LHS, RHS);
3089    return LHS->getType();
3090  }
3091
3092  // If both operands are the same structure or union type, the result is that
3093  // type.
3094  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
3095    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
3096      if (LHSRT->getDecl() == RHSRT->getDecl())
3097        // "If both the operands have structure or union type, the result has
3098        // that type."  This implies that CV qualifiers are dropped.
3099        return LHSTy.getUnqualifiedType();
3100    // FIXME: Type of conditional expression must be complete in C mode.
3101  }
3102
3103  // C99 6.5.15p5: "If both operands have void type, the result has void type."
3104  // The following || allows only one side to be void (a GCC-ism).
3105  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3106    if (!LHSTy->isVoidType())
3107      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3108        << RHS->getSourceRange();
3109    if (!RHSTy->isVoidType())
3110      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3111        << LHS->getSourceRange();
3112    ImpCastExprToType(LHS, Context.VoidTy);
3113    ImpCastExprToType(RHS, Context.VoidTy);
3114    return Context.VoidTy;
3115  }
3116  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3117  // the type of the other operand."
3118  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
3119      RHS->isNullPointerConstant(Context)) {
3120    ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3121    return LHSTy;
3122  }
3123  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
3124      LHS->isNullPointerConstant(Context)) {
3125    ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3126    return RHSTy;
3127  }
3128  // Handle things like Class and struct objc_class*.  Here we case the result
3129  // to the pseudo-builtin, because that will be implicitly cast back to the
3130  // redefinition type if an attempt is made to access its fields.
3131  if (LHSTy->isObjCClassType() &&
3132      (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3133    ImpCastExprToType(RHS, LHSTy);
3134    return LHSTy;
3135  }
3136  if (RHSTy->isObjCClassType() &&
3137      (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3138    ImpCastExprToType(LHS, RHSTy);
3139    return RHSTy;
3140  }
3141  // And the same for struct objc_object* / id
3142  if (LHSTy->isObjCIdType() &&
3143      (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3144    ImpCastExprToType(RHS, LHSTy);
3145    return LHSTy;
3146  }
3147  if (RHSTy->isObjCIdType() &&
3148      (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3149    ImpCastExprToType(LHS, RHSTy);
3150    return RHSTy;
3151  }
3152  // Handle block pointer types.
3153  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3154    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3155      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3156        QualType destType = Context.getPointerType(Context.VoidTy);
3157        ImpCastExprToType(LHS, destType);
3158        ImpCastExprToType(RHS, destType);
3159        return destType;
3160      }
3161      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3162            << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3163      return QualType();
3164    }
3165    // We have 2 block pointer types.
3166    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3167      // Two identical block pointer types are always compatible.
3168      return LHSTy;
3169    }
3170    // The block pointer types aren't identical, continue checking.
3171    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3172    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
3173
3174    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3175                                    rhptee.getUnqualifiedType())) {
3176      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3177        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3178      // In this situation, we assume void* type. No especially good
3179      // reason, but this is what gcc does, and we do have to pick
3180      // to get a consistent AST.
3181      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3182      ImpCastExprToType(LHS, incompatTy);
3183      ImpCastExprToType(RHS, incompatTy);
3184      return incompatTy;
3185    }
3186    // The block pointer types are compatible.
3187    ImpCastExprToType(LHS, LHSTy);
3188    ImpCastExprToType(RHS, LHSTy);
3189    return LHSTy;
3190  }
3191  // Check constraints for Objective-C object pointers types.
3192  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
3193
3194    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3195      // Two identical object pointer types are always compatible.
3196      return LHSTy;
3197    }
3198    const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3199    const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
3200    QualType compositeType = LHSTy;
3201
3202    // If both operands are interfaces and either operand can be
3203    // assigned to the other, use that type as the composite
3204    // type. This allows
3205    //   xxx ? (A*) a : (B*) b
3206    // where B is a subclass of A.
3207    //
3208    // Additionally, as for assignment, if either type is 'id'
3209    // allow silent coercion. Finally, if the types are
3210    // incompatible then make sure to use 'id' as the composite
3211    // type so the result is acceptable for sending messages to.
3212
3213    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3214    // It could return the composite type.
3215    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
3216      compositeType = LHSTy;
3217    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
3218      compositeType = RHSTy;
3219    } else if ((LHSTy->isObjCQualifiedIdType() ||
3220                RHSTy->isObjCQualifiedIdType()) &&
3221                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
3222      // Need to handle "id<xx>" explicitly.
3223      // GCC allows qualified id and any Objective-C type to devolve to
3224      // id. Currently localizing to here until clear this should be
3225      // part of ObjCQualifiedIdTypesAreCompatible.
3226      compositeType = Context.getObjCIdType();
3227    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
3228      compositeType = Context.getObjCIdType();
3229    } else {
3230      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3231        << LHSTy << RHSTy
3232        << LHS->getSourceRange() << RHS->getSourceRange();
3233      QualType incompatTy = Context.getObjCIdType();
3234      ImpCastExprToType(LHS, incompatTy);
3235      ImpCastExprToType(RHS, incompatTy);
3236      return incompatTy;
3237    }
3238    // The object pointer types are compatible.
3239    ImpCastExprToType(LHS, compositeType);
3240    ImpCastExprToType(RHS, compositeType);
3241    return compositeType;
3242  }
3243  // Check Objective-C object pointer types and 'void *'
3244  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
3245    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3246    QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3247    QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3248    QualType destType = Context.getPointerType(destPointee);
3249    ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3250    ImpCastExprToType(RHS, destType); // promote to void*
3251    return destType;
3252  }
3253  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3254    QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
3255    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3256    QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3257    QualType destType = Context.getPointerType(destPointee);
3258    ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3259    ImpCastExprToType(LHS, destType); // promote to void*
3260    return destType;
3261  }
3262  // Check constraints for C object pointers types (C99 6.5.15p3,6).
3263  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3264    // get the "pointed to" types
3265    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3266    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3267
3268    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3269    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3270      // Figure out necessary qualifiers (C99 6.5.15p6)
3271      QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3272      QualType destType = Context.getPointerType(destPointee);
3273      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3274      ImpCastExprToType(RHS, destType); // promote to void*
3275      return destType;
3276    }
3277    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3278      QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3279      QualType destType = Context.getPointerType(destPointee);
3280      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3281      ImpCastExprToType(RHS, destType); // promote to void*
3282      return destType;
3283    }
3284
3285    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3286      // Two identical pointer types are always compatible.
3287      return LHSTy;
3288    }
3289    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3290                                    rhptee.getUnqualifiedType())) {
3291      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3292        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3293      // In this situation, we assume void* type. No especially good
3294      // reason, but this is what gcc does, and we do have to pick
3295      // to get a consistent AST.
3296      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3297      ImpCastExprToType(LHS, incompatTy);
3298      ImpCastExprToType(RHS, incompatTy);
3299      return incompatTy;
3300    }
3301    // The pointer types are compatible.
3302    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3303    // differently qualified versions of compatible types, the result type is
3304    // a pointer to an appropriately qualified version of the *composite*
3305    // type.
3306    // FIXME: Need to calculate the composite type.
3307    // FIXME: Need to add qualifiers
3308    ImpCastExprToType(LHS, LHSTy);
3309    ImpCastExprToType(RHS, LHSTy);
3310    return LHSTy;
3311  }
3312
3313  // GCC compatibility: soften pointer/integer mismatch.
3314  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3315    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3316      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3317    ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3318    return RHSTy;
3319  }
3320  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3321    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3322      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3323    ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3324    return LHSTy;
3325  }
3326
3327  // Otherwise, the operands are not compatible.
3328  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3329    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3330  return QualType();
3331}
3332
3333/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3334/// in the case of a the GNU conditional expr extension.
3335Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3336                                                  SourceLocation ColonLoc,
3337                                                  ExprArg Cond, ExprArg LHS,
3338                                                  ExprArg RHS) {
3339  Expr *CondExpr = (Expr *) Cond.get();
3340  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
3341
3342  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3343  // was the condition.
3344  bool isLHSNull = LHSExpr == 0;
3345  if (isLHSNull)
3346    LHSExpr = CondExpr;
3347
3348  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
3349                                             RHSExpr, QuestionLoc);
3350  if (result.isNull())
3351    return ExprError();
3352
3353  Cond.release();
3354  LHS.release();
3355  RHS.release();
3356  return Owned(new (Context) ConditionalOperator(CondExpr,
3357                                                 isLHSNull ? 0 : LHSExpr,
3358                                                 RHSExpr, result));
3359}
3360
3361// CheckPointerTypesForAssignment - This is a very tricky routine (despite
3362// being closely modeled after the C99 spec:-). The odd characteristic of this
3363// routine is it effectively iqnores the qualifiers on the top level pointee.
3364// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3365// FIXME: add a couple examples in this comment.
3366Sema::AssignConvertType
3367Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3368  QualType lhptee, rhptee;
3369
3370  if ((lhsType->isObjCClassType() &&
3371       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3372     (rhsType->isObjCClassType() &&
3373       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3374      return Compatible;
3375  }
3376
3377  // get the "pointed to" type (ignoring qualifiers at the top level)
3378  lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3379  rhptee = rhsType->getAs<PointerType>()->getPointeeType();
3380
3381  // make sure we operate on the canonical type
3382  lhptee = Context.getCanonicalType(lhptee);
3383  rhptee = Context.getCanonicalType(rhptee);
3384
3385  AssignConvertType ConvTy = Compatible;
3386
3387  // C99 6.5.16.1p1: This following citation is common to constraints
3388  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3389  // qualifiers of the type *pointed to* by the right;
3390  // FIXME: Handle ExtQualType
3391  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
3392    ConvTy = CompatiblePointerDiscardsQualifiers;
3393
3394  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3395  // incomplete type and the other is a pointer to a qualified or unqualified
3396  // version of void...
3397  if (lhptee->isVoidType()) {
3398    if (rhptee->isIncompleteOrObjectType())
3399      return ConvTy;
3400
3401    // As an extension, we allow cast to/from void* to function pointer.
3402    assert(rhptee->isFunctionType());
3403    return FunctionVoidPointer;
3404  }
3405
3406  if (rhptee->isVoidType()) {
3407    if (lhptee->isIncompleteOrObjectType())
3408      return ConvTy;
3409
3410    // As an extension, we allow cast to/from void* to function pointer.
3411    assert(lhptee->isFunctionType());
3412    return FunctionVoidPointer;
3413  }
3414  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
3415  // unqualified versions of compatible types, ...
3416  lhptee = lhptee.getUnqualifiedType();
3417  rhptee = rhptee.getUnqualifiedType();
3418  if (!Context.typesAreCompatible(lhptee, rhptee)) {
3419    // Check if the pointee types are compatible ignoring the sign.
3420    // We explicitly check for char so that we catch "char" vs
3421    // "unsigned char" on systems where "char" is unsigned.
3422    if (lhptee->isCharType()) {
3423      lhptee = Context.UnsignedCharTy;
3424    } else if (lhptee->isSignedIntegerType()) {
3425      lhptee = Context.getCorrespondingUnsignedType(lhptee);
3426    }
3427    if (rhptee->isCharType()) {
3428      rhptee = Context.UnsignedCharTy;
3429    } else if (rhptee->isSignedIntegerType()) {
3430      rhptee = Context.getCorrespondingUnsignedType(rhptee);
3431    }
3432    if (lhptee == rhptee) {
3433      // Types are compatible ignoring the sign. Qualifier incompatibility
3434      // takes priority over sign incompatibility because the sign
3435      // warning can be disabled.
3436      if (ConvTy != Compatible)
3437        return ConvTy;
3438      return IncompatiblePointerSign;
3439    }
3440    // General pointer incompatibility takes priority over qualifiers.
3441    return IncompatiblePointer;
3442  }
3443  return ConvTy;
3444}
3445
3446/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3447/// block pointer types are compatible or whether a block and normal pointer
3448/// are compatible. It is more restrict than comparing two function pointer
3449// types.
3450Sema::AssignConvertType
3451Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
3452                                          QualType rhsType) {
3453  QualType lhptee, rhptee;
3454
3455  // get the "pointed to" type (ignoring qualifiers at the top level)
3456  lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3457  rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
3458
3459  // make sure we operate on the canonical type
3460  lhptee = Context.getCanonicalType(lhptee);
3461  rhptee = Context.getCanonicalType(rhptee);
3462
3463  AssignConvertType ConvTy = Compatible;
3464
3465  // For blocks we enforce that qualifiers are identical.
3466  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3467    ConvTy = CompatiblePointerDiscardsQualifiers;
3468
3469  if (!Context.typesAreCompatible(lhptee, rhptee))
3470    return IncompatibleBlockPointer;
3471  return ConvTy;
3472}
3473
3474/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3475/// has code to accommodate several GCC extensions when type checking
3476/// pointers. Here are some objectionable examples that GCC considers warnings:
3477///
3478///  int a, *pint;
3479///  short *pshort;
3480///  struct foo *pfoo;
3481///
3482///  pint = pshort; // warning: assignment from incompatible pointer type
3483///  a = pint; // warning: assignment makes integer from pointer without a cast
3484///  pint = a; // warning: assignment makes pointer from integer without a cast
3485///  pint = pfoo; // warning: assignment from incompatible pointer type
3486///
3487/// As a result, the code for dealing with pointers is more complex than the
3488/// C99 spec dictates.
3489///
3490Sema::AssignConvertType
3491Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
3492  // Get canonical types.  We're not formatting these types, just comparing
3493  // them.
3494  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3495  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
3496
3497  if (lhsType == rhsType)
3498    return Compatible; // Common case: fast path an exact match.
3499
3500  if ((lhsType->isObjCClassType() &&
3501       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3502     (rhsType->isObjCClassType() &&
3503       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3504      return Compatible;
3505  }
3506
3507  // If the left-hand side is a reference type, then we are in a
3508  // (rare!) case where we've allowed the use of references in C,
3509  // e.g., as a parameter type in a built-in function. In this case,
3510  // just make sure that the type referenced is compatible with the
3511  // right-hand side type. The caller is responsible for adjusting
3512  // lhsType so that the resulting expression does not have reference
3513  // type.
3514  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
3515    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
3516      return Compatible;
3517    return Incompatible;
3518  }
3519  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3520  // to the same ExtVector type.
3521  if (lhsType->isExtVectorType()) {
3522    if (rhsType->isExtVectorType())
3523      return lhsType == rhsType ? Compatible : Incompatible;
3524    if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3525      return Compatible;
3526  }
3527
3528  if (lhsType->isVectorType() || rhsType->isVectorType()) {
3529    // If we are allowing lax vector conversions, and LHS and RHS are both
3530    // vectors, the total size only needs to be the same. This is a bitcast;
3531    // no bits are changed but the result type is different.
3532    if (getLangOptions().LaxVectorConversions &&
3533        lhsType->isVectorType() && rhsType->isVectorType()) {
3534      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
3535        return IncompatibleVectors;
3536    }
3537    return Incompatible;
3538  }
3539
3540  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
3541    return Compatible;
3542
3543  if (isa<PointerType>(lhsType)) {
3544    if (rhsType->isIntegerType())
3545      return IntToPointer;
3546
3547    if (isa<PointerType>(rhsType))
3548      return CheckPointerTypesForAssignment(lhsType, rhsType);
3549
3550    // In general, C pointers are not compatible with ObjC object pointers.
3551    if (isa<ObjCObjectPointerType>(rhsType)) {
3552      if (lhsType->isVoidPointerType()) // an exception to the rule.
3553        return Compatible;
3554      return IncompatiblePointer;
3555    }
3556    if (rhsType->getAs<BlockPointerType>()) {
3557      if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3558        return Compatible;
3559
3560      // Treat block pointers as objects.
3561      if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
3562        return Compatible;
3563    }
3564    return Incompatible;
3565  }
3566
3567  if (isa<BlockPointerType>(lhsType)) {
3568    if (rhsType->isIntegerType())
3569      return IntToBlockPointer;
3570
3571    // Treat block pointers as objects.
3572    if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
3573      return Compatible;
3574
3575    if (rhsType->isBlockPointerType())
3576      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
3577
3578    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3579      if (RHSPT->getPointeeType()->isVoidType())
3580        return Compatible;
3581    }
3582    return Incompatible;
3583  }
3584
3585  if (isa<ObjCObjectPointerType>(lhsType)) {
3586    if (rhsType->isIntegerType())
3587      return IntToPointer;
3588
3589    // In general, C pointers are not compatible with ObjC object pointers.
3590    if (isa<PointerType>(rhsType)) {
3591      if (rhsType->isVoidPointerType()) // an exception to the rule.
3592        return Compatible;
3593      return IncompatiblePointer;
3594    }
3595    if (rhsType->isObjCObjectPointerType()) {
3596      if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3597        return Compatible;
3598      if (Context.typesAreCompatible(lhsType, rhsType))
3599        return Compatible;
3600      if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3601        return IncompatibleObjCQualifiedId;
3602      return IncompatiblePointer;
3603    }
3604    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3605      if (RHSPT->getPointeeType()->isVoidType())
3606        return Compatible;
3607    }
3608    // Treat block pointers as objects.
3609    if (rhsType->isBlockPointerType())
3610      return Compatible;
3611    return Incompatible;
3612  }
3613  if (isa<PointerType>(rhsType)) {
3614    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3615    if (lhsType == Context.BoolTy)
3616      return Compatible;
3617
3618    if (lhsType->isIntegerType())
3619      return PointerToInt;
3620
3621    if (isa<PointerType>(lhsType))
3622      return CheckPointerTypesForAssignment(lhsType, rhsType);
3623
3624    if (isa<BlockPointerType>(lhsType) &&
3625        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3626      return Compatible;
3627    return Incompatible;
3628  }
3629  if (isa<ObjCObjectPointerType>(rhsType)) {
3630    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3631    if (lhsType == Context.BoolTy)
3632      return Compatible;
3633
3634    if (lhsType->isIntegerType())
3635      return PointerToInt;
3636
3637    // In general, C pointers are not compatible with ObjC object pointers.
3638    if (isa<PointerType>(lhsType)) {
3639      if (lhsType->isVoidPointerType()) // an exception to the rule.
3640        return Compatible;
3641      return IncompatiblePointer;
3642    }
3643    if (isa<BlockPointerType>(lhsType) &&
3644        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3645      return Compatible;
3646    return Incompatible;
3647  }
3648
3649  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
3650    if (Context.typesAreCompatible(lhsType, rhsType))
3651      return Compatible;
3652  }
3653  return Incompatible;
3654}
3655
3656/// \brief Constructs a transparent union from an expression that is
3657/// used to initialize the transparent union.
3658static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3659                                      QualType UnionType, FieldDecl *Field) {
3660  // Build an initializer list that designates the appropriate member
3661  // of the transparent union.
3662  InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3663                                                   &E, 1,
3664                                                   SourceLocation());
3665  Initializer->setType(UnionType);
3666  Initializer->setInitializedFieldInUnion(Field);
3667
3668  // Build a compound literal constructing a value of the transparent
3669  // union type from this initializer list.
3670  E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3671                                  false);
3672}
3673
3674Sema::AssignConvertType
3675Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3676  QualType FromType = rExpr->getType();
3677
3678  // If the ArgType is a Union type, we want to handle a potential
3679  // transparent_union GCC extension.
3680  const RecordType *UT = ArgType->getAsUnionType();
3681  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3682    return Incompatible;
3683
3684  // The field to initialize within the transparent union.
3685  RecordDecl *UD = UT->getDecl();
3686  FieldDecl *InitField = 0;
3687  // It's compatible if the expression matches any of the fields.
3688  for (RecordDecl::field_iterator it = UD->field_begin(),
3689         itend = UD->field_end();
3690       it != itend; ++it) {
3691    if (it->getType()->isPointerType()) {
3692      // If the transparent union contains a pointer type, we allow:
3693      // 1) void pointer
3694      // 2) null pointer constant
3695      if (FromType->isPointerType())
3696        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
3697          ImpCastExprToType(rExpr, it->getType());
3698          InitField = *it;
3699          break;
3700        }
3701
3702      if (rExpr->isNullPointerConstant(Context)) {
3703        ImpCastExprToType(rExpr, it->getType());
3704        InitField = *it;
3705        break;
3706      }
3707    }
3708
3709    if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3710          == Compatible) {
3711      InitField = *it;
3712      break;
3713    }
3714  }
3715
3716  if (!InitField)
3717    return Incompatible;
3718
3719  ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3720  return Compatible;
3721}
3722
3723Sema::AssignConvertType
3724Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
3725  if (getLangOptions().CPlusPlus) {
3726    if (!lhsType->isRecordType()) {
3727      // C++ 5.17p3: If the left operand is not of class type, the
3728      // expression is implicitly converted (C++ 4) to the
3729      // cv-unqualified type of the left operand.
3730      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3731                                    "assigning"))
3732        return Incompatible;
3733      return Compatible;
3734    }
3735
3736    // FIXME: Currently, we fall through and treat C++ classes like C
3737    // structures.
3738  }
3739
3740  // C99 6.5.16.1p1: the left operand is a pointer and the right is
3741  // a null pointer constant.
3742  if ((lhsType->isPointerType() ||
3743       lhsType->isObjCObjectPointerType() ||
3744       lhsType->isBlockPointerType())
3745      && rExpr->isNullPointerConstant(Context)) {
3746    ImpCastExprToType(rExpr, lhsType);
3747    return Compatible;
3748  }
3749
3750  // This check seems unnatural, however it is necessary to ensure the proper
3751  // conversion of functions/arrays. If the conversion were done for all
3752  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
3753  // expressions that surpress this implicit conversion (&, sizeof).
3754  //
3755  // Suppress this for references: C++ 8.5.3p5.
3756  if (!lhsType->isReferenceType())
3757    DefaultFunctionArrayConversion(rExpr);
3758
3759  Sema::AssignConvertType result =
3760    CheckAssignmentConstraints(lhsType, rExpr->getType());
3761
3762  // C99 6.5.16.1p2: The value of the right operand is converted to the
3763  // type of the assignment expression.
3764  // CheckAssignmentConstraints allows the left-hand side to be a reference,
3765  // so that we can use references in built-in functions even in C.
3766  // The getNonReferenceType() call makes sure that the resulting expression
3767  // does not have reference type.
3768  if (result != Incompatible && rExpr->getType() != lhsType)
3769    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
3770  return result;
3771}
3772
3773QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
3774  Diag(Loc, diag::err_typecheck_invalid_operands)
3775    << lex->getType() << rex->getType()
3776    << lex->getSourceRange() << rex->getSourceRange();
3777  return QualType();
3778}
3779
3780inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
3781                                                              Expr *&rex) {
3782  // For conversion purposes, we ignore any qualifiers.
3783  // For example, "const float" and "float" are equivalent.
3784  QualType lhsType =
3785    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3786  QualType rhsType =
3787    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
3788
3789  // If the vector types are identical, return.
3790  if (lhsType == rhsType)
3791    return lhsType;
3792
3793  // Handle the case of a vector & extvector type of the same size and element
3794  // type.  It would be nice if we only had one vector type someday.
3795  if (getLangOptions().LaxVectorConversions) {
3796    // FIXME: Should we warn here?
3797    if (const VectorType *LV = lhsType->getAsVectorType()) {
3798      if (const VectorType *RV = rhsType->getAsVectorType())
3799        if (LV->getElementType() == RV->getElementType() &&
3800            LV->getNumElements() == RV->getNumElements()) {
3801          return lhsType->isExtVectorType() ? lhsType : rhsType;
3802        }
3803    }
3804  }
3805
3806  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3807  // swap back (so that we don't reverse the inputs to a subtract, for instance.
3808  bool swapped = false;
3809  if (rhsType->isExtVectorType()) {
3810    swapped = true;
3811    std::swap(rex, lex);
3812    std::swap(rhsType, lhsType);
3813  }
3814
3815  // Handle the case of an ext vector and scalar.
3816  if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3817    QualType EltTy = LV->getElementType();
3818    if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3819      if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
3820        ImpCastExprToType(rex, lhsType);
3821        if (swapped) std::swap(rex, lex);
3822        return lhsType;
3823      }
3824    }
3825    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3826        rhsType->isRealFloatingType()) {
3827      if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
3828        ImpCastExprToType(rex, lhsType);
3829        if (swapped) std::swap(rex, lex);
3830        return lhsType;
3831      }
3832    }
3833  }
3834
3835  // Vectors of different size or scalar and non-ext-vector are errors.
3836  Diag(Loc, diag::err_typecheck_vector_not_convertable)
3837    << lex->getType() << rex->getType()
3838    << lex->getSourceRange() << rex->getSourceRange();
3839  return QualType();
3840}
3841
3842inline QualType Sema::CheckMultiplyDivideOperands(
3843  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3844{
3845  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3846    return CheckVectorOperands(Loc, lex, rex);
3847
3848  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3849
3850  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3851    return compType;
3852  return InvalidOperands(Loc, lex, rex);
3853}
3854
3855inline QualType Sema::CheckRemainderOperands(
3856  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3857{
3858  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3859    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3860      return CheckVectorOperands(Loc, lex, rex);
3861    return InvalidOperands(Loc, lex, rex);
3862  }
3863
3864  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3865
3866  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3867    return compType;
3868  return InvalidOperands(Loc, lex, rex);
3869}
3870
3871inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
3872  Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
3873{
3874  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3875    QualType compType = CheckVectorOperands(Loc, lex, rex);
3876    if (CompLHSTy) *CompLHSTy = compType;
3877    return compType;
3878  }
3879
3880  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
3881
3882  // handle the common case first (both operands are arithmetic).
3883  if (lex->getType()->isArithmeticType() &&
3884      rex->getType()->isArithmeticType()) {
3885    if (CompLHSTy) *CompLHSTy = compType;
3886    return compType;
3887  }
3888
3889  // Put any potential pointer into PExp
3890  Expr* PExp = lex, *IExp = rex;
3891  if (IExp->getType()->isAnyPointerType())
3892    std::swap(PExp, IExp);
3893
3894  if (PExp->getType()->isAnyPointerType()) {
3895
3896    if (IExp->getType()->isIntegerType()) {
3897      QualType PointeeTy = PExp->getType()->getPointeeType();
3898
3899      // Check for arithmetic on pointers to incomplete types.
3900      if (PointeeTy->isVoidType()) {
3901        if (getLangOptions().CPlusPlus) {
3902          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3903            << lex->getSourceRange() << rex->getSourceRange();
3904          return QualType();
3905        }
3906
3907        // GNU extension: arithmetic on pointer to void
3908        Diag(Loc, diag::ext_gnu_void_ptr)
3909          << lex->getSourceRange() << rex->getSourceRange();
3910      } else if (PointeeTy->isFunctionType()) {
3911        if (getLangOptions().CPlusPlus) {
3912          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3913            << lex->getType() << lex->getSourceRange();
3914          return QualType();
3915        }
3916
3917        // GNU extension: arithmetic on pointer to function
3918        Diag(Loc, diag::ext_gnu_ptr_func_arith)
3919          << lex->getType() << lex->getSourceRange();
3920      } else {
3921        // Check if we require a complete type.
3922        if (((PExp->getType()->isPointerType() &&
3923              !PExp->getType()->isDependentType()) ||
3924              PExp->getType()->isObjCObjectPointerType()) &&
3925             RequireCompleteType(Loc, PointeeTy,
3926                                 diag::err_typecheck_arithmetic_incomplete_type,
3927                                 PExp->getSourceRange(), SourceRange(),
3928                                 PExp->getType()))
3929          return QualType();
3930      }
3931      // Diagnose bad cases where we step over interface counts.
3932      if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3933        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3934          << PointeeTy << PExp->getSourceRange();
3935        return QualType();
3936      }
3937
3938      if (CompLHSTy) {
3939        QualType LHSTy = Context.isPromotableBitField(lex);
3940        if (LHSTy.isNull()) {
3941          LHSTy = lex->getType();
3942          if (LHSTy->isPromotableIntegerType())
3943            LHSTy = Context.getPromotedIntegerType(LHSTy);
3944        }
3945        *CompLHSTy = LHSTy;
3946      }
3947      return PExp->getType();
3948    }
3949  }
3950
3951  return InvalidOperands(Loc, lex, rex);
3952}
3953
3954// C99 6.5.6
3955QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
3956                                        SourceLocation Loc, QualType* CompLHSTy) {
3957  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3958    QualType compType = CheckVectorOperands(Loc, lex, rex);
3959    if (CompLHSTy) *CompLHSTy = compType;
3960    return compType;
3961  }
3962
3963  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
3964
3965  // Enforce type constraints: C99 6.5.6p3.
3966
3967  // Handle the common case first (both operands are arithmetic).
3968  if (lex->getType()->isArithmeticType()
3969      && rex->getType()->isArithmeticType()) {
3970    if (CompLHSTy) *CompLHSTy = compType;
3971    return compType;
3972  }
3973
3974  // Either ptr - int   or   ptr - ptr.
3975  if (lex->getType()->isAnyPointerType()) {
3976    QualType lpointee = lex->getType()->getPointeeType();
3977
3978    // The LHS must be an completely-defined object type.
3979
3980    bool ComplainAboutVoid = false;
3981    Expr *ComplainAboutFunc = 0;
3982    if (lpointee->isVoidType()) {
3983      if (getLangOptions().CPlusPlus) {
3984        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3985          << lex->getSourceRange() << rex->getSourceRange();
3986        return QualType();
3987      }
3988
3989      // GNU C extension: arithmetic on pointer to void
3990      ComplainAboutVoid = true;
3991    } else if (lpointee->isFunctionType()) {
3992      if (getLangOptions().CPlusPlus) {
3993        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3994          << lex->getType() << lex->getSourceRange();
3995        return QualType();
3996      }
3997
3998      // GNU C extension: arithmetic on pointer to function
3999      ComplainAboutFunc = lex;
4000    } else if (!lpointee->isDependentType() &&
4001               RequireCompleteType(Loc, lpointee,
4002                                   diag::err_typecheck_sub_ptr_object,
4003                                   lex->getSourceRange(),
4004                                   SourceRange(),
4005                                   lex->getType()))
4006      return QualType();
4007
4008    // Diagnose bad cases where we step over interface counts.
4009    if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4010      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4011        << lpointee << lex->getSourceRange();
4012      return QualType();
4013    }
4014
4015    // The result type of a pointer-int computation is the pointer type.
4016    if (rex->getType()->isIntegerType()) {
4017      if (ComplainAboutVoid)
4018        Diag(Loc, diag::ext_gnu_void_ptr)
4019          << lex->getSourceRange() << rex->getSourceRange();
4020      if (ComplainAboutFunc)
4021        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4022          << ComplainAboutFunc->getType()
4023          << ComplainAboutFunc->getSourceRange();
4024
4025      if (CompLHSTy) *CompLHSTy = lex->getType();
4026      return lex->getType();
4027    }
4028
4029    // Handle pointer-pointer subtractions.
4030    if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
4031      QualType rpointee = RHSPTy->getPointeeType();
4032
4033      // RHS must be a completely-type object type.
4034      // Handle the GNU void* extension.
4035      if (rpointee->isVoidType()) {
4036        if (getLangOptions().CPlusPlus) {
4037          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4038            << lex->getSourceRange() << rex->getSourceRange();
4039          return QualType();
4040        }
4041
4042        ComplainAboutVoid = true;
4043      } else if (rpointee->isFunctionType()) {
4044        if (getLangOptions().CPlusPlus) {
4045          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4046            << rex->getType() << rex->getSourceRange();
4047          return QualType();
4048        }
4049
4050        // GNU extension: arithmetic on pointer to function
4051        if (!ComplainAboutFunc)
4052          ComplainAboutFunc = rex;
4053      } else if (!rpointee->isDependentType() &&
4054                 RequireCompleteType(Loc, rpointee,
4055                                     diag::err_typecheck_sub_ptr_object,
4056                                     rex->getSourceRange(),
4057                                     SourceRange(),
4058                                     rex->getType()))
4059        return QualType();
4060
4061      if (getLangOptions().CPlusPlus) {
4062        // Pointee types must be the same: C++ [expr.add]
4063        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4064          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4065            << lex->getType() << rex->getType()
4066            << lex->getSourceRange() << rex->getSourceRange();
4067          return QualType();
4068        }
4069      } else {
4070        // Pointee types must be compatible C99 6.5.6p3
4071        if (!Context.typesAreCompatible(
4072                Context.getCanonicalType(lpointee).getUnqualifiedType(),
4073                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4074          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4075            << lex->getType() << rex->getType()
4076            << lex->getSourceRange() << rex->getSourceRange();
4077          return QualType();
4078        }
4079      }
4080
4081      if (ComplainAboutVoid)
4082        Diag(Loc, diag::ext_gnu_void_ptr)
4083          << lex->getSourceRange() << rex->getSourceRange();
4084      if (ComplainAboutFunc)
4085        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4086          << ComplainAboutFunc->getType()
4087          << ComplainAboutFunc->getSourceRange();
4088
4089      if (CompLHSTy) *CompLHSTy = lex->getType();
4090      return Context.getPointerDiffType();
4091    }
4092  }
4093
4094  return InvalidOperands(Loc, lex, rex);
4095}
4096
4097// C99 6.5.7
4098QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4099                                  bool isCompAssign) {
4100  // C99 6.5.7p2: Each of the operands shall have integer type.
4101  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4102    return InvalidOperands(Loc, lex, rex);
4103
4104  // Shifts don't perform usual arithmetic conversions, they just do integer
4105  // promotions on each operand. C99 6.5.7p3
4106  QualType LHSTy = Context.isPromotableBitField(lex);
4107  if (LHSTy.isNull()) {
4108    LHSTy = lex->getType();
4109    if (LHSTy->isPromotableIntegerType())
4110      LHSTy = Context.getPromotedIntegerType(LHSTy);
4111  }
4112  if (!isCompAssign)
4113    ImpCastExprToType(lex, LHSTy);
4114
4115  UsualUnaryConversions(rex);
4116
4117  // Sanity-check shift operands
4118  llvm::APSInt Right;
4119  // Check right/shifter operand
4120  if (rex->isIntegerConstantExpr(Right, Context)) {
4121    if (Right.isNegative())
4122      Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4123    else {
4124      llvm::APInt LeftBits(Right.getBitWidth(),
4125                          Context.getTypeSize(lex->getType()));
4126      if (Right.uge(LeftBits))
4127        Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4128    }
4129  }
4130
4131  // "The type of the result is that of the promoted left operand."
4132  return LHSTy;
4133}
4134
4135// C99 6.5.8, C++ [expr.rel]
4136QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4137                                    unsigned OpaqueOpc, bool isRelational) {
4138  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4139
4140  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4141    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
4142
4143  // C99 6.5.8p3 / C99 6.5.9p4
4144  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4145    UsualArithmeticConversions(lex, rex);
4146  else {
4147    UsualUnaryConversions(lex);
4148    UsualUnaryConversions(rex);
4149  }
4150  QualType lType = lex->getType();
4151  QualType rType = rex->getType();
4152
4153  if (!lType->isFloatingType()
4154      && !(lType->isBlockPointerType() && isRelational)) {
4155    // For non-floating point types, check for self-comparisons of the form
4156    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4157    // often indicate logic errors in the program.
4158    // NOTE: Don't warn about comparisons of enum constants. These can arise
4159    //  from macro expansions, and are usually quite deliberate.
4160    Expr *LHSStripped = lex->IgnoreParens();
4161    Expr *RHSStripped = rex->IgnoreParens();
4162    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4163      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
4164        if (DRL->getDecl() == DRR->getDecl() &&
4165            !isa<EnumConstantDecl>(DRL->getDecl()))
4166          Diag(Loc, diag::warn_selfcomparison);
4167
4168    if (isa<CastExpr>(LHSStripped))
4169      LHSStripped = LHSStripped->IgnoreParenCasts();
4170    if (isa<CastExpr>(RHSStripped))
4171      RHSStripped = RHSStripped->IgnoreParenCasts();
4172
4173    // Warn about comparisons against a string constant (unless the other
4174    // operand is null), the user probably wants strcmp.
4175    Expr *literalString = 0;
4176    Expr *literalStringStripped = 0;
4177    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
4178        !RHSStripped->isNullPointerConstant(Context)) {
4179      literalString = lex;
4180      literalStringStripped = LHSStripped;
4181    } else if ((isa<StringLiteral>(RHSStripped) ||
4182                isa<ObjCEncodeExpr>(RHSStripped)) &&
4183               !LHSStripped->isNullPointerConstant(Context)) {
4184      literalString = rex;
4185      literalStringStripped = RHSStripped;
4186    }
4187
4188    if (literalString) {
4189      std::string resultComparison;
4190      switch (Opc) {
4191      case BinaryOperator::LT: resultComparison = ") < 0"; break;
4192      case BinaryOperator::GT: resultComparison = ") > 0"; break;
4193      case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4194      case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4195      case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4196      case BinaryOperator::NE: resultComparison = ") != 0"; break;
4197      default: assert(false && "Invalid comparison operator");
4198      }
4199      Diag(Loc, diag::warn_stringcompare)
4200        << isa<ObjCEncodeExpr>(literalStringStripped)
4201        << literalString->getSourceRange()
4202        << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4203        << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4204                                                 "strcmp(")
4205        << CodeModificationHint::CreateInsertion(
4206                                       PP.getLocForEndOfToken(rex->getLocEnd()),
4207                                       resultComparison);
4208    }
4209  }
4210
4211  // The result of comparisons is 'bool' in C++, 'int' in C.
4212  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
4213
4214  if (isRelational) {
4215    if (lType->isRealType() && rType->isRealType())
4216      return ResultTy;
4217  } else {
4218    // Check for comparisons of floating point operands using != and ==.
4219    if (lType->isFloatingType()) {
4220      assert(rType->isFloatingType());
4221      CheckFloatComparison(Loc,lex,rex);
4222    }
4223
4224    if (lType->isArithmeticType() && rType->isArithmeticType())
4225      return ResultTy;
4226  }
4227
4228  bool LHSIsNull = lex->isNullPointerConstant(Context);
4229  bool RHSIsNull = rex->isNullPointerConstant(Context);
4230
4231  // All of the following pointer related warnings are GCC extensions, except
4232  // when handling null pointer constants. One day, we can consider making them
4233  // errors (when -pedantic-errors is enabled).
4234  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
4235    QualType LCanPointeeTy =
4236      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
4237    QualType RCanPointeeTy =
4238      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
4239
4240    if (isRelational) {
4241      if (lType->isFunctionPointerType() || rType->isFunctionPointerType()) {
4242        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4243          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4244      }
4245      if (LCanPointeeTy->isVoidType() != RCanPointeeTy->isVoidType()) {
4246        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4247          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4248      }
4249    } else {
4250      if (lType->isFunctionPointerType() != rType->isFunctionPointerType()) {
4251        if (!LHSIsNull && !RHSIsNull)
4252          Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4253            << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4254      }
4255    }
4256
4257    // Simple check: if the pointee types are identical, we're done.
4258    if (LCanPointeeTy == RCanPointeeTy)
4259      return ResultTy;
4260
4261    if (getLangOptions().CPlusPlus) {
4262      // C++ [expr.rel]p2:
4263      //   [...] Pointer conversions (4.10) and qualification
4264      //   conversions (4.4) are performed on pointer operands (or on
4265      //   a pointer operand and a null pointer constant) to bring
4266      //   them to their composite pointer type. [...]
4267      //
4268      // C++ [expr.eq]p2 uses the same notion for (in)equality
4269      // comparisons of pointers.
4270      QualType T = FindCompositePointerType(lex, rex);
4271      if (T.isNull()) {
4272        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4273          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4274        return QualType();
4275      }
4276
4277      ImpCastExprToType(lex, T);
4278      ImpCastExprToType(rex, T);
4279      return ResultTy;
4280    }
4281
4282    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
4283        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
4284        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4285                                    RCanPointeeTy.getUnqualifiedType())) {
4286      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4287        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4288    }
4289    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4290    return ResultTy;
4291  }
4292  // C++ allows comparison of pointers with null pointer constants.
4293  if (getLangOptions().CPlusPlus) {
4294    if (lType->isPointerType() && RHSIsNull) {
4295      ImpCastExprToType(rex, lType);
4296      return ResultTy;
4297    }
4298    if (rType->isPointerType() && LHSIsNull) {
4299      ImpCastExprToType(lex, rType);
4300      return ResultTy;
4301    }
4302    // And comparison of nullptr_t with itself.
4303    if (lType->isNullPtrType() && rType->isNullPtrType())
4304      return ResultTy;
4305  }
4306  // Handle block pointer types.
4307  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
4308    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4309    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
4310
4311    if (!LHSIsNull && !RHSIsNull &&
4312        !Context.typesAreCompatible(lpointee, rpointee)) {
4313      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4314        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4315    }
4316    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4317    return ResultTy;
4318  }
4319  // Allow block pointers to be compared with null pointer constants.
4320  if (!isRelational
4321      && ((lType->isBlockPointerType() && rType->isPointerType())
4322          || (lType->isPointerType() && rType->isBlockPointerType()))) {
4323    if (!LHSIsNull && !RHSIsNull) {
4324      if (!((rType->isPointerType() && rType->getAs<PointerType>()
4325             ->getPointeeType()->isVoidType())
4326            || (lType->isPointerType() && lType->getAs<PointerType>()
4327                ->getPointeeType()->isVoidType())))
4328        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4329          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4330    }
4331    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4332    return ResultTy;
4333  }
4334
4335  if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
4336    if (lType->isPointerType() || rType->isPointerType()) {
4337      const PointerType *LPT = lType->getAs<PointerType>();
4338      const PointerType *RPT = rType->getAs<PointerType>();
4339      bool LPtrToVoid = LPT ?
4340        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
4341      bool RPtrToVoid = RPT ?
4342        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
4343
4344      if (!LPtrToVoid && !RPtrToVoid &&
4345          !Context.typesAreCompatible(lType, rType)) {
4346        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4347          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4348      }
4349      ImpCastExprToType(rex, lType);
4350      return ResultTy;
4351    }
4352    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4353      if (!Context.areComparableObjCPointerTypes(lType, rType)) {
4354        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4355          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4356      }
4357      ImpCastExprToType(rex, lType);
4358      return ResultTy;
4359    }
4360  }
4361  if (lType->isAnyPointerType() && rType->isIntegerType()) {
4362    if (isRelational)
4363      Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4364        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4365    else if (!RHSIsNull)
4366      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
4367        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4368    ImpCastExprToType(rex, lType); // promote the integer to pointer
4369    return ResultTy;
4370  }
4371  if (lType->isIntegerType() && rType->isAnyPointerType()) {
4372    if (isRelational)
4373      Diag(Loc, diag::ext_typecheck_ordered_comparison_of_pointer_integer)
4374        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4375    else if (!LHSIsNull)
4376      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
4377        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4378    ImpCastExprToType(lex, rType); // promote the integer to pointer
4379    return ResultTy;
4380  }
4381  // Handle block pointers.
4382  if (!isRelational && RHSIsNull
4383      && lType->isBlockPointerType() && rType->isIntegerType()) {
4384    ImpCastExprToType(rex, lType); // promote the integer to pointer
4385    return ResultTy;
4386  }
4387  if (!isRelational && LHSIsNull
4388      && lType->isIntegerType() && rType->isBlockPointerType()) {
4389    ImpCastExprToType(lex, rType); // promote the integer to pointer
4390    return ResultTy;
4391  }
4392  return InvalidOperands(Loc, lex, rex);
4393}
4394
4395/// CheckVectorCompareOperands - vector comparisons are a clang extension that
4396/// operates on extended vector types.  Instead of producing an IntTy result,
4397/// like a scalar comparison, a vector comparison produces a vector of integer
4398/// types.
4399QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
4400                                          SourceLocation Loc,
4401                                          bool isRelational) {
4402  // Check to make sure we're operating on vectors of the same type and width,
4403  // Allowing one side to be a scalar of element type.
4404  QualType vType = CheckVectorOperands(Loc, lex, rex);
4405  if (vType.isNull())
4406    return vType;
4407
4408  QualType lType = lex->getType();
4409  QualType rType = rex->getType();
4410
4411  // For non-floating point types, check for self-comparisons of the form
4412  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4413  // often indicate logic errors in the program.
4414  if (!lType->isFloatingType()) {
4415    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4416      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4417        if (DRL->getDecl() == DRR->getDecl())
4418          Diag(Loc, diag::warn_selfcomparison);
4419  }
4420
4421  // Check for comparisons of floating point operands using != and ==.
4422  if (!isRelational && lType->isFloatingType()) {
4423    assert (rType->isFloatingType());
4424    CheckFloatComparison(Loc,lex,rex);
4425  }
4426
4427  // Return the type for the comparison, which is the same as vector type for
4428  // integer vectors, or an integer type of identical size and number of
4429  // elements for floating point vectors.
4430  if (lType->isIntegerType())
4431    return lType;
4432
4433  const VectorType *VTy = lType->getAsVectorType();
4434  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
4435  if (TypeSize == Context.getTypeSize(Context.IntTy))
4436    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
4437  if (TypeSize == Context.getTypeSize(Context.LongTy))
4438    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4439
4440  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
4441         "Unhandled vector element size in vector compare");
4442  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4443}
4444
4445inline QualType Sema::CheckBitwiseOperands(
4446  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
4447{
4448  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4449    return CheckVectorOperands(Loc, lex, rex);
4450
4451  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4452
4453  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4454    return compType;
4455  return InvalidOperands(Loc, lex, rex);
4456}
4457
4458inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
4459  Expr *&lex, Expr *&rex, SourceLocation Loc)
4460{
4461  UsualUnaryConversions(lex);
4462  UsualUnaryConversions(rex);
4463
4464  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
4465    return Context.IntTy;
4466  return InvalidOperands(Loc, lex, rex);
4467}
4468
4469/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4470/// is a read-only property; return true if so. A readonly property expression
4471/// depends on various declarations and thus must be treated specially.
4472///
4473static bool IsReadonlyProperty(Expr *E, Sema &S)
4474{
4475  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4476    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4477    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4478      QualType BaseType = PropExpr->getBase()->getType();
4479      if (const ObjCObjectPointerType *OPT =
4480            BaseType->getAsObjCInterfacePointerType())
4481        if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4482          if (S.isPropertyReadonly(PDecl, IFace))
4483            return true;
4484    }
4485  }
4486  return false;
4487}
4488
4489/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
4490/// emit an error and return true.  If so, return false.
4491static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
4492  SourceLocation OrigLoc = Loc;
4493  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4494                                                              &Loc);
4495  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4496    IsLV = Expr::MLV_ReadonlyProperty;
4497  if (IsLV == Expr::MLV_Valid)
4498    return false;
4499
4500  unsigned Diag = 0;
4501  bool NeedType = false;
4502  switch (IsLV) { // C99 6.5.16p2
4503  default: assert(0 && "Unknown result from isModifiableLvalue!");
4504  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
4505  case Expr::MLV_ArrayType:
4506    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4507    NeedType = true;
4508    break;
4509  case Expr::MLV_NotObjectType:
4510    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4511    NeedType = true;
4512    break;
4513  case Expr::MLV_LValueCast:
4514    Diag = diag::err_typecheck_lvalue_casts_not_supported;
4515    break;
4516  case Expr::MLV_InvalidExpression:
4517    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4518    break;
4519  case Expr::MLV_IncompleteType:
4520  case Expr::MLV_IncompleteVoidType:
4521    return S.RequireCompleteType(Loc, E->getType(),
4522                      diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4523                                    E->getSourceRange());
4524  case Expr::MLV_DuplicateVectorComponents:
4525    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4526    break;
4527  case Expr::MLV_NotBlockQualified:
4528    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4529    break;
4530  case Expr::MLV_ReadonlyProperty:
4531    Diag = diag::error_readonly_property_assignment;
4532    break;
4533  case Expr::MLV_NoSetterProperty:
4534    Diag = diag::error_nosetter_property_assignment;
4535    break;
4536  }
4537
4538  SourceRange Assign;
4539  if (Loc != OrigLoc)
4540    Assign = SourceRange(OrigLoc, OrigLoc);
4541  if (NeedType)
4542    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
4543  else
4544    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
4545  return true;
4546}
4547
4548
4549
4550// C99 6.5.16.1
4551QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4552                                       SourceLocation Loc,
4553                                       QualType CompoundType) {
4554  // Verify that LHS is a modifiable lvalue, and emit error if not.
4555  if (CheckForModifiableLvalue(LHS, Loc, *this))
4556    return QualType();
4557
4558  QualType LHSType = LHS->getType();
4559  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
4560
4561  AssignConvertType ConvTy;
4562  if (CompoundType.isNull()) {
4563    // Simple assignment "x = y".
4564    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
4565    // Special case of NSObject attributes on c-style pointer types.
4566    if (ConvTy == IncompatiblePointer &&
4567        ((Context.isObjCNSObjectType(LHSType) &&
4568          RHSType->isObjCObjectPointerType()) ||
4569         (Context.isObjCNSObjectType(RHSType) &&
4570          LHSType->isObjCObjectPointerType())))
4571      ConvTy = Compatible;
4572
4573    // If the RHS is a unary plus or minus, check to see if they = and + are
4574    // right next to each other.  If so, the user may have typo'd "x =+ 4"
4575    // instead of "x += 4".
4576    Expr *RHSCheck = RHS;
4577    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4578      RHSCheck = ICE->getSubExpr();
4579    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4580      if ((UO->getOpcode() == UnaryOperator::Plus ||
4581           UO->getOpcode() == UnaryOperator::Minus) &&
4582          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
4583          // Only if the two operators are exactly adjacent.
4584          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4585          // And there is a space or other character before the subexpr of the
4586          // unary +/-.  We don't want to warn on "x=-1".
4587          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4588          UO->getSubExpr()->getLocStart().isFileID()) {
4589        Diag(Loc, diag::warn_not_compound_assign)
4590          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4591          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
4592      }
4593    }
4594  } else {
4595    // Compound assignment "x += y"
4596    ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
4597  }
4598
4599  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4600                               RHS, "assigning"))
4601    return QualType();
4602
4603  // C99 6.5.16p3: The type of an assignment expression is the type of the
4604  // left operand unless the left operand has qualified type, in which case
4605  // it is the unqualified version of the type of the left operand.
4606  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4607  // is converted to the type of the assignment expression (above).
4608  // C++ 5.17p1: the type of the assignment expression is that of its left
4609  // operand.
4610  return LHSType.getUnqualifiedType();
4611}
4612
4613// C99 6.5.17
4614QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
4615  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
4616  DefaultFunctionArrayConversion(RHS);
4617
4618  // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4619  // incomplete in C++).
4620
4621  return RHS->getType();
4622}
4623
4624/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4625/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
4626QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4627                                              bool isInc) {
4628  if (Op->isTypeDependent())
4629    return Context.DependentTy;
4630
4631  QualType ResType = Op->getType();
4632  assert(!ResType.isNull() && "no type for increment/decrement expression");
4633
4634  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4635    // Decrement of bool is not allowed.
4636    if (!isInc) {
4637      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4638      return QualType();
4639    }
4640    // Increment of bool sets it to true, but is deprecated.
4641    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4642  } else if (ResType->isRealType()) {
4643    // OK!
4644  } else if (ResType->isAnyPointerType()) {
4645    QualType PointeeTy = ResType->getPointeeType();
4646
4647    // C99 6.5.2.4p2, 6.5.6p2
4648    if (PointeeTy->isVoidType()) {
4649      if (getLangOptions().CPlusPlus) {
4650        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4651          << Op->getSourceRange();
4652        return QualType();
4653      }
4654
4655      // Pointer to void is a GNU extension in C.
4656      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
4657    } else if (PointeeTy->isFunctionType()) {
4658      if (getLangOptions().CPlusPlus) {
4659        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4660          << Op->getType() << Op->getSourceRange();
4661        return QualType();
4662      }
4663
4664      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
4665        << ResType << Op->getSourceRange();
4666    } else if (RequireCompleteType(OpLoc, PointeeTy,
4667                               diag::err_typecheck_arithmetic_incomplete_type,
4668                                   Op->getSourceRange(), SourceRange(),
4669                                   ResType))
4670      return QualType();
4671    // Diagnose bad cases where we step over interface counts.
4672    else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4673      Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4674        << PointeeTy << Op->getSourceRange();
4675      return QualType();
4676    }
4677  } else if (ResType->isComplexType()) {
4678    // C99 does not support ++/-- on complex types, we allow as an extension.
4679    Diag(OpLoc, diag::ext_integer_increment_complex)
4680      << ResType << Op->getSourceRange();
4681  } else {
4682    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
4683      << ResType << Op->getSourceRange();
4684    return QualType();
4685  }
4686  // At this point, we know we have a real, complex or pointer type.
4687  // Now make sure the operand is a modifiable lvalue.
4688  if (CheckForModifiableLvalue(Op, OpLoc, *this))
4689    return QualType();
4690  return ResType;
4691}
4692
4693/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
4694/// This routine allows us to typecheck complex/recursive expressions
4695/// where the declaration is needed for type checking. We only need to
4696/// handle cases when the expression references a function designator
4697/// or is an lvalue. Here are some examples:
4698///  - &(x) => x
4699///  - &*****f => f for f a function designator.
4700///  - &s.xx => s
4701///  - &s.zz[1].yy -> s, if zz is an array
4702///  - *(x + 1) -> x, if x is an array
4703///  - &"123"[2] -> 0
4704///  - & __real__ x -> x
4705static NamedDecl *getPrimaryDecl(Expr *E) {
4706  switch (E->getStmtClass()) {
4707  case Stmt::DeclRefExprClass:
4708  case Stmt::QualifiedDeclRefExprClass:
4709    return cast<DeclRefExpr>(E)->getDecl();
4710  case Stmt::MemberExprClass:
4711    // If this is an arrow operator, the address is an offset from
4712    // the base's value, so the object the base refers to is
4713    // irrelevant.
4714    if (cast<MemberExpr>(E)->isArrow())
4715      return 0;
4716    // Otherwise, the expression refers to a part of the base
4717    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
4718  case Stmt::ArraySubscriptExprClass: {
4719    // FIXME: This code shouldn't be necessary!  We should catch the implicit
4720    // promotion of register arrays earlier.
4721    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4722    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4723      if (ICE->getSubExpr()->getType()->isArrayType())
4724        return getPrimaryDecl(ICE->getSubExpr());
4725    }
4726    return 0;
4727  }
4728  case Stmt::UnaryOperatorClass: {
4729    UnaryOperator *UO = cast<UnaryOperator>(E);
4730
4731    switch(UO->getOpcode()) {
4732    case UnaryOperator::Real:
4733    case UnaryOperator::Imag:
4734    case UnaryOperator::Extension:
4735      return getPrimaryDecl(UO->getSubExpr());
4736    default:
4737      return 0;
4738    }
4739  }
4740  case Stmt::ParenExprClass:
4741    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
4742  case Stmt::ImplicitCastExprClass:
4743    // If the result of an implicit cast is an l-value, we care about
4744    // the sub-expression; otherwise, the result here doesn't matter.
4745    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
4746  default:
4747    return 0;
4748  }
4749}
4750
4751/// CheckAddressOfOperand - The operand of & must be either a function
4752/// designator or an lvalue designating an object. If it is an lvalue, the
4753/// object cannot be declared with storage class register or be a bit field.
4754/// Note: The usual conversions are *not* applied to the operand of the &
4755/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
4756/// In C++, the operand might be an overloaded function name, in which case
4757/// we allow the '&' but retain the overloaded-function type.
4758QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
4759  // Make sure to ignore parentheses in subsequent checks
4760  op = op->IgnoreParens();
4761
4762  if (op->isTypeDependent())
4763    return Context.DependentTy;
4764
4765  if (getLangOptions().C99) {
4766    // Implement C99-only parts of addressof rules.
4767    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4768      if (uOp->getOpcode() == UnaryOperator::Deref)
4769        // Per C99 6.5.3.2, the address of a deref always returns a valid result
4770        // (assuming the deref expression is valid).
4771        return uOp->getSubExpr()->getType();
4772    }
4773    // Technically, there should be a check for array subscript
4774    // expressions here, but the result of one is always an lvalue anyway.
4775  }
4776  NamedDecl *dcl = getPrimaryDecl(op);
4777  Expr::isLvalueResult lval = op->isLvalue(Context);
4778
4779  if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4780    // C99 6.5.3.2p1
4781    // The operand must be either an l-value or a function designator
4782    if (!op->getType()->isFunctionType()) {
4783      // FIXME: emit more specific diag...
4784      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4785        << op->getSourceRange();
4786      return QualType();
4787    }
4788  } else if (op->getBitField()) { // C99 6.5.3.2p1
4789    // The operand cannot be a bit-field
4790    Diag(OpLoc, diag::err_typecheck_address_of)
4791      << "bit-field" << op->getSourceRange();
4792        return QualType();
4793  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4794           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
4795    // The operand cannot be an element of a vector
4796    Diag(OpLoc, diag::err_typecheck_address_of)
4797      << "vector element" << op->getSourceRange();
4798    return QualType();
4799  } else if (isa<ObjCPropertyRefExpr>(op)) {
4800    // cannot take address of a property expression.
4801    Diag(OpLoc, diag::err_typecheck_address_of)
4802      << "property expression" << op->getSourceRange();
4803    return QualType();
4804  } else if (dcl) { // C99 6.5.3.2p1
4805    // We have an lvalue with a decl. Make sure the decl is not declared
4806    // with the register storage-class specifier.
4807    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4808      if (vd->getStorageClass() == VarDecl::Register) {
4809        Diag(OpLoc, diag::err_typecheck_address_of)
4810          << "register variable" << op->getSourceRange();
4811        return QualType();
4812      }
4813    } else if (isa<OverloadedFunctionDecl>(dcl) ||
4814               isa<FunctionTemplateDecl>(dcl)) {
4815      return Context.OverloadTy;
4816    } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
4817      // Okay: we can take the address of a field.
4818      // Could be a pointer to member, though, if there is an explicit
4819      // scope qualifier for the class.
4820      if (isa<QualifiedDeclRefExpr>(op)) {
4821        DeclContext *Ctx = dcl->getDeclContext();
4822        if (Ctx && Ctx->isRecord()) {
4823          if (FD->getType()->isReferenceType()) {
4824            Diag(OpLoc,
4825                 diag::err_cannot_form_pointer_to_member_of_reference_type)
4826              << FD->getDeclName() << FD->getType();
4827            return QualType();
4828          }
4829
4830          return Context.getMemberPointerType(op->getType(),
4831                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4832        }
4833      }
4834    } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
4835      // Okay: we can take the address of a function.
4836      // As above.
4837      if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4838        return Context.getMemberPointerType(op->getType(),
4839              Context.getTypeDeclType(MD->getParent()).getTypePtr());
4840    } else if (!isa<FunctionDecl>(dcl))
4841      assert(0 && "Unknown/unexpected decl type");
4842  }
4843
4844  if (lval == Expr::LV_IncompleteVoidType) {
4845    // Taking the address of a void variable is technically illegal, but we
4846    // allow it in cases which are otherwise valid.
4847    // Example: "extern void x; void* y = &x;".
4848    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4849  }
4850
4851  // If the operand has type "type", the result has type "pointer to type".
4852  return Context.getPointerType(op->getType());
4853}
4854
4855QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
4856  if (Op->isTypeDependent())
4857    return Context.DependentTy;
4858
4859  UsualUnaryConversions(Op);
4860  QualType Ty = Op->getType();
4861
4862  // Note that per both C89 and C99, this is always legal, even if ptype is an
4863  // incomplete type or void.  It would be possible to warn about dereferencing
4864  // a void pointer, but it's completely well-defined, and such a warning is
4865  // unlikely to catch any mistakes.
4866  if (const PointerType *PT = Ty->getAs<PointerType>())
4867    return PT->getPointeeType();
4868
4869  if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4870    return OPT->getPointeeType();
4871
4872  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
4873    << Ty << Op->getSourceRange();
4874  return QualType();
4875}
4876
4877static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4878  tok::TokenKind Kind) {
4879  BinaryOperator::Opcode Opc;
4880  switch (Kind) {
4881  default: assert(0 && "Unknown binop!");
4882  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
4883  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
4884  case tok::star:                 Opc = BinaryOperator::Mul; break;
4885  case tok::slash:                Opc = BinaryOperator::Div; break;
4886  case tok::percent:              Opc = BinaryOperator::Rem; break;
4887  case tok::plus:                 Opc = BinaryOperator::Add; break;
4888  case tok::minus:                Opc = BinaryOperator::Sub; break;
4889  case tok::lessless:             Opc = BinaryOperator::Shl; break;
4890  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
4891  case tok::lessequal:            Opc = BinaryOperator::LE; break;
4892  case tok::less:                 Opc = BinaryOperator::LT; break;
4893  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
4894  case tok::greater:              Opc = BinaryOperator::GT; break;
4895  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
4896  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
4897  case tok::amp:                  Opc = BinaryOperator::And; break;
4898  case tok::caret:                Opc = BinaryOperator::Xor; break;
4899  case tok::pipe:                 Opc = BinaryOperator::Or; break;
4900  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
4901  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
4902  case tok::equal:                Opc = BinaryOperator::Assign; break;
4903  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
4904  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
4905  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
4906  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
4907  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
4908  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
4909  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
4910  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
4911  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
4912  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
4913  case tok::comma:                Opc = BinaryOperator::Comma; break;
4914  }
4915  return Opc;
4916}
4917
4918static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
4919  tok::TokenKind Kind) {
4920  UnaryOperator::Opcode Opc;
4921  switch (Kind) {
4922  default: assert(0 && "Unknown unary op!");
4923  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
4924  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
4925  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
4926  case tok::star:         Opc = UnaryOperator::Deref; break;
4927  case tok::plus:         Opc = UnaryOperator::Plus; break;
4928  case tok::minus:        Opc = UnaryOperator::Minus; break;
4929  case tok::tilde:        Opc = UnaryOperator::Not; break;
4930  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
4931  case tok::kw___real:    Opc = UnaryOperator::Real; break;
4932  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
4933  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
4934  }
4935  return Opc;
4936}
4937
4938/// CreateBuiltinBinOp - Creates a new built-in binary operation with
4939/// operator @p Opc at location @c TokLoc. This routine only supports
4940/// built-in operations; ActOnBinOp handles overloaded operators.
4941Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
4942                                                  unsigned Op,
4943                                                  Expr *lhs, Expr *rhs) {
4944  QualType ResultTy;     // Result type of the binary operator.
4945  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
4946  // The following two variables are used for compound assignment operators
4947  QualType CompLHSTy;    // Type of LHS after promotions for computation
4948  QualType CompResultTy; // Type of computation result
4949
4950  switch (Opc) {
4951  case BinaryOperator::Assign:
4952    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
4953    break;
4954  case BinaryOperator::PtrMemD:
4955  case BinaryOperator::PtrMemI:
4956    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
4957                                            Opc == BinaryOperator::PtrMemI);
4958    break;
4959  case BinaryOperator::Mul:
4960  case BinaryOperator::Div:
4961    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
4962    break;
4963  case BinaryOperator::Rem:
4964    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
4965    break;
4966  case BinaryOperator::Add:
4967    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
4968    break;
4969  case BinaryOperator::Sub:
4970    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
4971    break;
4972  case BinaryOperator::Shl:
4973  case BinaryOperator::Shr:
4974    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
4975    break;
4976  case BinaryOperator::LE:
4977  case BinaryOperator::LT:
4978  case BinaryOperator::GE:
4979  case BinaryOperator::GT:
4980    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
4981    break;
4982  case BinaryOperator::EQ:
4983  case BinaryOperator::NE:
4984    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
4985    break;
4986  case BinaryOperator::And:
4987  case BinaryOperator::Xor:
4988  case BinaryOperator::Or:
4989    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
4990    break;
4991  case BinaryOperator::LAnd:
4992  case BinaryOperator::LOr:
4993    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
4994    break;
4995  case BinaryOperator::MulAssign:
4996  case BinaryOperator::DivAssign:
4997    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
4998    CompLHSTy = CompResultTy;
4999    if (!CompResultTy.isNull())
5000      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5001    break;
5002  case BinaryOperator::RemAssign:
5003    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5004    CompLHSTy = CompResultTy;
5005    if (!CompResultTy.isNull())
5006      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5007    break;
5008  case BinaryOperator::AddAssign:
5009    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5010    if (!CompResultTy.isNull())
5011      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5012    break;
5013  case BinaryOperator::SubAssign:
5014    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5015    if (!CompResultTy.isNull())
5016      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5017    break;
5018  case BinaryOperator::ShlAssign:
5019  case BinaryOperator::ShrAssign:
5020    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5021    CompLHSTy = CompResultTy;
5022    if (!CompResultTy.isNull())
5023      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5024    break;
5025  case BinaryOperator::AndAssign:
5026  case BinaryOperator::XorAssign:
5027  case BinaryOperator::OrAssign:
5028    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5029    CompLHSTy = CompResultTy;
5030    if (!CompResultTy.isNull())
5031      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5032    break;
5033  case BinaryOperator::Comma:
5034    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5035    break;
5036  }
5037  if (ResultTy.isNull())
5038    return ExprError();
5039  if (CompResultTy.isNull())
5040    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5041  else
5042    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
5043                                                      CompLHSTy, CompResultTy,
5044                                                      OpLoc));
5045}
5046
5047// Binary Operators.  'Tok' is the token for the operator.
5048Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5049                                          tok::TokenKind Kind,
5050                                          ExprArg LHS, ExprArg RHS) {
5051  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
5052  Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
5053
5054  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5055  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
5056
5057  if (getLangOptions().CPlusPlus &&
5058      (lhs->getType()->isOverloadableType() ||
5059       rhs->getType()->isOverloadableType())) {
5060    // Find all of the overloaded operators visible from this
5061    // point. We perform both an operator-name lookup from the local
5062    // scope and an argument-dependent lookup based on the types of
5063    // the arguments.
5064    FunctionSet Functions;
5065    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5066    if (OverOp != OO_None) {
5067      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5068                                   Functions);
5069      Expr *Args[2] = { lhs, rhs };
5070      DeclarationName OpName
5071        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5072      ArgumentDependentLookup(OpName, Args, 2, Functions);
5073    }
5074
5075    // Build the (potentially-overloaded, potentially-dependent)
5076    // binary operation.
5077    return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
5078  }
5079
5080  // Build a built-in binary operation.
5081  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
5082}
5083
5084Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5085                                                    unsigned OpcIn,
5086                                                    ExprArg InputArg) {
5087  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5088
5089  // FIXME: Input is modified below, but InputArg is not updated appropriately.
5090  Expr *Input = (Expr *)InputArg.get();
5091  QualType resultType;
5092  switch (Opc) {
5093  case UnaryOperator::OffsetOf:
5094    assert(false && "Invalid unary operator");
5095    break;
5096
5097  case UnaryOperator::PreInc:
5098  case UnaryOperator::PreDec:
5099  case UnaryOperator::PostInc:
5100  case UnaryOperator::PostDec:
5101    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
5102                                                Opc == UnaryOperator::PreInc ||
5103                                                Opc == UnaryOperator::PostInc);
5104    break;
5105  case UnaryOperator::AddrOf:
5106    resultType = CheckAddressOfOperand(Input, OpLoc);
5107    break;
5108  case UnaryOperator::Deref:
5109    DefaultFunctionArrayConversion(Input);
5110    resultType = CheckIndirectionOperand(Input, OpLoc);
5111    break;
5112  case UnaryOperator::Plus:
5113  case UnaryOperator::Minus:
5114    UsualUnaryConversions(Input);
5115    resultType = Input->getType();
5116    if (resultType->isDependentType())
5117      break;
5118    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5119      break;
5120    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5121             resultType->isEnumeralType())
5122      break;
5123    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5124             Opc == UnaryOperator::Plus &&
5125             resultType->isPointerType())
5126      break;
5127
5128    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5129      << resultType << Input->getSourceRange());
5130  case UnaryOperator::Not: // bitwise complement
5131    UsualUnaryConversions(Input);
5132    resultType = Input->getType();
5133    if (resultType->isDependentType())
5134      break;
5135    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5136    if (resultType->isComplexType() || resultType->isComplexIntegerType())
5137      // C99 does not support '~' for complex conjugation.
5138      Diag(OpLoc, diag::ext_integer_complement_complex)
5139        << resultType << Input->getSourceRange();
5140    else if (!resultType->isIntegerType())
5141      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5142        << resultType << Input->getSourceRange());
5143    break;
5144  case UnaryOperator::LNot: // logical negation
5145    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5146    DefaultFunctionArrayConversion(Input);
5147    resultType = Input->getType();
5148    if (resultType->isDependentType())
5149      break;
5150    if (!resultType->isScalarType()) // C99 6.5.3.3p1
5151      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5152        << resultType << Input->getSourceRange());
5153    // LNot always has type int. C99 6.5.3.3p5.
5154    // In C++, it's bool. C++ 5.3.1p8
5155    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
5156    break;
5157  case UnaryOperator::Real:
5158  case UnaryOperator::Imag:
5159    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
5160    break;
5161  case UnaryOperator::Extension:
5162    resultType = Input->getType();
5163    break;
5164  }
5165  if (resultType.isNull())
5166    return ExprError();
5167
5168  InputArg.release();
5169  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
5170}
5171
5172// Unary Operators.  'Tok' is the token for the operator.
5173Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5174                                            tok::TokenKind Op, ExprArg input) {
5175  Expr *Input = (Expr*)input.get();
5176  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5177
5178  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5179    // Find all of the overloaded operators visible from this
5180    // point. We perform both an operator-name lookup from the local
5181    // scope and an argument-dependent lookup based on the types of
5182    // the arguments.
5183    FunctionSet Functions;
5184    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5185    if (OverOp != OO_None) {
5186      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5187                                   Functions);
5188      DeclarationName OpName
5189        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5190      ArgumentDependentLookup(OpName, &Input, 1, Functions);
5191    }
5192
5193    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5194  }
5195
5196  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5197}
5198
5199/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5200Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5201                                            SourceLocation LabLoc,
5202                                            IdentifierInfo *LabelII) {
5203  // Look up the record for this label identifier.
5204  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
5205
5206  // If we haven't seen this label yet, create a forward reference. It
5207  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
5208  if (LabelDecl == 0)
5209    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
5210
5211  // Create the AST node.  The address of a label always has type 'void*'.
5212  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5213                                       Context.getPointerType(Context.VoidTy)));
5214}
5215
5216Sema::OwningExprResult
5217Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5218                    SourceLocation RPLoc) { // "({..})"
5219  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
5220  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5221  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5222
5223  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5224  if (isFileScope)
5225    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
5226
5227  // FIXME: there are a variety of strange constraints to enforce here, for
5228  // example, it is not possible to goto into a stmt expression apparently.
5229  // More semantic analysis is needed.
5230
5231  // If there are sub stmts in the compound stmt, take the type of the last one
5232  // as the type of the stmtexpr.
5233  QualType Ty = Context.VoidTy;
5234
5235  if (!Compound->body_empty()) {
5236    Stmt *LastStmt = Compound->body_back();
5237    // If LastStmt is a label, skip down through into the body.
5238    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5239      LastStmt = Label->getSubStmt();
5240
5241    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
5242      Ty = LastExpr->getType();
5243  }
5244
5245  // FIXME: Check that expression type is complete/non-abstract; statement
5246  // expressions are not lvalues.
5247
5248  substmt.release();
5249  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
5250}
5251
5252Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5253                                                  SourceLocation BuiltinLoc,
5254                                                  SourceLocation TypeLoc,
5255                                                  TypeTy *argty,
5256                                                  OffsetOfComponent *CompPtr,
5257                                                  unsigned NumComponents,
5258                                                  SourceLocation RPLoc) {
5259  // FIXME: This function leaks all expressions in the offset components on
5260  // error.
5261  // FIXME: Preserve type source info.
5262  QualType ArgTy = GetTypeFromParser(argty);
5263  assert(!ArgTy.isNull() && "Missing type argument!");
5264
5265  bool Dependent = ArgTy->isDependentType();
5266
5267  // We must have at least one component that refers to the type, and the first
5268  // one is known to be a field designator.  Verify that the ArgTy represents
5269  // a struct/union/class.
5270  if (!Dependent && !ArgTy->isRecordType())
5271    return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
5272
5273  // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5274  // with an incomplete type would be illegal.
5275
5276  // Otherwise, create a null pointer as the base, and iteratively process
5277  // the offsetof designators.
5278  QualType ArgTyPtr = Context.getPointerType(ArgTy);
5279  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
5280  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
5281                                    ArgTy, SourceLocation());
5282
5283  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5284  // GCC extension, diagnose them.
5285  // FIXME: This diagnostic isn't actually visible because the location is in
5286  // a system header!
5287  if (NumComponents != 1)
5288    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5289      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
5290
5291  if (!Dependent) {
5292    bool DidWarnAboutNonPOD = false;
5293
5294    // FIXME: Dependent case loses a lot of information here. And probably
5295    // leaks like a sieve.
5296    for (unsigned i = 0; i != NumComponents; ++i) {
5297      const OffsetOfComponent &OC = CompPtr[i];
5298      if (OC.isBrackets) {
5299        // Offset of an array sub-field.  TODO: Should we allow vector elements?
5300        const ArrayType *AT = Context.getAsArrayType(Res->getType());
5301        if (!AT) {
5302          Res->Destroy(Context);
5303          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5304            << Res->getType());
5305        }
5306
5307        // FIXME: C++: Verify that operator[] isn't overloaded.
5308
5309        // Promote the array so it looks more like a normal array subscript
5310        // expression.
5311        DefaultFunctionArrayConversion(Res);
5312
5313        // C99 6.5.2.1p1
5314        Expr *Idx = static_cast<Expr*>(OC.U.E);
5315        // FIXME: Leaks Res
5316        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
5317          return ExprError(Diag(Idx->getLocStart(),
5318                                diag::err_typecheck_subscript_not_integer)
5319            << Idx->getSourceRange());
5320
5321        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5322                                               OC.LocEnd);
5323        continue;
5324      }
5325
5326      const RecordType *RC = Res->getType()->getAs<RecordType>();
5327      if (!RC) {
5328        Res->Destroy(Context);
5329        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5330          << Res->getType());
5331      }
5332
5333      // Get the decl corresponding to this.
5334      RecordDecl *RD = RC->getDecl();
5335      if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5336        if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
5337          ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5338            << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5339            << Res->getType());
5340          DidWarnAboutNonPOD = true;
5341        }
5342      }
5343
5344      FieldDecl *MemberDecl
5345        = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5346                                                          LookupMemberName)
5347                                        .getAsDecl());
5348      // FIXME: Leaks Res
5349      if (!MemberDecl)
5350        return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5351         << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
5352
5353      // FIXME: C++: Verify that MemberDecl isn't a static field.
5354      // FIXME: Verify that MemberDecl isn't a bitfield.
5355      if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
5356        Res = BuildAnonymousStructUnionMemberReference(
5357            SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
5358      } else {
5359        // MemberDecl->getType() doesn't get the right qualifiers, but it
5360        // doesn't matter here.
5361        Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5362                MemberDecl->getType().getNonReferenceType());
5363      }
5364    }
5365  }
5366
5367  return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5368                                           Context.getSizeType(), BuiltinLoc));
5369}
5370
5371
5372Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5373                                                      TypeTy *arg1,TypeTy *arg2,
5374                                                      SourceLocation RPLoc) {
5375  // FIXME: Preserve type source info.
5376  QualType argT1 = GetTypeFromParser(arg1);
5377  QualType argT2 = GetTypeFromParser(arg2);
5378
5379  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
5380
5381  if (getLangOptions().CPlusPlus) {
5382    Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5383      << SourceRange(BuiltinLoc, RPLoc);
5384    return ExprError();
5385  }
5386
5387  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5388                                                 argT1, argT2, RPLoc));
5389}
5390
5391Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5392                                             ExprArg cond,
5393                                             ExprArg expr1, ExprArg expr2,
5394                                             SourceLocation RPLoc) {
5395  Expr *CondExpr = static_cast<Expr*>(cond.get());
5396  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5397  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
5398
5399  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5400
5401  QualType resType;
5402  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
5403    resType = Context.DependentTy;
5404  } else {
5405    // The conditional expression is required to be a constant expression.
5406    llvm::APSInt condEval(32);
5407    SourceLocation ExpLoc;
5408    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
5409      return ExprError(Diag(ExpLoc,
5410                       diag::err_typecheck_choose_expr_requires_constant)
5411        << CondExpr->getSourceRange());
5412
5413    // If the condition is > zero, then the AST type is the same as the LSHExpr.
5414    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5415  }
5416
5417  cond.release(); expr1.release(); expr2.release();
5418  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5419                                        resType, RPLoc));
5420}
5421
5422//===----------------------------------------------------------------------===//
5423// Clang Extensions.
5424//===----------------------------------------------------------------------===//
5425
5426/// ActOnBlockStart - This callback is invoked when a block literal is started.
5427void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
5428  // Analyze block parameters.
5429  BlockSemaInfo *BSI = new BlockSemaInfo();
5430
5431  // Add BSI to CurBlock.
5432  BSI->PrevBlockInfo = CurBlock;
5433  CurBlock = BSI;
5434
5435  BSI->ReturnType = QualType();
5436  BSI->TheScope = BlockScope;
5437  BSI->hasBlockDeclRefExprs = false;
5438  BSI->hasPrototype = false;
5439  BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5440  CurFunctionNeedsScopeChecking = false;
5441
5442  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
5443  PushDeclContext(BlockScope, BSI->TheDecl);
5444}
5445
5446void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
5447  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
5448
5449  if (ParamInfo.getNumTypeObjects() == 0
5450      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5451    ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5452    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5453
5454    if (T->isArrayType()) {
5455      Diag(ParamInfo.getSourceRange().getBegin(),
5456           diag::err_block_returns_array);
5457      return;
5458    }
5459
5460    // The parameter list is optional, if there was none, assume ().
5461    if (!T->isFunctionType())
5462      T = Context.getFunctionType(T, NULL, 0, 0, 0);
5463
5464    CurBlock->hasPrototype = true;
5465    CurBlock->isVariadic = false;
5466    // Check for a valid sentinel attribute on this block.
5467    if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5468      Diag(ParamInfo.getAttributes()->getLoc(),
5469           diag::warn_attribute_sentinel_not_variadic) << 1;
5470      // FIXME: remove the attribute.
5471    }
5472    QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5473
5474    // Do not allow returning a objc interface by-value.
5475    if (RetTy->isObjCInterfaceType()) {
5476      Diag(ParamInfo.getSourceRange().getBegin(),
5477           diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5478      return;
5479    }
5480    return;
5481  }
5482
5483  // Analyze arguments to block.
5484  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5485         "Not a function declarator!");
5486  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
5487
5488  CurBlock->hasPrototype = FTI.hasPrototype;
5489  CurBlock->isVariadic = true;
5490
5491  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5492  // no arguments, not a function that takes a single void argument.
5493  if (FTI.hasPrototype &&
5494      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5495     (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5496        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
5497    // empty arg list, don't push any params.
5498    CurBlock->isVariadic = false;
5499  } else if (FTI.hasPrototype) {
5500    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
5501      CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
5502    CurBlock->isVariadic = FTI.isVariadic;
5503  }
5504  CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
5505                               CurBlock->Params.size());
5506  CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
5507  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5508  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5509       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5510    // If this has an identifier, add it to the scope stack.
5511    if ((*AI)->getIdentifier())
5512      PushOnScopeChains(*AI, CurBlock->TheScope);
5513
5514  // Check for a valid sentinel attribute on this block.
5515  if (!CurBlock->isVariadic &&
5516      CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5517    Diag(ParamInfo.getAttributes()->getLoc(),
5518         diag::warn_attribute_sentinel_not_variadic) << 1;
5519    // FIXME: remove the attribute.
5520  }
5521
5522  // Analyze the return type.
5523  QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5524  QualType RetTy = T->getAsFunctionType()->getResultType();
5525
5526  // Do not allow returning a objc interface by-value.
5527  if (RetTy->isObjCInterfaceType()) {
5528    Diag(ParamInfo.getSourceRange().getBegin(),
5529         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5530  } else if (!RetTy->isDependentType())
5531    CurBlock->ReturnType = RetTy;
5532}
5533
5534/// ActOnBlockError - If there is an error parsing a block, this callback
5535/// is invoked to pop the information about the block from the action impl.
5536void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5537  // Ensure that CurBlock is deleted.
5538  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
5539
5540  CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5541
5542  // Pop off CurBlock, handle nested blocks.
5543  PopDeclContext();
5544  CurBlock = CurBlock->PrevBlockInfo;
5545  // FIXME: Delete the ParmVarDecl objects as well???
5546}
5547
5548/// ActOnBlockStmtExpr - This is called when the body of a block statement
5549/// literal was successfully completed.  ^(int x){...}
5550Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5551                                                StmtArg body, Scope *CurScope) {
5552  // If blocks are disabled, emit an error.
5553  if (!LangOpts.Blocks)
5554    Diag(CaretLoc, diag::err_blocks_disable);
5555
5556  // Ensure that CurBlock is deleted.
5557  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
5558
5559  PopDeclContext();
5560
5561  // Pop off CurBlock, handle nested blocks.
5562  CurBlock = CurBlock->PrevBlockInfo;
5563
5564  QualType RetTy = Context.VoidTy;
5565  if (!BSI->ReturnType.isNull())
5566    RetTy = BSI->ReturnType;
5567
5568  llvm::SmallVector<QualType, 8> ArgTypes;
5569  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5570    ArgTypes.push_back(BSI->Params[i]->getType());
5571
5572  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
5573  QualType BlockTy;
5574  if (!BSI->hasPrototype)
5575    BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5576                                      NoReturn);
5577  else
5578    BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
5579                                      BSI->isVariadic, 0, false, false, 0, 0,
5580                                      NoReturn);
5581
5582  // FIXME: Check that return/parameter types are complete/non-abstract
5583  DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
5584  BlockTy = Context.getBlockPointerType(BlockTy);
5585
5586  // If needed, diagnose invalid gotos and switches in the block.
5587  if (CurFunctionNeedsScopeChecking)
5588    DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5589  CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5590
5591  BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
5592  CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
5593  return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5594                                       BSI->hasBlockDeclRefExprs));
5595}
5596
5597Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5598                                        ExprArg expr, TypeTy *type,
5599                                        SourceLocation RPLoc) {
5600  QualType T = GetTypeFromParser(type);
5601  Expr *E = static_cast<Expr*>(expr.get());
5602  Expr *OrigExpr = E;
5603
5604  InitBuiltinVaListType();
5605
5606  // Get the va_list type
5607  QualType VaListType = Context.getBuiltinVaListType();
5608  if (VaListType->isArrayType()) {
5609    // Deal with implicit array decay; for example, on x86-64,
5610    // va_list is an array, but it's supposed to decay to
5611    // a pointer for va_arg.
5612    VaListType = Context.getArrayDecayedType(VaListType);
5613    // Make sure the input expression also decays appropriately.
5614    UsualUnaryConversions(E);
5615  } else {
5616    // Otherwise, the va_list argument must be an l-value because
5617    // it is modified by va_arg.
5618    if (!E->isTypeDependent() &&
5619        CheckForModifiableLvalue(E, BuiltinLoc, *this))
5620      return ExprError();
5621  }
5622
5623  if (!E->isTypeDependent() &&
5624      !Context.hasSameType(VaListType, E->getType())) {
5625    return ExprError(Diag(E->getLocStart(),
5626                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
5627      << OrigExpr->getType() << E->getSourceRange());
5628  }
5629
5630  // FIXME: Check that type is complete/non-abstract
5631  // FIXME: Warn if a non-POD type is passed in.
5632
5633  expr.release();
5634  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5635                                       RPLoc));
5636}
5637
5638Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
5639  // The type of __null will be int or long, depending on the size of
5640  // pointers on the target.
5641  QualType Ty;
5642  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5643    Ty = Context.IntTy;
5644  else
5645    Ty = Context.LongTy;
5646
5647  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
5648}
5649
5650bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5651                                    SourceLocation Loc,
5652                                    QualType DstType, QualType SrcType,
5653                                    Expr *SrcExpr, const char *Flavor) {
5654  // Decode the result (notice that AST's are still created for extensions).
5655  bool isInvalid = false;
5656  unsigned DiagKind;
5657  switch (ConvTy) {
5658  default: assert(0 && "Unknown conversion type");
5659  case Compatible: return false;
5660  case PointerToInt:
5661    DiagKind = diag::ext_typecheck_convert_pointer_int;
5662    break;
5663  case IntToPointer:
5664    DiagKind = diag::ext_typecheck_convert_int_pointer;
5665    break;
5666  case IncompatiblePointer:
5667    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5668    break;
5669  case IncompatiblePointerSign:
5670    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5671    break;
5672  case FunctionVoidPointer:
5673    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5674    break;
5675  case CompatiblePointerDiscardsQualifiers:
5676    // If the qualifiers lost were because we were applying the
5677    // (deprecated) C++ conversion from a string literal to a char*
5678    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
5679    // Ideally, this check would be performed in
5680    // CheckPointerTypesForAssignment. However, that would require a
5681    // bit of refactoring (so that the second argument is an
5682    // expression, rather than a type), which should be done as part
5683    // of a larger effort to fix CheckPointerTypesForAssignment for
5684    // C++ semantics.
5685    if (getLangOptions().CPlusPlus &&
5686        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5687      return false;
5688    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5689    break;
5690  case IntToBlockPointer:
5691    DiagKind = diag::err_int_to_block_pointer;
5692    break;
5693  case IncompatibleBlockPointer:
5694    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
5695    break;
5696  case IncompatibleObjCQualifiedId:
5697    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
5698    // it can give a more specific diagnostic.
5699    DiagKind = diag::warn_incompatible_qualified_id;
5700    break;
5701  case IncompatibleVectors:
5702    DiagKind = diag::warn_incompatible_vectors;
5703    break;
5704  case Incompatible:
5705    DiagKind = diag::err_typecheck_convert_incompatible;
5706    isInvalid = true;
5707    break;
5708  }
5709
5710  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5711    << SrcExpr->getSourceRange();
5712  return isInvalid;
5713}
5714
5715bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
5716  llvm::APSInt ICEResult;
5717  if (E->isIntegerConstantExpr(ICEResult, Context)) {
5718    if (Result)
5719      *Result = ICEResult;
5720    return false;
5721  }
5722
5723  Expr::EvalResult EvalResult;
5724
5725  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
5726      EvalResult.HasSideEffects) {
5727    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5728
5729    if (EvalResult.Diag) {
5730      // We only show the note if it's not the usual "invalid subexpression"
5731      // or if it's actually in a subexpression.
5732      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5733          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5734        Diag(EvalResult.DiagLoc, EvalResult.Diag);
5735    }
5736
5737    return true;
5738  }
5739
5740  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5741    E->getSourceRange();
5742
5743  if (EvalResult.Diag &&
5744      Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5745    Diag(EvalResult.DiagLoc, EvalResult.Diag);
5746
5747  if (Result)
5748    *Result = EvalResult.Val.getInt();
5749  return false;
5750}
5751
5752Sema::ExpressionEvaluationContext
5753Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5754  // Introduce a new set of potentially referenced declarations to the stack.
5755  if (NewContext == PotentiallyPotentiallyEvaluated)
5756    PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5757
5758  std::swap(ExprEvalContext, NewContext);
5759  return NewContext;
5760}
5761
5762void
5763Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5764                                     ExpressionEvaluationContext NewContext) {
5765  ExprEvalContext = NewContext;
5766
5767  if (OldContext == PotentiallyPotentiallyEvaluated) {
5768    // Mark any remaining declarations in the current position of the stack
5769    // as "referenced". If they were not meant to be referenced, semantic
5770    // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5771    PotentiallyReferencedDecls RemainingDecls;
5772    RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5773    PotentiallyReferencedDeclStack.pop_back();
5774
5775    for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5776                                           IEnd = RemainingDecls.end();
5777         I != IEnd; ++I)
5778      MarkDeclarationReferenced(I->first, I->second);
5779  }
5780}
5781
5782/// \brief Note that the given declaration was referenced in the source code.
5783///
5784/// This routine should be invoke whenever a given declaration is referenced
5785/// in the source code, and where that reference occurred. If this declaration
5786/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5787/// C99 6.9p3), then the declaration will be marked as used.
5788///
5789/// \param Loc the location where the declaration was referenced.
5790///
5791/// \param D the declaration that has been referenced by the source code.
5792void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5793  assert(D && "No declaration?");
5794
5795  if (D->isUsed())
5796    return;
5797
5798  // Mark a parameter declaration "used", regardless of whether we're in a
5799  // template or not.
5800  if (isa<ParmVarDecl>(D))
5801    D->setUsed(true);
5802
5803  // Do not mark anything as "used" within a dependent context; wait for
5804  // an instantiation.
5805  if (CurContext->isDependentContext())
5806    return;
5807
5808  switch (ExprEvalContext) {
5809    case Unevaluated:
5810      // We are in an expression that is not potentially evaluated; do nothing.
5811      return;
5812
5813    case PotentiallyEvaluated:
5814      // We are in a potentially-evaluated expression, so this declaration is
5815      // "used"; handle this below.
5816      break;
5817
5818    case PotentiallyPotentiallyEvaluated:
5819      // We are in an expression that may be potentially evaluated; queue this
5820      // declaration reference until we know whether the expression is
5821      // potentially evaluated.
5822      PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5823      return;
5824  }
5825
5826  // Note that this declaration has been used.
5827  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
5828    unsigned TypeQuals;
5829    if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5830        if (!Constructor->isUsed())
5831          DefineImplicitDefaultConstructor(Loc, Constructor);
5832    } else if (Constructor->isImplicit() &&
5833               Constructor->isCopyConstructor(Context, TypeQuals)) {
5834      if (!Constructor->isUsed())
5835        DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5836    }
5837  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5838    if (Destructor->isImplicit() && !Destructor->isUsed())
5839      DefineImplicitDestructor(Loc, Destructor);
5840
5841  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5842    if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5843        MethodDecl->getOverloadedOperator() == OO_Equal) {
5844      if (!MethodDecl->isUsed())
5845        DefineImplicitOverloadedAssign(Loc, MethodDecl);
5846    }
5847  }
5848  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
5849    // Implicit instantiation of function templates and member functions of
5850    // class templates.
5851    if (!Function->getBody()) {
5852      // FIXME: distinguish between implicit instantiations of function
5853      // templates and explicit specializations (the latter don't get
5854      // instantiated, naturally).
5855      if (Function->getInstantiatedFromMemberFunction() ||
5856          Function->getPrimaryTemplate())
5857        PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
5858    }
5859
5860
5861    // FIXME: keep track of references to static functions
5862    Function->setUsed(true);
5863    return;
5864  }
5865
5866  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
5867    // Implicit instantiation of static data members of class templates.
5868    // FIXME: distinguish between implicit instantiations (which we need to
5869    // actually instantiate) and explicit specializations.
5870    if (Var->isStaticDataMember() &&
5871        Var->getInstantiatedFromStaticDataMember())
5872      PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
5873
5874    // FIXME: keep track of references to static data?
5875
5876    D->setUsed(true);
5877    return;
5878}
5879}
5880
5881