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