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