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