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