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