SemaExpr.cpp revision cf13d4ad85bceb69c8dfb2fc9f2b4276ccd3a130
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                        const IdentifierInfo *CompName,
1807                        SourceLocation CompLoc) {
1808  const ExtVectorType *vecType = baseType->getAsExtVectorType();
1809
1810  // The vector accessor can't exceed the number of elements.
1811  const char *compStr = CompName->getName();
1812
1813  // This flag determines whether or not the component is one of the four
1814  // special names that indicate a subset of exactly half the elements are
1815  // to be selected.
1816  bool HalvingSwizzle = false;
1817
1818  // This flag determines whether or not CompName has an 's' char prefix,
1819  // indicating that it is a string of hex values to be used as vector indices.
1820  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
1821
1822  // Check that we've found one of the special components, or that the component
1823  // names must come from the same set.
1824  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1825      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1826    HalvingSwizzle = true;
1827  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1828    do
1829      compStr++;
1830    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1831  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1832    do
1833      compStr++;
1834    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1835  }
1836
1837  if (!HalvingSwizzle && *compStr) {
1838    // We didn't get to the end of the string. This means the component names
1839    // didn't come from the same set *or* we encountered an illegal name.
1840    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1841      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1842    return QualType();
1843  }
1844
1845  // Ensure no component accessor exceeds the width of the vector type it
1846  // operates on.
1847  if (!HalvingSwizzle) {
1848    compStr = CompName->getName();
1849
1850    if (HexSwizzle)
1851      compStr++;
1852
1853    while (*compStr) {
1854      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1855        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1856          << baseType << SourceRange(CompLoc);
1857        return QualType();
1858      }
1859    }
1860  }
1861
1862  // If this is a halving swizzle, verify that the base type has an even
1863  // number of elements.
1864  if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1865    Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1866      << baseType << SourceRange(CompLoc);
1867    return QualType();
1868  }
1869
1870  // The component accessor looks fine - now we need to compute the actual type.
1871  // The vector type is implied by the component accessor. For example,
1872  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1873  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1874  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1875  unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1876                                     : CompName->getLength();
1877  if (HexSwizzle)
1878    CompSize--;
1879
1880  if (CompSize == 1)
1881    return vecType->getElementType();
1882
1883  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1884  // Now look up the TypeDefDecl from the vector type. Without this,
1885  // diagostics look bad. We want extended vector types to appear built-in.
1886  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1887    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1888      return Context.getTypedefType(ExtVectorDecls[i]);
1889  }
1890  return VT; // should never get here (a typedef type should always be found).
1891}
1892
1893static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1894                                                IdentifierInfo *Member,
1895                                                const Selector &Sel,
1896                                                ASTContext &Context) {
1897
1898  if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
1899    return PD;
1900  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1901    return OMD;
1902
1903  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1904       E = PDecl->protocol_end(); I != E; ++I) {
1905    if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1906                                                     Context))
1907      return D;
1908  }
1909  return 0;
1910}
1911
1912static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
1913                                IdentifierInfo *Member,
1914                                const Selector &Sel,
1915                                ASTContext &Context) {
1916  // Check protocols on qualified interfaces.
1917  Decl *GDecl = 0;
1918  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1919       E = QIdTy->qual_end(); I != E; ++I) {
1920    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1921      GDecl = PD;
1922      break;
1923    }
1924    // Also must look for a getter name which uses property syntax.
1925    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1926      GDecl = OMD;
1927      break;
1928    }
1929  }
1930  if (!GDecl) {
1931    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1932         E = QIdTy->qual_end(); I != E; ++I) {
1933      // Search in the protocol-qualifier list of current protocol.
1934      GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
1935      if (GDecl)
1936        return GDecl;
1937    }
1938  }
1939  return GDecl;
1940}
1941
1942/// FindMethodInNestedImplementations - Look up a method in current and
1943/// all base class implementations.
1944///
1945ObjCMethodDecl *Sema::FindMethodInNestedImplementations(
1946                                              const ObjCInterfaceDecl *IFace,
1947                                              const Selector &Sel) {
1948  ObjCMethodDecl *Method = 0;
1949  if (ObjCImplementationDecl *ImpDecl = IFace->getImplementation())
1950    Method = ImpDecl->getInstanceMethod(Sel);
1951
1952  if (!Method && IFace->getSuperClass())
1953    return FindMethodInNestedImplementations(IFace->getSuperClass(), Sel);
1954  return Method;
1955}
1956
1957Action::OwningExprResult
1958Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1959                               tok::TokenKind OpKind, SourceLocation MemberLoc,
1960                               DeclarationName MemberName,
1961                               DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
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                                                         MemberName,
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                                                           MemberName,
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, MemberName, LookupMemberName, false);
2053
2054    if (SS && SS->isSet()) {
2055      QualType BaseTypeCanon
2056        = Context.getCanonicalType(BaseType).getUnqualifiedType();
2057      QualType MemberTypeCanon
2058        = Context.getCanonicalType(
2059            Context.getTypeDeclType(
2060                     dyn_cast<TypeDecl>(Result.getAsDecl()->getDeclContext())));
2061
2062      if (BaseTypeCanon != MemberTypeCanon &&
2063          !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2064        return ExprError(Diag(SS->getBeginLoc(),
2065                              diag::err_not_direct_base_or_virtual)
2066                         << MemberTypeCanon << BaseTypeCanon);
2067    }
2068
2069    if (!Result)
2070      return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
2071               << MemberName << BaseExpr->getSourceRange());
2072    if (Result.isAmbiguous()) {
2073      DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2074                              BaseExpr->getSourceRange());
2075      return ExprError();
2076    }
2077
2078    NamedDecl *MemberDecl = Result;
2079
2080    // If the decl being referenced had an error, return an error for this
2081    // sub-expr without emitting another error, in order to avoid cascading
2082    // error cases.
2083    if (MemberDecl->isInvalidDecl())
2084      return ExprError();
2085
2086    // Check the use of this field
2087    if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2088      return ExprError();
2089
2090    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2091      // We may have found a field within an anonymous union or struct
2092      // (C++ [class.union]).
2093      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2094        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2095                                                        BaseExpr, OpLoc);
2096
2097      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2098      QualType MemberType = FD->getType();
2099      if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2100        MemberType = Ref->getPointeeType();
2101      else {
2102        unsigned BaseAddrSpace = BaseType.getAddressSpace();
2103        unsigned combinedQualifiers =
2104          MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
2105        if (FD->isMutable())
2106          combinedQualifiers &= ~QualType::Const;
2107        MemberType = MemberType.getQualifiedType(combinedQualifiers);
2108        if (BaseAddrSpace != MemberType.getAddressSpace())
2109           MemberType = Context.getAddrSpaceQualType(MemberType, BaseAddrSpace);
2110      }
2111
2112      MarkDeclarationReferenced(MemberLoc, FD);
2113      if (PerformObjectMemberConversion(BaseExpr, FD))
2114        return ExprError();
2115      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
2116                                            MemberLoc, MemberType));
2117    }
2118
2119    if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2120      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2121      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2122                                            Var, MemberLoc,
2123                                         Var->getType().getNonReferenceType()));
2124    }
2125    if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2126      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2127      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2128                                            MemberFn, MemberLoc,
2129                                            MemberFn->getType()));
2130    }
2131    if (FunctionTemplateDecl *FunTmpl
2132          = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2133      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2134      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2135                                            FunTmpl, MemberLoc,
2136                                            Context.OverloadTy));
2137    }
2138    if (OverloadedFunctionDecl *Ovl
2139          = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
2140      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
2141                                            MemberLoc, Context.OverloadTy));
2142    if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2143      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2144      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
2145                                            Enum, MemberLoc, Enum->getType()));
2146    }
2147    if (isa<TypeDecl>(MemberDecl))
2148      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2149        << MemberName << int(OpKind == tok::arrow));
2150
2151    // We found a declaration kind that we didn't expect. This is a
2152    // generic error message that tells the user that she can't refer
2153    // to this member with '.' or '->'.
2154    return ExprError(Diag(MemberLoc,
2155                          diag::err_typecheck_member_reference_unknown)
2156      << MemberName << int(OpKind == tok::arrow));
2157  }
2158
2159  // Handle properties on ObjC 'Class' types.
2160  if (OpKind == tok::period && BaseType->isObjCClassType()) {
2161    // Also must look for a getter name which uses property syntax.
2162    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
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        << MemberName << 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      IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2216
2217      ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2218      ObjCInterfaceDecl *ClassDeclared;
2219      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
2220
2221      if (IV) {
2222        // If the decl being referenced had an error, return an error for this
2223        // sub-expr without emitting another error, in order to avoid cascading
2224        // error cases.
2225        if (IV->isInvalidDecl())
2226          return ExprError();
2227
2228        // Check whether we can reference this field.
2229        if (DiagnoseUseOfDecl(IV, MemberLoc))
2230          return ExprError();
2231        if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2232            IV->getAccessControl() != ObjCIvarDecl::Package) {
2233          ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2234          if (ObjCMethodDecl *MD = getCurMethodDecl())
2235            ClassOfMethodDecl =  MD->getClassInterface();
2236          else if (ObjCImpDecl && getCurFunctionDecl()) {
2237            // Case of a c-function declared inside an objc implementation.
2238            // FIXME: For a c-style function nested inside an objc implementation
2239            // class, there is no implementation context available, so we pass
2240            // down the context as argument to this routine. Ideally, this context
2241            // need be passed down in the AST node and somehow calculated from the
2242            // AST for a function decl.
2243            Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2244            if (ObjCImplementationDecl *IMPD =
2245                dyn_cast<ObjCImplementationDecl>(ImplDecl))
2246              ClassOfMethodDecl = IMPD->getClassInterface();
2247            else if (ObjCCategoryImplDecl* CatImplClass =
2248                        dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2249              ClassOfMethodDecl = CatImplClass->getClassInterface();
2250          }
2251
2252          if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2253            if (ClassDeclared != IDecl ||
2254                ClassOfMethodDecl != ClassDeclared)
2255              Diag(MemberLoc, diag::error_private_ivar_access)
2256                << IV->getDeclName();
2257          } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2258            // @protected
2259            Diag(MemberLoc, diag::error_protected_ivar_access)
2260              << IV->getDeclName();
2261        }
2262
2263        return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2264                                                   MemberLoc, BaseExpr,
2265                                                   OpKind == tok::arrow));
2266      }
2267      return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2268                         << IDecl->getDeclName() << MemberName
2269                         << BaseExpr->getSourceRange());
2270    }
2271  }
2272  // Handle properties on 'id' and qualified "id".
2273  if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2274                                BaseType->isObjCQualifiedIdType())) {
2275    const ObjCObjectPointerType *QIdTy = BaseType->getAsObjCObjectPointerType();
2276    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2277
2278    // Check protocols on qualified interfaces.
2279    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2280    if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2281      if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2282        // Check the use of this declaration
2283        if (DiagnoseUseOfDecl(PD, MemberLoc))
2284          return ExprError();
2285
2286        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2287                                                       MemberLoc, BaseExpr));
2288      }
2289      if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2290        // Check the use of this method.
2291        if (DiagnoseUseOfDecl(OMD, MemberLoc))
2292          return ExprError();
2293
2294        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2295                                                   OMD->getResultType(),
2296                                                   OMD, OpLoc, MemberLoc,
2297                                                   NULL, 0));
2298      }
2299    }
2300
2301    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2302                       << MemberName << BaseType);
2303  }
2304  // Handle Objective-C property access, which is "Obj.property" where Obj is a
2305  // pointer to a (potentially qualified) interface type.
2306  const ObjCObjectPointerType *OPT;
2307  if (OpKind == tok::period &&
2308      (OPT = BaseType->getAsObjCInterfacePointerType())) {
2309    const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2310    ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2311    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2312
2313    // Search for a declared property first.
2314    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
2315      // Check whether we can reference this property.
2316      if (DiagnoseUseOfDecl(PD, MemberLoc))
2317        return ExprError();
2318      QualType ResTy = PD->getType();
2319      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2320      ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2321      if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2322        ResTy = Getter->getResultType();
2323      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
2324                                                     MemberLoc, BaseExpr));
2325    }
2326    // Check protocols on qualified interfaces.
2327    for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2328         E = OPT->qual_end(); I != E; ++I)
2329      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2330        // Check whether we can reference this property.
2331        if (DiagnoseUseOfDecl(PD, MemberLoc))
2332          return ExprError();
2333
2334        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2335                                                       MemberLoc, BaseExpr));
2336      }
2337    for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2338         E = OPT->qual_end(); I != E; ++I)
2339      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2340        // Check whether we can reference this property.
2341        if (DiagnoseUseOfDecl(PD, MemberLoc))
2342          return ExprError();
2343
2344        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2345                                                       MemberLoc, BaseExpr));
2346      }
2347    // If that failed, look for an "implicit" property by seeing if the nullary
2348    // selector is implemented.
2349
2350    // FIXME: The logic for looking up nullary and unary selectors should be
2351    // shared with the code in ActOnInstanceMessage.
2352
2353    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2354    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2355
2356    // If this reference is in an @implementation, check for 'private' methods.
2357    if (!Getter)
2358      Getter = FindMethodInNestedImplementations(IFace, Sel);
2359
2360    // Look through local category implementations associated with the class.
2361    if (!Getter)
2362      Getter = IFace->getCategoryInstanceMethod(Sel);
2363    if (Getter) {
2364      // Check if we can reference this property.
2365      if (DiagnoseUseOfDecl(Getter, MemberLoc))
2366        return ExprError();
2367    }
2368    // If we found a getter then this may be a valid dot-reference, we
2369    // will look for the matching setter, in case it is needed.
2370    Selector SetterSel =
2371      SelectorTable::constructSetterName(PP.getIdentifierTable(),
2372                                         PP.getSelectorTable(), Member);
2373    ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2374    if (!Setter) {
2375      // If this reference is in an @implementation, also check for 'private'
2376      // methods.
2377      Setter = FindMethodInNestedImplementations(IFace, SetterSel);
2378    }
2379    // Look through local category implementations associated with the class.
2380    if (!Setter)
2381      Setter = IFace->getCategoryInstanceMethod(SetterSel);
2382
2383    if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2384      return ExprError();
2385
2386    if (Getter || Setter) {
2387      QualType PType;
2388
2389      if (Getter)
2390        PType = Getter->getResultType();
2391      else
2392        // Get the expression type from Setter's incoming parameter.
2393        PType = (*(Setter->param_end() -1))->getType();
2394      // FIXME: we must check that the setter has property type.
2395      return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
2396                                      Setter, MemberLoc, BaseExpr));
2397    }
2398    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2399      << MemberName << BaseType);
2400  }
2401
2402  // Handle the following exceptional case (*Obj).isa.
2403  if (OpKind == tok::period &&
2404      BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2405      MemberName.getAsIdentifierInfo()->isStr("isa"))
2406    return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2407                                           Context.getObjCIdType()));
2408
2409  // Handle 'field access' to vectors, such as 'V.xx'.
2410  if (BaseType->isExtVectorType()) {
2411    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2412    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2413    if (ret.isNull())
2414      return ExprError();
2415    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
2416                                                    MemberLoc));
2417  }
2418
2419  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2420    << BaseType << BaseExpr->getSourceRange();
2421
2422  // If the user is trying to apply -> or . to a function or function
2423  // pointer, it's probably because they forgot parentheses to call
2424  // the function. Suggest the addition of those parentheses.
2425  if (BaseType == Context.OverloadTy ||
2426      BaseType->isFunctionType() ||
2427      (BaseType->isPointerType() &&
2428       BaseType->getAs<PointerType>()->isFunctionType())) {
2429    SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2430    Diag(Loc, diag::note_member_reference_needs_call)
2431      << CodeModificationHint::CreateInsertion(Loc, "()");
2432  }
2433
2434  return ExprError();
2435}
2436
2437Action::OwningExprResult
2438Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2439                               tok::TokenKind OpKind, SourceLocation MemberLoc,
2440                               IdentifierInfo &Member,
2441                               DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2442  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2443                                  DeclarationName(&Member), ObjCImpDecl, SS);
2444}
2445
2446Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2447                                                    FunctionDecl *FD,
2448                                                    ParmVarDecl *Param) {
2449  if (Param->hasUnparsedDefaultArg()) {
2450    Diag (CallLoc,
2451          diag::err_use_of_default_argument_to_function_declared_later) <<
2452      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2453    Diag(UnparsedDefaultArgLocs[Param],
2454          diag::note_default_argument_declared_here);
2455  } else {
2456    if (Param->hasUninstantiatedDefaultArg()) {
2457      Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2458
2459      // Instantiate the expression.
2460      const TemplateArgumentList &ArgList = getTemplateInstantiationArgs(FD);
2461
2462      // FIXME: We should really make a new InstantiatingTemplate ctor
2463      // that has a better message - right now we're just piggy-backing
2464      // off the "default template argument" error message.
2465      InstantiatingTemplate Inst(*this, CallLoc, FD->getPrimaryTemplate(),
2466                                 ArgList.getFlatArgumentList(),
2467                                 ArgList.flat_size());
2468
2469      OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
2470      if (Result.isInvalid())
2471        return ExprError();
2472
2473      if (SetParamDefaultArgument(Param, move(Result),
2474                                  /*FIXME:EqualLoc*/
2475                                  UninstExpr->getSourceRange().getBegin()))
2476        return ExprError();
2477    }
2478
2479    Expr *DefaultExpr = Param->getDefaultArg();
2480
2481    // If the default expression creates temporaries, we need to
2482    // push them to the current stack of expression temporaries so they'll
2483    // be properly destroyed.
2484    if (CXXExprWithTemporaries *E
2485          = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2486      assert(!E->shouldDestroyTemporaries() &&
2487             "Can't destroy temporaries in a default argument expr!");
2488      for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2489        ExprTemporaries.push_back(E->getTemporary(I));
2490    }
2491  }
2492
2493  // We already type-checked the argument, so we know it works.
2494  return Owned(CXXDefaultArgExpr::Create(Context, Param));
2495}
2496
2497/// ConvertArgumentsForCall - Converts the arguments specified in
2498/// Args/NumArgs to the parameter types of the function FDecl with
2499/// function prototype Proto. Call is the call expression itself, and
2500/// Fn is the function expression. For a C++ member function, this
2501/// routine does not attempt to convert the object argument. Returns
2502/// true if the call is ill-formed.
2503bool
2504Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2505                              FunctionDecl *FDecl,
2506                              const FunctionProtoType *Proto,
2507                              Expr **Args, unsigned NumArgs,
2508                              SourceLocation RParenLoc) {
2509  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2510  // assignment, to the types of the corresponding parameter, ...
2511  unsigned NumArgsInProto = Proto->getNumArgs();
2512  unsigned NumArgsToCheck = NumArgs;
2513  bool Invalid = false;
2514
2515  // If too few arguments are available (and we don't have default
2516  // arguments for the remaining parameters), don't make the call.
2517  if (NumArgs < NumArgsInProto) {
2518    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2519      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2520        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2521    // Use default arguments for missing arguments
2522    NumArgsToCheck = NumArgsInProto;
2523    Call->setNumArgs(Context, NumArgsInProto);
2524  }
2525
2526  // If too many are passed and not variadic, error on the extras and drop
2527  // them.
2528  if (NumArgs > NumArgsInProto) {
2529    if (!Proto->isVariadic()) {
2530      Diag(Args[NumArgsInProto]->getLocStart(),
2531           diag::err_typecheck_call_too_many_args)
2532        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2533        << SourceRange(Args[NumArgsInProto]->getLocStart(),
2534                       Args[NumArgs-1]->getLocEnd());
2535      // This deletes the extra arguments.
2536      Call->setNumArgs(Context, NumArgsInProto);
2537      Invalid = true;
2538    }
2539    NumArgsToCheck = NumArgsInProto;
2540  }
2541
2542  // Continue to check argument types (even if we have too few/many args).
2543  for (unsigned i = 0; i != NumArgsToCheck; i++) {
2544    QualType ProtoArgType = Proto->getArgType(i);
2545
2546    Expr *Arg;
2547    if (i < NumArgs) {
2548      Arg = Args[i];
2549
2550      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2551                              ProtoArgType,
2552                              diag::err_call_incomplete_argument,
2553                              Arg->getSourceRange()))
2554        return true;
2555
2556      // Pass the argument.
2557      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2558        return true;
2559    } else {
2560      ParmVarDecl *Param = FDecl->getParamDecl(i);
2561
2562      OwningExprResult ArgExpr =
2563        BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2564                               FDecl, Param);
2565      if (ArgExpr.isInvalid())
2566        return true;
2567
2568      Arg = ArgExpr.takeAs<Expr>();
2569    }
2570
2571    Call->setArg(i, Arg);
2572  }
2573
2574  // If this is a variadic call, handle args passed through "...".
2575  if (Proto->isVariadic()) {
2576    VariadicCallType CallType = VariadicFunction;
2577    if (Fn->getType()->isBlockPointerType())
2578      CallType = VariadicBlock; // Block
2579    else if (isa<MemberExpr>(Fn))
2580      CallType = VariadicMethod;
2581
2582    // Promote the arguments (C99 6.5.2.2p7).
2583    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2584      Expr *Arg = Args[i];
2585      Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
2586      Call->setArg(i, Arg);
2587    }
2588  }
2589
2590  return Invalid;
2591}
2592
2593/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2594/// This provides the location of the left/right parens and a list of comma
2595/// locations.
2596Action::OwningExprResult
2597Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2598                    MultiExprArg args,
2599                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2600  unsigned NumArgs = args.size();
2601
2602  // Since this might be a postfix expression, get rid of ParenListExprs.
2603  fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2604
2605  Expr *Fn = fn.takeAs<Expr>();
2606  Expr **Args = reinterpret_cast<Expr**>(args.release());
2607  assert(Fn && "no function call expression");
2608  FunctionDecl *FDecl = NULL;
2609  NamedDecl *NDecl = NULL;
2610  DeclarationName UnqualifiedName;
2611
2612  if (getLangOptions().CPlusPlus) {
2613    // Determine whether this is a dependent call inside a C++ template,
2614    // in which case we won't do any semantic analysis now.
2615    // FIXME: Will need to cache the results of name lookup (including ADL) in
2616    // Fn.
2617    bool Dependent = false;
2618    if (Fn->isTypeDependent())
2619      Dependent = true;
2620    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2621      Dependent = true;
2622
2623    if (Dependent)
2624      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2625                                          Context.DependentTy, RParenLoc));
2626
2627    // Determine whether this is a call to an object (C++ [over.call.object]).
2628    if (Fn->getType()->isRecordType())
2629      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2630                                                CommaLocs, RParenLoc));
2631
2632    // Determine whether this is a call to a member function.
2633    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2634      NamedDecl *MemDecl = MemExpr->getMemberDecl();
2635      if (isa<OverloadedFunctionDecl>(MemDecl) ||
2636          isa<CXXMethodDecl>(MemDecl) ||
2637          (isa<FunctionTemplateDecl>(MemDecl) &&
2638           isa<CXXMethodDecl>(
2639                cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
2640        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2641                                               CommaLocs, RParenLoc));
2642    }
2643  }
2644
2645  // If we're directly calling a function, get the appropriate declaration.
2646  // Also, in C++, keep track of whether we should perform argument-dependent
2647  // lookup and whether there were any explicitly-specified template arguments.
2648  Expr *FnExpr = Fn;
2649  bool ADL = true;
2650  bool HasExplicitTemplateArgs = 0;
2651  const TemplateArgument *ExplicitTemplateArgs = 0;
2652  unsigned NumExplicitTemplateArgs = 0;
2653  while (true) {
2654    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2655      FnExpr = IcExpr->getSubExpr();
2656    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2657      // Parentheses around a function disable ADL
2658      // (C++0x [basic.lookup.argdep]p1).
2659      ADL = false;
2660      FnExpr = PExpr->getSubExpr();
2661    } else if (isa<UnaryOperator>(FnExpr) &&
2662               cast<UnaryOperator>(FnExpr)->getOpcode()
2663                 == UnaryOperator::AddrOf) {
2664      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2665    } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2666      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2667      ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2668      NDecl = dyn_cast<NamedDecl>(DRExpr->getDecl());
2669      break;
2670    } else if (UnresolvedFunctionNameExpr *DepName
2671                 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2672      UnqualifiedName = DepName->getName();
2673      break;
2674    } else if (TemplateIdRefExpr *TemplateIdRef
2675                 = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2676      NDecl = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2677      if (!NDecl)
2678        NDecl = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2679      HasExplicitTemplateArgs = true;
2680      ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2681      NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2682
2683      // C++ [temp.arg.explicit]p6:
2684      //   [Note: For simple function names, argument dependent lookup (3.4.2)
2685      //   applies even when the function name is not visible within the
2686      //   scope of the call. This is because the call still has the syntactic
2687      //   form of a function call (3.4.1). But when a function template with
2688      //   explicit template arguments is used, the call does not have the
2689      //   correct syntactic form unless there is a function template with
2690      //   that name visible at the point of the call. If no such name is
2691      //   visible, the call is not syntactically well-formed and
2692      //   argument-dependent lookup does not apply. If some such name is
2693      //   visible, argument dependent lookup applies and additional function
2694      //   templates may be found in other namespaces.
2695      //
2696      // The summary of this paragraph is that, if we get to this point and the
2697      // template-id was not a qualified name, then argument-dependent lookup
2698      // is still possible.
2699      if (TemplateIdRef->getQualifier())
2700        ADL = false;
2701      break;
2702    } else {
2703      // Any kind of name that does not refer to a declaration (or
2704      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2705      ADL = false;
2706      break;
2707    }
2708  }
2709
2710  OverloadedFunctionDecl *Ovl = 0;
2711  FunctionTemplateDecl *FunctionTemplate = 0;
2712  if (NDecl) {
2713    FDecl = dyn_cast<FunctionDecl>(NDecl);
2714    if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
2715      FDecl = FunctionTemplate->getTemplatedDecl();
2716    else
2717      FDecl = dyn_cast<FunctionDecl>(NDecl);
2718    Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
2719  }
2720
2721  if (Ovl || FunctionTemplate ||
2722      (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2723    // We don't perform ADL for implicit declarations of builtins.
2724    if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
2725      ADL = false;
2726
2727    // We don't perform ADL in C.
2728    if (!getLangOptions().CPlusPlus)
2729      ADL = false;
2730
2731    if (Ovl || FunctionTemplate || ADL) {
2732      FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2733                                      HasExplicitTemplateArgs,
2734                                      ExplicitTemplateArgs,
2735                                      NumExplicitTemplateArgs,
2736                                      LParenLoc, Args, NumArgs, CommaLocs,
2737                                      RParenLoc, ADL);
2738      if (!FDecl)
2739        return ExprError();
2740
2741      // Update Fn to refer to the actual function selected.
2742      Expr *NewFn = 0;
2743      if (QualifiedDeclRefExpr *QDRExpr
2744            = dyn_cast<QualifiedDeclRefExpr>(FnExpr))
2745        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2746                                                   QDRExpr->getLocation(),
2747                                                   false, false,
2748                                                 QDRExpr->getQualifierRange(),
2749                                                   QDRExpr->getQualifier());
2750      else
2751        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2752                                          Fn->getSourceRange().getBegin());
2753      Fn->Destroy(Context);
2754      Fn = NewFn;
2755    }
2756  }
2757
2758  // Promote the function operand.
2759  UsualUnaryConversions(Fn);
2760
2761  // Make the call expr early, before semantic checks.  This guarantees cleanup
2762  // of arguments and function on error.
2763  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2764                                                               Args, NumArgs,
2765                                                               Context.BoolTy,
2766                                                               RParenLoc));
2767
2768  const FunctionType *FuncT;
2769  if (!Fn->getType()->isBlockPointerType()) {
2770    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2771    // have type pointer to function".
2772    const PointerType *PT = Fn->getType()->getAs<PointerType>();
2773    if (PT == 0)
2774      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2775        << Fn->getType() << Fn->getSourceRange());
2776    FuncT = PT->getPointeeType()->getAsFunctionType();
2777  } else { // This is a block call.
2778    FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
2779                getAsFunctionType();
2780  }
2781  if (FuncT == 0)
2782    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2783      << Fn->getType() << Fn->getSourceRange());
2784
2785  // Check for a valid return type
2786  if (!FuncT->getResultType()->isVoidType() &&
2787      RequireCompleteType(Fn->getSourceRange().getBegin(),
2788                          FuncT->getResultType(),
2789                          diag::err_call_incomplete_return,
2790                          TheCall->getSourceRange()))
2791    return ExprError();
2792
2793  // We know the result type of the call, set it.
2794  TheCall->setType(FuncT->getResultType().getNonReferenceType());
2795
2796  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2797    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2798                                RParenLoc))
2799      return ExprError();
2800  } else {
2801    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2802
2803    if (FDecl) {
2804      // Check if we have too few/too many template arguments, based
2805      // on our knowledge of the function definition.
2806      const FunctionDecl *Def = 0;
2807      if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
2808        const FunctionProtoType *Proto =
2809            Def->getType()->getAsFunctionProtoType();
2810        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
2811          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
2812            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
2813        }
2814      }
2815    }
2816
2817    // Promote the arguments (C99 6.5.2.2p6).
2818    for (unsigned i = 0; i != NumArgs; i++) {
2819      Expr *Arg = Args[i];
2820      DefaultArgumentPromotion(Arg);
2821      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2822                              Arg->getType(),
2823                              diag::err_call_incomplete_argument,
2824                              Arg->getSourceRange()))
2825        return ExprError();
2826      TheCall->setArg(i, Arg);
2827    }
2828  }
2829
2830  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2831    if (!Method->isStatic())
2832      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2833        << Fn->getSourceRange());
2834
2835  // Check for sentinels
2836  if (NDecl)
2837    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
2838
2839  // Do special checking on direct calls to functions.
2840  if (FDecl) {
2841    if (CheckFunctionCall(FDecl, TheCall.get()))
2842      return ExprError();
2843
2844    if (unsigned BuiltinID = FDecl->getBuiltinID(Context))
2845      return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
2846  } else if (NDecl) {
2847    if (CheckBlockCall(NDecl, TheCall.get()))
2848      return ExprError();
2849  }
2850
2851  return MaybeBindToTemporary(TheCall.take());
2852}
2853
2854Action::OwningExprResult
2855Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2856                           SourceLocation RParenLoc, ExprArg InitExpr) {
2857  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
2858  //FIXME: Preserve type source info.
2859  QualType literalType = GetTypeFromParser(Ty);
2860  // FIXME: put back this assert when initializers are worked out.
2861  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
2862  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
2863
2864  if (literalType->isArrayType()) {
2865    if (literalType->isVariableArrayType())
2866      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2867        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
2868  } else if (!literalType->isDependentType() &&
2869             RequireCompleteType(LParenLoc, literalType,
2870                                 diag::err_typecheck_decl_incomplete_type,
2871                SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
2872    return ExprError();
2873
2874  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
2875                            DeclarationName(), /*FIXME:DirectInit=*/false))
2876    return ExprError();
2877
2878  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
2879  if (isFileScope) { // 6.5.2.5p3
2880    if (CheckForConstantInitializer(literalExpr, literalType))
2881      return ExprError();
2882  }
2883  InitExpr.release();
2884  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2885                                                 literalExpr, isFileScope));
2886}
2887
2888Action::OwningExprResult
2889Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2890                    SourceLocation RBraceLoc) {
2891  unsigned NumInit = initlist.size();
2892  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
2893
2894  // Semantic analysis for initializers is done by ActOnDeclarator() and
2895  // CheckInitializer() - it requires knowledge of the object being intialized.
2896
2897  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
2898                                               RBraceLoc);
2899  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
2900  return Owned(E);
2901}
2902
2903/// CheckCastTypes - Check type constraints for casting between types.
2904bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
2905                          CastExpr::CastKind& Kind,
2906                          CXXMethodDecl *& ConversionDecl,
2907                          bool FunctionalStyle) {
2908  if (getLangOptions().CPlusPlus)
2909    return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
2910                              ConversionDecl);
2911
2912  DefaultFunctionArrayConversion(castExpr);
2913
2914  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2915  // type needs to be scalar.
2916  if (castType->isVoidType()) {
2917    // Cast to void allows any expr type.
2918  } else if (!castType->isScalarType() && !castType->isVectorType()) {
2919    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2920        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2921        (castType->isStructureType() || castType->isUnionType())) {
2922      // GCC struct/union extension: allow cast to self.
2923      // FIXME: Check that the cast destination type is complete.
2924      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2925        << castType << castExpr->getSourceRange();
2926      Kind = CastExpr::CK_NoOp;
2927    } else if (castType->isUnionType()) {
2928      // GCC cast to union extension
2929      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
2930      RecordDecl::field_iterator Field, FieldEnd;
2931      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2932           Field != FieldEnd; ++Field) {
2933        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2934            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2935          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2936            << castExpr->getSourceRange();
2937          break;
2938        }
2939      }
2940      if (Field == FieldEnd)
2941        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2942          << castExpr->getType() << castExpr->getSourceRange();
2943      Kind = CastExpr::CK_ToUnion;
2944    } else {
2945      // Reject any other conversions to non-scalar types.
2946      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
2947        << castType << castExpr->getSourceRange();
2948    }
2949  } else if (!castExpr->getType()->isScalarType() &&
2950             !castExpr->getType()->isVectorType()) {
2951    return Diag(castExpr->getLocStart(),
2952                diag::err_typecheck_expect_scalar_operand)
2953      << castExpr->getType() << castExpr->getSourceRange();
2954  } else if (castType->isExtVectorType()) {
2955    if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
2956      return true;
2957  } else if (castType->isVectorType()) {
2958    if (CheckVectorCast(TyR, castType, castExpr->getType()))
2959      return true;
2960  } else if (castExpr->getType()->isVectorType()) {
2961    if (CheckVectorCast(TyR, castExpr->getType(), castType))
2962      return true;
2963  } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
2964    return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
2965  } else if (!castType->isArithmeticType()) {
2966    QualType castExprType = castExpr->getType();
2967    if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
2968      return Diag(castExpr->getLocStart(),
2969                  diag::err_cast_pointer_from_non_pointer_int)
2970        << castExprType << castExpr->getSourceRange();
2971  } else if (!castExpr->getType()->isArithmeticType()) {
2972    if (!castType->isIntegralType() && castType->isArithmeticType())
2973      return Diag(castExpr->getLocStart(),
2974                  diag::err_cast_pointer_to_non_pointer_int)
2975        << castType << castExpr->getSourceRange();
2976  }
2977  if (isa<ObjCSelectorExpr>(castExpr))
2978    return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
2979  return false;
2980}
2981
2982bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
2983  assert(VectorTy->isVectorType() && "Not a vector type!");
2984
2985  if (Ty->isVectorType() || Ty->isIntegerType()) {
2986    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
2987      return Diag(R.getBegin(),
2988                  Ty->isVectorType() ?
2989                  diag::err_invalid_conversion_between_vectors :
2990                  diag::err_invalid_conversion_between_vector_and_integer)
2991        << VectorTy << Ty << R;
2992  } else
2993    return Diag(R.getBegin(),
2994                diag::err_invalid_conversion_between_vector_and_scalar)
2995      << VectorTy << Ty << R;
2996
2997  return false;
2998}
2999
3000bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3001  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3002
3003  // If SrcTy is a VectorType, the total size must match to explicitly cast to
3004  // an ExtVectorType.
3005  if (SrcTy->isVectorType()) {
3006    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3007      return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3008        << DestTy << SrcTy << R;
3009    return false;
3010  }
3011
3012  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
3013  // conversion will take place first from scalar to elt type, and then
3014  // splat from elt type to vector.
3015  if (SrcTy->isPointerType())
3016    return Diag(R.getBegin(),
3017                diag::err_invalid_conversion_between_vector_and_scalar)
3018      << DestTy << SrcTy << R;
3019  return false;
3020}
3021
3022Action::OwningExprResult
3023Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
3024                    SourceLocation RParenLoc, ExprArg Op) {
3025  CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3026
3027  assert((Ty != 0) && (Op.get() != 0) &&
3028         "ActOnCastExpr(): missing type or expr");
3029
3030  Expr *castExpr = (Expr *)Op.get();
3031  //FIXME: Preserve type source info.
3032  QualType castType = GetTypeFromParser(Ty);
3033
3034  // If the Expr being casted is a ParenListExpr, handle it specially.
3035  if (isa<ParenListExpr>(castExpr))
3036    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
3037  CXXMethodDecl *ConversionDecl = 0;
3038  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3039                     Kind, ConversionDecl))
3040    return ExprError();
3041
3042  Op.release();
3043  return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
3044                                            Kind, castExpr, castType,
3045                                            LParenLoc, RParenLoc));
3046}
3047
3048/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3049/// of comma binary operators.
3050Action::OwningExprResult
3051Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3052  Expr *expr = EA.takeAs<Expr>();
3053  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3054  if (!E)
3055    return Owned(expr);
3056
3057  OwningExprResult Result(*this, E->getExpr(0));
3058
3059  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3060    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3061                        Owned(E->getExpr(i)));
3062
3063  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3064}
3065
3066Action::OwningExprResult
3067Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3068                               SourceLocation RParenLoc, ExprArg Op,
3069                               QualType Ty) {
3070  ParenListExpr *PE = (ParenListExpr *)Op.get();
3071
3072  // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3073  // then handle it as such.
3074  if (getLangOptions().AltiVec && Ty->isVectorType()) {
3075    if (PE->getNumExprs() == 0) {
3076      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3077      return ExprError();
3078    }
3079
3080    llvm::SmallVector<Expr *, 8> initExprs;
3081    for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3082      initExprs.push_back(PE->getExpr(i));
3083
3084    // FIXME: This means that pretty-printing the final AST will produce curly
3085    // braces instead of the original commas.
3086    Op.release();
3087    InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3088                                                 initExprs.size(), RParenLoc);
3089    E->setType(Ty);
3090    return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3091                                Owned(E));
3092  } else {
3093    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3094    // sequence of BinOp comma operators.
3095    Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3096    return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3097  }
3098}
3099
3100Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3101                                                  SourceLocation R,
3102                                                  MultiExprArg Val) {
3103  unsigned nexprs = Val.size();
3104  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3105  assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3106  Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3107  return Owned(expr);
3108}
3109
3110/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3111/// In that case, lhs = cond.
3112/// C99 6.5.15
3113QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3114                                        SourceLocation QuestionLoc) {
3115  // C++ is sufficiently different to merit its own checker.
3116  if (getLangOptions().CPlusPlus)
3117    return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3118
3119  UsualUnaryConversions(Cond);
3120  UsualUnaryConversions(LHS);
3121  UsualUnaryConversions(RHS);
3122  QualType CondTy = Cond->getType();
3123  QualType LHSTy = LHS->getType();
3124  QualType RHSTy = RHS->getType();
3125
3126  // first, check the condition.
3127  if (!CondTy->isScalarType()) { // C99 6.5.15p2
3128    Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3129      << CondTy;
3130    return QualType();
3131  }
3132
3133  // Now check the two expressions.
3134  if (LHSTy->isVectorType() || RHSTy->isVectorType())
3135    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3136
3137  // If both operands have arithmetic type, do the usual arithmetic conversions
3138  // to find a common type: C99 6.5.15p3,5.
3139  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3140    UsualArithmeticConversions(LHS, RHS);
3141    return LHS->getType();
3142  }
3143
3144  // If both operands are the same structure or union type, the result is that
3145  // type.
3146  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
3147    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
3148      if (LHSRT->getDecl() == RHSRT->getDecl())
3149        // "If both the operands have structure or union type, the result has
3150        // that type."  This implies that CV qualifiers are dropped.
3151        return LHSTy.getUnqualifiedType();
3152    // FIXME: Type of conditional expression must be complete in C mode.
3153  }
3154
3155  // C99 6.5.15p5: "If both operands have void type, the result has void type."
3156  // The following || allows only one side to be void (a GCC-ism).
3157  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3158    if (!LHSTy->isVoidType())
3159      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3160        << RHS->getSourceRange();
3161    if (!RHSTy->isVoidType())
3162      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3163        << LHS->getSourceRange();
3164    ImpCastExprToType(LHS, Context.VoidTy);
3165    ImpCastExprToType(RHS, Context.VoidTy);
3166    return Context.VoidTy;
3167  }
3168  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3169  // the type of the other operand."
3170  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
3171      RHS->isNullPointerConstant(Context)) {
3172    ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3173    return LHSTy;
3174  }
3175  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
3176      LHS->isNullPointerConstant(Context)) {
3177    ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3178    return RHSTy;
3179  }
3180  // Handle things like Class and struct objc_class*.  Here we case the result
3181  // to the pseudo-builtin, because that will be implicitly cast back to the
3182  // redefinition type if an attempt is made to access its fields.
3183  if (LHSTy->isObjCClassType() &&
3184      (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3185    ImpCastExprToType(RHS, LHSTy);
3186    return LHSTy;
3187  }
3188  if (RHSTy->isObjCClassType() &&
3189      (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3190    ImpCastExprToType(LHS, RHSTy);
3191    return RHSTy;
3192  }
3193  // And the same for struct objc_object* / id
3194  if (LHSTy->isObjCIdType() &&
3195      (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3196    ImpCastExprToType(RHS, LHSTy);
3197    return LHSTy;
3198  }
3199  if (RHSTy->isObjCIdType() &&
3200      (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3201    ImpCastExprToType(LHS, RHSTy);
3202    return RHSTy;
3203  }
3204  // Handle block pointer types.
3205  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3206    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3207      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3208        QualType destType = Context.getPointerType(Context.VoidTy);
3209        ImpCastExprToType(LHS, destType);
3210        ImpCastExprToType(RHS, destType);
3211        return destType;
3212      }
3213      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3214            << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3215      return QualType();
3216    }
3217    // We have 2 block pointer types.
3218    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3219      // Two identical block pointer types are always compatible.
3220      return LHSTy;
3221    }
3222    // The block pointer types aren't identical, continue checking.
3223    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3224    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
3225
3226    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3227                                    rhptee.getUnqualifiedType())) {
3228      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3229        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3230      // In this situation, we assume void* type. No especially good
3231      // reason, but this is what gcc does, and we do have to pick
3232      // to get a consistent AST.
3233      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3234      ImpCastExprToType(LHS, incompatTy);
3235      ImpCastExprToType(RHS, incompatTy);
3236      return incompatTy;
3237    }
3238    // The block pointer types are compatible.
3239    ImpCastExprToType(LHS, LHSTy);
3240    ImpCastExprToType(RHS, LHSTy);
3241    return LHSTy;
3242  }
3243  // Check constraints for Objective-C object pointers types.
3244  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
3245
3246    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3247      // Two identical object pointer types are always compatible.
3248      return LHSTy;
3249    }
3250    const ObjCObjectPointerType *LHSOPT = LHSTy->getAsObjCObjectPointerType();
3251    const ObjCObjectPointerType *RHSOPT = RHSTy->getAsObjCObjectPointerType();
3252    QualType compositeType = LHSTy;
3253
3254    // If both operands are interfaces and either operand can be
3255    // assigned to the other, use that type as the composite
3256    // type. This allows
3257    //   xxx ? (A*) a : (B*) b
3258    // where B is a subclass of A.
3259    //
3260    // Additionally, as for assignment, if either type is 'id'
3261    // allow silent coercion. Finally, if the types are
3262    // incompatible then make sure to use 'id' as the composite
3263    // type so the result is acceptable for sending messages to.
3264
3265    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3266    // It could return the composite type.
3267    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
3268      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
3269    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
3270      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
3271    } else if ((LHSTy->isObjCQualifiedIdType() ||
3272                RHSTy->isObjCQualifiedIdType()) &&
3273                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
3274      // Need to handle "id<xx>" explicitly.
3275      // GCC allows qualified id and any Objective-C type to devolve to
3276      // id. Currently localizing to here until clear this should be
3277      // part of ObjCQualifiedIdTypesAreCompatible.
3278      compositeType = Context.getObjCIdType();
3279    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
3280      compositeType = Context.getObjCIdType();
3281    } else {
3282      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3283        << LHSTy << RHSTy
3284        << LHS->getSourceRange() << RHS->getSourceRange();
3285      QualType incompatTy = Context.getObjCIdType();
3286      ImpCastExprToType(LHS, incompatTy);
3287      ImpCastExprToType(RHS, incompatTy);
3288      return incompatTy;
3289    }
3290    // The object pointer types are compatible.
3291    ImpCastExprToType(LHS, compositeType);
3292    ImpCastExprToType(RHS, compositeType);
3293    return compositeType;
3294  }
3295  // Check Objective-C object pointer types and 'void *'
3296  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
3297    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3298    QualType rhptee = RHSTy->getAsObjCObjectPointerType()->getPointeeType();
3299    QualType destPointee = lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3300    QualType destType = Context.getPointerType(destPointee);
3301    ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3302    ImpCastExprToType(RHS, destType); // promote to void*
3303    return destType;
3304  }
3305  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3306    QualType lhptee = LHSTy->getAsObjCObjectPointerType()->getPointeeType();
3307    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3308    QualType destPointee = rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3309    QualType destType = Context.getPointerType(destPointee);
3310    ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3311    ImpCastExprToType(LHS, destType); // promote to void*
3312    return destType;
3313  }
3314  // Check constraints for C object pointers types (C99 6.5.15p3,6).
3315  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3316    // get the "pointed to" types
3317    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3318    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3319
3320    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3321    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3322      // Figure out necessary qualifiers (C99 6.5.15p6)
3323      QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
3324      QualType destType = Context.getPointerType(destPointee);
3325      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3326      ImpCastExprToType(RHS, destType); // promote to void*
3327      return destType;
3328    }
3329    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3330      QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
3331      QualType destType = Context.getPointerType(destPointee);
3332      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3333      ImpCastExprToType(RHS, destType); // promote to void*
3334      return destType;
3335    }
3336
3337    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3338      // Two identical pointer types are always compatible.
3339      return LHSTy;
3340    }
3341    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3342                                    rhptee.getUnqualifiedType())) {
3343      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3344        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3345      // In this situation, we assume void* type. No especially good
3346      // reason, but this is what gcc does, and we do have to pick
3347      // to get a consistent AST.
3348      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3349      ImpCastExprToType(LHS, incompatTy);
3350      ImpCastExprToType(RHS, incompatTy);
3351      return incompatTy;
3352    }
3353    // The pointer types are compatible.
3354    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3355    // differently qualified versions of compatible types, the result type is
3356    // a pointer to an appropriately qualified version of the *composite*
3357    // type.
3358    // FIXME: Need to calculate the composite type.
3359    // FIXME: Need to add qualifiers
3360    ImpCastExprToType(LHS, LHSTy);
3361    ImpCastExprToType(RHS, LHSTy);
3362    return LHSTy;
3363  }
3364
3365  // GCC compatibility: soften pointer/integer mismatch.
3366  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3367    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3368      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3369    ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3370    return RHSTy;
3371  }
3372  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3373    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3374      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3375    ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3376    return LHSTy;
3377  }
3378
3379  // Otherwise, the operands are not compatible.
3380  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3381    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3382  return QualType();
3383}
3384
3385/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3386/// in the case of a the GNU conditional expr extension.
3387Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3388                                                  SourceLocation ColonLoc,
3389                                                  ExprArg Cond, ExprArg LHS,
3390                                                  ExprArg RHS) {
3391  Expr *CondExpr = (Expr *) Cond.get();
3392  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
3393
3394  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3395  // was the condition.
3396  bool isLHSNull = LHSExpr == 0;
3397  if (isLHSNull)
3398    LHSExpr = CondExpr;
3399
3400  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
3401                                             RHSExpr, QuestionLoc);
3402  if (result.isNull())
3403    return ExprError();
3404
3405  Cond.release();
3406  LHS.release();
3407  RHS.release();
3408  return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
3409                                                 isLHSNull ? 0 : LHSExpr,
3410                                                 ColonLoc, RHSExpr, result));
3411}
3412
3413// CheckPointerTypesForAssignment - This is a very tricky routine (despite
3414// being closely modeled after the C99 spec:-). The odd characteristic of this
3415// routine is it effectively iqnores the qualifiers on the top level pointee.
3416// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3417// FIXME: add a couple examples in this comment.
3418Sema::AssignConvertType
3419Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3420  QualType lhptee, rhptee;
3421
3422  if ((lhsType->isObjCClassType() &&
3423       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3424     (rhsType->isObjCClassType() &&
3425       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3426      return Compatible;
3427  }
3428
3429  // get the "pointed to" type (ignoring qualifiers at the top level)
3430  lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3431  rhptee = rhsType->getAs<PointerType>()->getPointeeType();
3432
3433  // make sure we operate on the canonical type
3434  lhptee = Context.getCanonicalType(lhptee);
3435  rhptee = Context.getCanonicalType(rhptee);
3436
3437  AssignConvertType ConvTy = Compatible;
3438
3439  // C99 6.5.16.1p1: This following citation is common to constraints
3440  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3441  // qualifiers of the type *pointed to* by the right;
3442  // FIXME: Handle ExtQualType
3443  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
3444    ConvTy = CompatiblePointerDiscardsQualifiers;
3445
3446  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3447  // incomplete type and the other is a pointer to a qualified or unqualified
3448  // version of void...
3449  if (lhptee->isVoidType()) {
3450    if (rhptee->isIncompleteOrObjectType())
3451      return ConvTy;
3452
3453    // As an extension, we allow cast to/from void* to function pointer.
3454    assert(rhptee->isFunctionType());
3455    return FunctionVoidPointer;
3456  }
3457
3458  if (rhptee->isVoidType()) {
3459    if (lhptee->isIncompleteOrObjectType())
3460      return ConvTy;
3461
3462    // As an extension, we allow cast to/from void* to function pointer.
3463    assert(lhptee->isFunctionType());
3464    return FunctionVoidPointer;
3465  }
3466  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
3467  // unqualified versions of compatible types, ...
3468  lhptee = lhptee.getUnqualifiedType();
3469  rhptee = rhptee.getUnqualifiedType();
3470  if (!Context.typesAreCompatible(lhptee, rhptee)) {
3471    // Check if the pointee types are compatible ignoring the sign.
3472    // We explicitly check for char so that we catch "char" vs
3473    // "unsigned char" on systems where "char" is unsigned.
3474    if (lhptee->isCharType()) {
3475      lhptee = Context.UnsignedCharTy;
3476    } else if (lhptee->isSignedIntegerType()) {
3477      lhptee = Context.getCorrespondingUnsignedType(lhptee);
3478    }
3479    if (rhptee->isCharType()) {
3480      rhptee = Context.UnsignedCharTy;
3481    } else if (rhptee->isSignedIntegerType()) {
3482      rhptee = Context.getCorrespondingUnsignedType(rhptee);
3483    }
3484    if (lhptee == rhptee) {
3485      // Types are compatible ignoring the sign. Qualifier incompatibility
3486      // takes priority over sign incompatibility because the sign
3487      // warning can be disabled.
3488      if (ConvTy != Compatible)
3489        return ConvTy;
3490      return IncompatiblePointerSign;
3491    }
3492    // General pointer incompatibility takes priority over qualifiers.
3493    return IncompatiblePointer;
3494  }
3495  return ConvTy;
3496}
3497
3498/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3499/// block pointer types are compatible or whether a block and normal pointer
3500/// are compatible. It is more restrict than comparing two function pointer
3501// types.
3502Sema::AssignConvertType
3503Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
3504                                          QualType rhsType) {
3505  QualType lhptee, rhptee;
3506
3507  // get the "pointed to" type (ignoring qualifiers at the top level)
3508  lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3509  rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
3510
3511  // make sure we operate on the canonical type
3512  lhptee = Context.getCanonicalType(lhptee);
3513  rhptee = Context.getCanonicalType(rhptee);
3514
3515  AssignConvertType ConvTy = Compatible;
3516
3517  // For blocks we enforce that qualifiers are identical.
3518  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3519    ConvTy = CompatiblePointerDiscardsQualifiers;
3520
3521  if (!Context.typesAreCompatible(lhptee, rhptee))
3522    return IncompatibleBlockPointer;
3523  return ConvTy;
3524}
3525
3526/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3527/// has code to accommodate several GCC extensions when type checking
3528/// pointers. Here are some objectionable examples that GCC considers warnings:
3529///
3530///  int a, *pint;
3531///  short *pshort;
3532///  struct foo *pfoo;
3533///
3534///  pint = pshort; // warning: assignment from incompatible pointer type
3535///  a = pint; // warning: assignment makes integer from pointer without a cast
3536///  pint = a; // warning: assignment makes pointer from integer without a cast
3537///  pint = pfoo; // warning: assignment from incompatible pointer type
3538///
3539/// As a result, the code for dealing with pointers is more complex than the
3540/// C99 spec dictates.
3541///
3542Sema::AssignConvertType
3543Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
3544  // Get canonical types.  We're not formatting these types, just comparing
3545  // them.
3546  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3547  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
3548
3549  if (lhsType == rhsType)
3550    return Compatible; // Common case: fast path an exact match.
3551
3552  if ((lhsType->isObjCClassType() &&
3553       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3554     (rhsType->isObjCClassType() &&
3555       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3556      return Compatible;
3557  }
3558
3559  // If the left-hand side is a reference type, then we are in a
3560  // (rare!) case where we've allowed the use of references in C,
3561  // e.g., as a parameter type in a built-in function. In this case,
3562  // just make sure that the type referenced is compatible with the
3563  // right-hand side type. The caller is responsible for adjusting
3564  // lhsType so that the resulting expression does not have reference
3565  // type.
3566  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
3567    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
3568      return Compatible;
3569    return Incompatible;
3570  }
3571  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3572  // to the same ExtVector type.
3573  if (lhsType->isExtVectorType()) {
3574    if (rhsType->isExtVectorType())
3575      return lhsType == rhsType ? Compatible : Incompatible;
3576    if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3577      return Compatible;
3578  }
3579
3580  if (lhsType->isVectorType() || rhsType->isVectorType()) {
3581    // If we are allowing lax vector conversions, and LHS and RHS are both
3582    // vectors, the total size only needs to be the same. This is a bitcast;
3583    // no bits are changed but the result type is different.
3584    if (getLangOptions().LaxVectorConversions &&
3585        lhsType->isVectorType() && rhsType->isVectorType()) {
3586      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
3587        return IncompatibleVectors;
3588    }
3589    return Incompatible;
3590  }
3591
3592  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
3593    return Compatible;
3594
3595  if (isa<PointerType>(lhsType)) {
3596    if (rhsType->isIntegerType())
3597      return IntToPointer;
3598
3599    if (isa<PointerType>(rhsType))
3600      return CheckPointerTypesForAssignment(lhsType, rhsType);
3601
3602    // In general, C pointers are not compatible with ObjC object pointers.
3603    if (isa<ObjCObjectPointerType>(rhsType)) {
3604      if (lhsType->isVoidPointerType()) // an exception to the rule.
3605        return Compatible;
3606      return IncompatiblePointer;
3607    }
3608    if (rhsType->getAs<BlockPointerType>()) {
3609      if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3610        return Compatible;
3611
3612      // Treat block pointers as objects.
3613      if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
3614        return Compatible;
3615    }
3616    return Incompatible;
3617  }
3618
3619  if (isa<BlockPointerType>(lhsType)) {
3620    if (rhsType->isIntegerType())
3621      return IntToBlockPointer;
3622
3623    // Treat block pointers as objects.
3624    if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
3625      return Compatible;
3626
3627    if (rhsType->isBlockPointerType())
3628      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
3629
3630    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3631      if (RHSPT->getPointeeType()->isVoidType())
3632        return Compatible;
3633    }
3634    return Incompatible;
3635  }
3636
3637  if (isa<ObjCObjectPointerType>(lhsType)) {
3638    if (rhsType->isIntegerType())
3639      return IntToPointer;
3640
3641    // In general, C pointers are not compatible with ObjC object pointers.
3642    if (isa<PointerType>(rhsType)) {
3643      if (rhsType->isVoidPointerType()) // an exception to the rule.
3644        return Compatible;
3645      return IncompatiblePointer;
3646    }
3647    if (rhsType->isObjCObjectPointerType()) {
3648      if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3649        return Compatible;
3650      if (Context.typesAreCompatible(lhsType, rhsType))
3651        return Compatible;
3652      if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3653        return IncompatibleObjCQualifiedId;
3654      return IncompatiblePointer;
3655    }
3656    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3657      if (RHSPT->getPointeeType()->isVoidType())
3658        return Compatible;
3659    }
3660    // Treat block pointers as objects.
3661    if (rhsType->isBlockPointerType())
3662      return Compatible;
3663    return Incompatible;
3664  }
3665  if (isa<PointerType>(rhsType)) {
3666    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3667    if (lhsType == Context.BoolTy)
3668      return Compatible;
3669
3670    if (lhsType->isIntegerType())
3671      return PointerToInt;
3672
3673    if (isa<PointerType>(lhsType))
3674      return CheckPointerTypesForAssignment(lhsType, rhsType);
3675
3676    if (isa<BlockPointerType>(lhsType) &&
3677        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3678      return Compatible;
3679    return Incompatible;
3680  }
3681  if (isa<ObjCObjectPointerType>(rhsType)) {
3682    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3683    if (lhsType == Context.BoolTy)
3684      return Compatible;
3685
3686    if (lhsType->isIntegerType())
3687      return PointerToInt;
3688
3689    // In general, C pointers are not compatible with ObjC object pointers.
3690    if (isa<PointerType>(lhsType)) {
3691      if (lhsType->isVoidPointerType()) // an exception to the rule.
3692        return Compatible;
3693      return IncompatiblePointer;
3694    }
3695    if (isa<BlockPointerType>(lhsType) &&
3696        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3697      return Compatible;
3698    return Incompatible;
3699  }
3700
3701  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
3702    if (Context.typesAreCompatible(lhsType, rhsType))
3703      return Compatible;
3704  }
3705  return Incompatible;
3706}
3707
3708/// \brief Constructs a transparent union from an expression that is
3709/// used to initialize the transparent union.
3710static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3711                                      QualType UnionType, FieldDecl *Field) {
3712  // Build an initializer list that designates the appropriate member
3713  // of the transparent union.
3714  InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3715                                                   &E, 1,
3716                                                   SourceLocation());
3717  Initializer->setType(UnionType);
3718  Initializer->setInitializedFieldInUnion(Field);
3719
3720  // Build a compound literal constructing a value of the transparent
3721  // union type from this initializer list.
3722  E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3723                                  false);
3724}
3725
3726Sema::AssignConvertType
3727Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3728  QualType FromType = rExpr->getType();
3729
3730  // If the ArgType is a Union type, we want to handle a potential
3731  // transparent_union GCC extension.
3732  const RecordType *UT = ArgType->getAsUnionType();
3733  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3734    return Incompatible;
3735
3736  // The field to initialize within the transparent union.
3737  RecordDecl *UD = UT->getDecl();
3738  FieldDecl *InitField = 0;
3739  // It's compatible if the expression matches any of the fields.
3740  for (RecordDecl::field_iterator it = UD->field_begin(),
3741         itend = UD->field_end();
3742       it != itend; ++it) {
3743    if (it->getType()->isPointerType()) {
3744      // If the transparent union contains a pointer type, we allow:
3745      // 1) void pointer
3746      // 2) null pointer constant
3747      if (FromType->isPointerType())
3748        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
3749          ImpCastExprToType(rExpr, it->getType());
3750          InitField = *it;
3751          break;
3752        }
3753
3754      if (rExpr->isNullPointerConstant(Context)) {
3755        ImpCastExprToType(rExpr, it->getType());
3756        InitField = *it;
3757        break;
3758      }
3759    }
3760
3761    if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
3762          == Compatible) {
3763      InitField = *it;
3764      break;
3765    }
3766  }
3767
3768  if (!InitField)
3769    return Incompatible;
3770
3771  ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
3772  return Compatible;
3773}
3774
3775Sema::AssignConvertType
3776Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
3777  if (getLangOptions().CPlusPlus) {
3778    if (!lhsType->isRecordType()) {
3779      // C++ 5.17p3: If the left operand is not of class type, the
3780      // expression is implicitly converted (C++ 4) to the
3781      // cv-unqualified type of the left operand.
3782      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
3783                                    "assigning"))
3784        return Incompatible;
3785      return Compatible;
3786    }
3787
3788    // FIXME: Currently, we fall through and treat C++ classes like C
3789    // structures.
3790  }
3791
3792  // C99 6.5.16.1p1: the left operand is a pointer and the right is
3793  // a null pointer constant.
3794  if ((lhsType->isPointerType() ||
3795       lhsType->isObjCObjectPointerType() ||
3796       lhsType->isBlockPointerType())
3797      && rExpr->isNullPointerConstant(Context)) {
3798    ImpCastExprToType(rExpr, lhsType);
3799    return Compatible;
3800  }
3801
3802  // This check seems unnatural, however it is necessary to ensure the proper
3803  // conversion of functions/arrays. If the conversion were done for all
3804  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
3805  // expressions that surpress this implicit conversion (&, sizeof).
3806  //
3807  // Suppress this for references: C++ 8.5.3p5.
3808  if (!lhsType->isReferenceType())
3809    DefaultFunctionArrayConversion(rExpr);
3810
3811  Sema::AssignConvertType result =
3812    CheckAssignmentConstraints(lhsType, rExpr->getType());
3813
3814  // C99 6.5.16.1p2: The value of the right operand is converted to the
3815  // type of the assignment expression.
3816  // CheckAssignmentConstraints allows the left-hand side to be a reference,
3817  // so that we can use references in built-in functions even in C.
3818  // The getNonReferenceType() call makes sure that the resulting expression
3819  // does not have reference type.
3820  if (result != Incompatible && rExpr->getType() != lhsType)
3821    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
3822  return result;
3823}
3824
3825QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
3826  Diag(Loc, diag::err_typecheck_invalid_operands)
3827    << lex->getType() << rex->getType()
3828    << lex->getSourceRange() << rex->getSourceRange();
3829  return QualType();
3830}
3831
3832inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
3833                                                              Expr *&rex) {
3834  // For conversion purposes, we ignore any qualifiers.
3835  // For example, "const float" and "float" are equivalent.
3836  QualType lhsType =
3837    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
3838  QualType rhsType =
3839    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
3840
3841  // If the vector types are identical, return.
3842  if (lhsType == rhsType)
3843    return lhsType;
3844
3845  // Handle the case of a vector & extvector type of the same size and element
3846  // type.  It would be nice if we only had one vector type someday.
3847  if (getLangOptions().LaxVectorConversions) {
3848    // FIXME: Should we warn here?
3849    if (const VectorType *LV = lhsType->getAsVectorType()) {
3850      if (const VectorType *RV = rhsType->getAsVectorType())
3851        if (LV->getElementType() == RV->getElementType() &&
3852            LV->getNumElements() == RV->getNumElements()) {
3853          return lhsType->isExtVectorType() ? lhsType : rhsType;
3854        }
3855    }
3856  }
3857
3858  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
3859  // swap back (so that we don't reverse the inputs to a subtract, for instance.
3860  bool swapped = false;
3861  if (rhsType->isExtVectorType()) {
3862    swapped = true;
3863    std::swap(rex, lex);
3864    std::swap(rhsType, lhsType);
3865  }
3866
3867  // Handle the case of an ext vector and scalar.
3868  if (const ExtVectorType *LV = lhsType->getAsExtVectorType()) {
3869    QualType EltTy = LV->getElementType();
3870    if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
3871      if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
3872        ImpCastExprToType(rex, lhsType);
3873        if (swapped) std::swap(rex, lex);
3874        return lhsType;
3875      }
3876    }
3877    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
3878        rhsType->isRealFloatingType()) {
3879      if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
3880        ImpCastExprToType(rex, lhsType);
3881        if (swapped) std::swap(rex, lex);
3882        return lhsType;
3883      }
3884    }
3885  }
3886
3887  // Vectors of different size or scalar and non-ext-vector are errors.
3888  Diag(Loc, diag::err_typecheck_vector_not_convertable)
3889    << lex->getType() << rex->getType()
3890    << lex->getSourceRange() << rex->getSourceRange();
3891  return QualType();
3892}
3893
3894inline QualType Sema::CheckMultiplyDivideOperands(
3895  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3896{
3897  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3898    return CheckVectorOperands(Loc, lex, rex);
3899
3900  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3901
3902  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3903    return compType;
3904  return InvalidOperands(Loc, lex, rex);
3905}
3906
3907inline QualType Sema::CheckRemainderOperands(
3908  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3909{
3910  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3911    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3912      return CheckVectorOperands(Loc, lex, rex);
3913    return InvalidOperands(Loc, lex, rex);
3914  }
3915
3916  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3917
3918  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3919    return compType;
3920  return InvalidOperands(Loc, lex, rex);
3921}
3922
3923inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
3924  Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy)
3925{
3926  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
3927    QualType compType = CheckVectorOperands(Loc, lex, rex);
3928    if (CompLHSTy) *CompLHSTy = compType;
3929    return compType;
3930  }
3931
3932  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
3933
3934  // handle the common case first (both operands are arithmetic).
3935  if (lex->getType()->isArithmeticType() &&
3936      rex->getType()->isArithmeticType()) {
3937    if (CompLHSTy) *CompLHSTy = compType;
3938    return compType;
3939  }
3940
3941  // Put any potential pointer into PExp
3942  Expr* PExp = lex, *IExp = rex;
3943  if (IExp->getType()->isAnyPointerType())
3944    std::swap(PExp, IExp);
3945
3946  if (PExp->getType()->isAnyPointerType()) {
3947
3948    if (IExp->getType()->isIntegerType()) {
3949      QualType PointeeTy = PExp->getType()->getPointeeType();
3950
3951      // Check for arithmetic on pointers to incomplete types.
3952      if (PointeeTy->isVoidType()) {
3953        if (getLangOptions().CPlusPlus) {
3954          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
3955            << lex->getSourceRange() << rex->getSourceRange();
3956          return QualType();
3957        }
3958
3959        // GNU extension: arithmetic on pointer to void
3960        Diag(Loc, diag::ext_gnu_void_ptr)
3961          << lex->getSourceRange() << rex->getSourceRange();
3962      } else if (PointeeTy->isFunctionType()) {
3963        if (getLangOptions().CPlusPlus) {
3964          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3965            << lex->getType() << lex->getSourceRange();
3966          return QualType();
3967        }
3968
3969        // GNU extension: arithmetic on pointer to function
3970        Diag(Loc, diag::ext_gnu_ptr_func_arith)
3971          << lex->getType() << lex->getSourceRange();
3972      } else {
3973        // Check if we require a complete type.
3974        if (((PExp->getType()->isPointerType() &&
3975              !PExp->getType()->isDependentType()) ||
3976              PExp->getType()->isObjCObjectPointerType()) &&
3977             RequireCompleteType(Loc, PointeeTy,
3978                                 diag::err_typecheck_arithmetic_incomplete_type,
3979                                 PExp->getSourceRange(), SourceRange(),
3980                                 PExp->getType()))
3981          return QualType();
3982      }
3983      // Diagnose bad cases where we step over interface counts.
3984      if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
3985        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
3986          << PointeeTy << PExp->getSourceRange();
3987        return QualType();
3988      }
3989
3990      if (CompLHSTy) {
3991        QualType LHSTy = Context.isPromotableBitField(lex);
3992        if (LHSTy.isNull()) {
3993          LHSTy = lex->getType();
3994          if (LHSTy->isPromotableIntegerType())
3995            LHSTy = Context.getPromotedIntegerType(LHSTy);
3996        }
3997        *CompLHSTy = LHSTy;
3998      }
3999      return PExp->getType();
4000    }
4001  }
4002
4003  return InvalidOperands(Loc, lex, rex);
4004}
4005
4006// C99 6.5.6
4007QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
4008                                        SourceLocation Loc, QualType* CompLHSTy) {
4009  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4010    QualType compType = CheckVectorOperands(Loc, lex, rex);
4011    if (CompLHSTy) *CompLHSTy = compType;
4012    return compType;
4013  }
4014
4015  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4016
4017  // Enforce type constraints: C99 6.5.6p3.
4018
4019  // Handle the common case first (both operands are arithmetic).
4020  if (lex->getType()->isArithmeticType()
4021      && rex->getType()->isArithmeticType()) {
4022    if (CompLHSTy) *CompLHSTy = compType;
4023    return compType;
4024  }
4025
4026  // Either ptr - int   or   ptr - ptr.
4027  if (lex->getType()->isAnyPointerType()) {
4028    QualType lpointee = lex->getType()->getPointeeType();
4029
4030    // The LHS must be an completely-defined object type.
4031
4032    bool ComplainAboutVoid = false;
4033    Expr *ComplainAboutFunc = 0;
4034    if (lpointee->isVoidType()) {
4035      if (getLangOptions().CPlusPlus) {
4036        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4037          << lex->getSourceRange() << rex->getSourceRange();
4038        return QualType();
4039      }
4040
4041      // GNU C extension: arithmetic on pointer to void
4042      ComplainAboutVoid = true;
4043    } else if (lpointee->isFunctionType()) {
4044      if (getLangOptions().CPlusPlus) {
4045        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4046          << lex->getType() << lex->getSourceRange();
4047        return QualType();
4048      }
4049
4050      // GNU C extension: arithmetic on pointer to function
4051      ComplainAboutFunc = lex;
4052    } else if (!lpointee->isDependentType() &&
4053               RequireCompleteType(Loc, lpointee,
4054                                   diag::err_typecheck_sub_ptr_object,
4055                                   lex->getSourceRange(),
4056                                   SourceRange(),
4057                                   lex->getType()))
4058      return QualType();
4059
4060    // Diagnose bad cases where we step over interface counts.
4061    if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4062      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4063        << lpointee << lex->getSourceRange();
4064      return QualType();
4065    }
4066
4067    // The result type of a pointer-int computation is the pointer type.
4068    if (rex->getType()->isIntegerType()) {
4069      if (ComplainAboutVoid)
4070        Diag(Loc, diag::ext_gnu_void_ptr)
4071          << lex->getSourceRange() << rex->getSourceRange();
4072      if (ComplainAboutFunc)
4073        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4074          << ComplainAboutFunc->getType()
4075          << ComplainAboutFunc->getSourceRange();
4076
4077      if (CompLHSTy) *CompLHSTy = lex->getType();
4078      return lex->getType();
4079    }
4080
4081    // Handle pointer-pointer subtractions.
4082    if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
4083      QualType rpointee = RHSPTy->getPointeeType();
4084
4085      // RHS must be a completely-type object type.
4086      // Handle the GNU void* extension.
4087      if (rpointee->isVoidType()) {
4088        if (getLangOptions().CPlusPlus) {
4089          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4090            << lex->getSourceRange() << rex->getSourceRange();
4091          return QualType();
4092        }
4093
4094        ComplainAboutVoid = true;
4095      } else if (rpointee->isFunctionType()) {
4096        if (getLangOptions().CPlusPlus) {
4097          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4098            << rex->getType() << rex->getSourceRange();
4099          return QualType();
4100        }
4101
4102        // GNU extension: arithmetic on pointer to function
4103        if (!ComplainAboutFunc)
4104          ComplainAboutFunc = rex;
4105      } else if (!rpointee->isDependentType() &&
4106                 RequireCompleteType(Loc, rpointee,
4107                                     diag::err_typecheck_sub_ptr_object,
4108                                     rex->getSourceRange(),
4109                                     SourceRange(),
4110                                     rex->getType()))
4111        return QualType();
4112
4113      if (getLangOptions().CPlusPlus) {
4114        // Pointee types must be the same: C++ [expr.add]
4115        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4116          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4117            << lex->getType() << rex->getType()
4118            << lex->getSourceRange() << rex->getSourceRange();
4119          return QualType();
4120        }
4121      } else {
4122        // Pointee types must be compatible C99 6.5.6p3
4123        if (!Context.typesAreCompatible(
4124                Context.getCanonicalType(lpointee).getUnqualifiedType(),
4125                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4126          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4127            << lex->getType() << rex->getType()
4128            << lex->getSourceRange() << rex->getSourceRange();
4129          return QualType();
4130        }
4131      }
4132
4133      if (ComplainAboutVoid)
4134        Diag(Loc, diag::ext_gnu_void_ptr)
4135          << lex->getSourceRange() << rex->getSourceRange();
4136      if (ComplainAboutFunc)
4137        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4138          << ComplainAboutFunc->getType()
4139          << ComplainAboutFunc->getSourceRange();
4140
4141      if (CompLHSTy) *CompLHSTy = lex->getType();
4142      return Context.getPointerDiffType();
4143    }
4144  }
4145
4146  return InvalidOperands(Loc, lex, rex);
4147}
4148
4149// C99 6.5.7
4150QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4151                                  bool isCompAssign) {
4152  // C99 6.5.7p2: Each of the operands shall have integer type.
4153  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4154    return InvalidOperands(Loc, lex, rex);
4155
4156  // Shifts don't perform usual arithmetic conversions, they just do integer
4157  // promotions on each operand. C99 6.5.7p3
4158  QualType LHSTy = Context.isPromotableBitField(lex);
4159  if (LHSTy.isNull()) {
4160    LHSTy = lex->getType();
4161    if (LHSTy->isPromotableIntegerType())
4162      LHSTy = Context.getPromotedIntegerType(LHSTy);
4163  }
4164  if (!isCompAssign)
4165    ImpCastExprToType(lex, LHSTy);
4166
4167  UsualUnaryConversions(rex);
4168
4169  // Sanity-check shift operands
4170  llvm::APSInt Right;
4171  // Check right/shifter operand
4172  if (rex->isIntegerConstantExpr(Right, Context)) {
4173    if (Right.isNegative())
4174      Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4175    else {
4176      llvm::APInt LeftBits(Right.getBitWidth(),
4177                          Context.getTypeSize(lex->getType()));
4178      if (Right.uge(LeftBits))
4179        Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4180    }
4181  }
4182
4183  // "The type of the result is that of the promoted left operand."
4184  return LHSTy;
4185}
4186
4187// C99 6.5.8, C++ [expr.rel]
4188QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4189                                    unsigned OpaqueOpc, bool isRelational) {
4190  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4191
4192  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4193    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
4194
4195  // C99 6.5.8p3 / C99 6.5.9p4
4196  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4197    UsualArithmeticConversions(lex, rex);
4198  else {
4199    UsualUnaryConversions(lex);
4200    UsualUnaryConversions(rex);
4201  }
4202  QualType lType = lex->getType();
4203  QualType rType = rex->getType();
4204
4205  if (!lType->isFloatingType()
4206      && !(lType->isBlockPointerType() && isRelational)) {
4207    // For non-floating point types, check for self-comparisons of the form
4208    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4209    // often indicate logic errors in the program.
4210    // NOTE: Don't warn about comparisons of enum constants. These can arise
4211    //  from macro expansions, and are usually quite deliberate.
4212    Expr *LHSStripped = lex->IgnoreParens();
4213    Expr *RHSStripped = rex->IgnoreParens();
4214    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4215      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
4216        if (DRL->getDecl() == DRR->getDecl() &&
4217            !isa<EnumConstantDecl>(DRL->getDecl()))
4218          Diag(Loc, diag::warn_selfcomparison);
4219
4220    if (isa<CastExpr>(LHSStripped))
4221      LHSStripped = LHSStripped->IgnoreParenCasts();
4222    if (isa<CastExpr>(RHSStripped))
4223      RHSStripped = RHSStripped->IgnoreParenCasts();
4224
4225    // Warn about comparisons against a string constant (unless the other
4226    // operand is null), the user probably wants strcmp.
4227    Expr *literalString = 0;
4228    Expr *literalStringStripped = 0;
4229    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
4230        !RHSStripped->isNullPointerConstant(Context)) {
4231      literalString = lex;
4232      literalStringStripped = LHSStripped;
4233    } else if ((isa<StringLiteral>(RHSStripped) ||
4234                isa<ObjCEncodeExpr>(RHSStripped)) &&
4235               !LHSStripped->isNullPointerConstant(Context)) {
4236      literalString = rex;
4237      literalStringStripped = RHSStripped;
4238    }
4239
4240    if (literalString) {
4241      std::string resultComparison;
4242      switch (Opc) {
4243      case BinaryOperator::LT: resultComparison = ") < 0"; break;
4244      case BinaryOperator::GT: resultComparison = ") > 0"; break;
4245      case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4246      case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4247      case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4248      case BinaryOperator::NE: resultComparison = ") != 0"; break;
4249      default: assert(false && "Invalid comparison operator");
4250      }
4251      Diag(Loc, diag::warn_stringcompare)
4252        << isa<ObjCEncodeExpr>(literalStringStripped)
4253        << literalString->getSourceRange()
4254        << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4255        << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4256                                                 "strcmp(")
4257        << CodeModificationHint::CreateInsertion(
4258                                       PP.getLocForEndOfToken(rex->getLocEnd()),
4259                                       resultComparison);
4260    }
4261  }
4262
4263  // The result of comparisons is 'bool' in C++, 'int' in C.
4264  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
4265
4266  if (isRelational) {
4267    if (lType->isRealType() && rType->isRealType())
4268      return ResultTy;
4269  } else {
4270    // Check for comparisons of floating point operands using != and ==.
4271    if (lType->isFloatingType()) {
4272      assert(rType->isFloatingType());
4273      CheckFloatComparison(Loc,lex,rex);
4274    }
4275
4276    if (lType->isArithmeticType() && rType->isArithmeticType())
4277      return ResultTy;
4278  }
4279
4280  bool LHSIsNull = lex->isNullPointerConstant(Context);
4281  bool RHSIsNull = rex->isNullPointerConstant(Context);
4282
4283  // All of the following pointer related warnings are GCC extensions, except
4284  // when handling null pointer constants. One day, we can consider making them
4285  // errors (when -pedantic-errors is enabled).
4286  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
4287    QualType LCanPointeeTy =
4288      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
4289    QualType RCanPointeeTy =
4290      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
4291
4292    if (getLangOptions().CPlusPlus) {
4293      if (LCanPointeeTy == RCanPointeeTy)
4294        return ResultTy;
4295
4296      // C++ [expr.rel]p2:
4297      //   [...] Pointer conversions (4.10) and qualification
4298      //   conversions (4.4) are performed on pointer operands (or on
4299      //   a pointer operand and a null pointer constant) to bring
4300      //   them to their composite pointer type. [...]
4301      //
4302      // C++ [expr.eq]p1 uses the same notion for (in)equality
4303      // comparisons of pointers.
4304      QualType T = FindCompositePointerType(lex, rex);
4305      if (T.isNull()) {
4306        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4307          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4308        return QualType();
4309      }
4310
4311      ImpCastExprToType(lex, T);
4312      ImpCastExprToType(rex, T);
4313      return ResultTy;
4314    }
4315    // C99 6.5.9p2 and C99 6.5.8p2
4316    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4317                                   RCanPointeeTy.getUnqualifiedType())) {
4318      // Valid unless a relational comparison of function pointers
4319      if (isRelational && LCanPointeeTy->isFunctionType()) {
4320        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4321          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4322      }
4323    } else if (!isRelational &&
4324               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4325      // Valid unless comparison between non-null pointer and function pointer
4326      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4327          && !LHSIsNull && !RHSIsNull) {
4328        Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4329          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4330      }
4331    } else {
4332      // Invalid
4333      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4334        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4335    }
4336    if (LCanPointeeTy != RCanPointeeTy)
4337      ImpCastExprToType(rex, lType); // promote the pointer to pointer
4338    return ResultTy;
4339  }
4340
4341  if (getLangOptions().CPlusPlus) {
4342    // Comparison of pointers with null pointer constants and equality
4343    // comparisons of member pointers to null pointer constants.
4344    if (RHSIsNull &&
4345        (lType->isPointerType() ||
4346         (!isRelational && lType->isMemberPointerType()))) {
4347      ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
4348      return ResultTy;
4349    }
4350    if (LHSIsNull &&
4351        (rType->isPointerType() ||
4352         (!isRelational && rType->isMemberPointerType()))) {
4353      ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
4354      return ResultTy;
4355    }
4356
4357    // Comparison of member pointers.
4358    if (!isRelational &&
4359        lType->isMemberPointerType() && rType->isMemberPointerType()) {
4360      // C++ [expr.eq]p2:
4361      //   In addition, pointers to members can be compared, or a pointer to
4362      //   member and a null pointer constant. Pointer to member conversions
4363      //   (4.11) and qualification conversions (4.4) are performed to bring
4364      //   them to a common type. If one operand is a null pointer constant,
4365      //   the common type is the type of the other operand. Otherwise, the
4366      //   common type is a pointer to member type similar (4.4) to the type
4367      //   of one of the operands, with a cv-qualification signature (4.4)
4368      //   that is the union of the cv-qualification signatures of the operand
4369      //   types.
4370      QualType T = FindCompositePointerType(lex, rex);
4371      if (T.isNull()) {
4372        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4373        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4374        return QualType();
4375      }
4376
4377      ImpCastExprToType(lex, T);
4378      ImpCastExprToType(rex, T);
4379      return ResultTy;
4380    }
4381
4382    // Comparison of nullptr_t with itself.
4383    if (lType->isNullPtrType() && rType->isNullPtrType())
4384      return ResultTy;
4385  }
4386
4387  // Handle block pointer types.
4388  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
4389    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4390    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
4391
4392    if (!LHSIsNull && !RHSIsNull &&
4393        !Context.typesAreCompatible(lpointee, rpointee)) {
4394      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4395        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4396    }
4397    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4398    return ResultTy;
4399  }
4400  // Allow block pointers to be compared with null pointer constants.
4401  if (!isRelational
4402      && ((lType->isBlockPointerType() && rType->isPointerType())
4403          || (lType->isPointerType() && rType->isBlockPointerType()))) {
4404    if (!LHSIsNull && !RHSIsNull) {
4405      if (!((rType->isPointerType() && rType->getAs<PointerType>()
4406             ->getPointeeType()->isVoidType())
4407            || (lType->isPointerType() && lType->getAs<PointerType>()
4408                ->getPointeeType()->isVoidType())))
4409        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4410          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4411    }
4412    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4413    return ResultTy;
4414  }
4415
4416  if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
4417    if (lType->isPointerType() || rType->isPointerType()) {
4418      const PointerType *LPT = lType->getAs<PointerType>();
4419      const PointerType *RPT = rType->getAs<PointerType>();
4420      bool LPtrToVoid = LPT ?
4421        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
4422      bool RPtrToVoid = RPT ?
4423        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
4424
4425      if (!LPtrToVoid && !RPtrToVoid &&
4426          !Context.typesAreCompatible(lType, rType)) {
4427        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4428          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4429      }
4430      ImpCastExprToType(rex, lType);
4431      return ResultTy;
4432    }
4433    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4434      if (!Context.areComparableObjCPointerTypes(lType, rType))
4435        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4436          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4437      ImpCastExprToType(rex, lType);
4438      return ResultTy;
4439    }
4440  }
4441  if (lType->isAnyPointerType() && rType->isIntegerType()) {
4442    unsigned DiagID = 0;
4443    if (RHSIsNull) {
4444      if (isRelational)
4445        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4446    } else if (isRelational)
4447      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4448    else
4449      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4450
4451    if (DiagID) {
4452      Diag(Loc, DiagID)
4453        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4454    }
4455    ImpCastExprToType(rex, lType); // promote the integer to pointer
4456    return ResultTy;
4457  }
4458  if (lType->isIntegerType() && rType->isAnyPointerType()) {
4459    unsigned DiagID = 0;
4460    if (LHSIsNull) {
4461      if (isRelational)
4462        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4463    } else if (isRelational)
4464      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4465    else
4466      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4467
4468    if (DiagID) {
4469      Diag(Loc, DiagID)
4470        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4471    }
4472    ImpCastExprToType(lex, rType); // promote the integer to pointer
4473    return ResultTy;
4474  }
4475  // Handle block pointers.
4476  if (!isRelational && RHSIsNull
4477      && lType->isBlockPointerType() && rType->isIntegerType()) {
4478    ImpCastExprToType(rex, lType); // promote the integer to pointer
4479    return ResultTy;
4480  }
4481  if (!isRelational && LHSIsNull
4482      && lType->isIntegerType() && rType->isBlockPointerType()) {
4483    ImpCastExprToType(lex, rType); // promote the integer to pointer
4484    return ResultTy;
4485  }
4486  return InvalidOperands(Loc, lex, rex);
4487}
4488
4489/// CheckVectorCompareOperands - vector comparisons are a clang extension that
4490/// operates on extended vector types.  Instead of producing an IntTy result,
4491/// like a scalar comparison, a vector comparison produces a vector of integer
4492/// types.
4493QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
4494                                          SourceLocation Loc,
4495                                          bool isRelational) {
4496  // Check to make sure we're operating on vectors of the same type and width,
4497  // Allowing one side to be a scalar of element type.
4498  QualType vType = CheckVectorOperands(Loc, lex, rex);
4499  if (vType.isNull())
4500    return vType;
4501
4502  QualType lType = lex->getType();
4503  QualType rType = rex->getType();
4504
4505  // For non-floating point types, check for self-comparisons of the form
4506  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4507  // often indicate logic errors in the program.
4508  if (!lType->isFloatingType()) {
4509    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4510      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4511        if (DRL->getDecl() == DRR->getDecl())
4512          Diag(Loc, diag::warn_selfcomparison);
4513  }
4514
4515  // Check for comparisons of floating point operands using != and ==.
4516  if (!isRelational && lType->isFloatingType()) {
4517    assert (rType->isFloatingType());
4518    CheckFloatComparison(Loc,lex,rex);
4519  }
4520
4521  // Return the type for the comparison, which is the same as vector type for
4522  // integer vectors, or an integer type of identical size and number of
4523  // elements for floating point vectors.
4524  if (lType->isIntegerType())
4525    return lType;
4526
4527  const VectorType *VTy = lType->getAsVectorType();
4528  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
4529  if (TypeSize == Context.getTypeSize(Context.IntTy))
4530    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
4531  if (TypeSize == Context.getTypeSize(Context.LongTy))
4532    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4533
4534  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
4535         "Unhandled vector element size in vector compare");
4536  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4537}
4538
4539inline QualType Sema::CheckBitwiseOperands(
4540  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
4541{
4542  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4543    return CheckVectorOperands(Loc, lex, rex);
4544
4545  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4546
4547  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4548    return compType;
4549  return InvalidOperands(Loc, lex, rex);
4550}
4551
4552inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
4553  Expr *&lex, Expr *&rex, SourceLocation Loc)
4554{
4555  UsualUnaryConversions(lex);
4556  UsualUnaryConversions(rex);
4557
4558  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
4559    return Context.IntTy;
4560  return InvalidOperands(Loc, lex, rex);
4561}
4562
4563/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4564/// is a read-only property; return true if so. A readonly property expression
4565/// depends on various declarations and thus must be treated specially.
4566///
4567static bool IsReadonlyProperty(Expr *E, Sema &S)
4568{
4569  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4570    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4571    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4572      QualType BaseType = PropExpr->getBase()->getType();
4573      if (const ObjCObjectPointerType *OPT =
4574            BaseType->getAsObjCInterfacePointerType())
4575        if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4576          if (S.isPropertyReadonly(PDecl, IFace))
4577            return true;
4578    }
4579  }
4580  return false;
4581}
4582
4583/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
4584/// emit an error and return true.  If so, return false.
4585static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
4586  SourceLocation OrigLoc = Loc;
4587  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4588                                                              &Loc);
4589  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4590    IsLV = Expr::MLV_ReadonlyProperty;
4591  if (IsLV == Expr::MLV_Valid)
4592    return false;
4593
4594  unsigned Diag = 0;
4595  bool NeedType = false;
4596  switch (IsLV) { // C99 6.5.16p2
4597  default: assert(0 && "Unknown result from isModifiableLvalue!");
4598  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
4599  case Expr::MLV_ArrayType:
4600    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4601    NeedType = true;
4602    break;
4603  case Expr::MLV_NotObjectType:
4604    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4605    NeedType = true;
4606    break;
4607  case Expr::MLV_LValueCast:
4608    Diag = diag::err_typecheck_lvalue_casts_not_supported;
4609    break;
4610  case Expr::MLV_InvalidExpression:
4611    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4612    break;
4613  case Expr::MLV_IncompleteType:
4614  case Expr::MLV_IncompleteVoidType:
4615    return S.RequireCompleteType(Loc, E->getType(),
4616                      diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
4617                                    E->getSourceRange());
4618  case Expr::MLV_DuplicateVectorComponents:
4619    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4620    break;
4621  case Expr::MLV_NotBlockQualified:
4622    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4623    break;
4624  case Expr::MLV_ReadonlyProperty:
4625    Diag = diag::error_readonly_property_assignment;
4626    break;
4627  case Expr::MLV_NoSetterProperty:
4628    Diag = diag::error_nosetter_property_assignment;
4629    break;
4630  }
4631
4632  SourceRange Assign;
4633  if (Loc != OrigLoc)
4634    Assign = SourceRange(OrigLoc, OrigLoc);
4635  if (NeedType)
4636    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
4637  else
4638    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
4639  return true;
4640}
4641
4642
4643
4644// C99 6.5.16.1
4645QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4646                                       SourceLocation Loc,
4647                                       QualType CompoundType) {
4648  // Verify that LHS is a modifiable lvalue, and emit error if not.
4649  if (CheckForModifiableLvalue(LHS, Loc, *this))
4650    return QualType();
4651
4652  QualType LHSType = LHS->getType();
4653  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
4654
4655  AssignConvertType ConvTy;
4656  if (CompoundType.isNull()) {
4657    // Simple assignment "x = y".
4658    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
4659    // Special case of NSObject attributes on c-style pointer types.
4660    if (ConvTy == IncompatiblePointer &&
4661        ((Context.isObjCNSObjectType(LHSType) &&
4662          RHSType->isObjCObjectPointerType()) ||
4663         (Context.isObjCNSObjectType(RHSType) &&
4664          LHSType->isObjCObjectPointerType())))
4665      ConvTy = Compatible;
4666
4667    // If the RHS is a unary plus or minus, check to see if they = and + are
4668    // right next to each other.  If so, the user may have typo'd "x =+ 4"
4669    // instead of "x += 4".
4670    Expr *RHSCheck = RHS;
4671    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4672      RHSCheck = ICE->getSubExpr();
4673    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4674      if ((UO->getOpcode() == UnaryOperator::Plus ||
4675           UO->getOpcode() == UnaryOperator::Minus) &&
4676          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
4677          // Only if the two operators are exactly adjacent.
4678          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4679          // And there is a space or other character before the subexpr of the
4680          // unary +/-.  We don't want to warn on "x=-1".
4681          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4682          UO->getSubExpr()->getLocStart().isFileID()) {
4683        Diag(Loc, diag::warn_not_compound_assign)
4684          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4685          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
4686      }
4687    }
4688  } else {
4689    // Compound assignment "x += y"
4690    ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
4691  }
4692
4693  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4694                               RHS, "assigning"))
4695    return QualType();
4696
4697  // C99 6.5.16p3: The type of an assignment expression is the type of the
4698  // left operand unless the left operand has qualified type, in which case
4699  // it is the unqualified version of the type of the left operand.
4700  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4701  // is converted to the type of the assignment expression (above).
4702  // C++ 5.17p1: the type of the assignment expression is that of its left
4703  // operand.
4704  return LHSType.getUnqualifiedType();
4705}
4706
4707// C99 6.5.17
4708QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
4709  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
4710  DefaultFunctionArrayConversion(RHS);
4711
4712  // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4713  // incomplete in C++).
4714
4715  return RHS->getType();
4716}
4717
4718/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4719/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
4720QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4721                                              bool isInc) {
4722  if (Op->isTypeDependent())
4723    return Context.DependentTy;
4724
4725  QualType ResType = Op->getType();
4726  assert(!ResType.isNull() && "no type for increment/decrement expression");
4727
4728  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4729    // Decrement of bool is not allowed.
4730    if (!isInc) {
4731      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4732      return QualType();
4733    }
4734    // Increment of bool sets it to true, but is deprecated.
4735    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4736  } else if (ResType->isRealType()) {
4737    // OK!
4738  } else if (ResType->isAnyPointerType()) {
4739    QualType PointeeTy = ResType->getPointeeType();
4740
4741    // C99 6.5.2.4p2, 6.5.6p2
4742    if (PointeeTy->isVoidType()) {
4743      if (getLangOptions().CPlusPlus) {
4744        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
4745          << Op->getSourceRange();
4746        return QualType();
4747      }
4748
4749      // Pointer to void is a GNU extension in C.
4750      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
4751    } else if (PointeeTy->isFunctionType()) {
4752      if (getLangOptions().CPlusPlus) {
4753        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
4754          << Op->getType() << Op->getSourceRange();
4755        return QualType();
4756      }
4757
4758      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
4759        << ResType << Op->getSourceRange();
4760    } else if (RequireCompleteType(OpLoc, PointeeTy,
4761                               diag::err_typecheck_arithmetic_incomplete_type,
4762                                   Op->getSourceRange(), SourceRange(),
4763                                   ResType))
4764      return QualType();
4765    // Diagnose bad cases where we step over interface counts.
4766    else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4767      Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
4768        << PointeeTy << Op->getSourceRange();
4769      return QualType();
4770    }
4771  } else if (ResType->isComplexType()) {
4772    // C99 does not support ++/-- on complex types, we allow as an extension.
4773    Diag(OpLoc, diag::ext_integer_increment_complex)
4774      << ResType << Op->getSourceRange();
4775  } else {
4776    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
4777      << ResType << Op->getSourceRange();
4778    return QualType();
4779  }
4780  // At this point, we know we have a real, complex or pointer type.
4781  // Now make sure the operand is a modifiable lvalue.
4782  if (CheckForModifiableLvalue(Op, OpLoc, *this))
4783    return QualType();
4784  return ResType;
4785}
4786
4787/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
4788/// This routine allows us to typecheck complex/recursive expressions
4789/// where the declaration is needed for type checking. We only need to
4790/// handle cases when the expression references a function designator
4791/// or is an lvalue. Here are some examples:
4792///  - &(x) => x
4793///  - &*****f => f for f a function designator.
4794///  - &s.xx => s
4795///  - &s.zz[1].yy -> s, if zz is an array
4796///  - *(x + 1) -> x, if x is an array
4797///  - &"123"[2] -> 0
4798///  - & __real__ x -> x
4799static NamedDecl *getPrimaryDecl(Expr *E) {
4800  switch (E->getStmtClass()) {
4801  case Stmt::DeclRefExprClass:
4802  case Stmt::QualifiedDeclRefExprClass:
4803    return cast<DeclRefExpr>(E)->getDecl();
4804  case Stmt::MemberExprClass:
4805    // If this is an arrow operator, the address is an offset from
4806    // the base's value, so the object the base refers to is
4807    // irrelevant.
4808    if (cast<MemberExpr>(E)->isArrow())
4809      return 0;
4810    // Otherwise, the expression refers to a part of the base
4811    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
4812  case Stmt::ArraySubscriptExprClass: {
4813    // FIXME: This code shouldn't be necessary!  We should catch the implicit
4814    // promotion of register arrays earlier.
4815    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
4816    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
4817      if (ICE->getSubExpr()->getType()->isArrayType())
4818        return getPrimaryDecl(ICE->getSubExpr());
4819    }
4820    return 0;
4821  }
4822  case Stmt::UnaryOperatorClass: {
4823    UnaryOperator *UO = cast<UnaryOperator>(E);
4824
4825    switch(UO->getOpcode()) {
4826    case UnaryOperator::Real:
4827    case UnaryOperator::Imag:
4828    case UnaryOperator::Extension:
4829      return getPrimaryDecl(UO->getSubExpr());
4830    default:
4831      return 0;
4832    }
4833  }
4834  case Stmt::ParenExprClass:
4835    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
4836  case Stmt::ImplicitCastExprClass:
4837    // If the result of an implicit cast is an l-value, we care about
4838    // the sub-expression; otherwise, the result here doesn't matter.
4839    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
4840  default:
4841    return 0;
4842  }
4843}
4844
4845/// CheckAddressOfOperand - The operand of & must be either a function
4846/// designator or an lvalue designating an object. If it is an lvalue, the
4847/// object cannot be declared with storage class register or be a bit field.
4848/// Note: The usual conversions are *not* applied to the operand of the &
4849/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
4850/// In C++, the operand might be an overloaded function name, in which case
4851/// we allow the '&' but retain the overloaded-function type.
4852QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
4853  // Make sure to ignore parentheses in subsequent checks
4854  op = op->IgnoreParens();
4855
4856  if (op->isTypeDependent())
4857    return Context.DependentTy;
4858
4859  if (getLangOptions().C99) {
4860    // Implement C99-only parts of addressof rules.
4861    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
4862      if (uOp->getOpcode() == UnaryOperator::Deref)
4863        // Per C99 6.5.3.2, the address of a deref always returns a valid result
4864        // (assuming the deref expression is valid).
4865        return uOp->getSubExpr()->getType();
4866    }
4867    // Technically, there should be a check for array subscript
4868    // expressions here, but the result of one is always an lvalue anyway.
4869  }
4870  NamedDecl *dcl = getPrimaryDecl(op);
4871  Expr::isLvalueResult lval = op->isLvalue(Context);
4872
4873  if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
4874    // C99 6.5.3.2p1
4875    // The operand must be either an l-value or a function designator
4876    if (!op->getType()->isFunctionType()) {
4877      // FIXME: emit more specific diag...
4878      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
4879        << op->getSourceRange();
4880      return QualType();
4881    }
4882  } else if (op->getBitField()) { // C99 6.5.3.2p1
4883    // The operand cannot be a bit-field
4884    Diag(OpLoc, diag::err_typecheck_address_of)
4885      << "bit-field" << op->getSourceRange();
4886        return QualType();
4887  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
4888           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
4889    // The operand cannot be an element of a vector
4890    Diag(OpLoc, diag::err_typecheck_address_of)
4891      << "vector element" << op->getSourceRange();
4892    return QualType();
4893  } else if (isa<ObjCPropertyRefExpr>(op)) {
4894    // cannot take address of a property expression.
4895    Diag(OpLoc, diag::err_typecheck_address_of)
4896      << "property expression" << op->getSourceRange();
4897    return QualType();
4898  } else if (dcl) { // C99 6.5.3.2p1
4899    // We have an lvalue with a decl. Make sure the decl is not declared
4900    // with the register storage-class specifier.
4901    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
4902      if (vd->getStorageClass() == VarDecl::Register) {
4903        Diag(OpLoc, diag::err_typecheck_address_of)
4904          << "register variable" << op->getSourceRange();
4905        return QualType();
4906      }
4907    } else if (isa<OverloadedFunctionDecl>(dcl) ||
4908               isa<FunctionTemplateDecl>(dcl)) {
4909      return Context.OverloadTy;
4910    } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
4911      // Okay: we can take the address of a field.
4912      // Could be a pointer to member, though, if there is an explicit
4913      // scope qualifier for the class.
4914      if (isa<QualifiedDeclRefExpr>(op)) {
4915        DeclContext *Ctx = dcl->getDeclContext();
4916        if (Ctx && Ctx->isRecord()) {
4917          if (FD->getType()->isReferenceType()) {
4918            Diag(OpLoc,
4919                 diag::err_cannot_form_pointer_to_member_of_reference_type)
4920              << FD->getDeclName() << FD->getType();
4921            return QualType();
4922          }
4923
4924          return Context.getMemberPointerType(op->getType(),
4925                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
4926        }
4927      }
4928    } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
4929      // Okay: we can take the address of a function.
4930      // As above.
4931      if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
4932        return Context.getMemberPointerType(op->getType(),
4933              Context.getTypeDeclType(MD->getParent()).getTypePtr());
4934    } else if (!isa<FunctionDecl>(dcl))
4935      assert(0 && "Unknown/unexpected decl type");
4936  }
4937
4938  if (lval == Expr::LV_IncompleteVoidType) {
4939    // Taking the address of a void variable is technically illegal, but we
4940    // allow it in cases which are otherwise valid.
4941    // Example: "extern void x; void* y = &x;".
4942    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
4943  }
4944
4945  // If the operand has type "type", the result has type "pointer to type".
4946  return Context.getPointerType(op->getType());
4947}
4948
4949QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
4950  if (Op->isTypeDependent())
4951    return Context.DependentTy;
4952
4953  UsualUnaryConversions(Op);
4954  QualType Ty = Op->getType();
4955
4956  // Note that per both C89 and C99, this is always legal, even if ptype is an
4957  // incomplete type or void.  It would be possible to warn about dereferencing
4958  // a void pointer, but it's completely well-defined, and such a warning is
4959  // unlikely to catch any mistakes.
4960  if (const PointerType *PT = Ty->getAs<PointerType>())
4961    return PT->getPointeeType();
4962
4963  if (const ObjCObjectPointerType *OPT = Ty->getAsObjCObjectPointerType())
4964    return OPT->getPointeeType();
4965
4966  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
4967    << Ty << Op->getSourceRange();
4968  return QualType();
4969}
4970
4971static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
4972  tok::TokenKind Kind) {
4973  BinaryOperator::Opcode Opc;
4974  switch (Kind) {
4975  default: assert(0 && "Unknown binop!");
4976  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
4977  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
4978  case tok::star:                 Opc = BinaryOperator::Mul; break;
4979  case tok::slash:                Opc = BinaryOperator::Div; break;
4980  case tok::percent:              Opc = BinaryOperator::Rem; break;
4981  case tok::plus:                 Opc = BinaryOperator::Add; break;
4982  case tok::minus:                Opc = BinaryOperator::Sub; break;
4983  case tok::lessless:             Opc = BinaryOperator::Shl; break;
4984  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
4985  case tok::lessequal:            Opc = BinaryOperator::LE; break;
4986  case tok::less:                 Opc = BinaryOperator::LT; break;
4987  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
4988  case tok::greater:              Opc = BinaryOperator::GT; break;
4989  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
4990  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
4991  case tok::amp:                  Opc = BinaryOperator::And; break;
4992  case tok::caret:                Opc = BinaryOperator::Xor; break;
4993  case tok::pipe:                 Opc = BinaryOperator::Or; break;
4994  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
4995  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
4996  case tok::equal:                Opc = BinaryOperator::Assign; break;
4997  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
4998  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
4999  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
5000  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
5001  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
5002  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
5003  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
5004  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
5005  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
5006  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
5007  case tok::comma:                Opc = BinaryOperator::Comma; break;
5008  }
5009  return Opc;
5010}
5011
5012static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5013  tok::TokenKind Kind) {
5014  UnaryOperator::Opcode Opc;
5015  switch (Kind) {
5016  default: assert(0 && "Unknown unary op!");
5017  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
5018  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
5019  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
5020  case tok::star:         Opc = UnaryOperator::Deref; break;
5021  case tok::plus:         Opc = UnaryOperator::Plus; break;
5022  case tok::minus:        Opc = UnaryOperator::Minus; break;
5023  case tok::tilde:        Opc = UnaryOperator::Not; break;
5024  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
5025  case tok::kw___real:    Opc = UnaryOperator::Real; break;
5026  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
5027  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5028  }
5029  return Opc;
5030}
5031
5032/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5033/// operator @p Opc at location @c TokLoc. This routine only supports
5034/// built-in operations; ActOnBinOp handles overloaded operators.
5035Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5036                                                  unsigned Op,
5037                                                  Expr *lhs, Expr *rhs) {
5038  QualType ResultTy;     // Result type of the binary operator.
5039  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
5040  // The following two variables are used for compound assignment operators
5041  QualType CompLHSTy;    // Type of LHS after promotions for computation
5042  QualType CompResultTy; // Type of computation result
5043
5044  switch (Opc) {
5045  case BinaryOperator::Assign:
5046    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5047    break;
5048  case BinaryOperator::PtrMemD:
5049  case BinaryOperator::PtrMemI:
5050    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5051                                            Opc == BinaryOperator::PtrMemI);
5052    break;
5053  case BinaryOperator::Mul:
5054  case BinaryOperator::Div:
5055    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5056    break;
5057  case BinaryOperator::Rem:
5058    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5059    break;
5060  case BinaryOperator::Add:
5061    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5062    break;
5063  case BinaryOperator::Sub:
5064    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5065    break;
5066  case BinaryOperator::Shl:
5067  case BinaryOperator::Shr:
5068    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5069    break;
5070  case BinaryOperator::LE:
5071  case BinaryOperator::LT:
5072  case BinaryOperator::GE:
5073  case BinaryOperator::GT:
5074    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
5075    break;
5076  case BinaryOperator::EQ:
5077  case BinaryOperator::NE:
5078    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
5079    break;
5080  case BinaryOperator::And:
5081  case BinaryOperator::Xor:
5082  case BinaryOperator::Or:
5083    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5084    break;
5085  case BinaryOperator::LAnd:
5086  case BinaryOperator::LOr:
5087    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5088    break;
5089  case BinaryOperator::MulAssign:
5090  case BinaryOperator::DivAssign:
5091    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5092    CompLHSTy = CompResultTy;
5093    if (!CompResultTy.isNull())
5094      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5095    break;
5096  case BinaryOperator::RemAssign:
5097    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5098    CompLHSTy = CompResultTy;
5099    if (!CompResultTy.isNull())
5100      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5101    break;
5102  case BinaryOperator::AddAssign:
5103    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5104    if (!CompResultTy.isNull())
5105      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5106    break;
5107  case BinaryOperator::SubAssign:
5108    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5109    if (!CompResultTy.isNull())
5110      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5111    break;
5112  case BinaryOperator::ShlAssign:
5113  case BinaryOperator::ShrAssign:
5114    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5115    CompLHSTy = CompResultTy;
5116    if (!CompResultTy.isNull())
5117      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5118    break;
5119  case BinaryOperator::AndAssign:
5120  case BinaryOperator::XorAssign:
5121  case BinaryOperator::OrAssign:
5122    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5123    CompLHSTy = CompResultTy;
5124    if (!CompResultTy.isNull())
5125      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5126    break;
5127  case BinaryOperator::Comma:
5128    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5129    break;
5130  }
5131  if (ResultTy.isNull())
5132    return ExprError();
5133  if (CompResultTy.isNull())
5134    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5135  else
5136    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
5137                                                      CompLHSTy, CompResultTy,
5138                                                      OpLoc));
5139}
5140
5141// Binary Operators.  'Tok' is the token for the operator.
5142Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5143                                          tok::TokenKind Kind,
5144                                          ExprArg LHS, ExprArg RHS) {
5145  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
5146  Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
5147
5148  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5149  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
5150
5151  if (getLangOptions().CPlusPlus &&
5152      (lhs->getType()->isOverloadableType() ||
5153       rhs->getType()->isOverloadableType())) {
5154    // Find all of the overloaded operators visible from this
5155    // point. We perform both an operator-name lookup from the local
5156    // scope and an argument-dependent lookup based on the types of
5157    // the arguments.
5158    FunctionSet Functions;
5159    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5160    if (OverOp != OO_None) {
5161      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5162                                   Functions);
5163      Expr *Args[2] = { lhs, rhs };
5164      DeclarationName OpName
5165        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5166      ArgumentDependentLookup(OpName, Args, 2, Functions);
5167    }
5168
5169    // Build the (potentially-overloaded, potentially-dependent)
5170    // binary operation.
5171    return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
5172  }
5173
5174  // Build a built-in binary operation.
5175  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
5176}
5177
5178Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5179                                                    unsigned OpcIn,
5180                                                    ExprArg InputArg) {
5181  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5182
5183  // FIXME: Input is modified below, but InputArg is not updated appropriately.
5184  Expr *Input = (Expr *)InputArg.get();
5185  QualType resultType;
5186  switch (Opc) {
5187  case UnaryOperator::OffsetOf:
5188    assert(false && "Invalid unary operator");
5189    break;
5190
5191  case UnaryOperator::PreInc:
5192  case UnaryOperator::PreDec:
5193  case UnaryOperator::PostInc:
5194  case UnaryOperator::PostDec:
5195    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
5196                                                Opc == UnaryOperator::PreInc ||
5197                                                Opc == UnaryOperator::PostInc);
5198    break;
5199  case UnaryOperator::AddrOf:
5200    resultType = CheckAddressOfOperand(Input, OpLoc);
5201    break;
5202  case UnaryOperator::Deref:
5203    DefaultFunctionArrayConversion(Input);
5204    resultType = CheckIndirectionOperand(Input, OpLoc);
5205    break;
5206  case UnaryOperator::Plus:
5207  case UnaryOperator::Minus:
5208    UsualUnaryConversions(Input);
5209    resultType = Input->getType();
5210    if (resultType->isDependentType())
5211      break;
5212    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5213      break;
5214    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5215             resultType->isEnumeralType())
5216      break;
5217    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5218             Opc == UnaryOperator::Plus &&
5219             resultType->isPointerType())
5220      break;
5221
5222    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5223      << resultType << Input->getSourceRange());
5224  case UnaryOperator::Not: // bitwise complement
5225    UsualUnaryConversions(Input);
5226    resultType = Input->getType();
5227    if (resultType->isDependentType())
5228      break;
5229    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5230    if (resultType->isComplexType() || resultType->isComplexIntegerType())
5231      // C99 does not support '~' for complex conjugation.
5232      Diag(OpLoc, diag::ext_integer_complement_complex)
5233        << resultType << Input->getSourceRange();
5234    else if (!resultType->isIntegerType())
5235      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5236        << resultType << Input->getSourceRange());
5237    break;
5238  case UnaryOperator::LNot: // logical negation
5239    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5240    DefaultFunctionArrayConversion(Input);
5241    resultType = Input->getType();
5242    if (resultType->isDependentType())
5243      break;
5244    if (!resultType->isScalarType()) // C99 6.5.3.3p1
5245      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5246        << resultType << Input->getSourceRange());
5247    // LNot always has type int. C99 6.5.3.3p5.
5248    // In C++, it's bool. C++ 5.3.1p8
5249    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
5250    break;
5251  case UnaryOperator::Real:
5252  case UnaryOperator::Imag:
5253    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
5254    break;
5255  case UnaryOperator::Extension:
5256    resultType = Input->getType();
5257    break;
5258  }
5259  if (resultType.isNull())
5260    return ExprError();
5261
5262  InputArg.release();
5263  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
5264}
5265
5266// Unary Operators.  'Tok' is the token for the operator.
5267Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5268                                            tok::TokenKind Op, ExprArg input) {
5269  Expr *Input = (Expr*)input.get();
5270  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5271
5272  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5273    // Find all of the overloaded operators visible from this
5274    // point. We perform both an operator-name lookup from the local
5275    // scope and an argument-dependent lookup based on the types of
5276    // the arguments.
5277    FunctionSet Functions;
5278    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5279    if (OverOp != OO_None) {
5280      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5281                                   Functions);
5282      DeclarationName OpName
5283        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5284      ArgumentDependentLookup(OpName, &Input, 1, Functions);
5285    }
5286
5287    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5288  }
5289
5290  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5291}
5292
5293/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5294Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5295                                            SourceLocation LabLoc,
5296                                            IdentifierInfo *LabelII) {
5297  // Look up the record for this label identifier.
5298  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
5299
5300  // If we haven't seen this label yet, create a forward reference. It
5301  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
5302  if (LabelDecl == 0)
5303    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
5304
5305  // Create the AST node.  The address of a label always has type 'void*'.
5306  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5307                                       Context.getPointerType(Context.VoidTy)));
5308}
5309
5310Sema::OwningExprResult
5311Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5312                    SourceLocation RPLoc) { // "({..})"
5313  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
5314  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5315  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5316
5317  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5318  if (isFileScope)
5319    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
5320
5321  // FIXME: there are a variety of strange constraints to enforce here, for
5322  // example, it is not possible to goto into a stmt expression apparently.
5323  // More semantic analysis is needed.
5324
5325  // If there are sub stmts in the compound stmt, take the type of the last one
5326  // as the type of the stmtexpr.
5327  QualType Ty = Context.VoidTy;
5328
5329  if (!Compound->body_empty()) {
5330    Stmt *LastStmt = Compound->body_back();
5331    // If LastStmt is a label, skip down through into the body.
5332    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5333      LastStmt = Label->getSubStmt();
5334
5335    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
5336      Ty = LastExpr->getType();
5337  }
5338
5339  // FIXME: Check that expression type is complete/non-abstract; statement
5340  // expressions are not lvalues.
5341
5342  substmt.release();
5343  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
5344}
5345
5346Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5347                                                  SourceLocation BuiltinLoc,
5348                                                  SourceLocation TypeLoc,
5349                                                  TypeTy *argty,
5350                                                  OffsetOfComponent *CompPtr,
5351                                                  unsigned NumComponents,
5352                                                  SourceLocation RPLoc) {
5353  // FIXME: This function leaks all expressions in the offset components on
5354  // error.
5355  // FIXME: Preserve type source info.
5356  QualType ArgTy = GetTypeFromParser(argty);
5357  assert(!ArgTy.isNull() && "Missing type argument!");
5358
5359  bool Dependent = ArgTy->isDependentType();
5360
5361  // We must have at least one component that refers to the type, and the first
5362  // one is known to be a field designator.  Verify that the ArgTy represents
5363  // a struct/union/class.
5364  if (!Dependent && !ArgTy->isRecordType())
5365    return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
5366
5367  // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5368  // with an incomplete type would be illegal.
5369
5370  // Otherwise, create a null pointer as the base, and iteratively process
5371  // the offsetof designators.
5372  QualType ArgTyPtr = Context.getPointerType(ArgTy);
5373  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
5374  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
5375                                    ArgTy, SourceLocation());
5376
5377  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5378  // GCC extension, diagnose them.
5379  // FIXME: This diagnostic isn't actually visible because the location is in
5380  // a system header!
5381  if (NumComponents != 1)
5382    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5383      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
5384
5385  if (!Dependent) {
5386    bool DidWarnAboutNonPOD = false;
5387
5388    // FIXME: Dependent case loses a lot of information here. And probably
5389    // leaks like a sieve.
5390    for (unsigned i = 0; i != NumComponents; ++i) {
5391      const OffsetOfComponent &OC = CompPtr[i];
5392      if (OC.isBrackets) {
5393        // Offset of an array sub-field.  TODO: Should we allow vector elements?
5394        const ArrayType *AT = Context.getAsArrayType(Res->getType());
5395        if (!AT) {
5396          Res->Destroy(Context);
5397          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5398            << Res->getType());
5399        }
5400
5401        // FIXME: C++: Verify that operator[] isn't overloaded.
5402
5403        // Promote the array so it looks more like a normal array subscript
5404        // expression.
5405        DefaultFunctionArrayConversion(Res);
5406
5407        // C99 6.5.2.1p1
5408        Expr *Idx = static_cast<Expr*>(OC.U.E);
5409        // FIXME: Leaks Res
5410        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
5411          return ExprError(Diag(Idx->getLocStart(),
5412                                diag::err_typecheck_subscript_not_integer)
5413            << Idx->getSourceRange());
5414
5415        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5416                                               OC.LocEnd);
5417        continue;
5418      }
5419
5420      const RecordType *RC = Res->getType()->getAs<RecordType>();
5421      if (!RC) {
5422        Res->Destroy(Context);
5423        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5424          << Res->getType());
5425      }
5426
5427      // Get the decl corresponding to this.
5428      RecordDecl *RD = RC->getDecl();
5429      if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5430        if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
5431          ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5432            << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5433            << Res->getType());
5434          DidWarnAboutNonPOD = true;
5435        }
5436      }
5437
5438      FieldDecl *MemberDecl
5439        = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
5440                                                          LookupMemberName)
5441                                        .getAsDecl());
5442      // FIXME: Leaks Res
5443      if (!MemberDecl)
5444        return ExprError(Diag(BuiltinLoc, diag::err_typecheck_no_member)
5445         << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd));
5446
5447      // FIXME: C++: Verify that MemberDecl isn't a static field.
5448      // FIXME: Verify that MemberDecl isn't a bitfield.
5449      if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
5450        Res = BuildAnonymousStructUnionMemberReference(
5451            SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
5452      } else {
5453        // MemberDecl->getType() doesn't get the right qualifiers, but it
5454        // doesn't matter here.
5455        Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5456                MemberDecl->getType().getNonReferenceType());
5457      }
5458    }
5459  }
5460
5461  return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5462                                           Context.getSizeType(), BuiltinLoc));
5463}
5464
5465
5466Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5467                                                      TypeTy *arg1,TypeTy *arg2,
5468                                                      SourceLocation RPLoc) {
5469  // FIXME: Preserve type source info.
5470  QualType argT1 = GetTypeFromParser(arg1);
5471  QualType argT2 = GetTypeFromParser(arg2);
5472
5473  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
5474
5475  if (getLangOptions().CPlusPlus) {
5476    Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5477      << SourceRange(BuiltinLoc, RPLoc);
5478    return ExprError();
5479  }
5480
5481  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5482                                                 argT1, argT2, RPLoc));
5483}
5484
5485Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5486                                             ExprArg cond,
5487                                             ExprArg expr1, ExprArg expr2,
5488                                             SourceLocation RPLoc) {
5489  Expr *CondExpr = static_cast<Expr*>(cond.get());
5490  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5491  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
5492
5493  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5494
5495  QualType resType;
5496  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
5497    resType = Context.DependentTy;
5498  } else {
5499    // The conditional expression is required to be a constant expression.
5500    llvm::APSInt condEval(32);
5501    SourceLocation ExpLoc;
5502    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
5503      return ExprError(Diag(ExpLoc,
5504                       diag::err_typecheck_choose_expr_requires_constant)
5505        << CondExpr->getSourceRange());
5506
5507    // If the condition is > zero, then the AST type is the same as the LSHExpr.
5508    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5509  }
5510
5511  cond.release(); expr1.release(); expr2.release();
5512  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5513                                        resType, RPLoc));
5514}
5515
5516//===----------------------------------------------------------------------===//
5517// Clang Extensions.
5518//===----------------------------------------------------------------------===//
5519
5520/// ActOnBlockStart - This callback is invoked when a block literal is started.
5521void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
5522  // Analyze block parameters.
5523  BlockSemaInfo *BSI = new BlockSemaInfo();
5524
5525  // Add BSI to CurBlock.
5526  BSI->PrevBlockInfo = CurBlock;
5527  CurBlock = BSI;
5528
5529  BSI->ReturnType = QualType();
5530  BSI->TheScope = BlockScope;
5531  BSI->hasBlockDeclRefExprs = false;
5532  BSI->hasPrototype = false;
5533  BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5534  CurFunctionNeedsScopeChecking = false;
5535
5536  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
5537  PushDeclContext(BlockScope, BSI->TheDecl);
5538}
5539
5540void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
5541  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
5542
5543  if (ParamInfo.getNumTypeObjects() == 0
5544      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5545    ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5546    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5547
5548    if (T->isArrayType()) {
5549      Diag(ParamInfo.getSourceRange().getBegin(),
5550           diag::err_block_returns_array);
5551      return;
5552    }
5553
5554    // The parameter list is optional, if there was none, assume ().
5555    if (!T->isFunctionType())
5556      T = Context.getFunctionType(T, NULL, 0, 0, 0);
5557
5558    CurBlock->hasPrototype = true;
5559    CurBlock->isVariadic = false;
5560    // Check for a valid sentinel attribute on this block.
5561    if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5562      Diag(ParamInfo.getAttributes()->getLoc(),
5563           diag::warn_attribute_sentinel_not_variadic) << 1;
5564      // FIXME: remove the attribute.
5565    }
5566    QualType RetTy = T.getTypePtr()->getAsFunctionType()->getResultType();
5567
5568    // Do not allow returning a objc interface by-value.
5569    if (RetTy->isObjCInterfaceType()) {
5570      Diag(ParamInfo.getSourceRange().getBegin(),
5571           diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5572      return;
5573    }
5574    return;
5575  }
5576
5577  // Analyze arguments to block.
5578  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5579         "Not a function declarator!");
5580  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
5581
5582  CurBlock->hasPrototype = FTI.hasPrototype;
5583  CurBlock->isVariadic = true;
5584
5585  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5586  // no arguments, not a function that takes a single void argument.
5587  if (FTI.hasPrototype &&
5588      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5589     (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5590        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
5591    // empty arg list, don't push any params.
5592    CurBlock->isVariadic = false;
5593  } else if (FTI.hasPrototype) {
5594    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
5595      CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
5596    CurBlock->isVariadic = FTI.isVariadic;
5597  }
5598  CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
5599                               CurBlock->Params.size());
5600  CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
5601  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5602  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5603       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5604    // If this has an identifier, add it to the scope stack.
5605    if ((*AI)->getIdentifier())
5606      PushOnScopeChains(*AI, CurBlock->TheScope);
5607
5608  // Check for a valid sentinel attribute on this block.
5609  if (!CurBlock->isVariadic &&
5610      CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5611    Diag(ParamInfo.getAttributes()->getLoc(),
5612         diag::warn_attribute_sentinel_not_variadic) << 1;
5613    // FIXME: remove the attribute.
5614  }
5615
5616  // Analyze the return type.
5617  QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5618  QualType RetTy = T->getAsFunctionType()->getResultType();
5619
5620  // Do not allow returning a objc interface by-value.
5621  if (RetTy->isObjCInterfaceType()) {
5622    Diag(ParamInfo.getSourceRange().getBegin(),
5623         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5624  } else if (!RetTy->isDependentType())
5625    CurBlock->ReturnType = RetTy;
5626}
5627
5628/// ActOnBlockError - If there is an error parsing a block, this callback
5629/// is invoked to pop the information about the block from the action impl.
5630void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5631  // Ensure that CurBlock is deleted.
5632  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
5633
5634  CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5635
5636  // Pop off CurBlock, handle nested blocks.
5637  PopDeclContext();
5638  CurBlock = CurBlock->PrevBlockInfo;
5639  // FIXME: Delete the ParmVarDecl objects as well???
5640}
5641
5642/// ActOnBlockStmtExpr - This is called when the body of a block statement
5643/// literal was successfully completed.  ^(int x){...}
5644Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5645                                                StmtArg body, Scope *CurScope) {
5646  // If blocks are disabled, emit an error.
5647  if (!LangOpts.Blocks)
5648    Diag(CaretLoc, diag::err_blocks_disable);
5649
5650  // Ensure that CurBlock is deleted.
5651  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
5652
5653  PopDeclContext();
5654
5655  // Pop off CurBlock, handle nested blocks.
5656  CurBlock = CurBlock->PrevBlockInfo;
5657
5658  QualType RetTy = Context.VoidTy;
5659  if (!BSI->ReturnType.isNull())
5660    RetTy = BSI->ReturnType;
5661
5662  llvm::SmallVector<QualType, 8> ArgTypes;
5663  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5664    ArgTypes.push_back(BSI->Params[i]->getType());
5665
5666  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
5667  QualType BlockTy;
5668  if (!BSI->hasPrototype)
5669    BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5670                                      NoReturn);
5671  else
5672    BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
5673                                      BSI->isVariadic, 0, false, false, 0, 0,
5674                                      NoReturn);
5675
5676  // FIXME: Check that return/parameter types are complete/non-abstract
5677  DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
5678  BlockTy = Context.getBlockPointerType(BlockTy);
5679
5680  // If needed, diagnose invalid gotos and switches in the block.
5681  if (CurFunctionNeedsScopeChecking)
5682    DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5683  CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5684
5685  BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
5686  CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
5687  return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5688                                       BSI->hasBlockDeclRefExprs));
5689}
5690
5691Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5692                                        ExprArg expr, TypeTy *type,
5693                                        SourceLocation RPLoc) {
5694  QualType T = GetTypeFromParser(type);
5695  Expr *E = static_cast<Expr*>(expr.get());
5696  Expr *OrigExpr = E;
5697
5698  InitBuiltinVaListType();
5699
5700  // Get the va_list type
5701  QualType VaListType = Context.getBuiltinVaListType();
5702  if (VaListType->isArrayType()) {
5703    // Deal with implicit array decay; for example, on x86-64,
5704    // va_list is an array, but it's supposed to decay to
5705    // a pointer for va_arg.
5706    VaListType = Context.getArrayDecayedType(VaListType);
5707    // Make sure the input expression also decays appropriately.
5708    UsualUnaryConversions(E);
5709  } else {
5710    // Otherwise, the va_list argument must be an l-value because
5711    // it is modified by va_arg.
5712    if (!E->isTypeDependent() &&
5713        CheckForModifiableLvalue(E, BuiltinLoc, *this))
5714      return ExprError();
5715  }
5716
5717  if (!E->isTypeDependent() &&
5718      !Context.hasSameType(VaListType, E->getType())) {
5719    return ExprError(Diag(E->getLocStart(),
5720                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
5721      << OrigExpr->getType() << E->getSourceRange());
5722  }
5723
5724  // FIXME: Check that type is complete/non-abstract
5725  // FIXME: Warn if a non-POD type is passed in.
5726
5727  expr.release();
5728  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5729                                       RPLoc));
5730}
5731
5732Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
5733  // The type of __null will be int or long, depending on the size of
5734  // pointers on the target.
5735  QualType Ty;
5736  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
5737    Ty = Context.IntTy;
5738  else
5739    Ty = Context.LongTy;
5740
5741  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
5742}
5743
5744bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
5745                                    SourceLocation Loc,
5746                                    QualType DstType, QualType SrcType,
5747                                    Expr *SrcExpr, const char *Flavor) {
5748  // Decode the result (notice that AST's are still created for extensions).
5749  bool isInvalid = false;
5750  unsigned DiagKind;
5751  switch (ConvTy) {
5752  default: assert(0 && "Unknown conversion type");
5753  case Compatible: return false;
5754  case PointerToInt:
5755    DiagKind = diag::ext_typecheck_convert_pointer_int;
5756    break;
5757  case IntToPointer:
5758    DiagKind = diag::ext_typecheck_convert_int_pointer;
5759    break;
5760  case IncompatiblePointer:
5761    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
5762    break;
5763  case IncompatiblePointerSign:
5764    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
5765    break;
5766  case FunctionVoidPointer:
5767    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
5768    break;
5769  case CompatiblePointerDiscardsQualifiers:
5770    // If the qualifiers lost were because we were applying the
5771    // (deprecated) C++ conversion from a string literal to a char*
5772    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
5773    // Ideally, this check would be performed in
5774    // CheckPointerTypesForAssignment. However, that would require a
5775    // bit of refactoring (so that the second argument is an
5776    // expression, rather than a type), which should be done as part
5777    // of a larger effort to fix CheckPointerTypesForAssignment for
5778    // C++ semantics.
5779    if (getLangOptions().CPlusPlus &&
5780        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
5781      return false;
5782    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
5783    break;
5784  case IntToBlockPointer:
5785    DiagKind = diag::err_int_to_block_pointer;
5786    break;
5787  case IncompatibleBlockPointer:
5788    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
5789    break;
5790  case IncompatibleObjCQualifiedId:
5791    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
5792    // it can give a more specific diagnostic.
5793    DiagKind = diag::warn_incompatible_qualified_id;
5794    break;
5795  case IncompatibleVectors:
5796    DiagKind = diag::warn_incompatible_vectors;
5797    break;
5798  case Incompatible:
5799    DiagKind = diag::err_typecheck_convert_incompatible;
5800    isInvalid = true;
5801    break;
5802  }
5803
5804  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
5805    << SrcExpr->getSourceRange();
5806  return isInvalid;
5807}
5808
5809bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
5810  llvm::APSInt ICEResult;
5811  if (E->isIntegerConstantExpr(ICEResult, Context)) {
5812    if (Result)
5813      *Result = ICEResult;
5814    return false;
5815  }
5816
5817  Expr::EvalResult EvalResult;
5818
5819  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
5820      EvalResult.HasSideEffects) {
5821    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
5822
5823    if (EvalResult.Diag) {
5824      // We only show the note if it's not the usual "invalid subexpression"
5825      // or if it's actually in a subexpression.
5826      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
5827          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
5828        Diag(EvalResult.DiagLoc, EvalResult.Diag);
5829    }
5830
5831    return true;
5832  }
5833
5834  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
5835    E->getSourceRange();
5836
5837  if (EvalResult.Diag &&
5838      Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
5839    Diag(EvalResult.DiagLoc, EvalResult.Diag);
5840
5841  if (Result)
5842    *Result = EvalResult.Val.getInt();
5843  return false;
5844}
5845
5846Sema::ExpressionEvaluationContext
5847Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
5848  // Introduce a new set of potentially referenced declarations to the stack.
5849  if (NewContext == PotentiallyPotentiallyEvaluated)
5850    PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
5851
5852  std::swap(ExprEvalContext, NewContext);
5853  return NewContext;
5854}
5855
5856void
5857Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
5858                                     ExpressionEvaluationContext NewContext) {
5859  ExprEvalContext = NewContext;
5860
5861  if (OldContext == PotentiallyPotentiallyEvaluated) {
5862    // Mark any remaining declarations in the current position of the stack
5863    // as "referenced". If they were not meant to be referenced, semantic
5864    // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
5865    PotentiallyReferencedDecls RemainingDecls;
5866    RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
5867    PotentiallyReferencedDeclStack.pop_back();
5868
5869    for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
5870                                           IEnd = RemainingDecls.end();
5871         I != IEnd; ++I)
5872      MarkDeclarationReferenced(I->first, I->second);
5873  }
5874}
5875
5876/// \brief Note that the given declaration was referenced in the source code.
5877///
5878/// This routine should be invoke whenever a given declaration is referenced
5879/// in the source code, and where that reference occurred. If this declaration
5880/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
5881/// C99 6.9p3), then the declaration will be marked as used.
5882///
5883/// \param Loc the location where the declaration was referenced.
5884///
5885/// \param D the declaration that has been referenced by the source code.
5886void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
5887  assert(D && "No declaration?");
5888
5889  if (D->isUsed())
5890    return;
5891
5892  // Mark a parameter declaration "used", regardless of whether we're in a
5893  // template or not.
5894  if (isa<ParmVarDecl>(D))
5895    D->setUsed(true);
5896
5897  // Do not mark anything as "used" within a dependent context; wait for
5898  // an instantiation.
5899  if (CurContext->isDependentContext())
5900    return;
5901
5902  switch (ExprEvalContext) {
5903    case Unevaluated:
5904      // We are in an expression that is not potentially evaluated; do nothing.
5905      return;
5906
5907    case PotentiallyEvaluated:
5908      // We are in a potentially-evaluated expression, so this declaration is
5909      // "used"; handle this below.
5910      break;
5911
5912    case PotentiallyPotentiallyEvaluated:
5913      // We are in an expression that may be potentially evaluated; queue this
5914      // declaration reference until we know whether the expression is
5915      // potentially evaluated.
5916      PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
5917      return;
5918  }
5919
5920  // Note that this declaration has been used.
5921  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
5922    unsigned TypeQuals;
5923    if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
5924        if (!Constructor->isUsed())
5925          DefineImplicitDefaultConstructor(Loc, Constructor);
5926    } else if (Constructor->isImplicit() &&
5927               Constructor->isCopyConstructor(Context, TypeQuals)) {
5928      if (!Constructor->isUsed())
5929        DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
5930    }
5931  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
5932    if (Destructor->isImplicit() && !Destructor->isUsed())
5933      DefineImplicitDestructor(Loc, Destructor);
5934
5935  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
5936    if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
5937        MethodDecl->getOverloadedOperator() == OO_Equal) {
5938      if (!MethodDecl->isUsed())
5939        DefineImplicitOverloadedAssign(Loc, MethodDecl);
5940    }
5941  }
5942  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
5943    // Implicit instantiation of function templates and member functions of
5944    // class templates.
5945    if (!Function->getBody()) {
5946      // FIXME: distinguish between implicit instantiations of function
5947      // templates and explicit specializations (the latter don't get
5948      // instantiated, naturally).
5949      if (Function->getInstantiatedFromMemberFunction() ||
5950          Function->getPrimaryTemplate())
5951        PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
5952    }
5953
5954
5955    // FIXME: keep track of references to static functions
5956    Function->setUsed(true);
5957    return;
5958  }
5959
5960  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
5961    // Implicit instantiation of static data members of class templates.
5962    // FIXME: distinguish between implicit instantiations (which we need to
5963    // actually instantiate) and explicit specializations.
5964    if (Var->isStaticDataMember() &&
5965        Var->getInstantiatedFromStaticDataMember())
5966      PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
5967
5968    // FIXME: keep track of references to static data?
5969
5970    D->setUsed(true);
5971    return;
5972}
5973}
5974
5975