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