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