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