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