SemaExpr.cpp revision 5205938085c9bb3123b20745be5719d8d3be4b60
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/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Parse/DeclSpec.h"
25#include "clang/Parse/Scope.h"
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29//  Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
32/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34  QualType Ty = E->getType();
35  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37  if (const ReferenceType *ref = Ty->getAsReferenceType()) {
38    ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
39    Ty = E->getType();
40  }
41  if (Ty->isFunctionType())
42    ImpCastExprToType(E, Context.getPointerType(Ty));
43  else if (Ty->isArrayType()) {
44    // In C90 mode, arrays only promote to pointers if the array expression is
45    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
46    // type 'array of type' is converted to an expression that has type 'pointer
47    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
48    // that has type 'array of type' ...".  The relevant change is "an lvalue"
49    // (C90) to "an expression" (C99).
50    //
51    // C++ 4.2p1:
52    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
53    // T" can be converted to an rvalue of type "pointer to T".
54    //
55    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
56        E->isLvalue(Context) == Expr::LV_Valid)
57      ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
58  }
59}
60
61/// UsualUnaryConversions - Performs various conversions that are common to most
62/// operators (C99 6.3). The conversions of array and function types are
63/// sometimes surpressed. For example, the array->pointer conversion doesn't
64/// apply if the array is an argument to the sizeof or address (&) operators.
65/// In these instances, this routine should *not* be called.
66Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
67  QualType Ty = Expr->getType();
68  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
69
70  if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
71    ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
72    Ty = Expr->getType();
73  }
74  if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
75    ImpCastExprToType(Expr, Context.IntTy);
76  else
77    DefaultFunctionArrayConversion(Expr);
78
79  return Expr;
80}
81
82/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
83/// do not have a prototype. Arguments that have type float are promoted to
84/// double. All other argument types are converted by UsualUnaryConversions().
85void Sema::DefaultArgumentPromotion(Expr *&Expr) {
86  QualType Ty = Expr->getType();
87  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
88
89  // If this is a 'float' (CVR qualified or typedef) promote to double.
90  if (const BuiltinType *BT = Ty->getAsBuiltinType())
91    if (BT->getKind() == BuiltinType::Float)
92      return ImpCastExprToType(Expr, Context.DoubleTy);
93
94  UsualUnaryConversions(Expr);
95}
96
97/// UsualArithmeticConversions - Performs various conversions that are common to
98/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
99/// routine returns the first non-arithmetic type found. The client is
100/// responsible for emitting appropriate error diagnostics.
101/// FIXME: verify the conversion rules for "complex int" are consistent with
102/// GCC.
103QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
104                                          bool isCompAssign) {
105  if (!isCompAssign) {
106    UsualUnaryConversions(lhsExpr);
107    UsualUnaryConversions(rhsExpr);
108  }
109  // For conversion purposes, we ignore any qualifiers.
110  // For example, "const float" and "float" are equivalent.
111  QualType lhs =
112    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
113  QualType rhs =
114    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
115
116  // If both types are identical, no conversion is needed.
117  if (lhs == rhs)
118    return lhs;
119
120  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
121  // The caller can deal with this (e.g. pointer + int).
122  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
123    return lhs;
124
125  // At this point, we have two different arithmetic types.
126
127  // Handle complex types first (C99 6.3.1.8p1).
128  if (lhs->isComplexType() || rhs->isComplexType()) {
129    // if we have an integer operand, the result is the complex type.
130    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
131      // convert the rhs to the lhs complex type.
132      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
133      return lhs;
134    }
135    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
136      // convert the lhs to the rhs complex type.
137      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
138      return rhs;
139    }
140    // This handles complex/complex, complex/float, or float/complex.
141    // When both operands are complex, the shorter operand is converted to the
142    // type of the longer, and that is the type of the result. This corresponds
143    // to what is done when combining two real floating-point operands.
144    // The fun begins when size promotion occur across type domains.
145    // From H&S 6.3.4: When one operand is complex and the other is a real
146    // floating-point type, the less precise type is converted, within it's
147    // real or complex domain, to the precision of the other type. For example,
148    // when combining a "long double" with a "double _Complex", the
149    // "double _Complex" is promoted to "long double _Complex".
150    int result = Context.getFloatingTypeOrder(lhs, rhs);
151
152    if (result > 0) { // The left side is bigger, convert rhs.
153      rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
154      if (!isCompAssign)
155        ImpCastExprToType(rhsExpr, rhs);
156    } else if (result < 0) { // The right side is bigger, convert lhs.
157      lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
158      if (!isCompAssign)
159        ImpCastExprToType(lhsExpr, lhs);
160    }
161    // At this point, lhs and rhs have the same rank/size. Now, make sure the
162    // domains match. This is a requirement for our implementation, C99
163    // does not require this promotion.
164    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
165      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
166        if (!isCompAssign)
167          ImpCastExprToType(lhsExpr, rhs);
168        return rhs;
169      } else { // handle "_Complex double, double".
170        if (!isCompAssign)
171          ImpCastExprToType(rhsExpr, lhs);
172        return lhs;
173      }
174    }
175    return lhs; // The domain/size match exactly.
176  }
177  // Now handle "real" floating types (i.e. float, double, long double).
178  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
179    // if we have an integer operand, the result is the real floating type.
180    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
181      // convert rhs to the lhs floating point type.
182      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
183      return lhs;
184    }
185    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
186      // convert lhs to the rhs floating point type.
187      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
188      return rhs;
189    }
190    // We have two real floating types, float/complex combos were handled above.
191    // Convert the smaller operand to the bigger result.
192    int result = Context.getFloatingTypeOrder(lhs, rhs);
193
194    if (result > 0) { // convert the rhs
195      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
196      return lhs;
197    }
198    if (result < 0) { // convert the lhs
199      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
200      return rhs;
201    }
202    assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
203  }
204  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
205    // Handle GCC complex int extension.
206    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
207    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
208
209    if (lhsComplexInt && rhsComplexInt) {
210      if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
211                                      rhsComplexInt->getElementType()) >= 0) {
212        // convert the rhs
213        if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
214        return lhs;
215      }
216      if (!isCompAssign)
217        ImpCastExprToType(lhsExpr, rhs); // convert the lhs
218      return rhs;
219    } else if (lhsComplexInt && rhs->isIntegerType()) {
220      // convert the rhs to the lhs complex type.
221      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
222      return lhs;
223    } else if (rhsComplexInt && lhs->isIntegerType()) {
224      // convert the lhs to the rhs complex type.
225      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
226      return rhs;
227    }
228  }
229  // Finally, we have two differing integer types.
230  // The rules for this case are in C99 6.3.1.8
231  int compare = Context.getIntegerTypeOrder(lhs, rhs);
232  bool lhsSigned = lhs->isSignedIntegerType(),
233       rhsSigned = rhs->isSignedIntegerType();
234  QualType destType;
235  if (lhsSigned == rhsSigned) {
236    // Same signedness; use the higher-ranked type
237    destType = compare >= 0 ? lhs : rhs;
238  } else if (compare != (lhsSigned ? 1 : -1)) {
239    // The unsigned type has greater than or equal rank to the
240    // signed type, so use the unsigned type
241    destType = lhsSigned ? rhs : lhs;
242  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
243    // The two types are different widths; if we are here, that
244    // means the signed type is larger than the unsigned type, so
245    // use the signed type.
246    destType = lhsSigned ? lhs : rhs;
247  } else {
248    // The signed type is higher-ranked than the unsigned type,
249    // but isn't actually any bigger (like unsigned int and long
250    // on most 32-bit systems).  Use the unsigned type corresponding
251    // to the signed type.
252    destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
253  }
254  if (!isCompAssign) {
255    ImpCastExprToType(lhsExpr, destType);
256    ImpCastExprToType(rhsExpr, destType);
257  }
258  return destType;
259}
260
261//===----------------------------------------------------------------------===//
262//  Semantic Analysis for various Expression Types
263//===----------------------------------------------------------------------===//
264
265
266/// ActOnStringLiteral - The specified tokens were lexed as pasted string
267/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
268/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
269/// multiple tokens.  However, the common case is that StringToks points to one
270/// string.
271///
272Action::ExprResult
273Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
274  assert(NumStringToks && "Must have at least one string!");
275
276  StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
277  if (Literal.hadError)
278    return ExprResult(true);
279
280  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
281  for (unsigned i = 0; i != NumStringToks; ++i)
282    StringTokLocs.push_back(StringToks[i].getLocation());
283
284  // Verify that pascal strings aren't too large.
285  if (Literal.Pascal && Literal.GetStringLength() > 256)
286    return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
287                SourceRange(StringToks[0].getLocation(),
288                            StringToks[NumStringToks-1].getLocation()));
289
290  QualType StrTy = Context.CharTy;
291  if (Literal.AnyWide) StrTy = Context.getWCharType();
292  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
293
294  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
295  if (getLangOptions().CPlusPlus)
296    StrTy.addConst();
297
298  // Get an array type for the string, according to C99 6.4.5.  This includes
299  // the nul terminator character as well as the string length for pascal
300  // strings.
301  StrTy = Context.getConstantArrayType(StrTy,
302                                   llvm::APInt(32, Literal.GetStringLength()+1),
303                                       ArrayType::Normal, 0);
304
305  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
306  return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
307                           Literal.AnyWide, StrTy,
308                           StringToks[0].getLocation(),
309                           StringToks[NumStringToks-1].getLocation());
310}
311
312/// ActOnIdentifierExpr - The parser read an identifier in expression context,
313/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
314/// identifier is used in a function call context.
315Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
316                                           IdentifierInfo &II,
317                                           bool HasTrailingLParen) {
318  // Could be enum-constant, value decl, instance variable, etc.
319  Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
320
321  // If this reference is in an Objective-C method, then ivar lookup happens as
322  // well.
323  if (getCurMethodDecl()) {
324    ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
325    // There are two cases to handle here.  1) scoped lookup could have failed,
326    // in which case we should look for an ivar.  2) scoped lookup could have
327    // found a decl, but that decl is outside the current method (i.e. a global
328    // variable).  In these two cases, we do a lookup for an ivar with this
329    // name, if the lookup suceeds, we replace it our current decl.
330    if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
331      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
332      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II)) {
333        // FIXME: This should use a new expr for a direct reference, don't turn
334        // this into Self->ivar, just return a BareIVarExpr or something.
335        IdentifierInfo &II = Context.Idents.get("self");
336        ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
337        return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
338                                 static_cast<Expr*>(SelfExpr.Val), true, true);
339      }
340    }
341    // Needed to implement property "super.method" notation.
342    if (SD == 0 && &II == SuperID) {
343      QualType T = Context.getPointerType(Context.getObjCInterfaceType(
344                     getCurMethodDecl()->getClassInterface()));
345      return new PredefinedExpr(Loc, T, PredefinedExpr::ObjCSuper);
346    }
347  }
348  if (D == 0) {
349    // Otherwise, this could be an implicitly declared function reference (legal
350    // in C90, extension in C99).
351    if (HasTrailingLParen &&
352        !getLangOptions().CPlusPlus) // Not in C++.
353      D = ImplicitlyDefineFunction(Loc, II, S);
354    else {
355      // If this name wasn't predeclared and if this is not a function call,
356      // diagnose the problem.
357      return Diag(Loc, diag::err_undeclared_var_use, II.getName());
358    }
359  }
360
361  if (CXXFieldDecl *FD = dyn_cast<CXXFieldDecl>(D)) {
362    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
363      if (MD->isStatic())
364        // "invalid use of member 'x' in static member function"
365        return Diag(Loc, diag::err_invalid_member_use_in_static_method,
366                    FD->getName());
367      if (cast<CXXRecordDecl>(MD->getParent()) != FD->getParent())
368        // "invalid use of nonstatic data member 'x'"
369        return Diag(Loc, diag::err_invalid_non_static_member_use,
370                    FD->getName());
371
372      if (FD->isInvalidDecl())
373        return true;
374
375      // FIXME: Use DeclRefExpr or a new Expr for a direct CXXField reference.
376      ExprResult ThisExpr = ActOnCXXThis(SourceLocation());
377      return new MemberExpr(static_cast<Expr*>(ThisExpr.Val),
378                            true, FD, Loc, FD->getType());
379    }
380
381    return Diag(Loc, diag::err_invalid_non_static_member_use, FD->getName());
382  }
383  if (isa<TypedefDecl>(D))
384    return Diag(Loc, diag::err_unexpected_typedef, II.getName());
385  if (isa<ObjCInterfaceDecl>(D))
386    return Diag(Loc, diag::err_unexpected_interface, II.getName());
387  if (isa<NamespaceDecl>(D))
388    return Diag(Loc, diag::err_unexpected_namespace, II.getName());
389
390  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
391  ValueDecl *VD = cast<ValueDecl>(D);
392
393  // check if referencing an identifier with __attribute__((deprecated)).
394  if (VD->getAttr<DeprecatedAttr>())
395    Diag(Loc, diag::warn_deprecated, VD->getName());
396
397  // Only create DeclRefExpr's for valid Decl's.
398  if (VD->isInvalidDecl())
399    return true;
400
401  // FIXME: This will create BlockDeclRefExprs for global variables,
402  // function references, etc which is suboptimal :) and breaks
403  // things like "integer constant expression" tests.
404  //
405  if (CurBlock && (CurBlock->TheDecl != VD->getDeclContext()) &&
406      !isa<EnumConstantDecl>(VD)) {
407    // If we are in a block and the variable is outside the current block,
408    // bind the variable reference with a BlockDeclRefExpr.
409
410    // The BlocksAttr indicates the variable is bound by-reference.
411    if (VD->getAttr<BlocksAttr>())
412      return new BlockDeclRefExpr(VD, VD->getType(), Loc, true);
413
414    // Variable will be bound by-copy, make it const within the closure.
415    VD->getType().addConst();
416    return new BlockDeclRefExpr(VD, VD->getType(), Loc, false);
417  }
418  // If this reference is not in a block or if the referenced variable is
419  // within the block, create a normal DeclRefExpr.
420  return new DeclRefExpr(VD, VD->getType(), Loc);
421}
422
423Sema::ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
424                                           tok::TokenKind Kind) {
425  PredefinedExpr::IdentType IT;
426
427  switch (Kind) {
428  default: assert(0 && "Unknown simple primary expr!");
429  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
430  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
431  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
432  }
433
434  // Verify that this is in a function context.
435  if (getCurFunctionDecl() == 0 && getCurMethodDecl() == 0)
436    return Diag(Loc, diag::err_predef_outside_function);
437
438  // Pre-defined identifiers are of type char[x], where x is the length of the
439  // string.
440  unsigned Length;
441  if (getCurFunctionDecl())
442    Length = getCurFunctionDecl()->getIdentifier()->getLength();
443  else
444    Length = getCurMethodDecl()->getSynthesizedMethodSize();
445
446  llvm::APInt LengthI(32, Length + 1);
447  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
448  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
449  return new PredefinedExpr(Loc, ResTy, IT);
450}
451
452Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
453  llvm::SmallString<16> CharBuffer;
454  CharBuffer.resize(Tok.getLength());
455  const char *ThisTokBegin = &CharBuffer[0];
456  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
457
458  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
459                            Tok.getLocation(), PP);
460  if (Literal.hadError())
461    return ExprResult(true);
462
463  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
464
465  return new CharacterLiteral(Literal.getValue(), Literal.isWide(), type,
466                              Tok.getLocation());
467}
468
469Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
470  // fast path for a single digit (which is quite common). A single digit
471  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
472  if (Tok.getLength() == 1) {
473    const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
474
475    unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
476    return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
477                                         Context.IntTy,
478                                         Tok.getLocation()));
479  }
480  llvm::SmallString<512> IntegerBuffer;
481  // Add padding so that NumericLiteralParser can overread by one character.
482  IntegerBuffer.resize(Tok.getLength()+1);
483  const char *ThisTokBegin = &IntegerBuffer[0];
484
485  // Get the spelling of the token, which eliminates trigraphs, etc.
486  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
487
488  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
489                               Tok.getLocation(), PP);
490  if (Literal.hadError)
491    return ExprResult(true);
492
493  Expr *Res;
494
495  if (Literal.isFloatingLiteral()) {
496    QualType Ty;
497    if (Literal.isFloat)
498      Ty = Context.FloatTy;
499    else if (!Literal.isLong)
500      Ty = Context.DoubleTy;
501    else
502      Ty = Context.LongDoubleTy;
503
504    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
505
506    // isExact will be set by GetFloatValue().
507    bool isExact = false;
508    Res = new FloatingLiteral(Literal.GetFloatValue(Format, &isExact), &isExact,
509                              Ty, Tok.getLocation());
510
511  } else if (!Literal.isIntegerLiteral()) {
512    return ExprResult(true);
513  } else {
514    QualType Ty;
515
516    // long long is a C99 feature.
517    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
518        Literal.isLongLong)
519      Diag(Tok.getLocation(), diag::ext_longlong);
520
521    // Get the value in the widest-possible width.
522    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
523
524    if (Literal.GetIntegerValue(ResultVal)) {
525      // If this value didn't fit into uintmax_t, warn and force to ull.
526      Diag(Tok.getLocation(), diag::warn_integer_too_large);
527      Ty = Context.UnsignedLongLongTy;
528      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
529             "long long is not intmax_t?");
530    } else {
531      // If this value fits into a ULL, try to figure out what else it fits into
532      // according to the rules of C99 6.4.4.1p5.
533
534      // Octal, Hexadecimal, and integers with a U suffix are allowed to
535      // be an unsigned int.
536      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
537
538      // Check from smallest to largest, picking the smallest type we can.
539      unsigned Width = 0;
540      if (!Literal.isLong && !Literal.isLongLong) {
541        // Are int/unsigned possibilities?
542        unsigned IntSize = Context.Target.getIntWidth();
543
544        // Does it fit in a unsigned int?
545        if (ResultVal.isIntN(IntSize)) {
546          // Does it fit in a signed int?
547          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
548            Ty = Context.IntTy;
549          else if (AllowUnsigned)
550            Ty = Context.UnsignedIntTy;
551          Width = IntSize;
552        }
553      }
554
555      // Are long/unsigned long possibilities?
556      if (Ty.isNull() && !Literal.isLongLong) {
557        unsigned LongSize = Context.Target.getLongWidth();
558
559        // Does it fit in a unsigned long?
560        if (ResultVal.isIntN(LongSize)) {
561          // Does it fit in a signed long?
562          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
563            Ty = Context.LongTy;
564          else if (AllowUnsigned)
565            Ty = Context.UnsignedLongTy;
566          Width = LongSize;
567        }
568      }
569
570      // Finally, check long long if needed.
571      if (Ty.isNull()) {
572        unsigned LongLongSize = Context.Target.getLongLongWidth();
573
574        // Does it fit in a unsigned long long?
575        if (ResultVal.isIntN(LongLongSize)) {
576          // Does it fit in a signed long long?
577          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
578            Ty = Context.LongLongTy;
579          else if (AllowUnsigned)
580            Ty = Context.UnsignedLongLongTy;
581          Width = LongLongSize;
582        }
583      }
584
585      // If we still couldn't decide a type, we probably have something that
586      // does not fit in a signed long long, but has no U suffix.
587      if (Ty.isNull()) {
588        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
589        Ty = Context.UnsignedLongLongTy;
590        Width = Context.Target.getLongLongWidth();
591      }
592
593      if (ResultVal.getBitWidth() != Width)
594        ResultVal.trunc(Width);
595    }
596
597    Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
598  }
599
600  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
601  if (Literal.isImaginary)
602    Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
603
604  return Res;
605}
606
607Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
608                                        ExprTy *Val) {
609  Expr *E = (Expr *)Val;
610  assert((E != 0) && "ActOnParenExpr() missing expr");
611  return new ParenExpr(L, R, E);
612}
613
614/// The UsualUnaryConversions() function is *not* called by this routine.
615/// See C99 6.3.2.1p[2-4] for more details.
616QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
617                                         SourceLocation OpLoc,
618                                         const SourceRange &ExprRange,
619                                         bool isSizeof) {
620  // C99 6.5.3.4p1:
621  if (isa<FunctionType>(exprType) && isSizeof)
622    // alignof(function) is allowed.
623    Diag(OpLoc, diag::ext_sizeof_function_type, ExprRange);
624  else if (exprType->isVoidType())
625    Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof",
626         ExprRange);
627  else if (exprType->isIncompleteType()) {
628    Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
629                           diag::err_alignof_incomplete_type,
630         exprType.getAsString(), ExprRange);
631    return QualType(); // error
632  }
633  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
634  return Context.getSizeType();
635}
636
637Action::ExprResult Sema::
638ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
639                           SourceLocation LPLoc, TypeTy *Ty,
640                           SourceLocation RPLoc) {
641  // If error parsing type, ignore.
642  if (Ty == 0) return true;
643
644  // Verify that this is a valid expression.
645  QualType ArgTy = QualType::getFromOpaquePtr(Ty);
646
647  QualType resultType =
648    CheckSizeOfAlignOfOperand(ArgTy, OpLoc, SourceRange(LPLoc, RPLoc),isSizeof);
649
650  if (resultType.isNull())
651    return true;
652  return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
653}
654
655QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
656  DefaultFunctionArrayConversion(V);
657
658  // These operators return the element type of a complex type.
659  if (const ComplexType *CT = V->getType()->getAsComplexType())
660    return CT->getElementType();
661
662  // Otherwise they pass through real integer and floating point types here.
663  if (V->getType()->isArithmeticType())
664    return V->getType();
665
666  // Reject anything else.
667  Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
668  return QualType();
669}
670
671
672
673Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
674                                             tok::TokenKind Kind,
675                                             ExprTy *Input) {
676  UnaryOperator::Opcode Opc;
677  switch (Kind) {
678  default: assert(0 && "Unknown unary op!");
679  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
680  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
681  }
682  QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
683  if (result.isNull())
684    return true;
685  return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
686}
687
688Action::ExprResult Sema::
689ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
690                        ExprTy *Idx, SourceLocation RLoc) {
691  Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
692
693  // Perform default conversions.
694  DefaultFunctionArrayConversion(LHSExp);
695  DefaultFunctionArrayConversion(RHSExp);
696
697  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
698
699  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
700  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
701  // in the subscript position. As a result, we need to derive the array base
702  // and index from the expression types.
703  Expr *BaseExpr, *IndexExpr;
704  QualType ResultType;
705  if (const PointerType *PTy = LHSTy->getAsPointerType()) {
706    BaseExpr = LHSExp;
707    IndexExpr = RHSExp;
708    // FIXME: need to deal with const...
709    ResultType = PTy->getPointeeType();
710  } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
711     // Handle the uncommon case of "123[Ptr]".
712    BaseExpr = RHSExp;
713    IndexExpr = LHSExp;
714    // FIXME: need to deal with const...
715    ResultType = PTy->getPointeeType();
716  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
717    BaseExpr = LHSExp;    // vectors: V[123]
718    IndexExpr = RHSExp;
719
720    // Component access limited to variables (reject vec4.rg[1]).
721    if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
722        !isa<ExtVectorElementExpr>(BaseExpr))
723      return Diag(LLoc, diag::err_ext_vector_component_access,
724                  SourceRange(LLoc, RLoc));
725    // FIXME: need to deal with const...
726    ResultType = VTy->getElementType();
727  } else {
728    return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
729                RHSExp->getSourceRange());
730  }
731  // C99 6.5.2.1p1
732  if (!IndexExpr->getType()->isIntegerType())
733    return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
734                IndexExpr->getSourceRange());
735
736  // C99 6.5.2.1p1: "shall have type "pointer to *object* type".  In practice,
737  // the following check catches trying to index a pointer to a function (e.g.
738  // void (*)(int)) and pointers to incomplete types.  Functions are not
739  // objects in C99.
740  if (!ResultType->isObjectType())
741    return Diag(BaseExpr->getLocStart(),
742                diag::err_typecheck_subscript_not_object,
743                BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
744
745  return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
746}
747
748QualType Sema::
749CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
750                        IdentifierInfo &CompName, SourceLocation CompLoc) {
751  const ExtVectorType *vecType = baseType->getAsExtVectorType();
752
753  // This flag determines whether or not the component is to be treated as a
754  // special name, or a regular GLSL-style component access.
755  bool SpecialComponent = false;
756
757  // The vector accessor can't exceed the number of elements.
758  const char *compStr = CompName.getName();
759  if (strlen(compStr) > vecType->getNumElements()) {
760    Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
761                baseType.getAsString(), SourceRange(CompLoc));
762    return QualType();
763  }
764
765  // Check that we've found one of the special components, or that the component
766  // names must come from the same set.
767  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
768      !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
769    SpecialComponent = true;
770  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
771    do
772      compStr++;
773    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
774  } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
775    do
776      compStr++;
777    while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
778  } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
779    do
780      compStr++;
781    while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
782  }
783
784  if (!SpecialComponent && *compStr) {
785    // We didn't get to the end of the string. This means the component names
786    // didn't come from the same set *or* we encountered an illegal name.
787    Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
788         std::string(compStr,compStr+1), SourceRange(CompLoc));
789    return QualType();
790  }
791  // Each component accessor can't exceed the vector type.
792  compStr = CompName.getName();
793  while (*compStr) {
794    if (vecType->isAccessorWithinNumElements(*compStr))
795      compStr++;
796    else
797      break;
798  }
799  if (!SpecialComponent && *compStr) {
800    // We didn't get to the end of the string. This means a component accessor
801    // exceeds the number of elements in the vector.
802    Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
803                baseType.getAsString(), SourceRange(CompLoc));
804    return QualType();
805  }
806
807  // If we have a special component name, verify that the current vector length
808  // is an even number, since all special component names return exactly half
809  // the elements.
810  if (SpecialComponent && (vecType->getNumElements() & 1U)) {
811    Diag(OpLoc, diag::err_ext_vector_component_requires_even,
812         baseType.getAsString(), SourceRange(CompLoc));
813    return QualType();
814  }
815
816  // The component accessor looks fine - now we need to compute the actual type.
817  // The vector type is implied by the component accessor. For example,
818  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
819  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
820  unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
821                                       : strlen(CompName.getName());
822  if (CompSize == 1)
823    return vecType->getElementType();
824
825  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
826  // Now look up the TypeDefDecl from the vector type. Without this,
827  // diagostics look bad. We want extended vector types to appear built-in.
828  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
829    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
830      return Context.getTypedefType(ExtVectorDecls[i]);
831  }
832  return VT; // should never get here (a typedef type should always be found).
833}
834
835/// constructSetterName - Return the setter name for the given
836/// identifier, i.e. "set" + Name where the initial character of Name
837/// has been capitalized.
838// FIXME: Merge with same routine in Parser. But where should this
839// live?
840static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
841                                           const IdentifierInfo *Name) {
842  unsigned N = Name->getLength();
843  char *SelectorName = new char[3 + N];
844  memcpy(SelectorName, "set", 3);
845  memcpy(&SelectorName[3], Name->getName(), N);
846  SelectorName[3] = toupper(SelectorName[3]);
847
848  IdentifierInfo *Setter =
849    &Idents.get(SelectorName, &SelectorName[3 + N]);
850  delete[] SelectorName;
851  return Setter;
852}
853
854Action::ExprResult Sema::
855ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
856                         tok::TokenKind OpKind, SourceLocation MemberLoc,
857                         IdentifierInfo &Member) {
858  Expr *BaseExpr = static_cast<Expr *>(Base);
859  assert(BaseExpr && "no record expression");
860
861  // Perform default conversions.
862  DefaultFunctionArrayConversion(BaseExpr);
863
864  QualType BaseType = BaseExpr->getType();
865  assert(!BaseType.isNull() && "no type for member expression");
866
867  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
868  // must have pointer type, and the accessed type is the pointee.
869  if (OpKind == tok::arrow) {
870    if (const PointerType *PT = BaseType->getAsPointerType())
871      BaseType = PT->getPointeeType();
872    else
873      return Diag(MemberLoc, diag::err_typecheck_member_reference_arrow,
874                  BaseType.getAsString(), BaseExpr->getSourceRange());
875  }
876
877  // Handle field access to simple records.  This also handles access to fields
878  // of the ObjC 'id' struct.
879  if (const RecordType *RTy = BaseType->getAsRecordType()) {
880    RecordDecl *RDecl = RTy->getDecl();
881    if (RTy->isIncompleteType())
882      return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
883                  BaseExpr->getSourceRange());
884    // The record definition is complete, now make sure the member is valid.
885    FieldDecl *MemberDecl = RDecl->getMember(&Member);
886    if (!MemberDecl)
887      return Diag(MemberLoc, diag::err_typecheck_no_member, Member.getName(),
888                  BaseExpr->getSourceRange());
889
890    // Figure out the type of the member; see C99 6.5.2.3p3
891    // FIXME: Handle address space modifiers
892    QualType MemberType = MemberDecl->getType();
893    unsigned combinedQualifiers =
894        MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
895    MemberType = MemberType.getQualifiedType(combinedQualifiers);
896
897    return new MemberExpr(BaseExpr, OpKind == tok::arrow, MemberDecl,
898                          MemberLoc, MemberType);
899  }
900
901  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
902  // (*Obj).ivar.
903  if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
904    if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member))
905      return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
906                                 OpKind == tok::arrow);
907    return Diag(MemberLoc, diag::err_typecheck_member_reference_ivar,
908                IFTy->getDecl()->getName(), Member.getName(),
909                BaseExpr->getSourceRange());
910  }
911
912  // Handle Objective-C property access, which is "Obj.property" where Obj is a
913  // pointer to a (potentially qualified) interface type.
914  const PointerType *PTy;
915  const ObjCInterfaceType *IFTy;
916  if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
917      (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
918    ObjCInterfaceDecl *IFace = IFTy->getDecl();
919
920    // Search for a declared property first.
921    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
922      return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
923
924    // Check protocols on qualified interfaces.
925    for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
926         E = IFTy->qual_end(); I != E; ++I)
927      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
928        return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
929
930    // If that failed, look for an "implicit" property by seeing if the nullary
931    // selector is implemented.
932
933    // FIXME: The logic for looking up nullary and unary selectors should be
934    // shared with the code in ActOnInstanceMessage.
935
936    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
937    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
938
939    // If this reference is in an @implementation, check for 'private' methods.
940    if (!Getter)
941      if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
942        if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
943          if (ObjCImplementationDecl *ImpDecl =
944              ObjCImplementations[ClassDecl->getIdentifier()])
945            Getter = ImpDecl->getInstanceMethod(Sel);
946
947    if (Getter) {
948      // If we found a getter then this may be a valid dot-reference, we
949      // need to also look for the matching setter.
950      IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
951                                                       &Member);
952      Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
953      ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
954
955      if (!Setter) {
956        if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
957          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
958            if (ObjCImplementationDecl *ImpDecl =
959                ObjCImplementations[ClassDecl->getIdentifier()])
960              Setter = ImpDecl->getInstanceMethod(SetterSel);
961      }
962
963      // FIXME: There are some issues here. First, we are not
964      // diagnosing accesses to read-only properties because we do not
965      // know if this is a getter or setter yet. Second, we are
966      // checking that the type of the setter matches the type we
967      // expect.
968      return new ObjCPropertyRefExpr(Getter, Setter, Getter->getResultType(),
969                                     MemberLoc, BaseExpr);
970    }
971  }
972
973  // Handle 'field access' to vectors, such as 'V.xx'.
974  if (BaseType->isExtVectorType() && OpKind == tok::period) {
975    // Component access limited to variables (reject vec4.rg.g).
976    if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
977        !isa<ExtVectorElementExpr>(BaseExpr))
978      return Diag(MemberLoc, diag::err_ext_vector_component_access,
979                  BaseExpr->getSourceRange());
980    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
981    if (ret.isNull())
982      return true;
983    return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
984  }
985
986  return Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union,
987              BaseType.getAsString(), BaseExpr->getSourceRange());
988}
989
990/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
991/// This provides the location of the left/right parens and a list of comma
992/// locations.
993Action::ExprResult Sema::
994ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
995              ExprTy **args, unsigned NumArgs,
996              SourceLocation *CommaLocs, SourceLocation RParenLoc) {
997  Expr *Fn = static_cast<Expr *>(fn);
998  Expr **Args = reinterpret_cast<Expr**>(args);
999  assert(Fn && "no function call expression");
1000  FunctionDecl *FDecl = NULL;
1001
1002  // Promote the function operand.
1003  UsualUnaryConversions(Fn);
1004
1005  // If we're directly calling a function, get the declaration for
1006  // that function.
1007  if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
1008    if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
1009      FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1010
1011  // Make the call expr early, before semantic checks.  This guarantees cleanup
1012  // of arguments and function on error.
1013  llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
1014                                                 Context.BoolTy, RParenLoc));
1015  const FunctionType *FuncT;
1016  if (!Fn->getType()->isBlockPointerType()) {
1017    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1018    // have type pointer to function".
1019    const PointerType *PT = Fn->getType()->getAsPointerType();
1020    if (PT == 0)
1021      return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1022                  Fn->getSourceRange());
1023    FuncT = PT->getPointeeType()->getAsFunctionType();
1024  } else { // This is a block call.
1025    FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1026                getAsFunctionType();
1027  }
1028  if (FuncT == 0)
1029    return Diag(LParenLoc, diag::err_typecheck_call_not_function,
1030                Fn->getSourceRange());
1031
1032  // We know the result type of the call, set it.
1033  TheCall->setType(FuncT->getResultType());
1034
1035  if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
1036    // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1037    // assignment, to the types of the corresponding parameter, ...
1038    unsigned NumArgsInProto = Proto->getNumArgs();
1039    unsigned NumArgsToCheck = NumArgs;
1040
1041    // If too few arguments are available (and we don't have default
1042    // arguments for the remaining parameters), don't make the call.
1043    if (NumArgs < NumArgsInProto) {
1044      if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
1045        // Use default arguments for missing arguments
1046        NumArgsToCheck = NumArgsInProto;
1047        TheCall->setNumArgs(NumArgsInProto);
1048      } else
1049        return Diag(RParenLoc,
1050                    !Fn->getType()->isBlockPointerType()
1051                      ? diag::err_typecheck_call_too_few_args
1052                      : diag::err_typecheck_block_too_few_args,
1053                    Fn->getSourceRange());
1054    }
1055
1056    // If too many are passed and not variadic, error on the extras and drop
1057    // them.
1058    if (NumArgs > NumArgsInProto) {
1059      if (!Proto->isVariadic()) {
1060        Diag(Args[NumArgsInProto]->getLocStart(),
1061               !Fn->getType()->isBlockPointerType()
1062                 ? diag::err_typecheck_call_too_many_args
1063                 : diag::err_typecheck_block_too_many_args,
1064             Fn->getSourceRange(),
1065             SourceRange(Args[NumArgsInProto]->getLocStart(),
1066                         Args[NumArgs-1]->getLocEnd()));
1067        // This deletes the extra arguments.
1068        TheCall->setNumArgs(NumArgsInProto);
1069      }
1070      NumArgsToCheck = NumArgsInProto;
1071    }
1072
1073    // Continue to check argument types (even if we have too few/many args).
1074    for (unsigned i = 0; i != NumArgsToCheck; i++) {
1075      QualType ProtoArgType = Proto->getArgType(i);
1076
1077      Expr *Arg;
1078      if (i < NumArgs)
1079        Arg = Args[i];
1080      else
1081        Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
1082      QualType ArgType = Arg->getType();
1083
1084      // Compute implicit casts from the operand to the formal argument type.
1085      AssignConvertType ConvTy =
1086        CheckSingleAssignmentConstraints(ProtoArgType, Arg);
1087      TheCall->setArg(i, Arg);
1088
1089      if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
1090                                   ArgType, Arg, "passing"))
1091        return true;
1092    }
1093
1094    // If this is a variadic call, handle args passed through "...".
1095    if (Proto->isVariadic()) {
1096      // Promote the arguments (C99 6.5.2.2p7).
1097      for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1098        Expr *Arg = Args[i];
1099        DefaultArgumentPromotion(Arg);
1100        TheCall->setArg(i, Arg);
1101      }
1102    }
1103  } else {
1104    assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1105
1106    // Promote the arguments (C99 6.5.2.2p6).
1107    for (unsigned i = 0; i != NumArgs; i++) {
1108      Expr *Arg = Args[i];
1109      DefaultArgumentPromotion(Arg);
1110      TheCall->setArg(i, Arg);
1111    }
1112  }
1113
1114  // Do special checking on direct calls to functions.
1115  if (FDecl)
1116    return CheckFunctionCall(FDecl, TheCall.take());
1117
1118  return TheCall.take();
1119}
1120
1121Action::ExprResult Sema::
1122ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1123                     SourceLocation RParenLoc, ExprTy *InitExpr) {
1124  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
1125  QualType literalType = QualType::getFromOpaquePtr(Ty);
1126  // FIXME: put back this assert when initializers are worked out.
1127  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
1128  Expr *literalExpr = static_cast<Expr*>(InitExpr);
1129
1130  if (literalType->isArrayType()) {
1131    if (literalType->isVariableArrayType())
1132      return Diag(LParenLoc,
1133                  diag::err_variable_object_no_init,
1134                  SourceRange(LParenLoc,
1135                              literalExpr->getSourceRange().getEnd()));
1136  } else if (literalType->isIncompleteType()) {
1137    return Diag(LParenLoc,
1138                diag::err_typecheck_decl_incomplete_type,
1139                literalType.getAsString(),
1140                SourceRange(LParenLoc,
1141                            literalExpr->getSourceRange().getEnd()));
1142  }
1143
1144  if (CheckInitializerTypes(literalExpr, literalType))
1145    return true;
1146
1147  bool isFileScope = !getCurFunctionDecl() && !getCurMethodDecl();
1148  if (isFileScope) { // 6.5.2.5p3
1149    if (CheckForConstantInitializer(literalExpr, literalType))
1150      return true;
1151  }
1152  return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
1153}
1154
1155Action::ExprResult Sema::
1156ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
1157              SourceLocation RBraceLoc) {
1158  Expr **InitList = reinterpret_cast<Expr**>(initlist);
1159
1160  // Semantic analysis for initializers is done by ActOnDeclarator() and
1161  // CheckInitializer() - it requires knowledge of the object being intialized.
1162
1163  InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
1164  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
1165  return E;
1166}
1167
1168/// CheckCastTypes - Check type constraints for casting between types.
1169bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
1170  UsualUnaryConversions(castExpr);
1171
1172  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
1173  // type needs to be scalar.
1174  if (castType->isVoidType()) {
1175    // Cast to void allows any expr type.
1176  } else if (!castType->isScalarType() && !castType->isVectorType()) {
1177    // GCC struct/union extension: allow cast to self.
1178    if (Context.getCanonicalType(castType) !=
1179        Context.getCanonicalType(castExpr->getType()) ||
1180        (!castType->isStructureType() && !castType->isUnionType())) {
1181      // Reject any other conversions to non-scalar types.
1182      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar,
1183                  castType.getAsString(), castExpr->getSourceRange());
1184    }
1185
1186    // accept this, but emit an ext-warn.
1187    Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar,
1188         castType.getAsString(), castExpr->getSourceRange());
1189  } else if (!castExpr->getType()->isScalarType() &&
1190             !castExpr->getType()->isVectorType()) {
1191    return Diag(castExpr->getLocStart(),
1192                diag::err_typecheck_expect_scalar_operand,
1193                castExpr->getType().getAsString(),castExpr->getSourceRange());
1194  } else if (castExpr->getType()->isVectorType()) {
1195    if (CheckVectorCast(TyR, castExpr->getType(), castType))
1196      return true;
1197  } else if (castType->isVectorType()) {
1198    if (CheckVectorCast(TyR, castType, castExpr->getType()))
1199      return true;
1200  }
1201  return false;
1202}
1203
1204bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
1205  assert(VectorTy->isVectorType() && "Not a vector type!");
1206
1207  if (Ty->isVectorType() || Ty->isIntegerType()) {
1208    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
1209      return Diag(R.getBegin(),
1210                  Ty->isVectorType() ?
1211                  diag::err_invalid_conversion_between_vectors :
1212                  diag::err_invalid_conversion_between_vector_and_integer,
1213                  VectorTy.getAsString().c_str(),
1214                  Ty.getAsString().c_str(), R);
1215  } else
1216    return Diag(R.getBegin(),
1217                diag::err_invalid_conversion_between_vector_and_scalar,
1218                VectorTy.getAsString().c_str(),
1219                Ty.getAsString().c_str(), R);
1220
1221  return false;
1222}
1223
1224Action::ExprResult Sema::
1225ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
1226              SourceLocation RParenLoc, ExprTy *Op) {
1227  assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
1228
1229  Expr *castExpr = static_cast<Expr*>(Op);
1230  QualType castType = QualType::getFromOpaquePtr(Ty);
1231
1232  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
1233    return true;
1234  return new ExplicitCastExpr(castType, castExpr, LParenLoc);
1235}
1236
1237/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
1238/// In that case, lex = cond.
1239inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
1240  Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
1241  UsualUnaryConversions(cond);
1242  UsualUnaryConversions(lex);
1243  UsualUnaryConversions(rex);
1244  QualType condT = cond->getType();
1245  QualType lexT = lex->getType();
1246  QualType rexT = rex->getType();
1247
1248  // first, check the condition.
1249  if (!condT->isScalarType()) { // C99 6.5.15p2
1250    Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
1251         condT.getAsString());
1252    return QualType();
1253  }
1254
1255  // Now check the two expressions.
1256
1257  // If both operands have arithmetic type, do the usual arithmetic conversions
1258  // to find a common type: C99 6.5.15p3,5.
1259  if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
1260    UsualArithmeticConversions(lex, rex);
1261    return lex->getType();
1262  }
1263
1264  // If both operands are the same structure or union type, the result is that
1265  // type.
1266  if (const RecordType *LHSRT = lexT->getAsRecordType()) {    // C99 6.5.15p3
1267    if (const RecordType *RHSRT = rexT->getAsRecordType())
1268      if (LHSRT->getDecl() == RHSRT->getDecl())
1269        // "If both the operands have structure or union type, the result has
1270        // that type."  This implies that CV qualifiers are dropped.
1271        return lexT.getUnqualifiedType();
1272  }
1273
1274  // C99 6.5.15p5: "If both operands have void type, the result has void type."
1275  // The following || allows only one side to be void (a GCC-ism).
1276  if (lexT->isVoidType() || rexT->isVoidType()) {
1277    if (!lexT->isVoidType())
1278      Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
1279           rex->getSourceRange());
1280    if (!rexT->isVoidType())
1281      Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
1282           lex->getSourceRange());
1283    ImpCastExprToType(lex, Context.VoidTy);
1284    ImpCastExprToType(rex, Context.VoidTy);
1285    return Context.VoidTy;
1286  }
1287  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
1288  // the type of the other operand."
1289  if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
1290       Context.isObjCObjectPointerType(lexT)) &&
1291      rex->isNullPointerConstant(Context)) {
1292    ImpCastExprToType(rex, lexT); // promote the null to a pointer.
1293    return lexT;
1294  }
1295  if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
1296       Context.isObjCObjectPointerType(rexT)) &&
1297      lex->isNullPointerConstant(Context)) {
1298    ImpCastExprToType(lex, rexT); // promote the null to a pointer.
1299    return rexT;
1300  }
1301  // Handle the case where both operands are pointers before we handle null
1302  // pointer constants in case both operands are null pointer constants.
1303  if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
1304    if (const PointerType *RHSPT = rexT->getAsPointerType()) {
1305      // get the "pointed to" types
1306      QualType lhptee = LHSPT->getPointeeType();
1307      QualType rhptee = RHSPT->getPointeeType();
1308
1309      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
1310      if (lhptee->isVoidType() &&
1311          rhptee->isIncompleteOrObjectType()) {
1312        // Figure out necessary qualifiers (C99 6.5.15p6)
1313        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
1314        QualType destType = Context.getPointerType(destPointee);
1315        ImpCastExprToType(lex, destType); // add qualifiers if necessary
1316        ImpCastExprToType(rex, destType); // promote to void*
1317        return destType;
1318      }
1319      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
1320        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
1321        QualType destType = Context.getPointerType(destPointee);
1322        ImpCastExprToType(lex, destType); // add qualifiers if necessary
1323        ImpCastExprToType(rex, destType); // promote to void*
1324        return destType;
1325      }
1326
1327      QualType compositeType = lexT;
1328
1329      // If either type is an Objective-C object type then check
1330      // compatibility according to Objective-C.
1331      if (Context.isObjCObjectPointerType(lexT) ||
1332          Context.isObjCObjectPointerType(rexT)) {
1333        // If both operands are interfaces and either operand can be
1334        // assigned to the other, use that type as the composite
1335        // type. This allows
1336        //   xxx ? (A*) a : (B*) b
1337        // where B is a subclass of A.
1338        //
1339        // Additionally, as for assignment, if either type is 'id'
1340        // allow silent coercion. Finally, if the types are
1341        // incompatible then make sure to use 'id' as the composite
1342        // type so the result is acceptable for sending messages to.
1343
1344        // FIXME: This code should not be localized to here. Also this
1345        // should use a compatible check instead of abusing the
1346        // canAssignObjCInterfaces code.
1347        const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1348        const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1349        if (LHSIface && RHSIface &&
1350            Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1351          compositeType = lexT;
1352        } else if (LHSIface && RHSIface &&
1353                   Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
1354          compositeType = rexT;
1355        } else if (Context.isObjCIdType(lhptee) ||
1356                   Context.isObjCIdType(rhptee)) {
1357          // FIXME: This code looks wrong, because isObjCIdType checks
1358          // the struct but getObjCIdType returns the pointer to
1359          // struct. This is horrible and should be fixed.
1360          compositeType = Context.getObjCIdType();
1361        } else {
1362          QualType incompatTy = Context.getObjCIdType();
1363          ImpCastExprToType(lex, incompatTy);
1364          ImpCastExprToType(rex, incompatTy);
1365          return incompatTy;
1366        }
1367      } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1368                                             rhptee.getUnqualifiedType())) {
1369        Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
1370             lexT.getAsString(), rexT.getAsString(),
1371             lex->getSourceRange(), rex->getSourceRange());
1372        // In this situation, we assume void* type. No especially good
1373        // reason, but this is what gcc does, and we do have to pick
1374        // to get a consistent AST.
1375        QualType incompatTy = Context.getPointerType(Context.VoidTy);
1376        ImpCastExprToType(lex, incompatTy);
1377        ImpCastExprToType(rex, incompatTy);
1378        return incompatTy;
1379      }
1380      // The pointer types are compatible.
1381      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
1382      // differently qualified versions of compatible types, the result type is
1383      // a pointer to an appropriately qualified version of the *composite*
1384      // type.
1385      // FIXME: Need to calculate the composite type.
1386      // FIXME: Need to add qualifiers
1387      ImpCastExprToType(lex, compositeType);
1388      ImpCastExprToType(rex, compositeType);
1389      return compositeType;
1390    }
1391  }
1392  // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
1393  // evaluates to "struct objc_object *" (and is handled above when comparing
1394  // id with statically typed objects).
1395  if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
1396    // GCC allows qualified id and any Objective-C type to devolve to
1397    // id. Currently localizing to here until clear this should be
1398    // part of ObjCQualifiedIdTypesAreCompatible.
1399    if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
1400        (lexT->isObjCQualifiedIdType() &&
1401         Context.isObjCObjectPointerType(rexT)) ||
1402        (rexT->isObjCQualifiedIdType() &&
1403         Context.isObjCObjectPointerType(lexT))) {
1404      // FIXME: This is not the correct composite type. This only
1405      // happens to work because id can more or less be used anywhere,
1406      // however this may change the type of method sends.
1407      // FIXME: gcc adds some type-checking of the arguments and emits
1408      // (confusing) incompatible comparison warnings in some
1409      // cases. Investigate.
1410      QualType compositeType = Context.getObjCIdType();
1411      ImpCastExprToType(lex, compositeType);
1412      ImpCastExprToType(rex, compositeType);
1413      return compositeType;
1414    }
1415  }
1416
1417  // Selection between block pointer types is ok as long as they are the same.
1418  if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
1419      Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
1420    return lexT;
1421
1422  // Otherwise, the operands are not compatible.
1423  Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1424       lexT.getAsString(), rexT.getAsString(),
1425       lex->getSourceRange(), rex->getSourceRange());
1426  return QualType();
1427}
1428
1429/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
1430/// in the case of a the GNU conditional expr extension.
1431Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
1432                                            SourceLocation ColonLoc,
1433                                            ExprTy *Cond, ExprTy *LHS,
1434                                            ExprTy *RHS) {
1435  Expr *CondExpr = (Expr *) Cond;
1436  Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
1437
1438  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1439  // was the condition.
1440  bool isLHSNull = LHSExpr == 0;
1441  if (isLHSNull)
1442    LHSExpr = CondExpr;
1443
1444  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1445                                             RHSExpr, QuestionLoc);
1446  if (result.isNull())
1447    return true;
1448  return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1449                                 RHSExpr, result);
1450}
1451
1452
1453// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1454// being closely modeled after the C99 spec:-). The odd characteristic of this
1455// routine is it effectively iqnores the qualifiers on the top level pointee.
1456// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1457// FIXME: add a couple examples in this comment.
1458Sema::AssignConvertType
1459Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1460  QualType lhptee, rhptee;
1461
1462  // get the "pointed to" type (ignoring qualifiers at the top level)
1463  lhptee = lhsType->getAsPointerType()->getPointeeType();
1464  rhptee = rhsType->getAsPointerType()->getPointeeType();
1465
1466  // make sure we operate on the canonical type
1467  lhptee = Context.getCanonicalType(lhptee);
1468  rhptee = Context.getCanonicalType(rhptee);
1469
1470  AssignConvertType ConvTy = Compatible;
1471
1472  // C99 6.5.16.1p1: This following citation is common to constraints
1473  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1474  // qualifiers of the type *pointed to* by the right;
1475  // FIXME: Handle ASQualType
1476  if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1477       rhptee.getCVRQualifiers())
1478    ConvTy = CompatiblePointerDiscardsQualifiers;
1479
1480  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1481  // incomplete type and the other is a pointer to a qualified or unqualified
1482  // version of void...
1483  if (lhptee->isVoidType()) {
1484    if (rhptee->isIncompleteOrObjectType())
1485      return ConvTy;
1486
1487    // As an extension, we allow cast to/from void* to function pointer.
1488    assert(rhptee->isFunctionType());
1489    return FunctionVoidPointer;
1490  }
1491
1492  if (rhptee->isVoidType()) {
1493    if (lhptee->isIncompleteOrObjectType())
1494      return ConvTy;
1495
1496    // As an extension, we allow cast to/from void* to function pointer.
1497    assert(lhptee->isFunctionType());
1498    return FunctionVoidPointer;
1499  }
1500
1501  // Check for ObjC interfaces
1502  const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
1503  const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
1504  if (LHSIface && RHSIface &&
1505      Context.canAssignObjCInterfaces(LHSIface, RHSIface))
1506    return ConvTy;
1507
1508  // ID acts sort of like void* for ObjC interfaces
1509  if (LHSIface && Context.isObjCIdType(rhptee))
1510    return ConvTy;
1511  if (RHSIface && Context.isObjCIdType(lhptee))
1512    return ConvTy;
1513
1514  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1515  // unqualified versions of compatible types, ...
1516  if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1517                                  rhptee.getUnqualifiedType()))
1518    return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1519  return ConvTy;
1520}
1521
1522/// CheckBlockPointerTypesForAssignment - This routine determines whether two
1523/// block pointer types are compatible or whether a block and normal pointer
1524/// are compatible. It is more restrict than comparing two function pointer
1525// types.
1526Sema::AssignConvertType
1527Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
1528                                          QualType rhsType) {
1529  QualType lhptee, rhptee;
1530
1531  // get the "pointed to" type (ignoring qualifiers at the top level)
1532  lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
1533  rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
1534
1535  // make sure we operate on the canonical type
1536  lhptee = Context.getCanonicalType(lhptee);
1537  rhptee = Context.getCanonicalType(rhptee);
1538
1539  AssignConvertType ConvTy = Compatible;
1540
1541  // For blocks we enforce that qualifiers are identical.
1542  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
1543    ConvTy = CompatiblePointerDiscardsQualifiers;
1544
1545  if (!Context.typesAreBlockCompatible(lhptee, rhptee))
1546    return IncompatibleBlockPointer;
1547  return ConvTy;
1548}
1549
1550/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1551/// has code to accommodate several GCC extensions when type checking
1552/// pointers. Here are some objectionable examples that GCC considers warnings:
1553///
1554///  int a, *pint;
1555///  short *pshort;
1556///  struct foo *pfoo;
1557///
1558///  pint = pshort; // warning: assignment from incompatible pointer type
1559///  a = pint; // warning: assignment makes integer from pointer without a cast
1560///  pint = a; // warning: assignment makes pointer from integer without a cast
1561///  pint = pfoo; // warning: assignment from incompatible pointer type
1562///
1563/// As a result, the code for dealing with pointers is more complex than the
1564/// C99 spec dictates.
1565///
1566Sema::AssignConvertType
1567Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
1568  // Get canonical types.  We're not formatting these types, just comparing
1569  // them.
1570  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
1571  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
1572
1573  if (lhsType == rhsType)
1574    return Compatible; // Common case: fast path an exact match.
1575
1576  if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1577    if (Context.typesAreCompatible(lhsType, rhsType))
1578      return Compatible;
1579    return Incompatible;
1580  }
1581
1582  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1583    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
1584      return Compatible;
1585    // Relax integer conversions like we do for pointers below.
1586    if (rhsType->isIntegerType())
1587      return IntToPointer;
1588    if (lhsType->isIntegerType())
1589      return PointerToInt;
1590    return Incompatible;
1591  }
1592
1593  if (lhsType->isVectorType() || rhsType->isVectorType()) {
1594    // For ExtVector, allow vector splats; float -> <n x float>
1595    if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
1596      if (LV->getElementType() == rhsType)
1597        return Compatible;
1598
1599    // If we are allowing lax vector conversions, and LHS and RHS are both
1600    // vectors, the total size only needs to be the same. This is a bitcast;
1601    // no bits are changed but the result type is different.
1602    if (getLangOptions().LaxVectorConversions &&
1603        lhsType->isVectorType() && rhsType->isVectorType()) {
1604      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1605        return Compatible;
1606    }
1607    return Incompatible;
1608  }
1609
1610  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
1611    return Compatible;
1612
1613  if (isa<PointerType>(lhsType)) {
1614    if (rhsType->isIntegerType())
1615      return IntToPointer;
1616
1617    if (isa<PointerType>(rhsType))
1618      return CheckPointerTypesForAssignment(lhsType, rhsType);
1619
1620    if (rhsType->getAsBlockPointerType()) {
1621      if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
1622        return BlockVoidPointer;
1623
1624      // Treat block pointers as objects.
1625      if (getLangOptions().ObjC1 &&
1626          lhsType == Context.getCanonicalType(Context.getObjCIdType()))
1627        return Compatible;
1628    }
1629    return Incompatible;
1630  }
1631
1632  if (isa<BlockPointerType>(lhsType)) {
1633    if (rhsType->isIntegerType())
1634      return IntToPointer;
1635
1636    // Treat block pointers as objects.
1637    if (getLangOptions().ObjC1 &&
1638        rhsType == Context.getCanonicalType(Context.getObjCIdType()))
1639      return Compatible;
1640
1641    if (rhsType->isBlockPointerType())
1642      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
1643
1644    if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
1645      if (RHSPT->getPointeeType()->isVoidType())
1646        return BlockVoidPointer;
1647    }
1648    return Incompatible;
1649  }
1650
1651  if (isa<PointerType>(rhsType)) {
1652    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1653    if (lhsType == Context.BoolTy)
1654      return Compatible;
1655
1656    if (lhsType->isIntegerType())
1657      return PointerToInt;
1658
1659    if (isa<PointerType>(lhsType))
1660      return CheckPointerTypesForAssignment(lhsType, rhsType);
1661
1662    if (isa<BlockPointerType>(lhsType) &&
1663        rhsType->getAsPointerType()->getPointeeType()->isVoidType())
1664      return BlockVoidPointer;
1665    return Incompatible;
1666  }
1667
1668  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1669    if (Context.typesAreCompatible(lhsType, rhsType))
1670      return Compatible;
1671  }
1672  return Incompatible;
1673}
1674
1675Sema::AssignConvertType
1676Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1677  // C99 6.5.16.1p1: the left operand is a pointer and the right is
1678  // a null pointer constant.
1679  if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
1680       lhsType->isBlockPointerType())
1681      && rExpr->isNullPointerConstant(Context)) {
1682    ImpCastExprToType(rExpr, lhsType);
1683    return Compatible;
1684  }
1685
1686  // We don't allow conversion of non-null-pointer constants to integers.
1687  if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
1688    return IntToBlockPointer;
1689
1690  // This check seems unnatural, however it is necessary to ensure the proper
1691  // conversion of functions/arrays. If the conversion were done for all
1692  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
1693  // expressions that surpress this implicit conversion (&, sizeof).
1694  //
1695  // Suppress this for references: C99 8.5.3p5.  FIXME: revisit when references
1696  // are better understood.
1697  if (!lhsType->isReferenceType())
1698    DefaultFunctionArrayConversion(rExpr);
1699
1700  Sema::AssignConvertType result =
1701    CheckAssignmentConstraints(lhsType, rExpr->getType());
1702
1703  // C99 6.5.16.1p2: The value of the right operand is converted to the
1704  // type of the assignment expression.
1705  if (rExpr->getType() != lhsType)
1706    ImpCastExprToType(rExpr, lhsType);
1707  return result;
1708}
1709
1710Sema::AssignConvertType
1711Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1712  return CheckAssignmentConstraints(lhsType, rhsType);
1713}
1714
1715QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1716  Diag(loc, diag::err_typecheck_invalid_operands,
1717       lex->getType().getAsString(), rex->getType().getAsString(),
1718       lex->getSourceRange(), rex->getSourceRange());
1719  return QualType();
1720}
1721
1722inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1723                                                              Expr *&rex) {
1724  // For conversion purposes, we ignore any qualifiers.
1725  // For example, "const float" and "float" are equivalent.
1726  QualType lhsType =
1727    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
1728  QualType rhsType =
1729    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
1730
1731  // If the vector types are identical, return.
1732  if (lhsType == rhsType)
1733    return lhsType;
1734
1735  // Handle the case of a vector & extvector type of the same size and element
1736  // type.  It would be nice if we only had one vector type someday.
1737  if (getLangOptions().LaxVectorConversions)
1738    if (const VectorType *LV = lhsType->getAsVectorType())
1739      if (const VectorType *RV = rhsType->getAsVectorType())
1740        if (LV->getElementType() == RV->getElementType() &&
1741            LV->getNumElements() == RV->getNumElements())
1742          return lhsType->isExtVectorType() ? lhsType : rhsType;
1743
1744  // If the lhs is an extended vector and the rhs is a scalar of the same type
1745  // or a literal, promote the rhs to the vector type.
1746  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
1747    QualType eltType = V->getElementType();
1748
1749    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
1750        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
1751        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
1752      ImpCastExprToType(rex, lhsType);
1753      return lhsType;
1754    }
1755  }
1756
1757  // If the rhs is an extended vector and the lhs is a scalar of the same type,
1758  // promote the lhs to the vector type.
1759  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
1760    QualType eltType = V->getElementType();
1761
1762    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
1763        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
1764        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
1765      ImpCastExprToType(lex, rhsType);
1766      return rhsType;
1767    }
1768  }
1769
1770  // You cannot convert between vector values of different size.
1771  Diag(loc, diag::err_typecheck_vector_not_convertable,
1772       lex->getType().getAsString(), rex->getType().getAsString(),
1773       lex->getSourceRange(), rex->getSourceRange());
1774  return QualType();
1775}
1776
1777inline QualType Sema::CheckMultiplyDivideOperands(
1778  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1779{
1780  QualType lhsType = lex->getType(), rhsType = rex->getType();
1781
1782  if (lhsType->isVectorType() || rhsType->isVectorType())
1783    return CheckVectorOperands(loc, lex, rex);
1784
1785  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1786
1787  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1788    return compType;
1789  return InvalidOperands(loc, lex, rex);
1790}
1791
1792inline QualType Sema::CheckRemainderOperands(
1793  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1794{
1795  QualType lhsType = lex->getType(), rhsType = rex->getType();
1796
1797  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1798
1799  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1800    return compType;
1801  return InvalidOperands(loc, lex, rex);
1802}
1803
1804inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
1805  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1806{
1807  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1808    return CheckVectorOperands(loc, lex, rex);
1809
1810  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1811
1812  // handle the common case first (both operands are arithmetic).
1813  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1814    return compType;
1815
1816  // Put any potential pointer into PExp
1817  Expr* PExp = lex, *IExp = rex;
1818  if (IExp->getType()->isPointerType())
1819    std::swap(PExp, IExp);
1820
1821  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1822    if (IExp->getType()->isIntegerType()) {
1823      // Check for arithmetic on pointers to incomplete types
1824      if (!PTy->getPointeeType()->isObjectType()) {
1825        if (PTy->getPointeeType()->isVoidType()) {
1826          Diag(loc, diag::ext_gnu_void_ptr,
1827               lex->getSourceRange(), rex->getSourceRange());
1828        } else {
1829          Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1830               lex->getType().getAsString(), lex->getSourceRange());
1831          return QualType();
1832        }
1833      }
1834      return PExp->getType();
1835    }
1836  }
1837
1838  return InvalidOperands(loc, lex, rex);
1839}
1840
1841// C99 6.5.6
1842QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1843                                        SourceLocation loc, bool isCompAssign) {
1844  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1845    return CheckVectorOperands(loc, lex, rex);
1846
1847  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1848
1849  // Enforce type constraints: C99 6.5.6p3.
1850
1851  // Handle the common case first (both operands are arithmetic).
1852  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1853    return compType;
1854
1855  // Either ptr - int   or   ptr - ptr.
1856  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1857    QualType lpointee = LHSPTy->getPointeeType();
1858
1859    // The LHS must be an object type, not incomplete, function, etc.
1860    if (!lpointee->isObjectType()) {
1861      // Handle the GNU void* extension.
1862      if (lpointee->isVoidType()) {
1863        Diag(loc, diag::ext_gnu_void_ptr,
1864             lex->getSourceRange(), rex->getSourceRange());
1865      } else {
1866        Diag(loc, diag::err_typecheck_sub_ptr_object,
1867             lex->getType().getAsString(), lex->getSourceRange());
1868        return QualType();
1869      }
1870    }
1871
1872    // The result type of a pointer-int computation is the pointer type.
1873    if (rex->getType()->isIntegerType())
1874      return lex->getType();
1875
1876    // Handle pointer-pointer subtractions.
1877    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1878      QualType rpointee = RHSPTy->getPointeeType();
1879
1880      // RHS must be an object type, unless void (GNU).
1881      if (!rpointee->isObjectType()) {
1882        // Handle the GNU void* extension.
1883        if (rpointee->isVoidType()) {
1884          if (!lpointee->isVoidType())
1885            Diag(loc, diag::ext_gnu_void_ptr,
1886                 lex->getSourceRange(), rex->getSourceRange());
1887        } else {
1888          Diag(loc, diag::err_typecheck_sub_ptr_object,
1889               rex->getType().getAsString(), rex->getSourceRange());
1890          return QualType();
1891        }
1892      }
1893
1894      // Pointee types must be compatible.
1895      if (!Context.typesAreCompatible(
1896              Context.getCanonicalType(lpointee).getUnqualifiedType(),
1897              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
1898        Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1899             lex->getType().getAsString(), rex->getType().getAsString(),
1900             lex->getSourceRange(), rex->getSourceRange());
1901        return QualType();
1902      }
1903
1904      return Context.getPointerDiffType();
1905    }
1906  }
1907
1908  return InvalidOperands(loc, lex, rex);
1909}
1910
1911// C99 6.5.7
1912QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1913                                  bool isCompAssign) {
1914  // C99 6.5.7p2: Each of the operands shall have integer type.
1915  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1916    return InvalidOperands(loc, lex, rex);
1917
1918  // Shifts don't perform usual arithmetic conversions, they just do integer
1919  // promotions on each operand. C99 6.5.7p3
1920  if (!isCompAssign)
1921    UsualUnaryConversions(lex);
1922  UsualUnaryConversions(rex);
1923
1924  // "The type of the result is that of the promoted left operand."
1925  return lex->getType();
1926}
1927
1928static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
1929                                        ASTContext& Context) {
1930  const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
1931  const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
1932  // ID acts sort of like void* for ObjC interfaces
1933  if (LHSIface && Context.isObjCIdType(RHS))
1934    return true;
1935  if (RHSIface && Context.isObjCIdType(LHS))
1936    return true;
1937  if (!LHSIface || !RHSIface)
1938    return false;
1939  return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
1940         Context.canAssignObjCInterfaces(RHSIface, LHSIface);
1941}
1942
1943// C99 6.5.8
1944QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1945                                    bool isRelational) {
1946  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1947    return CheckVectorCompareOperands(lex, rex, loc, isRelational);
1948
1949  // C99 6.5.8p3 / C99 6.5.9p4
1950  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1951    UsualArithmeticConversions(lex, rex);
1952  else {
1953    UsualUnaryConversions(lex);
1954    UsualUnaryConversions(rex);
1955  }
1956  QualType lType = lex->getType();
1957  QualType rType = rex->getType();
1958
1959  // For non-floating point types, check for self-comparisons of the form
1960  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
1961  // often indicate logic errors in the program.
1962  if (!lType->isFloatingType()) {
1963    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1964      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1965        if (DRL->getDecl() == DRR->getDecl())
1966          Diag(loc, diag::warn_selfcomparison);
1967  }
1968
1969  if (isRelational) {
1970    if (lType->isRealType() && rType->isRealType())
1971      return Context.IntTy;
1972  } else {
1973    // Check for comparisons of floating point operands using != and ==.
1974    if (lType->isFloatingType()) {
1975      assert (rType->isFloatingType());
1976      CheckFloatComparison(loc,lex,rex);
1977    }
1978
1979    if (lType->isArithmeticType() && rType->isArithmeticType())
1980      return Context.IntTy;
1981  }
1982
1983  bool LHSIsNull = lex->isNullPointerConstant(Context);
1984  bool RHSIsNull = rex->isNullPointerConstant(Context);
1985
1986  // All of the following pointer related warnings are GCC extensions, except
1987  // when handling null pointer constants. One day, we can consider making them
1988  // errors (when -pedantic-errors is enabled).
1989  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
1990    QualType LCanPointeeTy =
1991      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
1992    QualType RCanPointeeTy =
1993      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
1994
1995    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
1996        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1997        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1998                                    RCanPointeeTy.getUnqualifiedType()) &&
1999        !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
2000      Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
2001           lType.getAsString(), rType.getAsString(),
2002           lex->getSourceRange(), rex->getSourceRange());
2003    }
2004    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2005    return Context.IntTy;
2006  }
2007  // Handle block pointer types.
2008  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2009    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2010    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2011
2012    if (!LHSIsNull && !RHSIsNull &&
2013        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2014      Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2015           lType.getAsString(), rType.getAsString(),
2016           lex->getSourceRange(), rex->getSourceRange());
2017    }
2018    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2019    return Context.IntTy;
2020  }
2021  // Allow block pointers to be compared with null pointer constants.
2022  if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2023      (lType->isPointerType() && rType->isBlockPointerType())) {
2024    if (!LHSIsNull && !RHSIsNull) {
2025      Diag(loc, diag::err_typecheck_comparison_of_distinct_blocks,
2026           lType.getAsString(), rType.getAsString(),
2027           lex->getSourceRange(), rex->getSourceRange());
2028    }
2029    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2030    return Context.IntTy;
2031  }
2032
2033  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
2034    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
2035      ImpCastExprToType(rex, lType);
2036      return Context.IntTy;
2037    }
2038  }
2039  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
2040       rType->isIntegerType()) {
2041    if (!RHSIsNull)
2042      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2043           lType.getAsString(), rType.getAsString(),
2044           lex->getSourceRange(), rex->getSourceRange());
2045    ImpCastExprToType(rex, lType); // promote the integer to pointer
2046    return Context.IntTy;
2047  }
2048  if (lType->isIntegerType() &&
2049      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
2050    if (!LHSIsNull)
2051      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2052           lType.getAsString(), rType.getAsString(),
2053           lex->getSourceRange(), rex->getSourceRange());
2054    ImpCastExprToType(lex, rType); // promote the integer to pointer
2055    return Context.IntTy;
2056  }
2057  // Handle block pointers.
2058  if (lType->isBlockPointerType() && rType->isIntegerType()) {
2059    if (!RHSIsNull)
2060      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2061           lType.getAsString(), rType.getAsString(),
2062           lex->getSourceRange(), rex->getSourceRange());
2063    ImpCastExprToType(rex, lType); // promote the integer to pointer
2064    return Context.IntTy;
2065  }
2066  if (lType->isIntegerType() && rType->isBlockPointerType()) {
2067    if (!LHSIsNull)
2068      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
2069           lType.getAsString(), rType.getAsString(),
2070           lex->getSourceRange(), rex->getSourceRange());
2071    ImpCastExprToType(lex, rType); // promote the integer to pointer
2072    return Context.IntTy;
2073  }
2074  return InvalidOperands(loc, lex, rex);
2075}
2076
2077/// CheckVectorCompareOperands - vector comparisons are a clang extension that
2078/// operates on extended vector types.  Instead of producing an IntTy result,
2079/// like a scalar comparison, a vector comparison produces a vector of integer
2080/// types.
2081QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
2082                                          SourceLocation loc,
2083                                          bool isRelational) {
2084  // Check to make sure we're operating on vectors of the same type and width,
2085  // Allowing one side to be a scalar of element type.
2086  QualType vType = CheckVectorOperands(loc, lex, rex);
2087  if (vType.isNull())
2088    return vType;
2089
2090  QualType lType = lex->getType();
2091  QualType rType = rex->getType();
2092
2093  // For non-floating point types, check for self-comparisons of the form
2094  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
2095  // often indicate logic errors in the program.
2096  if (!lType->isFloatingType()) {
2097    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2098      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2099        if (DRL->getDecl() == DRR->getDecl())
2100          Diag(loc, diag::warn_selfcomparison);
2101  }
2102
2103  // Check for comparisons of floating point operands using != and ==.
2104  if (!isRelational && lType->isFloatingType()) {
2105    assert (rType->isFloatingType());
2106    CheckFloatComparison(loc,lex,rex);
2107  }
2108
2109  // Return the type for the comparison, which is the same as vector type for
2110  // integer vectors, or an integer type of identical size and number of
2111  // elements for floating point vectors.
2112  if (lType->isIntegerType())
2113    return lType;
2114
2115  const VectorType *VTy = lType->getAsVectorType();
2116
2117  // FIXME: need to deal with non-32b int / non-64b long long
2118  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
2119  if (TypeSize == 32) {
2120    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
2121  }
2122  assert(TypeSize == 64 && "Unhandled vector element size in vector compare");
2123  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
2124}
2125
2126inline QualType Sema::CheckBitwiseOperands(
2127  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
2128{
2129  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2130    return CheckVectorOperands(loc, lex, rex);
2131
2132  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2133
2134  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2135    return compType;
2136  return InvalidOperands(loc, lex, rex);
2137}
2138
2139inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
2140  Expr *&lex, Expr *&rex, SourceLocation loc)
2141{
2142  UsualUnaryConversions(lex);
2143  UsualUnaryConversions(rex);
2144
2145  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
2146    return Context.IntTy;
2147  return InvalidOperands(loc, lex, rex);
2148}
2149
2150inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
2151  Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
2152{
2153  QualType lhsType = lex->getType();
2154  QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
2155  Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue(Context);
2156
2157  switch (mlval) { // C99 6.5.16p2
2158  case Expr::MLV_Valid:
2159    break;
2160  case Expr::MLV_ConstQualified:
2161    Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
2162    return QualType();
2163  case Expr::MLV_ArrayType:
2164    Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
2165         lhsType.getAsString(), lex->getSourceRange());
2166    return QualType();
2167  case Expr::MLV_NotObjectType:
2168    Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
2169         lhsType.getAsString(), lex->getSourceRange());
2170    return QualType();
2171  case Expr::MLV_InvalidExpression:
2172    Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
2173         lex->getSourceRange());
2174    return QualType();
2175  case Expr::MLV_IncompleteType:
2176  case Expr::MLV_IncompleteVoidType:
2177    Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
2178         lhsType.getAsString(), lex->getSourceRange());
2179    return QualType();
2180  case Expr::MLV_DuplicateVectorComponents:
2181    Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
2182         lex->getSourceRange());
2183    return QualType();
2184  case Expr::MLV_NotBlockQualified:
2185    Diag(loc, diag::err_block_decl_ref_not_modifiable_lvalue,
2186         lex->getSourceRange());
2187    return QualType();
2188  }
2189
2190  AssignConvertType ConvTy;
2191  if (compoundType.isNull()) {
2192    // Simple assignment "x = y".
2193    ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
2194
2195    // If the RHS is a unary plus or minus, check to see if they = and + are
2196    // right next to each other.  If so, the user may have typo'd "x =+ 4"
2197    // instead of "x += 4".
2198    Expr *RHSCheck = rex;
2199    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
2200      RHSCheck = ICE->getSubExpr();
2201    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
2202      if ((UO->getOpcode() == UnaryOperator::Plus ||
2203           UO->getOpcode() == UnaryOperator::Minus) &&
2204          loc.isFileID() && UO->getOperatorLoc().isFileID() &&
2205          // Only if the two operators are exactly adjacent.
2206          loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
2207        Diag(loc, diag::warn_not_compound_assign,
2208             UO->getOpcode() == UnaryOperator::Plus ? "+" : "-",
2209             SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc()));
2210    }
2211  } else {
2212    // Compound assignment "x += y"
2213    ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
2214  }
2215
2216  if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
2217                               rex, "assigning"))
2218    return QualType();
2219
2220  // C99 6.5.16p3: The type of an assignment expression is the type of the
2221  // left operand unless the left operand has qualified type, in which case
2222  // it is the unqualified version of the type of the left operand.
2223  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
2224  // is converted to the type of the assignment expression (above).
2225  // C++ 5.17p1: the type of the assignment expression is that of its left
2226  // oprdu.
2227  return lhsType.getUnqualifiedType();
2228}
2229
2230inline QualType Sema::CheckCommaOperands( // C99 6.5.17
2231  Expr *&lex, Expr *&rex, SourceLocation loc) {
2232
2233  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
2234  DefaultFunctionArrayConversion(rex);
2235  return rex->getType();
2236}
2237
2238/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
2239/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
2240QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
2241  QualType resType = op->getType();
2242  assert(!resType.isNull() && "no type for increment/decrement expression");
2243
2244  // C99 6.5.2.4p1: We allow complex as a GCC extension.
2245  if (const PointerType *pt = resType->getAsPointerType()) {
2246    if (pt->getPointeeType()->isVoidType()) {
2247      Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
2248    } else if (!pt->getPointeeType()->isObjectType()) {
2249      // C99 6.5.2.4p2, 6.5.6p2
2250      Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
2251           resType.getAsString(), op->getSourceRange());
2252      return QualType();
2253    }
2254  } else if (!resType->isRealType()) {
2255    if (resType->isComplexType())
2256      // C99 does not support ++/-- on complex types.
2257      Diag(OpLoc, diag::ext_integer_increment_complex,
2258           resType.getAsString(), op->getSourceRange());
2259    else {
2260      Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
2261           resType.getAsString(), op->getSourceRange());
2262      return QualType();
2263    }
2264  }
2265  // At this point, we know we have a real, complex or pointer type.
2266  // Now make sure the operand is a modifiable lvalue.
2267  Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue(Context);
2268  if (mlval != Expr::MLV_Valid) {
2269    // FIXME: emit a more precise diagnostic...
2270    Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
2271         op->getSourceRange());
2272    return QualType();
2273  }
2274  return resType;
2275}
2276
2277/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
2278/// This routine allows us to typecheck complex/recursive expressions
2279/// where the declaration is needed for type checking. We only need to
2280/// handle cases when the expression references a function designator
2281/// or is an lvalue. Here are some examples:
2282///  - &(x) => x
2283///  - &*****f => f for f a function designator.
2284///  - &s.xx => s
2285///  - &s.zz[1].yy -> s, if zz is an array
2286///  - *(x + 1) -> x, if x is an array
2287///  - &"123"[2] -> 0
2288///  - & __real__ x -> x
2289static ValueDecl *getPrimaryDecl(Expr *E) {
2290  switch (E->getStmtClass()) {
2291  case Stmt::DeclRefExprClass:
2292    return cast<DeclRefExpr>(E)->getDecl();
2293  case Stmt::MemberExprClass:
2294    // Fields cannot be declared with a 'register' storage class.
2295    // &X->f is always ok, even if X is declared register.
2296    if (cast<MemberExpr>(E)->isArrow())
2297      return 0;
2298    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
2299  case Stmt::ArraySubscriptExprClass: {
2300    // &X[4] and &4[X] refers to X if X is not a pointer.
2301
2302    ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
2303    if (!VD || VD->getType()->isPointerType())
2304      return 0;
2305    else
2306      return VD;
2307  }
2308  case Stmt::UnaryOperatorClass: {
2309    UnaryOperator *UO = cast<UnaryOperator>(E);
2310
2311    switch(UO->getOpcode()) {
2312    case UnaryOperator::Deref: {
2313      // *(X + 1) refers to X if X is not a pointer.
2314      ValueDecl *VD = getPrimaryDecl(UO->getSubExpr());
2315      if (!VD || VD->getType()->isPointerType())
2316        return 0;
2317      return VD;
2318    }
2319    case UnaryOperator::Real:
2320    case UnaryOperator::Imag:
2321    case UnaryOperator::Extension:
2322      return getPrimaryDecl(UO->getSubExpr());
2323    default:
2324      return 0;
2325    }
2326  }
2327  case Stmt::BinaryOperatorClass: {
2328    BinaryOperator *BO = cast<BinaryOperator>(E);
2329
2330    // Handle cases involving pointer arithmetic. The result of an
2331    // Assign or AddAssign is not an lvalue so they can be ignored.
2332
2333    // (x + n) or (n + x) => x
2334    if (BO->getOpcode() == BinaryOperator::Add) {
2335      if (BO->getLHS()->getType()->isPointerType()) {
2336        return getPrimaryDecl(BO->getLHS());
2337      } else if (BO->getRHS()->getType()->isPointerType()) {
2338        return getPrimaryDecl(BO->getRHS());
2339      }
2340    }
2341
2342    return 0;
2343  }
2344  case Stmt::ParenExprClass:
2345    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
2346  case Stmt::ImplicitCastExprClass:
2347    // &X[4] when X is an array, has an implicit cast from array to pointer.
2348    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
2349  default:
2350    return 0;
2351  }
2352}
2353
2354/// CheckAddressOfOperand - The operand of & must be either a function
2355/// designator or an lvalue designating an object. If it is an lvalue, the
2356/// object cannot be declared with storage class register or be a bit field.
2357/// Note: The usual conversions are *not* applied to the operand of the &
2358/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
2359QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
2360  if (getLangOptions().C99) {
2361    // Implement C99-only parts of addressof rules.
2362    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
2363      if (uOp->getOpcode() == UnaryOperator::Deref)
2364        // Per C99 6.5.3.2, the address of a deref always returns a valid result
2365        // (assuming the deref expression is valid).
2366        return uOp->getSubExpr()->getType();
2367    }
2368    // Technically, there should be a check for array subscript
2369    // expressions here, but the result of one is always an lvalue anyway.
2370  }
2371  ValueDecl *dcl = getPrimaryDecl(op);
2372  Expr::isLvalueResult lval = op->isLvalue(Context);
2373
2374  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
2375    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
2376      // FIXME: emit more specific diag...
2377      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
2378           op->getSourceRange());
2379      return QualType();
2380    }
2381  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
2382    if (MemExpr->getMemberDecl()->isBitField()) {
2383      Diag(OpLoc, diag::err_typecheck_address_of,
2384           std::string("bit-field"), op->getSourceRange());
2385      return QualType();
2386    }
2387  // Check for Apple extension for accessing vector components.
2388  } else if (isa<ArraySubscriptExpr>(op) &&
2389           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
2390    Diag(OpLoc, diag::err_typecheck_address_of,
2391         std::string("vector"), op->getSourceRange());
2392    return QualType();
2393  } else if (dcl) { // C99 6.5.3.2p1
2394    // We have an lvalue with a decl. Make sure the decl is not declared
2395    // with the register storage-class specifier.
2396    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
2397      if (vd->getStorageClass() == VarDecl::Register) {
2398        Diag(OpLoc, diag::err_typecheck_address_of,
2399             std::string("register variable"), op->getSourceRange());
2400        return QualType();
2401      }
2402    } else
2403      assert(0 && "Unknown/unexpected decl type");
2404  }
2405
2406  // If the operand has type "type", the result has type "pointer to type".
2407  return Context.getPointerType(op->getType());
2408}
2409
2410QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
2411  UsualUnaryConversions(op);
2412  QualType qType = op->getType();
2413
2414  if (const PointerType *PT = qType->getAsPointerType()) {
2415    // Note that per both C89 and C99, this is always legal, even
2416    // if ptype is an incomplete type or void.
2417    // It would be possible to warn about dereferencing a
2418    // void pointer, but it's completely well-defined,
2419    // and such a warning is unlikely to catch any mistakes.
2420    return PT->getPointeeType();
2421  }
2422  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
2423       qType.getAsString(), op->getSourceRange());
2424  return QualType();
2425}
2426
2427static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
2428  tok::TokenKind Kind) {
2429  BinaryOperator::Opcode Opc;
2430  switch (Kind) {
2431  default: assert(0 && "Unknown binop!");
2432  case tok::star:                 Opc = BinaryOperator::Mul; break;
2433  case tok::slash:                Opc = BinaryOperator::Div; break;
2434  case tok::percent:              Opc = BinaryOperator::Rem; break;
2435  case tok::plus:                 Opc = BinaryOperator::Add; break;
2436  case tok::minus:                Opc = BinaryOperator::Sub; break;
2437  case tok::lessless:             Opc = BinaryOperator::Shl; break;
2438  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
2439  case tok::lessequal:            Opc = BinaryOperator::LE; break;
2440  case tok::less:                 Opc = BinaryOperator::LT; break;
2441  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
2442  case tok::greater:              Opc = BinaryOperator::GT; break;
2443  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
2444  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
2445  case tok::amp:                  Opc = BinaryOperator::And; break;
2446  case tok::caret:                Opc = BinaryOperator::Xor; break;
2447  case tok::pipe:                 Opc = BinaryOperator::Or; break;
2448  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
2449  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
2450  case tok::equal:                Opc = BinaryOperator::Assign; break;
2451  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
2452  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
2453  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
2454  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
2455  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
2456  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
2457  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
2458  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
2459  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
2460  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
2461  case tok::comma:                Opc = BinaryOperator::Comma; break;
2462  }
2463  return Opc;
2464}
2465
2466static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
2467  tok::TokenKind Kind) {
2468  UnaryOperator::Opcode Opc;
2469  switch (Kind) {
2470  default: assert(0 && "Unknown unary op!");
2471  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
2472  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
2473  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
2474  case tok::star:         Opc = UnaryOperator::Deref; break;
2475  case tok::plus:         Opc = UnaryOperator::Plus; break;
2476  case tok::minus:        Opc = UnaryOperator::Minus; break;
2477  case tok::tilde:        Opc = UnaryOperator::Not; break;
2478  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
2479  case tok::kw_sizeof:    Opc = UnaryOperator::SizeOf; break;
2480  case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
2481  case tok::kw___real:    Opc = UnaryOperator::Real; break;
2482  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
2483  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
2484  }
2485  return Opc;
2486}
2487
2488// Binary Operators.  'Tok' is the token for the operator.
2489Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
2490                                    ExprTy *LHS, ExprTy *RHS) {
2491  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
2492  Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
2493
2494  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
2495  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
2496
2497  QualType ResultTy;  // Result type of the binary operator.
2498  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
2499
2500  switch (Opc) {
2501  default:
2502    assert(0 && "Unknown binary expr!");
2503  case BinaryOperator::Assign:
2504    ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
2505    break;
2506  case BinaryOperator::Mul:
2507  case BinaryOperator::Div:
2508    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2509    break;
2510  case BinaryOperator::Rem:
2511    ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2512    break;
2513  case BinaryOperator::Add:
2514    ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2515    break;
2516  case BinaryOperator::Sub:
2517    ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2518    break;
2519  case BinaryOperator::Shl:
2520  case BinaryOperator::Shr:
2521    ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2522    break;
2523  case BinaryOperator::LE:
2524  case BinaryOperator::LT:
2525  case BinaryOperator::GE:
2526  case BinaryOperator::GT:
2527    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
2528    break;
2529  case BinaryOperator::EQ:
2530  case BinaryOperator::NE:
2531    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
2532    break;
2533  case BinaryOperator::And:
2534  case BinaryOperator::Xor:
2535  case BinaryOperator::Or:
2536    ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2537    break;
2538  case BinaryOperator::LAnd:
2539  case BinaryOperator::LOr:
2540    ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2541    break;
2542  case BinaryOperator::MulAssign:
2543  case BinaryOperator::DivAssign:
2544    CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
2545    if (!CompTy.isNull())
2546      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2547    break;
2548  case BinaryOperator::RemAssign:
2549    CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
2550    if (!CompTy.isNull())
2551      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2552    break;
2553  case BinaryOperator::AddAssign:
2554    CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
2555    if (!CompTy.isNull())
2556      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2557    break;
2558  case BinaryOperator::SubAssign:
2559    CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
2560    if (!CompTy.isNull())
2561      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2562    break;
2563  case BinaryOperator::ShlAssign:
2564  case BinaryOperator::ShrAssign:
2565    CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
2566    if (!CompTy.isNull())
2567      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2568    break;
2569  case BinaryOperator::AndAssign:
2570  case BinaryOperator::XorAssign:
2571  case BinaryOperator::OrAssign:
2572    CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
2573    if (!CompTy.isNull())
2574      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2575    break;
2576  case BinaryOperator::Comma:
2577    ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2578    break;
2579  }
2580  if (ResultTy.isNull())
2581    return true;
2582  if (CompTy.isNull())
2583    return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2584  else
2585    return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
2586}
2587
2588// Unary Operators.  'Tok' is the token for the operator.
2589Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
2590                                      ExprTy *input) {
2591  Expr *Input = (Expr*)input;
2592  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2593  QualType resultType;
2594  switch (Opc) {
2595  default:
2596    assert(0 && "Unimplemented unary expr!");
2597  case UnaryOperator::PreInc:
2598  case UnaryOperator::PreDec:
2599    resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2600    break;
2601  case UnaryOperator::AddrOf:
2602    resultType = CheckAddressOfOperand(Input, OpLoc);
2603    break;
2604  case UnaryOperator::Deref:
2605    DefaultFunctionArrayConversion(Input);
2606    resultType = CheckIndirectionOperand(Input, OpLoc);
2607    break;
2608  case UnaryOperator::Plus:
2609  case UnaryOperator::Minus:
2610    UsualUnaryConversions(Input);
2611    resultType = Input->getType();
2612    if (!resultType->isArithmeticType())  // C99 6.5.3.3p1
2613      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2614                  resultType.getAsString());
2615    break;
2616  case UnaryOperator::Not: // bitwise complement
2617    UsualUnaryConversions(Input);
2618    resultType = Input->getType();
2619    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
2620    if (resultType->isComplexType() || resultType->isComplexIntegerType())
2621      // C99 does not support '~' for complex conjugation.
2622      Diag(OpLoc, diag::ext_integer_complement_complex,
2623           resultType.getAsString(), Input->getSourceRange());
2624    else if (!resultType->isIntegerType())
2625      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2626                  resultType.getAsString(), Input->getSourceRange());
2627    break;
2628  case UnaryOperator::LNot: // logical negation
2629    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2630    DefaultFunctionArrayConversion(Input);
2631    resultType = Input->getType();
2632    if (!resultType->isScalarType()) // C99 6.5.3.3p1
2633      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2634                  resultType.getAsString());
2635    // LNot always has type int. C99 6.5.3.3p5.
2636    resultType = Context.IntTy;
2637    break;
2638  case UnaryOperator::SizeOf:
2639    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2640                                           Input->getSourceRange(), true);
2641    break;
2642  case UnaryOperator::AlignOf:
2643    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc,
2644                                           Input->getSourceRange(), false);
2645    break;
2646  case UnaryOperator::Real:
2647  case UnaryOperator::Imag:
2648    resultType = CheckRealImagOperand(Input, OpLoc);
2649    break;
2650  case UnaryOperator::Extension:
2651    resultType = Input->getType();
2652    break;
2653  }
2654  if (resultType.isNull())
2655    return true;
2656  return new UnaryOperator(Input, Opc, resultType, OpLoc);
2657}
2658
2659/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2660Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
2661                                      SourceLocation LabLoc,
2662                                      IdentifierInfo *LabelII) {
2663  // Look up the record for this label identifier.
2664  LabelStmt *&LabelDecl = LabelMap[LabelII];
2665
2666  // If we haven't seen this label yet, create a forward reference. It
2667  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
2668  if (LabelDecl == 0)
2669    LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2670
2671  // Create the AST node.  The address of a label always has type 'void*'.
2672  return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2673                           Context.getPointerType(Context.VoidTy));
2674}
2675
2676Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
2677                                     SourceLocation RPLoc) { // "({..})"
2678  Stmt *SubStmt = static_cast<Stmt*>(substmt);
2679  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2680  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2681
2682  // FIXME: there are a variety of strange constraints to enforce here, for
2683  // example, it is not possible to goto into a stmt expression apparently.
2684  // More semantic analysis is needed.
2685
2686  // FIXME: the last statement in the compount stmt has its value used.  We
2687  // should not warn about it being unused.
2688
2689  // If there are sub stmts in the compound stmt, take the type of the last one
2690  // as the type of the stmtexpr.
2691  QualType Ty = Context.VoidTy;
2692
2693  if (!Compound->body_empty()) {
2694    Stmt *LastStmt = Compound->body_back();
2695    // If LastStmt is a label, skip down through into the body.
2696    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
2697      LastStmt = Label->getSubStmt();
2698
2699    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
2700      Ty = LastExpr->getType();
2701  }
2702
2703  return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2704}
2705
2706Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
2707                                            SourceLocation TypeLoc,
2708                                            TypeTy *argty,
2709                                            OffsetOfComponent *CompPtr,
2710                                            unsigned NumComponents,
2711                                            SourceLocation RPLoc) {
2712  QualType ArgTy = QualType::getFromOpaquePtr(argty);
2713  assert(!ArgTy.isNull() && "Missing type argument!");
2714
2715  // We must have at least one component that refers to the type, and the first
2716  // one is known to be a field designator.  Verify that the ArgTy represents
2717  // a struct/union/class.
2718  if (!ArgTy->isRecordType())
2719    return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2720
2721  // Otherwise, create a compound literal expression as the base, and
2722  // iteratively process the offsetof designators.
2723  Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
2724
2725  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2726  // GCC extension, diagnose them.
2727  if (NumComponents != 1)
2728    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2729         SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2730
2731  for (unsigned i = 0; i != NumComponents; ++i) {
2732    const OffsetOfComponent &OC = CompPtr[i];
2733    if (OC.isBrackets) {
2734      // Offset of an array sub-field.  TODO: Should we allow vector elements?
2735      const ArrayType *AT = Context.getAsArrayType(Res->getType());
2736      if (!AT) {
2737        delete Res;
2738        return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2739                    Res->getType().getAsString());
2740      }
2741
2742      // FIXME: C++: Verify that operator[] isn't overloaded.
2743
2744      // C99 6.5.2.1p1
2745      Expr *Idx = static_cast<Expr*>(OC.U.E);
2746      if (!Idx->getType()->isIntegerType())
2747        return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2748                    Idx->getSourceRange());
2749
2750      Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2751      continue;
2752    }
2753
2754    const RecordType *RC = Res->getType()->getAsRecordType();
2755    if (!RC) {
2756      delete Res;
2757      return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2758                  Res->getType().getAsString());
2759    }
2760
2761    // Get the decl corresponding to this.
2762    RecordDecl *RD = RC->getDecl();
2763    FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2764    if (!MemberDecl)
2765      return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2766                  OC.U.IdentInfo->getName(),
2767                  SourceRange(OC.LocStart, OC.LocEnd));
2768
2769    // FIXME: C++: Verify that MemberDecl isn't a static field.
2770    // FIXME: Verify that MemberDecl isn't a bitfield.
2771    // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2772    // matter here.
2773    Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
2774  }
2775
2776  return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2777                           BuiltinLoc);
2778}
2779
2780
2781Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
2782                                                TypeTy *arg1, TypeTy *arg2,
2783                                                SourceLocation RPLoc) {
2784  QualType argT1 = QualType::getFromOpaquePtr(arg1);
2785  QualType argT2 = QualType::getFromOpaquePtr(arg2);
2786
2787  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2788
2789  return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
2790}
2791
2792Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
2793                                       ExprTy *expr1, ExprTy *expr2,
2794                                       SourceLocation RPLoc) {
2795  Expr *CondExpr = static_cast<Expr*>(cond);
2796  Expr *LHSExpr = static_cast<Expr*>(expr1);
2797  Expr *RHSExpr = static_cast<Expr*>(expr2);
2798
2799  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2800
2801  // The conditional expression is required to be a constant expression.
2802  llvm::APSInt condEval(32);
2803  SourceLocation ExpLoc;
2804  if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2805    return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2806                 CondExpr->getSourceRange());
2807
2808  // If the condition is > zero, then the AST type is the same as the LSHExpr.
2809  QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2810                                               RHSExpr->getType();
2811  return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2812}
2813
2814//===----------------------------------------------------------------------===//
2815// Clang Extensions.
2816//===----------------------------------------------------------------------===//
2817
2818/// ActOnBlockStart - This callback is invoked when a block literal is started.
2819void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
2820  // Analyze block parameters.
2821  BlockSemaInfo *BSI = new BlockSemaInfo();
2822
2823  // Add BSI to CurBlock.
2824  BSI->PrevBlockInfo = CurBlock;
2825  CurBlock = BSI;
2826
2827  BSI->ReturnType = 0;
2828  BSI->TheScope = BlockScope;
2829
2830  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
2831  PushDeclContext(BSI->TheDecl);
2832}
2833
2834void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
2835  // Analyze arguments to block.
2836  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2837         "Not a function declarator!");
2838  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
2839
2840  CurBlock->hasPrototype = FTI.hasPrototype;
2841  CurBlock->isVariadic = true;
2842
2843  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
2844  // no arguments, not a function that takes a single void argument.
2845  if (FTI.hasPrototype &&
2846      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
2847      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
2848        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
2849    // empty arg list, don't push any params.
2850    CurBlock->isVariadic = false;
2851  } else if (FTI.hasPrototype) {
2852    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
2853      CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
2854    CurBlock->isVariadic = FTI.isVariadic;
2855  }
2856  CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
2857
2858  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
2859       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
2860    // If this has an identifier, add it to the scope stack.
2861    if ((*AI)->getIdentifier())
2862      PushOnScopeChains(*AI, CurBlock->TheScope);
2863}
2864
2865/// ActOnBlockError - If there is an error parsing a block, this callback
2866/// is invoked to pop the information about the block from the action impl.
2867void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
2868  // Ensure that CurBlock is deleted.
2869  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
2870
2871  // Pop off CurBlock, handle nested blocks.
2872  CurBlock = CurBlock->PrevBlockInfo;
2873
2874  // FIXME: Delete the ParmVarDecl objects as well???
2875
2876}
2877
2878/// ActOnBlockStmtExpr - This is called when the body of a block statement
2879/// literal was successfully completed.  ^(int x){...}
2880Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
2881                                          Scope *CurScope) {
2882  // Ensure that CurBlock is deleted.
2883  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
2884  llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
2885
2886  PopDeclContext();
2887
2888  // Pop off CurBlock, handle nested blocks.
2889  CurBlock = CurBlock->PrevBlockInfo;
2890
2891  QualType RetTy = Context.VoidTy;
2892  if (BSI->ReturnType)
2893    RetTy = QualType(BSI->ReturnType, 0);
2894
2895  llvm::SmallVector<QualType, 8> ArgTypes;
2896  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
2897    ArgTypes.push_back(BSI->Params[i]->getType());
2898
2899  QualType BlockTy;
2900  if (!BSI->hasPrototype)
2901    BlockTy = Context.getFunctionTypeNoProto(RetTy);
2902  else
2903    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
2904                                      BSI->isVariadic);
2905
2906  BlockTy = Context.getBlockPointerType(BlockTy);
2907
2908  BSI->TheDecl->setBody(Body.take());
2909  return new BlockExpr(BSI->TheDecl, BlockTy);
2910}
2911
2912/// ExprsMatchFnType - return true if the Exprs in array Args have
2913/// QualTypes that match the QualTypes of the arguments of the FnType.
2914/// The number of arguments has already been validated to match the number of
2915/// arguments in FnType.
2916static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
2917                             ASTContext &Context) {
2918  unsigned NumParams = FnType->getNumArgs();
2919  for (unsigned i = 0; i != NumParams; ++i) {
2920    QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
2921    QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
2922
2923    if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
2924      return false;
2925  }
2926  return true;
2927}
2928
2929Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2930                                         SourceLocation *CommaLocs,
2931                                         SourceLocation BuiltinLoc,
2932                                         SourceLocation RParenLoc) {
2933  // __builtin_overload requires at least 2 arguments
2934  if (NumArgs < 2)
2935    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2936                SourceRange(BuiltinLoc, RParenLoc));
2937
2938  // The first argument is required to be a constant expression.  It tells us
2939  // the number of arguments to pass to each of the functions to be overloaded.
2940  Expr **Args = reinterpret_cast<Expr**>(args);
2941  Expr *NParamsExpr = Args[0];
2942  llvm::APSInt constEval(32);
2943  SourceLocation ExpLoc;
2944  if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2945    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2946                NParamsExpr->getSourceRange());
2947
2948  // Verify that the number of parameters is > 0
2949  unsigned NumParams = constEval.getZExtValue();
2950  if (NumParams == 0)
2951    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2952                NParamsExpr->getSourceRange());
2953  // Verify that we have at least 1 + NumParams arguments to the builtin.
2954  if ((NumParams + 1) > NumArgs)
2955    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2956                SourceRange(BuiltinLoc, RParenLoc));
2957
2958  // Figure out the return type, by matching the args to one of the functions
2959  // listed after the parameters.
2960  OverloadExpr *OE = 0;
2961  for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2962    // UsualUnaryConversions will convert the function DeclRefExpr into a
2963    // pointer to function.
2964    Expr *Fn = UsualUnaryConversions(Args[i]);
2965    const FunctionTypeProto *FnType = 0;
2966    if (const PointerType *PT = Fn->getType()->getAsPointerType())
2967      FnType = PT->getPointeeType()->getAsFunctionTypeProto();
2968
2969    // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2970    // parameters, and the number of parameters must match the value passed to
2971    // the builtin.
2972    if (!FnType || (FnType->getNumArgs() != NumParams))
2973      return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2974                  Fn->getSourceRange());
2975
2976    // Scan the parameter list for the FunctionType, checking the QualType of
2977    // each parameter against the QualTypes of the arguments to the builtin.
2978    // If they match, return a new OverloadExpr.
2979    if (ExprsMatchFnType(Args+1, FnType, Context)) {
2980      if (OE)
2981        return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2982                    OE->getFn()->getSourceRange());
2983      // Remember our match, and continue processing the remaining arguments
2984      // to catch any errors.
2985      OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2986                            BuiltinLoc, RParenLoc);
2987    }
2988  }
2989  // Return the newly created OverloadExpr node, if we succeded in matching
2990  // exactly one of the candidate functions.
2991  if (OE)
2992    return OE;
2993
2994  // If we didn't find a matching function Expr in the __builtin_overload list
2995  // the return an error.
2996  std::string typeNames;
2997  for (unsigned i = 0; i != NumParams; ++i) {
2998    if (i != 0) typeNames += ", ";
2999    typeNames += Args[i+1]->getType().getAsString();
3000  }
3001
3002  return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
3003              SourceRange(BuiltinLoc, RParenLoc));
3004}
3005
3006Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
3007                                  ExprTy *expr, TypeTy *type,
3008                                  SourceLocation RPLoc) {
3009  Expr *E = static_cast<Expr*>(expr);
3010  QualType T = QualType::getFromOpaquePtr(type);
3011
3012  InitBuiltinVaListType();
3013
3014  // Get the va_list type
3015  QualType VaListType = Context.getBuiltinVaListType();
3016  // Deal with implicit array decay; for example, on x86-64,
3017  // va_list is an array, but it's supposed to decay to
3018  // a pointer for va_arg.
3019  if (VaListType->isArrayType())
3020    VaListType = Context.getArrayDecayedType(VaListType);
3021  // Make sure the input expression also decays appropriately.
3022  UsualUnaryConversions(E);
3023
3024  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
3025    return Diag(E->getLocStart(),
3026                diag::err_first_argument_to_va_arg_not_of_type_va_list,
3027                E->getType().getAsString(),
3028                E->getSourceRange());
3029
3030  // FIXME: Warn if a non-POD type is passed in.
3031
3032  return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
3033}
3034
3035bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
3036                                    SourceLocation Loc,
3037                                    QualType DstType, QualType SrcType,
3038                                    Expr *SrcExpr, const char *Flavor) {
3039  // Decode the result (notice that AST's are still created for extensions).
3040  bool isInvalid = false;
3041  unsigned DiagKind;
3042  switch (ConvTy) {
3043  default: assert(0 && "Unknown conversion type");
3044  case Compatible: return false;
3045  case PointerToInt:
3046    DiagKind = diag::ext_typecheck_convert_pointer_int;
3047    break;
3048  case IntToPointer:
3049    DiagKind = diag::ext_typecheck_convert_int_pointer;
3050    break;
3051  case IncompatiblePointer:
3052    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
3053    break;
3054  case FunctionVoidPointer:
3055    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
3056    break;
3057  case CompatiblePointerDiscardsQualifiers:
3058    // If the qualifiers lost were because we were applying the
3059    // (deprecated) C++ conversion from a string literal to a char*
3060    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
3061    // Ideally, this check would be performed in
3062    // CheckPointerTypesForAssignment. However, that would require a
3063    // bit of refactoring (so that the second argument is an
3064    // expression, rather than a type), which should be done as part
3065    // of a larger effort to fix CheckPointerTypesForAssignment for
3066    // C++ semantics.
3067    if (getLangOptions().CPlusPlus &&
3068        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
3069      return false;
3070    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
3071    break;
3072  case IntToBlockPointer:
3073    DiagKind = diag::err_int_to_block_pointer;
3074    break;
3075  case IncompatibleBlockPointer:
3076    DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
3077    break;
3078  case BlockVoidPointer:
3079    DiagKind = diag::ext_typecheck_convert_pointer_void_block;
3080    break;
3081  case Incompatible:
3082    DiagKind = diag::err_typecheck_convert_incompatible;
3083    isInvalid = true;
3084    break;
3085  }
3086
3087  Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
3088       SrcExpr->getSourceRange());
3089  return isInvalid;
3090}
3091