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