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