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