SemaExpr.cpp revision f025aac0b835baa716774a8eaef8ec018232541e
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 "SemaUtil.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Parse/DeclSpec.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Lex/LiteralSupport.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/TargetInfo.h"
25#include "llvm/ADT/OwningPtr.h"
26#include "llvm/ADT/SmallString.h"
27#include "llvm/ADT/StringExtras.h"
28using namespace clang;
29
30/// ActOnStringLiteral - The specified tokens were lexed as pasted string
31/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
32/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
33/// multiple tokens.  However, the common case is that StringToks points to one
34/// string.
35///
36Action::ExprResult
37Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
38  assert(NumStringToks && "Must have at least one string!");
39
40  StringLiteralParser Literal(StringToks, NumStringToks, PP, Context.Target);
41  if (Literal.hadError)
42    return ExprResult(true);
43
44  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
45  for (unsigned i = 0; i != NumStringToks; ++i)
46    StringTokLocs.push_back(StringToks[i].getLocation());
47
48  // Verify that pascal strings aren't too large.
49  if (Literal.Pascal && Literal.GetStringLength() > 256)
50    return Diag(StringToks[0].getLocation(), diag::err_pascal_string_too_long,
51                SourceRange(StringToks[0].getLocation(),
52                            StringToks[NumStringToks-1].getLocation()));
53
54  QualType StrTy = Context.CharTy;
55  if (Literal.AnyWide) StrTy = Context.getWcharType();
56  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
57
58  // Get an array type for the string, according to C99 6.4.5.  This includes
59  // the nul terminator character as well as the string length for pascal
60  // strings.
61  StrTy = Context.getConstantArrayType(StrTy,
62                                   llvm::APInt(32, Literal.GetStringLength()+1),
63                                       ArrayType::Normal, 0);
64
65  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
66  return new StringLiteral(Literal.GetString(), Literal.GetStringLength(),
67                           Literal.AnyWide, StrTy,
68                           StringToks[0].getLocation(),
69                           StringToks[NumStringToks-1].getLocation());
70}
71
72
73/// ActOnIdentifierExpr - The parser read an identifier in expression context,
74/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
75/// identifier is used in a function call context.
76Sema::ExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
77                                           IdentifierInfo &II,
78                                           bool HasTrailingLParen) {
79  // Could be enum-constant, value decl, instance variable, etc.
80  Decl *D = LookupDecl(&II, Decl::IDNS_Ordinary, S);
81
82  // If this reference is in an Objective-C method, then ivar lookup happens as
83  // well.
84  if (CurMethodDecl) {
85    ScopedDecl *SD = dyn_cast_or_null<ScopedDecl>(D);
86    // There are two cases to handle here.  1) scoped lookup could have failed,
87    // in which case we should look for an ivar.  2) scoped lookup could have
88    // found a decl, but that decl is outside the current method (i.e. a global
89    // variable).  In these two cases, we do a lookup for an ivar with this
90    // name, if the lookup suceeds, we replace it our current decl.
91    if (SD == 0 || SD->isDefinedOutsideFunctionOrMethod()) {
92      ObjCInterfaceDecl *IFace = CurMethodDecl->getClassInterface(), *DeclClass;
93      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&II, DeclClass)) {
94        // FIXME: This should use a new expr for a direct reference, don't turn
95        // this into Self->ivar, just return a BareIVarExpr or something.
96        IdentifierInfo &II = Context.Idents.get("self");
97        ExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
98        return new ObjCIvarRefExpr(IV, IV->getType(), Loc,
99                                 static_cast<Expr*>(SelfExpr.Val), true, true);
100      }
101    }
102    if (SD == 0 && !strncmp(II.getName(), "super", 5)) {
103      QualType T = Context.getPointerType(Context.getObjCInterfaceType(
104                     CurMethodDecl->getClassInterface()));
105      return new ObjCSuperRefExpr(T, Loc);
106    }
107  }
108
109  if (D == 0) {
110    // Otherwise, this could be an implicitly declared function reference (legal
111    // in C90, extension in C99).
112    if (HasTrailingLParen &&
113        !getLangOptions().CPlusPlus) // Not in C++.
114      D = ImplicitlyDefineFunction(Loc, II, S);
115    else {
116      // If this name wasn't predeclared and if this is not a function call,
117      // diagnose the problem.
118      return Diag(Loc, diag::err_undeclared_var_use, II.getName());
119    }
120  }
121
122  if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
123    // check if referencing an identifier with __attribute__((deprecated)).
124    if (VD->getAttr<DeprecatedAttr>())
125      Diag(Loc, diag::warn_deprecated, VD->getName());
126
127    // Only create DeclRefExpr's for valid Decl's.
128    if (VD->isInvalidDecl())
129      return true;
130    return new DeclRefExpr(VD, VD->getType(), Loc);
131  }
132
133  if (isa<TypedefDecl>(D))
134    return Diag(Loc, diag::err_unexpected_typedef, II.getName());
135  if (isa<ObjCInterfaceDecl>(D))
136    return Diag(Loc, diag::err_unexpected_interface, II.getName());
137  if (isa<NamespaceDecl>(D))
138    return Diag(Loc, diag::err_unexpected_namespace, II.getName());
139
140  assert(0 && "Invalid decl");
141  abort();
142}
143
144Sema::ExprResult Sema::ActOnPreDefinedExpr(SourceLocation Loc,
145                                           tok::TokenKind Kind) {
146  PreDefinedExpr::IdentType IT;
147
148  switch (Kind) {
149  default: assert(0 && "Unknown simple primary expr!");
150  case tok::kw___func__: IT = PreDefinedExpr::Func; break; // [C99 6.4.2.2]
151  case tok::kw___FUNCTION__: IT = PreDefinedExpr::Function; break;
152  case tok::kw___PRETTY_FUNCTION__: IT = PreDefinedExpr::PrettyFunction; break;
153  }
154
155  // Verify that this is in a function context.
156  if (CurFunctionDecl == 0 && CurMethodDecl == 0)
157    return Diag(Loc, diag::err_predef_outside_function);
158
159  // Pre-defined identifiers are of type char[x], where x is the length of the
160  // string.
161  unsigned Length;
162  if (CurFunctionDecl)
163    Length = CurFunctionDecl->getIdentifier()->getLength();
164  else
165    Length = CurMethodDecl->getSynthesizedMethodSize();
166
167  llvm::APInt LengthI(32, Length + 1);
168  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
169  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
170  return new PreDefinedExpr(Loc, ResTy, IT);
171}
172
173Sema::ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
174  llvm::SmallString<16> CharBuffer;
175  CharBuffer.resize(Tok.getLength());
176  const char *ThisTokBegin = &CharBuffer[0];
177  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
178
179  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
180                            Tok.getLocation(), PP);
181  if (Literal.hadError())
182    return ExprResult(true);
183
184  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
185
186  return new CharacterLiteral(Literal.getValue(), type, Tok.getLocation());
187}
188
189Action::ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
190  // fast path for a single digit (which is quite common). A single digit
191  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
192  if (Tok.getLength() == 1) {
193    const char *Ty = PP.getSourceManager().getCharacterData(Tok.getLocation());
194
195    unsigned IntSize =static_cast<unsigned>(Context.getTypeSize(Context.IntTy));
196    return ExprResult(new IntegerLiteral(llvm::APInt(IntSize, *Ty-'0'),
197                                         Context.IntTy,
198                                         Tok.getLocation()));
199  }
200  llvm::SmallString<512> IntegerBuffer;
201  IntegerBuffer.resize(Tok.getLength());
202  const char *ThisTokBegin = &IntegerBuffer[0];
203
204  // Get the spelling of the token, which eliminates trigraphs, etc.
205  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
206  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
207                               Tok.getLocation(), PP);
208  if (Literal.hadError)
209    return ExprResult(true);
210
211  Expr *Res;
212
213  if (Literal.isFloatingLiteral()) {
214    QualType Ty;
215    const llvm::fltSemantics *Format;
216
217    if (Literal.isFloat) {
218      Ty = Context.FloatTy;
219      Format = Context.Target.getFloatFormat();
220    } else if (!Literal.isLong) {
221      Ty = Context.DoubleTy;
222      Format = Context.Target.getDoubleFormat();
223    } else {
224      Ty = Context.LongDoubleTy;
225      Format = Context.Target.getLongDoubleFormat();
226    }
227
228    // isExact will be set by GetFloatValue().
229    bool isExact = false;
230
231    Res = new FloatingLiteral(Literal.GetFloatValue(*Format,&isExact), &isExact,
232                              Ty, Tok.getLocation());
233
234  } else if (!Literal.isIntegerLiteral()) {
235    return ExprResult(true);
236  } else {
237    QualType Ty;
238
239    // long long is a C99 feature.
240    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
241        Literal.isLongLong)
242      Diag(Tok.getLocation(), diag::ext_longlong);
243
244    // Get the value in the widest-possible width.
245    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
246
247    if (Literal.GetIntegerValue(ResultVal)) {
248      // If this value didn't fit into uintmax_t, warn and force to ull.
249      Diag(Tok.getLocation(), diag::warn_integer_too_large);
250      Ty = Context.UnsignedLongLongTy;
251      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
252             "long long is not intmax_t?");
253    } else {
254      // If this value fits into a ULL, try to figure out what else it fits into
255      // according to the rules of C99 6.4.4.1p5.
256
257      // Octal, Hexadecimal, and integers with a U suffix are allowed to
258      // be an unsigned int.
259      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
260
261      // Check from smallest to largest, picking the smallest type we can.
262      unsigned Width = 0;
263      if (!Literal.isLong && !Literal.isLongLong) {
264        // Are int/unsigned possibilities?
265        unsigned IntSize = Context.Target.getIntWidth();
266
267        // Does it fit in a unsigned int?
268        if (ResultVal.isIntN(IntSize)) {
269          // Does it fit in a signed int?
270          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
271            Ty = Context.IntTy;
272          else if (AllowUnsigned)
273            Ty = Context.UnsignedIntTy;
274          Width = IntSize;
275        }
276      }
277
278      // Are long/unsigned long possibilities?
279      if (Ty.isNull() && !Literal.isLongLong) {
280        unsigned LongSize = Context.Target.getLongWidth();
281
282        // Does it fit in a unsigned long?
283        if (ResultVal.isIntN(LongSize)) {
284          // Does it fit in a signed long?
285          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
286            Ty = Context.LongTy;
287          else if (AllowUnsigned)
288            Ty = Context.UnsignedLongTy;
289          Width = LongSize;
290        }
291      }
292
293      // Finally, check long long if needed.
294      if (Ty.isNull()) {
295        unsigned LongLongSize = Context.Target.getLongLongWidth();
296
297        // Does it fit in a unsigned long long?
298        if (ResultVal.isIntN(LongLongSize)) {
299          // Does it fit in a signed long long?
300          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
301            Ty = Context.LongLongTy;
302          else if (AllowUnsigned)
303            Ty = Context.UnsignedLongLongTy;
304          Width = LongLongSize;
305        }
306      }
307
308      // If we still couldn't decide a type, we probably have something that
309      // does not fit in a signed long long, but has no U suffix.
310      if (Ty.isNull()) {
311        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
312        Ty = Context.UnsignedLongLongTy;
313        Width = Context.Target.getLongLongWidth();
314      }
315
316      if (ResultVal.getBitWidth() != Width)
317        ResultVal.trunc(Width);
318    }
319
320    Res = new IntegerLiteral(ResultVal, Ty, Tok.getLocation());
321  }
322
323  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
324  if (Literal.isImaginary)
325    Res = new ImaginaryLiteral(Res, Context.getComplexType(Res->getType()));
326
327  return Res;
328}
329
330Action::ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R,
331                                        ExprTy *Val) {
332  Expr *E = (Expr *)Val;
333  assert((E != 0) && "ActOnParenExpr() missing expr");
334  return new ParenExpr(L, R, E);
335}
336
337/// The UsualUnaryConversions() function is *not* called by this routine.
338/// See C99 6.3.2.1p[2-4] for more details.
339QualType Sema::CheckSizeOfAlignOfOperand(QualType exprType,
340                                         SourceLocation OpLoc, bool isSizeof) {
341  // C99 6.5.3.4p1:
342  if (isa<FunctionType>(exprType) && isSizeof)
343    // alignof(function) is allowed.
344    Diag(OpLoc, diag::ext_sizeof_function_type);
345  else if (exprType->isVoidType())
346    Diag(OpLoc, diag::ext_sizeof_void_type, isSizeof ? "sizeof" : "__alignof");
347  else if (exprType->isIncompleteType()) {
348    Diag(OpLoc, isSizeof ? diag::err_sizeof_incomplete_type :
349                           diag::err_alignof_incomplete_type,
350         exprType.getAsString());
351    return QualType(); // error
352  }
353  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
354  return Context.getSizeType();
355}
356
357Action::ExprResult Sema::
358ActOnSizeOfAlignOfTypeExpr(SourceLocation OpLoc, bool isSizeof,
359                           SourceLocation LPLoc, TypeTy *Ty,
360                           SourceLocation RPLoc) {
361  // If error parsing type, ignore.
362  if (Ty == 0) return true;
363
364  // Verify that this is a valid expression.
365  QualType ArgTy = QualType::getFromOpaquePtr(Ty);
366
367  QualType resultType = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, isSizeof);
368
369  if (resultType.isNull())
370    return true;
371  return new SizeOfAlignOfTypeExpr(isSizeof, ArgTy, resultType, OpLoc, RPLoc);
372}
373
374QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
375  DefaultFunctionArrayConversion(V);
376
377  // These operators return the element type of a complex type.
378  if (const ComplexType *CT = V->getType()->getAsComplexType())
379    return CT->getElementType();
380
381  // Otherwise they pass through real integer and floating point types here.
382  if (V->getType()->isArithmeticType())
383    return V->getType();
384
385  // Reject anything else.
386  Diag(Loc, diag::err_realimag_invalid_type, V->getType().getAsString());
387  return QualType();
388}
389
390
391
392Action::ExprResult Sema::ActOnPostfixUnaryOp(SourceLocation OpLoc,
393                                             tok::TokenKind Kind,
394                                             ExprTy *Input) {
395  UnaryOperator::Opcode Opc;
396  switch (Kind) {
397  default: assert(0 && "Unknown unary op!");
398  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
399  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
400  }
401  QualType result = CheckIncrementDecrementOperand((Expr *)Input, OpLoc);
402  if (result.isNull())
403    return true;
404  return new UnaryOperator((Expr *)Input, Opc, result, OpLoc);
405}
406
407Action::ExprResult Sema::
408ActOnArraySubscriptExpr(ExprTy *Base, SourceLocation LLoc,
409                        ExprTy *Idx, SourceLocation RLoc) {
410  Expr *LHSExp = static_cast<Expr*>(Base), *RHSExp = static_cast<Expr*>(Idx);
411
412  // Perform default conversions.
413  DefaultFunctionArrayConversion(LHSExp);
414  DefaultFunctionArrayConversion(RHSExp);
415
416  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
417
418  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
419  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
420  // in the subscript position. As a result, we need to derive the array base
421  // and index from the expression types.
422  Expr *BaseExpr, *IndexExpr;
423  QualType ResultType;
424  if (const PointerType *PTy = LHSTy->getAsPointerType()) {
425    BaseExpr = LHSExp;
426    IndexExpr = RHSExp;
427    // FIXME: need to deal with const...
428    ResultType = PTy->getPointeeType();
429  } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
430     // Handle the uncommon case of "123[Ptr]".
431    BaseExpr = RHSExp;
432    IndexExpr = LHSExp;
433    // FIXME: need to deal with const...
434    ResultType = PTy->getPointeeType();
435  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
436    BaseExpr = LHSExp;    // vectors: V[123]
437    IndexExpr = RHSExp;
438
439    // Component access limited to variables (reject vec4.rg[1]).
440    if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
441        !isa<ExtVectorElementExpr>(BaseExpr))
442      return Diag(LLoc, diag::err_ext_vector_component_access,
443                  SourceRange(LLoc, RLoc));
444    // FIXME: need to deal with const...
445    ResultType = VTy->getElementType();
446  } else {
447    return Diag(LHSExp->getLocStart(), diag::err_typecheck_subscript_value,
448                RHSExp->getSourceRange());
449  }
450  // C99 6.5.2.1p1
451  if (!IndexExpr->getType()->isIntegerType())
452    return Diag(IndexExpr->getLocStart(), diag::err_typecheck_subscript,
453                IndexExpr->getSourceRange());
454
455  // C99 6.5.2.1p1: "shall have type "pointer to *object* type".  In practice,
456  // the following check catches trying to index a pointer to a function (e.g.
457  // void (*)(int)) and pointers to incomplete types.  Functions are not
458  // objects in C99.
459  if (!ResultType->isObjectType())
460    return Diag(BaseExpr->getLocStart(),
461                diag::err_typecheck_subscript_not_object,
462                BaseExpr->getType().getAsString(), BaseExpr->getSourceRange());
463
464  return new ArraySubscriptExpr(LHSExp, RHSExp, ResultType, RLoc);
465}
466
467QualType Sema::
468CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
469                        IdentifierInfo &CompName, SourceLocation CompLoc) {
470  const ExtVectorType *vecType = baseType->getAsExtVectorType();
471
472  // This flag determines whether or not the component is to be treated as a
473  // special name, or a regular GLSL-style component access.
474  bool SpecialComponent = false;
475
476  // The vector accessor can't exceed the number of elements.
477  const char *compStr = CompName.getName();
478  if (strlen(compStr) > vecType->getNumElements()) {
479    Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
480                baseType.getAsString(), SourceRange(CompLoc));
481    return QualType();
482  }
483
484  // Check that we've found one of the special components, or that the component
485  // names must come from the same set.
486  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
487      !strcmp(compStr, "e") || !strcmp(compStr, "o")) {
488    SpecialComponent = true;
489  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
490    do
491      compStr++;
492    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
493  } else if (vecType->getColorAccessorIdx(*compStr) != -1) {
494    do
495      compStr++;
496    while (*compStr && vecType->getColorAccessorIdx(*compStr) != -1);
497  } else if (vecType->getTextureAccessorIdx(*compStr) != -1) {
498    do
499      compStr++;
500    while (*compStr && vecType->getTextureAccessorIdx(*compStr) != -1);
501  }
502
503  if (!SpecialComponent && *compStr) {
504    // We didn't get to the end of the string. This means the component names
505    // didn't come from the same set *or* we encountered an illegal name.
506    Diag(OpLoc, diag::err_ext_vector_component_name_illegal,
507         std::string(compStr,compStr+1), SourceRange(CompLoc));
508    return QualType();
509  }
510  // Each component accessor can't exceed the vector type.
511  compStr = CompName.getName();
512  while (*compStr) {
513    if (vecType->isAccessorWithinNumElements(*compStr))
514      compStr++;
515    else
516      break;
517  }
518  if (!SpecialComponent && *compStr) {
519    // We didn't get to the end of the string. This means a component accessor
520    // exceeds the number of elements in the vector.
521    Diag(OpLoc, diag::err_ext_vector_component_exceeds_length,
522                baseType.getAsString(), SourceRange(CompLoc));
523    return QualType();
524  }
525
526  // If we have a special component name, verify that the current vector length
527  // is an even number, since all special component names return exactly half
528  // the elements.
529  if (SpecialComponent && (vecType->getNumElements() & 1U)) {
530    return QualType();
531  }
532
533  // The component accessor looks fine - now we need to compute the actual type.
534  // The vector type is implied by the component accessor. For example,
535  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
536  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
537  unsigned CompSize = SpecialComponent ? vecType->getNumElements() / 2
538                                       : strlen(CompName.getName());
539  if (CompSize == 1)
540    return vecType->getElementType();
541
542  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
543  // Now look up the TypeDefDecl from the vector type. Without this,
544  // diagostics look bad. We want extended vector types to appear built-in.
545  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
546    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
547      return Context.getTypedefType(ExtVectorDecls[i]);
548  }
549  return VT; // should never get here (a typedef type should always be found).
550}
551
552Action::ExprResult Sema::
553ActOnMemberReferenceExpr(ExprTy *Base, SourceLocation OpLoc,
554                         tok::TokenKind OpKind, SourceLocation MemberLoc,
555                         IdentifierInfo &Member) {
556  Expr *BaseExpr = static_cast<Expr *>(Base);
557  assert(BaseExpr && "no record expression");
558
559  // Perform default conversions.
560  DefaultFunctionArrayConversion(BaseExpr);
561
562  QualType BaseType = BaseExpr->getType();
563  assert(!BaseType.isNull() && "no type for member expression");
564
565  if (OpKind == tok::arrow) {
566    if (const PointerType *PT = BaseType->getAsPointerType())
567      BaseType = PT->getPointeeType();
568    else
569      return Diag(OpLoc, diag::err_typecheck_member_reference_arrow,
570                  SourceRange(MemberLoc));
571  }
572  // The base type is either a record or an ExtVectorType.
573  if (const RecordType *RTy = BaseType->getAsRecordType()) {
574    RecordDecl *RDecl = RTy->getDecl();
575    if (RTy->isIncompleteType())
576      return Diag(OpLoc, diag::err_typecheck_incomplete_tag, RDecl->getName(),
577                  BaseExpr->getSourceRange());
578    // The record definition is complete, now make sure the member is valid.
579    FieldDecl *MemberDecl = RDecl->getMember(&Member);
580    if (!MemberDecl)
581      return Diag(OpLoc, diag::err_typecheck_no_member, Member.getName(),
582                  SourceRange(MemberLoc));
583
584    // Figure out the type of the member; see C99 6.5.2.3p3
585    // FIXME: Handle address space modifiers
586    QualType MemberType = MemberDecl->getType();
587    unsigned combinedQualifiers =
588        MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
589    MemberType = MemberType.getQualifiedType(combinedQualifiers);
590
591    return new MemberExpr(BaseExpr, OpKind==tok::arrow, MemberDecl,
592                          MemberLoc, MemberType);
593  } else if (BaseType->isExtVectorType() && OpKind == tok::period) {
594    // Component access limited to variables (reject vec4.rg.g).
595    if (!isa<DeclRefExpr>(BaseExpr) && !isa<ArraySubscriptExpr>(BaseExpr) &&
596        !isa<ExtVectorElementExpr>(BaseExpr))
597      return Diag(OpLoc, diag::err_ext_vector_component_access,
598                  SourceRange(MemberLoc));
599    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
600    if (ret.isNull())
601      return true;
602    return new ExtVectorElementExpr(ret, BaseExpr, Member, MemberLoc);
603  } else if (BaseType->isObjCInterfaceType()) {
604    ObjCInterfaceDecl *IFace;
605    if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
606      IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
607    else
608      IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
609    ObjCInterfaceDecl *clsDeclared;
610    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
611      return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
612                                 OpKind==tok::arrow);
613  } else if (isObjCObjectPointerType(BaseType)) {
614    PointerType *pointerType = static_cast<PointerType*>(BaseType.getTypePtr());
615    BaseType = pointerType->getPointeeType();
616    ObjCInterfaceDecl *IFace;
617    if (isa<ObjCInterfaceType>(BaseType.getCanonicalType()))
618      IFace = dyn_cast<ObjCInterfaceType>(BaseType)->getDecl();
619    else
620      IFace = dyn_cast<ObjCQualifiedInterfaceType>(BaseType)->getDecl();
621    ObjCInterfaceDecl *clsDeclared;
622    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(&Member, clsDeclared))
623      return new ObjCIvarRefExpr(IV, IV->getType(), MemberLoc, BaseExpr,
624                                 OpKind==tok::arrow);
625    // Check for properties.
626    if (OpKind==tok::period) {
627      // Before we look for explicit property declarations, we check for
628      // nullary methods (which allow '.' notation).
629      Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
630      ObjCMethodDecl *MD = IFace->lookupInstanceMethod(Sel);
631      if (MD)
632        return new ObjCPropertyRefExpr(MD, MD->getResultType(),
633                                       MemberLoc, BaseExpr);
634      // FIXME: Need to deal with setter methods that take 1 argument. E.g.:
635      // @interface NSBundle : NSObject {}
636      // - (NSString *)bundlePath;
637      // - (void)setBundlePath:(NSString *)x;
638      // @end
639      // void someMethod() { frameworkBundle.bundlePath = 0; }
640      //
641      ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member);
642      if (PD)
643        return new ObjCPropertyRefExpr(PD, PD->getType(), MemberLoc, BaseExpr);
644    }
645  }
646  return Diag(OpLoc, diag::err_typecheck_member_reference_structUnion,
647              SourceRange(MemberLoc));
648}
649
650/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
651/// This provides the location of the left/right parens and a list of comma
652/// locations.
653Action::ExprResult Sema::
654ActOnCallExpr(ExprTy *fn, SourceLocation LParenLoc,
655              ExprTy **args, unsigned NumArgs,
656              SourceLocation *CommaLocs, SourceLocation RParenLoc) {
657  Expr *Fn = static_cast<Expr *>(fn);
658  Expr **Args = reinterpret_cast<Expr**>(args);
659  assert(Fn && "no function call expression");
660  FunctionDecl *FDecl = NULL;
661
662  // Promote the function operand.
663  UsualUnaryConversions(Fn);
664
665  // If we're directly calling a function, get the declaration for
666  // that function.
667  if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(Fn))
668    if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(IcExpr->getSubExpr()))
669      FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
670
671  // Make the call expr early, before semantic checks.  This guarantees cleanup
672  // of arguments and function on error.
673  llvm::OwningPtr<CallExpr> TheCall(new CallExpr(Fn, Args, NumArgs,
674                                                 Context.BoolTy, RParenLoc));
675
676  // C99 6.5.2.2p1 - "The expression that denotes the called function shall have
677  // type pointer to function".
678  const PointerType *PT = Fn->getType()->getAsPointerType();
679  if (PT == 0)
680    return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
681                SourceRange(Fn->getLocStart(), RParenLoc));
682  const FunctionType *FuncT = PT->getPointeeType()->getAsFunctionType();
683  if (FuncT == 0)
684    return Diag(Fn->getLocStart(), diag::err_typecheck_call_not_function,
685                SourceRange(Fn->getLocStart(), RParenLoc));
686
687  // We know the result type of the call, set it.
688  TheCall->setType(FuncT->getResultType());
689
690  if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
691    // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
692    // assignment, to the types of the corresponding parameter, ...
693    unsigned NumArgsInProto = Proto->getNumArgs();
694    unsigned NumArgsToCheck = NumArgs;
695
696    // If too few arguments are available (and we don't have default
697    // arguments for the remaining parameters), don't make the call.
698    if (NumArgs < NumArgsInProto) {
699      if (FDecl && NumArgs >= FDecl->getMinRequiredArguments()) {
700        // Use default arguments for missing arguments
701        NumArgsToCheck = NumArgsInProto;
702        TheCall->setNumArgs(NumArgsInProto);
703      } else
704        return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
705                    Fn->getSourceRange());
706    }
707
708    // If too many are passed and not variadic, error on the extras and drop
709    // them.
710    if (NumArgs > NumArgsInProto) {
711      if (!Proto->isVariadic()) {
712        Diag(Args[NumArgsInProto]->getLocStart(),
713             diag::err_typecheck_call_too_many_args, Fn->getSourceRange(),
714             SourceRange(Args[NumArgsInProto]->getLocStart(),
715                         Args[NumArgs-1]->getLocEnd()));
716        // This deletes the extra arguments.
717        TheCall->setNumArgs(NumArgsInProto);
718      }
719      NumArgsToCheck = NumArgsInProto;
720    }
721
722    // Continue to check argument types (even if we have too few/many args).
723    for (unsigned i = 0; i != NumArgsToCheck; i++) {
724      QualType ProtoArgType = Proto->getArgType(i);
725
726      Expr *Arg;
727      if (i < NumArgs)
728        Arg = Args[i];
729      else
730        Arg = new CXXDefaultArgExpr(FDecl->getParamDecl(i));
731      QualType ArgType = Arg->getType();
732
733      // Compute implicit casts from the operand to the formal argument type.
734      AssignConvertType ConvTy =
735        CheckSingleAssignmentConstraints(ProtoArgType, Arg);
736      TheCall->setArg(i, Arg);
737
738      if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), ProtoArgType,
739                                   ArgType, Arg, "passing"))
740        return true;
741    }
742
743    // If this is a variadic call, handle args passed through "...".
744    if (Proto->isVariadic()) {
745      // Promote the arguments (C99 6.5.2.2p7).
746      for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
747        Expr *Arg = Args[i];
748        DefaultArgumentPromotion(Arg);
749        TheCall->setArg(i, Arg);
750      }
751    }
752  } else {
753    assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
754
755    // Promote the arguments (C99 6.5.2.2p6).
756    for (unsigned i = 0; i != NumArgs; i++) {
757      Expr *Arg = Args[i];
758      DefaultArgumentPromotion(Arg);
759      TheCall->setArg(i, Arg);
760    }
761  }
762
763  // Do special checking on direct calls to functions.
764  if (FDecl)
765    return CheckFunctionCall(FDecl, TheCall.take());
766
767  return TheCall.take();
768}
769
770Action::ExprResult Sema::
771ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
772                     SourceLocation RParenLoc, ExprTy *InitExpr) {
773  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
774  QualType literalType = QualType::getFromOpaquePtr(Ty);
775  // FIXME: put back this assert when initializers are worked out.
776  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
777  Expr *literalExpr = static_cast<Expr*>(InitExpr);
778
779  if (literalType->isArrayType()) {
780    if (literalType->getAsVariableArrayType())
781      return Diag(LParenLoc,
782                  diag::err_variable_object_no_init,
783                  SourceRange(LParenLoc,
784                              literalExpr->getSourceRange().getEnd()));
785  } else if (literalType->isIncompleteType()) {
786    return Diag(LParenLoc,
787                diag::err_typecheck_decl_incomplete_type,
788                literalType.getAsString(),
789                SourceRange(LParenLoc,
790                            literalExpr->getSourceRange().getEnd()));
791  }
792
793  if (CheckInitializerTypes(literalExpr, literalType))
794    return true;
795
796  bool isFileScope = !CurFunctionDecl && !CurMethodDecl;
797  if (isFileScope) { // 6.5.2.5p3
798    if (CheckForConstantInitializer(literalExpr, literalType))
799      return true;
800  }
801  return new CompoundLiteralExpr(LParenLoc, literalType, literalExpr, isFileScope);
802}
803
804Action::ExprResult Sema::
805ActOnInitList(SourceLocation LBraceLoc, ExprTy **initlist, unsigned NumInit,
806              SourceLocation RBraceLoc) {
807  Expr **InitList = reinterpret_cast<Expr**>(initlist);
808
809  // Semantic analysis for initializers is done by ActOnDeclarator() and
810  // CheckInitializer() - it requires knowledge of the object being intialized.
811
812  InitListExpr *E = new InitListExpr(LBraceLoc, InitList, NumInit, RBraceLoc);
813  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
814  return E;
815}
816
817bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
818  assert(VectorTy->isVectorType() && "Not a vector type!");
819
820  if (Ty->isVectorType() || Ty->isIntegerType()) {
821    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
822      return Diag(R.getBegin(),
823                  Ty->isVectorType() ?
824                  diag::err_invalid_conversion_between_vectors :
825                  diag::err_invalid_conversion_between_vector_and_integer,
826                  VectorTy.getAsString().c_str(),
827                  Ty.getAsString().c_str(), R);
828  } else
829    return Diag(R.getBegin(),
830                diag::err_invalid_conversion_between_vector_and_scalar,
831                VectorTy.getAsString().c_str(),
832                Ty.getAsString().c_str(), R);
833
834  return false;
835}
836
837Action::ExprResult Sema::
838ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
839              SourceLocation RParenLoc, ExprTy *Op) {
840  assert((Ty != 0) && (Op != 0) && "ActOnCastExpr(): missing type or expr");
841
842  Expr *castExpr = static_cast<Expr*>(Op);
843  QualType castType = QualType::getFromOpaquePtr(Ty);
844
845  UsualUnaryConversions(castExpr);
846
847  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
848  // type needs to be scalar.
849  if (!castType->isVoidType()) {  // Cast to void allows any expr type.
850    if (!castType->isScalarType() && !castType->isVectorType()) {
851      // GCC struct/union extension.
852      if (castType == castExpr->getType() &&
853          castType->isStructureType() || castType->isUnionType()) {
854        Diag(LParenLoc, diag::ext_typecheck_cast_nonscalar,
855             SourceRange(LParenLoc, RParenLoc));
856        return new CastExpr(castType, castExpr, LParenLoc);
857      } else
858        return Diag(LParenLoc, diag::err_typecheck_cond_expect_scalar,
859                    castType.getAsString(), SourceRange(LParenLoc, RParenLoc));
860    }
861    if (!castExpr->getType()->isScalarType() &&
862        !castExpr->getType()->isVectorType())
863      return Diag(castExpr->getLocStart(),
864                  diag::err_typecheck_expect_scalar_operand,
865                  castExpr->getType().getAsString(),castExpr->getSourceRange());
866
867    if (castExpr->getType()->isVectorType()) {
868      if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
869                          castExpr->getType(), castType))
870        return true;
871    } else if (castType->isVectorType()) {
872      if (CheckVectorCast(SourceRange(LParenLoc, RParenLoc),
873                          castType, castExpr->getType()))
874        return true;
875    }
876  }
877  return new CastExpr(castType, castExpr, LParenLoc);
878}
879
880/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
881/// In that case, lex = cond.
882inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
883  Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
884  UsualUnaryConversions(cond);
885  UsualUnaryConversions(lex);
886  UsualUnaryConversions(rex);
887  QualType condT = cond->getType();
888  QualType lexT = lex->getType();
889  QualType rexT = rex->getType();
890
891  // first, check the condition.
892  if (!condT->isScalarType()) { // C99 6.5.15p2
893    Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar,
894         condT.getAsString());
895    return QualType();
896  }
897
898  // Now check the two expressions.
899
900  // If both operands have arithmetic type, do the usual arithmetic conversions
901  // to find a common type: C99 6.5.15p3,5.
902  if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
903    UsualArithmeticConversions(lex, rex);
904    return lex->getType();
905  }
906
907  // If both operands are the same structure or union type, the result is that
908  // type.
909  if (const RecordType *LHSRT = lexT->getAsRecordType()) {    // C99 6.5.15p3
910    if (const RecordType *RHSRT = rexT->getAsRecordType())
911      if (LHSRT->getDecl() == RHSRT->getDecl())
912        // "If both the operands have structure or union type, the result has
913        // that type."  This implies that CV qualifiers are dropped.
914        return lexT.getUnqualifiedType();
915  }
916
917  // C99 6.5.15p5: "If both operands have void type, the result has void type."
918  // The following || allows only one side to be void (a GCC-ism).
919  if (lexT->isVoidType() || rexT->isVoidType()) {
920    if (!lexT->isVoidType())
921      Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void,
922           rex->getSourceRange());
923    if (!rexT->isVoidType())
924      Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void,
925           lex->getSourceRange());
926    ImpCastExprToType(lex, Context.VoidTy);
927    ImpCastExprToType(rex, Context.VoidTy);
928    return Context.VoidTy;
929  }
930  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
931  // the type of the other operand."
932  if (lexT->isPointerType() && rex->isNullPointerConstant(Context)) {
933    ImpCastExprToType(rex, lexT); // promote the null to a pointer.
934    return lexT;
935  }
936  if (rexT->isPointerType() && lex->isNullPointerConstant(Context)) {
937    ImpCastExprToType(lex, rexT); // promote the null to a pointer.
938    return rexT;
939  }
940  // Handle the case where both operands are pointers before we handle null
941  // pointer constants in case both operands are null pointer constants.
942  if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
943    if (const PointerType *RHSPT = rexT->getAsPointerType()) {
944      // get the "pointed to" types
945      QualType lhptee = LHSPT->getPointeeType();
946      QualType rhptee = RHSPT->getPointeeType();
947
948      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
949      if (lhptee->isVoidType() &&
950          rhptee->isIncompleteOrObjectType()) {
951        // Figure out necessary qualifiers (C99 6.5.15p6)
952        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
953        QualType destType = Context.getPointerType(destPointee);
954        ImpCastExprToType(lex, destType); // add qualifiers if necessary
955        ImpCastExprToType(rex, destType); // promote to void*
956        return destType;
957      }
958      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
959        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
960        QualType destType = Context.getPointerType(destPointee);
961        ImpCastExprToType(lex, destType); // add qualifiers if necessary
962        ImpCastExprToType(rex, destType); // promote to void*
963        return destType;
964      }
965
966      if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
967                                      rhptee.getUnqualifiedType())) {
968        Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers,
969             lexT.getAsString(), rexT.getAsString(),
970             lex->getSourceRange(), rex->getSourceRange());
971        // In this situation, we assume void* type. No especially good
972        // reason, but this is what gcc does, and we do have to pick
973        // to get a consistent AST.
974        QualType voidPtrTy = Context.getPointerType(Context.VoidTy);
975        ImpCastExprToType(lex, voidPtrTy);
976        ImpCastExprToType(rex, voidPtrTy);
977        return voidPtrTy;
978      }
979      // The pointer types are compatible.
980      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
981      // differently qualified versions of compatible types, the result type is
982      // a pointer to an appropriately qualified version of the *composite*
983      // type.
984      // FIXME: Need to calculate the composite type.
985      // FIXME: Need to add qualifiers
986      QualType compositeType = lexT;
987      ImpCastExprToType(lex, compositeType);
988      ImpCastExprToType(rex, compositeType);
989      return compositeType;
990    }
991  }
992  // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
993  // evaluates to "struct objc_object *" (and is handled above when comparing
994  // id with statically typed objects). FIXME: Do we need an ImpCastExprToType?
995  if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
996    if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true))
997      return Context.getObjCIdType();
998  }
999  // Otherwise, the operands are not compatible.
1000  Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands,
1001       lexT.getAsString(), rexT.getAsString(),
1002       lex->getSourceRange(), rex->getSourceRange());
1003  return QualType();
1004}
1005
1006/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
1007/// in the case of a the GNU conditional expr extension.
1008Action::ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
1009                                            SourceLocation ColonLoc,
1010                                            ExprTy *Cond, ExprTy *LHS,
1011                                            ExprTy *RHS) {
1012  Expr *CondExpr = (Expr *) Cond;
1013  Expr *LHSExpr = (Expr *) LHS, *RHSExpr = (Expr *) RHS;
1014
1015  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
1016  // was the condition.
1017  bool isLHSNull = LHSExpr == 0;
1018  if (isLHSNull)
1019    LHSExpr = CondExpr;
1020
1021  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
1022                                             RHSExpr, QuestionLoc);
1023  if (result.isNull())
1024    return true;
1025  return new ConditionalOperator(CondExpr, isLHSNull ? 0 : LHSExpr,
1026                                 RHSExpr, result);
1027}
1028
1029/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
1030/// do not have a prototype. Arguments that have type float are promoted to
1031/// double. All other argument types are converted by UsualUnaryConversions().
1032void Sema::DefaultArgumentPromotion(Expr *&Expr) {
1033  QualType Ty = Expr->getType();
1034  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
1035
1036  if (Ty == Context.FloatTy)
1037    ImpCastExprToType(Expr, Context.DoubleTy);
1038  else
1039    UsualUnaryConversions(Expr);
1040}
1041
1042/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
1043void Sema::DefaultFunctionArrayConversion(Expr *&E) {
1044  QualType Ty = E->getType();
1045  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
1046
1047  if (const ReferenceType *ref = Ty->getAsReferenceType()) {
1048    ImpCastExprToType(E, ref->getPointeeType()); // C++ [expr]
1049    Ty = E->getType();
1050  }
1051  if (Ty->isFunctionType())
1052    ImpCastExprToType(E, Context.getPointerType(Ty));
1053  else if (Ty->isArrayType())
1054    ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
1055}
1056
1057/// UsualUnaryConversions - Performs various conversions that are common to most
1058/// operators (C99 6.3). The conversions of array and function types are
1059/// sometimes surpressed. For example, the array->pointer conversion doesn't
1060/// apply if the array is an argument to the sizeof or address (&) operators.
1061/// In these instances, this routine should *not* be called.
1062Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
1063  QualType Ty = Expr->getType();
1064  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
1065
1066  if (const ReferenceType *Ref = Ty->getAsReferenceType()) {
1067    ImpCastExprToType(Expr, Ref->getPointeeType()); // C++ [expr]
1068    Ty = Expr->getType();
1069  }
1070  if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
1071    ImpCastExprToType(Expr, Context.IntTy);
1072  else
1073    DefaultFunctionArrayConversion(Expr);
1074
1075  return Expr;
1076}
1077
1078/// UsualArithmeticConversions - Performs various conversions that are common to
1079/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
1080/// routine returns the first non-arithmetic type found. The client is
1081/// responsible for emitting appropriate error diagnostics.
1082/// FIXME: verify the conversion rules for "complex int" are consistent with
1083/// GCC.
1084QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
1085                                          bool isCompAssign) {
1086  if (!isCompAssign) {
1087    UsualUnaryConversions(lhsExpr);
1088    UsualUnaryConversions(rhsExpr);
1089  }
1090  // For conversion purposes, we ignore any qualifiers.
1091  // For example, "const float" and "float" are equivalent.
1092  QualType lhs = lhsExpr->getType().getCanonicalType().getUnqualifiedType();
1093  QualType rhs = rhsExpr->getType().getCanonicalType().getUnqualifiedType();
1094
1095  // If both types are identical, no conversion is needed.
1096  if (lhs == rhs)
1097    return lhs;
1098
1099  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
1100  // The caller can deal with this (e.g. pointer + int).
1101  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
1102    return lhs;
1103
1104  // At this point, we have two different arithmetic types.
1105
1106  // Handle complex types first (C99 6.3.1.8p1).
1107  if (lhs->isComplexType() || rhs->isComplexType()) {
1108    // if we have an integer operand, the result is the complex type.
1109    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
1110      // convert the rhs to the lhs complex type.
1111      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1112      return lhs;
1113    }
1114    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
1115      // convert the lhs to the rhs complex type.
1116      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1117      return rhs;
1118    }
1119    // This handles complex/complex, complex/float, or float/complex.
1120    // When both operands are complex, the shorter operand is converted to the
1121    // type of the longer, and that is the type of the result. This corresponds
1122    // to what is done when combining two real floating-point operands.
1123    // The fun begins when size promotion occur across type domains.
1124    // From H&S 6.3.4: When one operand is complex and the other is a real
1125    // floating-point type, the less precise type is converted, within it's
1126    // real or complex domain, to the precision of the other type. For example,
1127    // when combining a "long double" with a "double _Complex", the
1128    // "double _Complex" is promoted to "long double _Complex".
1129    int result = Context.getFloatingTypeOrder(lhs, rhs);
1130
1131    if (result > 0) { // The left side is bigger, convert rhs.
1132      rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
1133      if (!isCompAssign)
1134        ImpCastExprToType(rhsExpr, rhs);
1135    } else if (result < 0) { // The right side is bigger, convert lhs.
1136      lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
1137      if (!isCompAssign)
1138        ImpCastExprToType(lhsExpr, lhs);
1139    }
1140    // At this point, lhs and rhs have the same rank/size. Now, make sure the
1141    // domains match. This is a requirement for our implementation, C99
1142    // does not require this promotion.
1143    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
1144      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
1145        if (!isCompAssign)
1146          ImpCastExprToType(lhsExpr, rhs);
1147        return rhs;
1148      } else { // handle "_Complex double, double".
1149        if (!isCompAssign)
1150          ImpCastExprToType(rhsExpr, lhs);
1151        return lhs;
1152      }
1153    }
1154    return lhs; // The domain/size match exactly.
1155  }
1156  // Now handle "real" floating types (i.e. float, double, long double).
1157  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
1158    // if we have an integer operand, the result is the real floating type.
1159    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
1160      // convert rhs to the lhs floating point type.
1161      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1162      return lhs;
1163    }
1164    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
1165      // convert lhs to the rhs floating point type.
1166      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1167      return rhs;
1168    }
1169    // We have two real floating types, float/complex combos were handled above.
1170    // Convert the smaller operand to the bigger result.
1171    int result = Context.getFloatingTypeOrder(lhs, rhs);
1172
1173    if (result > 0) { // convert the rhs
1174      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1175      return lhs;
1176    }
1177    if (result < 0) { // convert the lhs
1178      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1179      return rhs;
1180    }
1181    assert(0 && "Sema::UsualArithmeticConversions(): illegal float comparison");
1182  }
1183  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
1184    // Handle GCC complex int extension.
1185    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
1186    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
1187
1188    if (lhsComplexInt && rhsComplexInt) {
1189      if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
1190                                      rhsComplexInt->getElementType()) >= 0) {
1191        // convert the rhs
1192        if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1193        return lhs;
1194      }
1195      if (!isCompAssign)
1196        ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1197      return rhs;
1198    } else if (lhsComplexInt && rhs->isIntegerType()) {
1199      // convert the rhs to the lhs complex type.
1200      if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1201      return lhs;
1202    } else if (rhsComplexInt && lhs->isIntegerType()) {
1203      // convert the lhs to the rhs complex type.
1204      if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs);
1205      return rhs;
1206    }
1207  }
1208  // Finally, we have two differing integer types.
1209  if (Context.getIntegerTypeOrder(lhs, rhs) >= 0) { // convert the rhs
1210    if (!isCompAssign) ImpCastExprToType(rhsExpr, lhs);
1211    return lhs;
1212  }
1213  if (!isCompAssign) ImpCastExprToType(lhsExpr, rhs); // convert the lhs
1214  return rhs;
1215}
1216
1217// CheckPointerTypesForAssignment - This is a very tricky routine (despite
1218// being closely modeled after the C99 spec:-). The odd characteristic of this
1219// routine is it effectively iqnores the qualifiers on the top level pointee.
1220// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
1221// FIXME: add a couple examples in this comment.
1222Sema::AssignConvertType
1223Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
1224  QualType lhptee, rhptee;
1225
1226  // get the "pointed to" type (ignoring qualifiers at the top level)
1227  lhptee = lhsType->getAsPointerType()->getPointeeType();
1228  rhptee = rhsType->getAsPointerType()->getPointeeType();
1229
1230  // make sure we operate on the canonical type
1231  lhptee = lhptee.getCanonicalType();
1232  rhptee = rhptee.getCanonicalType();
1233
1234  AssignConvertType ConvTy = Compatible;
1235
1236  // C99 6.5.16.1p1: This following citation is common to constraints
1237  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
1238  // qualifiers of the type *pointed to* by the right;
1239  // FIXME: Handle ASQualType
1240  if ((lhptee.getCVRQualifiers() & rhptee.getCVRQualifiers()) !=
1241       rhptee.getCVRQualifiers())
1242    ConvTy = CompatiblePointerDiscardsQualifiers;
1243
1244  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
1245  // incomplete type and the other is a pointer to a qualified or unqualified
1246  // version of void...
1247  if (lhptee->isVoidType()) {
1248    if (rhptee->isIncompleteOrObjectType())
1249      return ConvTy;
1250
1251    // As an extension, we allow cast to/from void* to function pointer.
1252    assert(rhptee->isFunctionType());
1253    return FunctionVoidPointer;
1254  }
1255
1256  if (rhptee->isVoidType()) {
1257    if (lhptee->isIncompleteOrObjectType())
1258      return ConvTy;
1259
1260    // As an extension, we allow cast to/from void* to function pointer.
1261    assert(lhptee->isFunctionType());
1262    return FunctionVoidPointer;
1263  }
1264
1265  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
1266  // unqualified versions of compatible types, ...
1267  if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
1268                                  rhptee.getUnqualifiedType()))
1269    return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
1270  return ConvTy;
1271}
1272
1273/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
1274/// has code to accommodate several GCC extensions when type checking
1275/// pointers. Here are some objectionable examples that GCC considers warnings:
1276///
1277///  int a, *pint;
1278///  short *pshort;
1279///  struct foo *pfoo;
1280///
1281///  pint = pshort; // warning: assignment from incompatible pointer type
1282///  a = pint; // warning: assignment makes integer from pointer without a cast
1283///  pint = a; // warning: assignment makes pointer from integer without a cast
1284///  pint = pfoo; // warning: assignment from incompatible pointer type
1285///
1286/// As a result, the code for dealing with pointers is more complex than the
1287/// C99 spec dictates.
1288///
1289Sema::AssignConvertType
1290Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
1291  // Get canonical types.  We're not formatting these types, just comparing
1292  // them.
1293  lhsType = lhsType.getCanonicalType().getUnqualifiedType();
1294  rhsType = rhsType.getCanonicalType().getUnqualifiedType();
1295
1296  if (lhsType == rhsType)
1297    return Compatible; // Common case: fast path an exact match.
1298
1299  if (lhsType->isReferenceType() || rhsType->isReferenceType()) {
1300    if (Context.typesAreCompatible(lhsType, rhsType))
1301      return Compatible;
1302    return Incompatible;
1303  }
1304
1305  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
1306    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
1307      return Compatible;
1308    // Relax integer conversions like we do for pointers below.
1309    if (rhsType->isIntegerType())
1310      return IntToPointer;
1311    if (lhsType->isIntegerType())
1312      return PointerToInt;
1313    return Incompatible;
1314  }
1315
1316  if (isa<VectorType>(lhsType) || isa<VectorType>(rhsType)) {
1317    // For ExtVector, allow vector splats; float -> <n x float>
1318    if (const ExtVectorType *LV = dyn_cast<ExtVectorType>(lhsType)) {
1319      if (LV->getElementType().getTypePtr() == rhsType.getTypePtr())
1320        return Compatible;
1321    }
1322
1323    // If LHS and RHS are both vectors of integer or both vectors of floating
1324    // point types, and the total vector length is the same, allow the
1325    // conversion.  This is a bitcast; no bits are changed but the result type
1326    // is different.
1327    if (getLangOptions().LaxVectorConversions &&
1328        lhsType->isVectorType() && rhsType->isVectorType()) {
1329      if ((lhsType->isIntegerType() && rhsType->isIntegerType()) ||
1330          (lhsType->isRealFloatingType() && rhsType->isRealFloatingType())) {
1331        if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
1332          return Compatible;
1333      }
1334    }
1335    return Incompatible;
1336  }
1337
1338  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
1339    return Compatible;
1340
1341  if (isa<PointerType>(lhsType)) {
1342    if (rhsType->isIntegerType())
1343      return IntToPointer;
1344
1345    if (isa<PointerType>(rhsType))
1346      return CheckPointerTypesForAssignment(lhsType, rhsType);
1347    return Incompatible;
1348  }
1349
1350  if (isa<PointerType>(rhsType)) {
1351    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
1352    if (lhsType == Context.BoolTy)
1353      return Compatible;
1354
1355    if (lhsType->isIntegerType())
1356      return PointerToInt;
1357
1358    if (isa<PointerType>(lhsType))
1359      return CheckPointerTypesForAssignment(lhsType, rhsType);
1360    return Incompatible;
1361  }
1362
1363  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
1364    if (Context.typesAreCompatible(lhsType, rhsType))
1365      return Compatible;
1366  }
1367  return Incompatible;
1368}
1369
1370Sema::AssignConvertType
1371Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
1372  // C99 6.5.16.1p1: the left operand is a pointer and the right is
1373  // a null pointer constant.
1374  if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType())
1375      && rExpr->isNullPointerConstant(Context)) {
1376    ImpCastExprToType(rExpr, lhsType);
1377    return Compatible;
1378  }
1379  // This check seems unnatural, however it is necessary to ensure the proper
1380  // conversion of functions/arrays. If the conversion were done for all
1381  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
1382  // expressions that surpress this implicit conversion (&, sizeof).
1383  //
1384  // Suppress this for references: C99 8.5.3p5.  FIXME: revisit when references
1385  // are better understood.
1386  if (!lhsType->isReferenceType())
1387    DefaultFunctionArrayConversion(rExpr);
1388
1389  Sema::AssignConvertType result =
1390    CheckAssignmentConstraints(lhsType, rExpr->getType());
1391
1392  // C99 6.5.16.1p2: The value of the right operand is converted to the
1393  // type of the assignment expression.
1394  if (rExpr->getType() != lhsType)
1395    ImpCastExprToType(rExpr, lhsType);
1396  return result;
1397}
1398
1399Sema::AssignConvertType
1400Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
1401  return CheckAssignmentConstraints(lhsType, rhsType);
1402}
1403
1404QualType Sema::InvalidOperands(SourceLocation loc, Expr *&lex, Expr *&rex) {
1405  Diag(loc, diag::err_typecheck_invalid_operands,
1406       lex->getType().getAsString(), rex->getType().getAsString(),
1407       lex->getSourceRange(), rex->getSourceRange());
1408  return QualType();
1409}
1410
1411inline QualType Sema::CheckVectorOperands(SourceLocation loc, Expr *&lex,
1412                                                              Expr *&rex) {
1413  // For conversion purposes, we ignore any qualifiers.
1414  // For example, "const float" and "float" are equivalent.
1415  QualType lhsType = lex->getType().getCanonicalType().getUnqualifiedType();
1416  QualType rhsType = rex->getType().getCanonicalType().getUnqualifiedType();
1417
1418  // make sure the vector types are identical.
1419  if (lhsType == rhsType)
1420    return lhsType;
1421
1422  // if the lhs is an extended vector and the rhs is a scalar of the same type,
1423  // promote the rhs to the vector type.
1424  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
1425    if (V->getElementType().getCanonicalType().getTypePtr()
1426        == rhsType.getCanonicalType().getTypePtr()) {
1427      ImpCastExprToType(rex, lhsType);
1428      return lhsType;
1429    }
1430  }
1431
1432  // if the rhs is an extended vector and the lhs is a scalar of the same type,
1433  // promote the lhs to the vector type.
1434  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
1435    if (V->getElementType().getCanonicalType().getTypePtr()
1436        == lhsType.getCanonicalType().getTypePtr()) {
1437      ImpCastExprToType(lex, rhsType);
1438      return rhsType;
1439    }
1440  }
1441
1442  // You cannot convert between vector values of different size.
1443  Diag(loc, diag::err_typecheck_vector_not_convertable,
1444       lex->getType().getAsString(), rex->getType().getAsString(),
1445       lex->getSourceRange(), rex->getSourceRange());
1446  return QualType();
1447}
1448
1449inline QualType Sema::CheckMultiplyDivideOperands(
1450  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1451{
1452  QualType lhsType = lex->getType(), rhsType = rex->getType();
1453
1454  if (lhsType->isVectorType() || rhsType->isVectorType())
1455    return CheckVectorOperands(loc, lex, rex);
1456
1457  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1458
1459  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1460    return compType;
1461  return InvalidOperands(loc, lex, rex);
1462}
1463
1464inline QualType Sema::CheckRemainderOperands(
1465  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1466{
1467  QualType lhsType = lex->getType(), rhsType = rex->getType();
1468
1469  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1470
1471  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1472    return compType;
1473  return InvalidOperands(loc, lex, rex);
1474}
1475
1476inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
1477  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1478{
1479  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1480    return CheckVectorOperands(loc, lex, rex);
1481
1482  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1483
1484  // handle the common case first (both operands are arithmetic).
1485  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1486    return compType;
1487
1488  // Put any potential pointer into PExp
1489  Expr* PExp = lex, *IExp = rex;
1490  if (IExp->getType()->isPointerType())
1491    std::swap(PExp, IExp);
1492
1493  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
1494    if (IExp->getType()->isIntegerType()) {
1495      // Check for arithmetic on pointers to incomplete types
1496      if (!PTy->getPointeeType()->isObjectType()) {
1497        if (PTy->getPointeeType()->isVoidType()) {
1498          Diag(loc, diag::ext_gnu_void_ptr,
1499               lex->getSourceRange(), rex->getSourceRange());
1500        } else {
1501          Diag(loc, diag::err_typecheck_arithmetic_incomplete_type,
1502               lex->getType().getAsString(), lex->getSourceRange());
1503          return QualType();
1504        }
1505      }
1506      return PExp->getType();
1507    }
1508  }
1509
1510  return InvalidOperands(loc, lex, rex);
1511}
1512
1513// C99 6.5.6
1514QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
1515                                        SourceLocation loc, bool isCompAssign) {
1516  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1517    return CheckVectorOperands(loc, lex, rex);
1518
1519  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1520
1521  // Enforce type constraints: C99 6.5.6p3.
1522
1523  // Handle the common case first (both operands are arithmetic).
1524  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1525    return compType;
1526
1527  // Either ptr - int   or   ptr - ptr.
1528  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
1529    QualType lpointee = LHSPTy->getPointeeType();
1530
1531    // The LHS must be an object type, not incomplete, function, etc.
1532    if (!lpointee->isObjectType()) {
1533      // Handle the GNU void* extension.
1534      if (lpointee->isVoidType()) {
1535        Diag(loc, diag::ext_gnu_void_ptr,
1536             lex->getSourceRange(), rex->getSourceRange());
1537      } else {
1538        Diag(loc, diag::err_typecheck_sub_ptr_object,
1539             lex->getType().getAsString(), lex->getSourceRange());
1540        return QualType();
1541      }
1542    }
1543
1544    // The result type of a pointer-int computation is the pointer type.
1545    if (rex->getType()->isIntegerType())
1546      return lex->getType();
1547
1548    // Handle pointer-pointer subtractions.
1549    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
1550      QualType rpointee = RHSPTy->getPointeeType();
1551
1552      // RHS must be an object type, unless void (GNU).
1553      if (!rpointee->isObjectType()) {
1554        // Handle the GNU void* extension.
1555        if (rpointee->isVoidType()) {
1556          if (!lpointee->isVoidType())
1557            Diag(loc, diag::ext_gnu_void_ptr,
1558                 lex->getSourceRange(), rex->getSourceRange());
1559        } else {
1560          Diag(loc, diag::err_typecheck_sub_ptr_object,
1561               rex->getType().getAsString(), rex->getSourceRange());
1562          return QualType();
1563        }
1564      }
1565
1566      // Pointee types must be compatible.
1567      if (!Context.typesAreCompatible(lpointee.getUnqualifiedType(),
1568                                      rpointee.getUnqualifiedType())) {
1569        Diag(loc, diag::err_typecheck_sub_ptr_compatible,
1570             lex->getType().getAsString(), rex->getType().getAsString(),
1571             lex->getSourceRange(), rex->getSourceRange());
1572        return QualType();
1573      }
1574
1575      return Context.getPointerDiffType();
1576    }
1577  }
1578
1579  return InvalidOperands(loc, lex, rex);
1580}
1581
1582// C99 6.5.7
1583QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1584                                  bool isCompAssign) {
1585  // C99 6.5.7p2: Each of the operands shall have integer type.
1586  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
1587    return InvalidOperands(loc, lex, rex);
1588
1589  // Shifts don't perform usual arithmetic conversions, they just do integer
1590  // promotions on each operand. C99 6.5.7p3
1591  if (!isCompAssign)
1592    UsualUnaryConversions(lex);
1593  UsualUnaryConversions(rex);
1594
1595  // "The type of the result is that of the promoted left operand."
1596  return lex->getType();
1597}
1598
1599// C99 6.5.8
1600QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation loc,
1601                                    bool isRelational) {
1602  // C99 6.5.8p3 / C99 6.5.9p4
1603  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
1604    UsualArithmeticConversions(lex, rex);
1605  else {
1606    UsualUnaryConversions(lex);
1607    UsualUnaryConversions(rex);
1608  }
1609  QualType lType = lex->getType();
1610  QualType rType = rex->getType();
1611
1612  // For non-floating point types, check for self-comparisons of the form
1613  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
1614  // often indicate logic errors in the program.
1615  if (!lType->isFloatingType()) {
1616    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
1617      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
1618        if (DRL->getDecl() == DRR->getDecl())
1619          Diag(loc, diag::warn_selfcomparison);
1620  }
1621
1622  if (isRelational) {
1623    if (lType->isRealType() && rType->isRealType())
1624      return Context.IntTy;
1625  } else {
1626    // Check for comparisons of floating point operands using != and ==.
1627    if (lType->isFloatingType()) {
1628      assert (rType->isFloatingType());
1629      CheckFloatComparison(loc,lex,rex);
1630    }
1631
1632    if (lType->isArithmeticType() && rType->isArithmeticType())
1633      return Context.IntTy;
1634  }
1635
1636  bool LHSIsNull = lex->isNullPointerConstant(Context);
1637  bool RHSIsNull = rex->isNullPointerConstant(Context);
1638
1639  // All of the following pointer related warnings are GCC extensions, except
1640  // when handling null pointer constants. One day, we can consider making them
1641  // errors (when -pedantic-errors is enabled).
1642  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
1643    QualType LCanPointeeTy =
1644      lType->getAsPointerType()->getPointeeType().getCanonicalType();
1645    QualType RCanPointeeTy =
1646      rType->getAsPointerType()->getPointeeType().getCanonicalType();
1647
1648    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
1649        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
1650        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
1651                                    RCanPointeeTy.getUnqualifiedType())) {
1652      Diag(loc, diag::ext_typecheck_comparison_of_distinct_pointers,
1653           lType.getAsString(), rType.getAsString(),
1654           lex->getSourceRange(), rex->getSourceRange());
1655    }
1656    ImpCastExprToType(rex, lType); // promote the pointer to pointer
1657    return Context.IntTy;
1658  }
1659  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
1660    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
1661      ImpCastExprToType(rex, lType);
1662      return Context.IntTy;
1663    }
1664  }
1665  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
1666       rType->isIntegerType()) {
1667    if (!RHSIsNull)
1668      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1669           lType.getAsString(), rType.getAsString(),
1670           lex->getSourceRange(), rex->getSourceRange());
1671    ImpCastExprToType(rex, lType); // promote the integer to pointer
1672    return Context.IntTy;
1673  }
1674  if (lType->isIntegerType() &&
1675      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
1676    if (!LHSIsNull)
1677      Diag(loc, diag::ext_typecheck_comparison_of_pointer_integer,
1678           lType.getAsString(), rType.getAsString(),
1679           lex->getSourceRange(), rex->getSourceRange());
1680    ImpCastExprToType(lex, rType); // promote the integer to pointer
1681    return Context.IntTy;
1682  }
1683  return InvalidOperands(loc, lex, rex);
1684}
1685
1686inline QualType Sema::CheckBitwiseOperands(
1687  Expr *&lex, Expr *&rex, SourceLocation loc, bool isCompAssign)
1688{
1689  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
1690    return CheckVectorOperands(loc, lex, rex);
1691
1692  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
1693
1694  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
1695    return compType;
1696  return InvalidOperands(loc, lex, rex);
1697}
1698
1699inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
1700  Expr *&lex, Expr *&rex, SourceLocation loc)
1701{
1702  UsualUnaryConversions(lex);
1703  UsualUnaryConversions(rex);
1704
1705  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
1706    return Context.IntTy;
1707  return InvalidOperands(loc, lex, rex);
1708}
1709
1710inline QualType Sema::CheckAssignmentOperands( // C99 6.5.16.1
1711  Expr *lex, Expr *&rex, SourceLocation loc, QualType compoundType)
1712{
1713  QualType lhsType = lex->getType();
1714  QualType rhsType = compoundType.isNull() ? rex->getType() : compoundType;
1715  Expr::isModifiableLvalueResult mlval = lex->isModifiableLvalue();
1716
1717  switch (mlval) { // C99 6.5.16p2
1718  case Expr::MLV_Valid:
1719    break;
1720  case Expr::MLV_ConstQualified:
1721    Diag(loc, diag::err_typecheck_assign_const, lex->getSourceRange());
1722    return QualType();
1723  case Expr::MLV_ArrayType:
1724    Diag(loc, diag::err_typecheck_array_not_modifiable_lvalue,
1725         lhsType.getAsString(), lex->getSourceRange());
1726    return QualType();
1727  case Expr::MLV_NotObjectType:
1728    Diag(loc, diag::err_typecheck_non_object_not_modifiable_lvalue,
1729         lhsType.getAsString(), lex->getSourceRange());
1730    return QualType();
1731  case Expr::MLV_InvalidExpression:
1732    Diag(loc, diag::err_typecheck_expression_not_modifiable_lvalue,
1733         lex->getSourceRange());
1734    return QualType();
1735  case Expr::MLV_IncompleteType:
1736  case Expr::MLV_IncompleteVoidType:
1737    Diag(loc, diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
1738         lhsType.getAsString(), lex->getSourceRange());
1739    return QualType();
1740  case Expr::MLV_DuplicateVectorComponents:
1741    Diag(loc, diag::err_typecheck_duplicate_vector_components_not_mlvalue,
1742         lex->getSourceRange());
1743    return QualType();
1744  }
1745
1746  AssignConvertType ConvTy;
1747  if (compoundType.isNull())
1748    ConvTy = CheckSingleAssignmentConstraints(lhsType, rex);
1749  else
1750    ConvTy = CheckCompoundAssignmentConstraints(lhsType, rhsType);
1751
1752  if (DiagnoseAssignmentResult(ConvTy, loc, lhsType, rhsType,
1753                               rex, "assigning"))
1754    return QualType();
1755
1756  // C99 6.5.16p3: The type of an assignment expression is the type of the
1757  // left operand unless the left operand has qualified type, in which case
1758  // it is the unqualified version of the type of the left operand.
1759  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
1760  // is converted to the type of the assignment expression (above).
1761  // C++ 5.17p1: the type of the assignment expression is that of its left
1762  // oprdu.
1763  return lhsType.getUnqualifiedType();
1764}
1765
1766inline QualType Sema::CheckCommaOperands( // C99 6.5.17
1767  Expr *&lex, Expr *&rex, SourceLocation loc) {
1768  UsualUnaryConversions(rex);
1769  return rex->getType();
1770}
1771
1772/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
1773/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
1774QualType Sema::CheckIncrementDecrementOperand(Expr *op, SourceLocation OpLoc) {
1775  QualType resType = op->getType();
1776  assert(!resType.isNull() && "no type for increment/decrement expression");
1777
1778  // C99 6.5.2.4p1: We allow complex as a GCC extension.
1779  if (const PointerType *pt = resType->getAsPointerType()) {
1780    if (pt->getPointeeType()->isVoidType()) {
1781      Diag(OpLoc, diag::ext_gnu_void_ptr, op->getSourceRange());
1782    } else if (!pt->getPointeeType()->isObjectType()) {
1783      // C99 6.5.2.4p2, 6.5.6p2
1784      Diag(OpLoc, diag::err_typecheck_arithmetic_incomplete_type,
1785           resType.getAsString(), op->getSourceRange());
1786      return QualType();
1787    }
1788  } else if (!resType->isRealType()) {
1789    if (resType->isComplexType())
1790      // C99 does not support ++/-- on complex types.
1791      Diag(OpLoc, diag::ext_integer_increment_complex,
1792           resType.getAsString(), op->getSourceRange());
1793    else {
1794      Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement,
1795           resType.getAsString(), op->getSourceRange());
1796      return QualType();
1797    }
1798  }
1799  // At this point, we know we have a real, complex or pointer type.
1800  // Now make sure the operand is a modifiable lvalue.
1801  Expr::isModifiableLvalueResult mlval = op->isModifiableLvalue();
1802  if (mlval != Expr::MLV_Valid) {
1803    // FIXME: emit a more precise diagnostic...
1804    Diag(OpLoc, diag::err_typecheck_invalid_lvalue_incr_decr,
1805         op->getSourceRange());
1806    return QualType();
1807  }
1808  return resType;
1809}
1810
1811/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
1812/// This routine allows us to typecheck complex/recursive expressions
1813/// where the declaration is needed for type checking. Here are some
1814/// examples: &s.xx, &s.zz[1].yy, &(1+2), &(XX), &"123"[2].
1815static ValueDecl *getPrimaryDecl(Expr *E) {
1816  switch (E->getStmtClass()) {
1817  case Stmt::DeclRefExprClass:
1818    return cast<DeclRefExpr>(E)->getDecl();
1819  case Stmt::MemberExprClass:
1820    // Fields cannot be declared with a 'register' storage class.
1821    // &X->f is always ok, even if X is declared register.
1822    if (cast<MemberExpr>(E)->isArrow())
1823      return 0;
1824    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
1825  case Stmt::ArraySubscriptExprClass: {
1826    // &X[4] and &4[X] is invalid if X is invalid and X is not a pointer.
1827
1828    ValueDecl *VD = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
1829    if (!VD || VD->getType()->isPointerType())
1830      return 0;
1831    else
1832      return VD;
1833  }
1834  case Stmt::UnaryOperatorClass:
1835    return getPrimaryDecl(cast<UnaryOperator>(E)->getSubExpr());
1836  case Stmt::ParenExprClass:
1837    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
1838  case Stmt::ImplicitCastExprClass:
1839    // &X[4] when X is an array, has an implicit cast from array to pointer.
1840    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
1841  default:
1842    return 0;
1843  }
1844}
1845
1846/// CheckAddressOfOperand - The operand of & must be either a function
1847/// designator or an lvalue designating an object. If it is an lvalue, the
1848/// object cannot be declared with storage class register or be a bit field.
1849/// Note: The usual conversions are *not* applied to the operand of the &
1850/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
1851QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
1852  if (getLangOptions().C99) {
1853    // Implement C99-only parts of addressof rules.
1854    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
1855      if (uOp->getOpcode() == UnaryOperator::Deref)
1856        // Per C99 6.5.3.2, the address of a deref always returns a valid result
1857        // (assuming the deref expression is valid).
1858        return uOp->getSubExpr()->getType();
1859    }
1860    // Technically, there should be a check for array subscript
1861    // expressions here, but the result of one is always an lvalue anyway.
1862  }
1863  ValueDecl *dcl = getPrimaryDecl(op);
1864  Expr::isLvalueResult lval = op->isLvalue();
1865
1866  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
1867    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
1868      // FIXME: emit more specific diag...
1869      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof,
1870           op->getSourceRange());
1871      return QualType();
1872    }
1873  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
1874    if (MemExpr->getMemberDecl()->isBitField()) {
1875      Diag(OpLoc, diag::err_typecheck_address_of,
1876           std::string("bit-field"), op->getSourceRange());
1877      return QualType();
1878    }
1879  // Check for Apple extension for accessing vector components.
1880  } else if (isa<ArraySubscriptExpr>(op) &&
1881           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
1882    Diag(OpLoc, diag::err_typecheck_address_of,
1883         std::string("vector"), op->getSourceRange());
1884    return QualType();
1885  } else if (dcl) { // C99 6.5.3.2p1
1886    // We have an lvalue with a decl. Make sure the decl is not declared
1887    // with the register storage-class specifier.
1888    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
1889      if (vd->getStorageClass() == VarDecl::Register) {
1890        Diag(OpLoc, diag::err_typecheck_address_of,
1891             std::string("register variable"), op->getSourceRange());
1892        return QualType();
1893      }
1894    } else
1895      assert(0 && "Unknown/unexpected decl type");
1896  }
1897  // If the operand has type "type", the result has type "pointer to type".
1898  return Context.getPointerType(op->getType());
1899}
1900
1901QualType Sema::CheckIndirectionOperand(Expr *op, SourceLocation OpLoc) {
1902  UsualUnaryConversions(op);
1903  QualType qType = op->getType();
1904
1905  if (const PointerType *PT = qType->getAsPointerType()) {
1906    // Note that per both C89 and C99, this is always legal, even
1907    // if ptype is an incomplete type or void.
1908    // It would be possible to warn about dereferencing a
1909    // void pointer, but it's completely well-defined,
1910    // and such a warning is unlikely to catch any mistakes.
1911    return PT->getPointeeType();
1912  }
1913  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer,
1914       qType.getAsString(), op->getSourceRange());
1915  return QualType();
1916}
1917
1918static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
1919  tok::TokenKind Kind) {
1920  BinaryOperator::Opcode Opc;
1921  switch (Kind) {
1922  default: assert(0 && "Unknown binop!");
1923  case tok::star:                 Opc = BinaryOperator::Mul; break;
1924  case tok::slash:                Opc = BinaryOperator::Div; break;
1925  case tok::percent:              Opc = BinaryOperator::Rem; break;
1926  case tok::plus:                 Opc = BinaryOperator::Add; break;
1927  case tok::minus:                Opc = BinaryOperator::Sub; break;
1928  case tok::lessless:             Opc = BinaryOperator::Shl; break;
1929  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
1930  case tok::lessequal:            Opc = BinaryOperator::LE; break;
1931  case tok::less:                 Opc = BinaryOperator::LT; break;
1932  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
1933  case tok::greater:              Opc = BinaryOperator::GT; break;
1934  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
1935  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
1936  case tok::amp:                  Opc = BinaryOperator::And; break;
1937  case tok::caret:                Opc = BinaryOperator::Xor; break;
1938  case tok::pipe:                 Opc = BinaryOperator::Or; break;
1939  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
1940  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
1941  case tok::equal:                Opc = BinaryOperator::Assign; break;
1942  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
1943  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
1944  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
1945  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
1946  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
1947  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
1948  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
1949  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
1950  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
1951  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
1952  case tok::comma:                Opc = BinaryOperator::Comma; break;
1953  }
1954  return Opc;
1955}
1956
1957static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
1958  tok::TokenKind Kind) {
1959  UnaryOperator::Opcode Opc;
1960  switch (Kind) {
1961  default: assert(0 && "Unknown unary op!");
1962  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
1963  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
1964  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
1965  case tok::star:         Opc = UnaryOperator::Deref; break;
1966  case tok::plus:         Opc = UnaryOperator::Plus; break;
1967  case tok::minus:        Opc = UnaryOperator::Minus; break;
1968  case tok::tilde:        Opc = UnaryOperator::Not; break;
1969  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
1970  case tok::kw_sizeof:    Opc = UnaryOperator::SizeOf; break;
1971  case tok::kw___alignof: Opc = UnaryOperator::AlignOf; break;
1972  case tok::kw___real:    Opc = UnaryOperator::Real; break;
1973  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
1974  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
1975  }
1976  return Opc;
1977}
1978
1979// Binary Operators.  'Tok' is the token for the operator.
1980Action::ExprResult Sema::ActOnBinOp(SourceLocation TokLoc, tok::TokenKind Kind,
1981                                    ExprTy *LHS, ExprTy *RHS) {
1982  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
1983  Expr *lhs = (Expr *)LHS, *rhs = (Expr*)RHS;
1984
1985  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
1986  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
1987
1988  QualType ResultTy;  // Result type of the binary operator.
1989  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
1990
1991  switch (Opc) {
1992  default:
1993    assert(0 && "Unknown binary expr!");
1994  case BinaryOperator::Assign:
1995    ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, QualType());
1996    break;
1997  case BinaryOperator::Mul:
1998  case BinaryOperator::Div:
1999    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc);
2000    break;
2001  case BinaryOperator::Rem:
2002    ResultTy = CheckRemainderOperands(lhs, rhs, TokLoc);
2003    break;
2004  case BinaryOperator::Add:
2005    ResultTy = CheckAdditionOperands(lhs, rhs, TokLoc);
2006    break;
2007  case BinaryOperator::Sub:
2008    ResultTy = CheckSubtractionOperands(lhs, rhs, TokLoc);
2009    break;
2010  case BinaryOperator::Shl:
2011  case BinaryOperator::Shr:
2012    ResultTy = CheckShiftOperands(lhs, rhs, TokLoc);
2013    break;
2014  case BinaryOperator::LE:
2015  case BinaryOperator::LT:
2016  case BinaryOperator::GE:
2017  case BinaryOperator::GT:
2018    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, true);
2019    break;
2020  case BinaryOperator::EQ:
2021  case BinaryOperator::NE:
2022    ResultTy = CheckCompareOperands(lhs, rhs, TokLoc, false);
2023    break;
2024  case BinaryOperator::And:
2025  case BinaryOperator::Xor:
2026  case BinaryOperator::Or:
2027    ResultTy = CheckBitwiseOperands(lhs, rhs, TokLoc);
2028    break;
2029  case BinaryOperator::LAnd:
2030  case BinaryOperator::LOr:
2031    ResultTy = CheckLogicalOperands(lhs, rhs, TokLoc);
2032    break;
2033  case BinaryOperator::MulAssign:
2034  case BinaryOperator::DivAssign:
2035    CompTy = CheckMultiplyDivideOperands(lhs, rhs, TokLoc, true);
2036    if (!CompTy.isNull())
2037      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2038    break;
2039  case BinaryOperator::RemAssign:
2040    CompTy = CheckRemainderOperands(lhs, rhs, TokLoc, true);
2041    if (!CompTy.isNull())
2042      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2043    break;
2044  case BinaryOperator::AddAssign:
2045    CompTy = CheckAdditionOperands(lhs, rhs, TokLoc, true);
2046    if (!CompTy.isNull())
2047      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2048    break;
2049  case BinaryOperator::SubAssign:
2050    CompTy = CheckSubtractionOperands(lhs, rhs, TokLoc, true);
2051    if (!CompTy.isNull())
2052      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2053    break;
2054  case BinaryOperator::ShlAssign:
2055  case BinaryOperator::ShrAssign:
2056    CompTy = CheckShiftOperands(lhs, rhs, TokLoc, true);
2057    if (!CompTy.isNull())
2058      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2059    break;
2060  case BinaryOperator::AndAssign:
2061  case BinaryOperator::XorAssign:
2062  case BinaryOperator::OrAssign:
2063    CompTy = CheckBitwiseOperands(lhs, rhs, TokLoc, true);
2064    if (!CompTy.isNull())
2065      ResultTy = CheckAssignmentOperands(lhs, rhs, TokLoc, CompTy);
2066    break;
2067  case BinaryOperator::Comma:
2068    ResultTy = CheckCommaOperands(lhs, rhs, TokLoc);
2069    break;
2070  }
2071  if (ResultTy.isNull())
2072    return true;
2073  if (CompTy.isNull())
2074    return new BinaryOperator(lhs, rhs, Opc, ResultTy, TokLoc);
2075  else
2076    return new CompoundAssignOperator(lhs, rhs, Opc, ResultTy, CompTy, TokLoc);
2077}
2078
2079// Unary Operators.  'Tok' is the token for the operator.
2080Action::ExprResult Sema::ActOnUnaryOp(SourceLocation OpLoc, tok::TokenKind Op,
2081                                      ExprTy *input) {
2082  Expr *Input = (Expr*)input;
2083  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
2084  QualType resultType;
2085  switch (Opc) {
2086  default:
2087    assert(0 && "Unimplemented unary expr!");
2088  case UnaryOperator::PreInc:
2089  case UnaryOperator::PreDec:
2090    resultType = CheckIncrementDecrementOperand(Input, OpLoc);
2091    break;
2092  case UnaryOperator::AddrOf:
2093    resultType = CheckAddressOfOperand(Input, OpLoc);
2094    break;
2095  case UnaryOperator::Deref:
2096    DefaultFunctionArrayConversion(Input);
2097    resultType = CheckIndirectionOperand(Input, OpLoc);
2098    break;
2099  case UnaryOperator::Plus:
2100  case UnaryOperator::Minus:
2101    UsualUnaryConversions(Input);
2102    resultType = Input->getType();
2103    if (!resultType->isArithmeticType())  // C99 6.5.3.3p1
2104      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2105                  resultType.getAsString());
2106    break;
2107  case UnaryOperator::Not: // bitwise complement
2108    UsualUnaryConversions(Input);
2109    resultType = Input->getType();
2110    // C99 6.5.3.3p1. We allow complex as a GCC extension.
2111    if (!resultType->isIntegerType()) {
2112      if (resultType->isComplexType())
2113        // C99 does not support '~' for complex conjugation.
2114        Diag(OpLoc, diag::ext_integer_complement_complex,
2115                    resultType.getAsString());
2116      else
2117        return Diag(OpLoc, diag::err_typecheck_unary_expr,
2118                    resultType.getAsString());
2119    }
2120    break;
2121  case UnaryOperator::LNot: // logical negation
2122    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
2123    DefaultFunctionArrayConversion(Input);
2124    resultType = Input->getType();
2125    if (!resultType->isScalarType()) // C99 6.5.3.3p1
2126      return Diag(OpLoc, diag::err_typecheck_unary_expr,
2127                  resultType.getAsString());
2128    // LNot always has type int. C99 6.5.3.3p5.
2129    resultType = Context.IntTy;
2130    break;
2131  case UnaryOperator::SizeOf:
2132    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, true);
2133    break;
2134  case UnaryOperator::AlignOf:
2135    resultType = CheckSizeOfAlignOfOperand(Input->getType(), OpLoc, false);
2136    break;
2137  case UnaryOperator::Real:
2138  case UnaryOperator::Imag:
2139    resultType = CheckRealImagOperand(Input, OpLoc);
2140    break;
2141  case UnaryOperator::Extension:
2142    resultType = Input->getType();
2143    break;
2144  }
2145  if (resultType.isNull())
2146    return true;
2147  return new UnaryOperator(Input, Opc, resultType, OpLoc);
2148}
2149
2150/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
2151Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
2152                                      SourceLocation LabLoc,
2153                                      IdentifierInfo *LabelII) {
2154  // Look up the record for this label identifier.
2155  LabelStmt *&LabelDecl = LabelMap[LabelII];
2156
2157  // If we haven't seen this label yet, create a forward reference.
2158  if (LabelDecl == 0)
2159    LabelDecl = new LabelStmt(LabLoc, LabelII, 0);
2160
2161  // Create the AST node.  The address of a label always has type 'void*'.
2162  return new AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
2163                           Context.getPointerType(Context.VoidTy));
2164}
2165
2166Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
2167                                     SourceLocation RPLoc) { // "({..})"
2168  Stmt *SubStmt = static_cast<Stmt*>(substmt);
2169  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
2170  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
2171
2172  // FIXME: there are a variety of strange constraints to enforce here, for
2173  // example, it is not possible to goto into a stmt expression apparently.
2174  // More semantic analysis is needed.
2175
2176  // FIXME: the last statement in the compount stmt has its value used.  We
2177  // should not warn about it being unused.
2178
2179  // If there are sub stmts in the compound stmt, take the type of the last one
2180  // as the type of the stmtexpr.
2181  QualType Ty = Context.VoidTy;
2182
2183  if (!Compound->body_empty())
2184    if (Expr *LastExpr = dyn_cast<Expr>(Compound->body_back()))
2185      Ty = LastExpr->getType();
2186
2187  return new StmtExpr(Compound, Ty, LPLoc, RPLoc);
2188}
2189
2190Sema::ExprResult Sema::ActOnBuiltinOffsetOf(SourceLocation BuiltinLoc,
2191                                            SourceLocation TypeLoc,
2192                                            TypeTy *argty,
2193                                            OffsetOfComponent *CompPtr,
2194                                            unsigned NumComponents,
2195                                            SourceLocation RPLoc) {
2196  QualType ArgTy = QualType::getFromOpaquePtr(argty);
2197  assert(!ArgTy.isNull() && "Missing type argument!");
2198
2199  // We must have at least one component that refers to the type, and the first
2200  // one is known to be a field designator.  Verify that the ArgTy represents
2201  // a struct/union/class.
2202  if (!ArgTy->isRecordType())
2203    return Diag(TypeLoc, diag::err_offsetof_record_type,ArgTy.getAsString());
2204
2205  // Otherwise, create a compound literal expression as the base, and
2206  // iteratively process the offsetof designators.
2207  Expr *Res = new CompoundLiteralExpr(SourceLocation(), ArgTy, 0, false);
2208
2209  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
2210  // GCC extension, diagnose them.
2211  if (NumComponents != 1)
2212    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator,
2213         SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd));
2214
2215  for (unsigned i = 0; i != NumComponents; ++i) {
2216    const OffsetOfComponent &OC = CompPtr[i];
2217    if (OC.isBrackets) {
2218      // Offset of an array sub-field.  TODO: Should we allow vector elements?
2219      const ArrayType *AT = Res->getType()->getAsArrayType();
2220      if (!AT) {
2221        delete Res;
2222        return Diag(OC.LocEnd, diag::err_offsetof_array_type,
2223                    Res->getType().getAsString());
2224      }
2225
2226      // FIXME: C++: Verify that operator[] isn't overloaded.
2227
2228      // C99 6.5.2.1p1
2229      Expr *Idx = static_cast<Expr*>(OC.U.E);
2230      if (!Idx->getType()->isIntegerType())
2231        return Diag(Idx->getLocStart(), diag::err_typecheck_subscript,
2232                    Idx->getSourceRange());
2233
2234      Res = new ArraySubscriptExpr(Res, Idx, AT->getElementType(), OC.LocEnd);
2235      continue;
2236    }
2237
2238    const RecordType *RC = Res->getType()->getAsRecordType();
2239    if (!RC) {
2240      delete Res;
2241      return Diag(OC.LocEnd, diag::err_offsetof_record_type,
2242                  Res->getType().getAsString());
2243    }
2244
2245    // Get the decl corresponding to this.
2246    RecordDecl *RD = RC->getDecl();
2247    FieldDecl *MemberDecl = RD->getMember(OC.U.IdentInfo);
2248    if (!MemberDecl)
2249      return Diag(BuiltinLoc, diag::err_typecheck_no_member,
2250                  OC.U.IdentInfo->getName(),
2251                  SourceRange(OC.LocStart, OC.LocEnd));
2252
2253    // FIXME: C++: Verify that MemberDecl isn't a static field.
2254    // FIXME: Verify that MemberDecl isn't a bitfield.
2255    // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
2256    // matter here.
2257    Res = new MemberExpr(Res, false, MemberDecl, OC.LocEnd, MemberDecl->getType());
2258  }
2259
2260  return new UnaryOperator(Res, UnaryOperator::OffsetOf, Context.getSizeType(),
2261                           BuiltinLoc);
2262}
2263
2264
2265Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
2266                                                TypeTy *arg1, TypeTy *arg2,
2267                                                SourceLocation RPLoc) {
2268  QualType argT1 = QualType::getFromOpaquePtr(arg1);
2269  QualType argT2 = QualType::getFromOpaquePtr(arg2);
2270
2271  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
2272
2273  return new TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1, argT2,RPLoc);
2274}
2275
2276Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
2277                                       ExprTy *expr1, ExprTy *expr2,
2278                                       SourceLocation RPLoc) {
2279  Expr *CondExpr = static_cast<Expr*>(cond);
2280  Expr *LHSExpr = static_cast<Expr*>(expr1);
2281  Expr *RHSExpr = static_cast<Expr*>(expr2);
2282
2283  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
2284
2285  // The conditional expression is required to be a constant expression.
2286  llvm::APSInt condEval(32);
2287  SourceLocation ExpLoc;
2288  if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
2289    return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant,
2290                 CondExpr->getSourceRange());
2291
2292  // If the condition is > zero, then the AST type is the same as the LSHExpr.
2293  QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
2294                                               RHSExpr->getType();
2295  return new ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr, resType, RPLoc);
2296}
2297
2298/// ExprsMatchFnType - return true if the Exprs in array Args have
2299/// QualTypes that match the QualTypes of the arguments of the FnType.
2300/// The number of arguments has already been validated to match the number of
2301/// arguments in FnType.
2302static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType) {
2303  unsigned NumParams = FnType->getNumArgs();
2304  for (unsigned i = 0; i != NumParams; ++i) {
2305    QualType ExprTy = Args[i]->getType().getCanonicalType();
2306    QualType ParmTy = FnType->getArgType(i).getCanonicalType();
2307
2308    if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
2309      return false;
2310  }
2311  return true;
2312}
2313
2314Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
2315                                         SourceLocation *CommaLocs,
2316                                         SourceLocation BuiltinLoc,
2317                                         SourceLocation RParenLoc) {
2318  // __builtin_overload requires at least 2 arguments
2319  if (NumArgs < 2)
2320    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2321                SourceRange(BuiltinLoc, RParenLoc));
2322
2323  // The first argument is required to be a constant expression.  It tells us
2324  // the number of arguments to pass to each of the functions to be overloaded.
2325  Expr **Args = reinterpret_cast<Expr**>(args);
2326  Expr *NParamsExpr = Args[0];
2327  llvm::APSInt constEval(32);
2328  SourceLocation ExpLoc;
2329  if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
2330    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2331                NParamsExpr->getSourceRange());
2332
2333  // Verify that the number of parameters is > 0
2334  unsigned NumParams = constEval.getZExtValue();
2335  if (NumParams == 0)
2336    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant,
2337                NParamsExpr->getSourceRange());
2338  // Verify that we have at least 1 + NumParams arguments to the builtin.
2339  if ((NumParams + 1) > NumArgs)
2340    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args,
2341                SourceRange(BuiltinLoc, RParenLoc));
2342
2343  // Figure out the return type, by matching the args to one of the functions
2344  // listed after the parameters.
2345  OverloadExpr *OE = 0;
2346  for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
2347    // UsualUnaryConversions will convert the function DeclRefExpr into a
2348    // pointer to function.
2349    Expr *Fn = UsualUnaryConversions(Args[i]);
2350    FunctionTypeProto *FnType = 0;
2351    if (const PointerType *PT = Fn->getType()->getAsPointerType()) {
2352      QualType PointeeType = PT->getPointeeType().getCanonicalType();
2353      FnType = dyn_cast<FunctionTypeProto>(PointeeType);
2354    }
2355
2356    // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
2357    // parameters, and the number of parameters must match the value passed to
2358    // the builtin.
2359    if (!FnType || (FnType->getNumArgs() != NumParams))
2360      return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype,
2361                  Fn->getSourceRange());
2362
2363    // Scan the parameter list for the FunctionType, checking the QualType of
2364    // each parameter against the QualTypes of the arguments to the builtin.
2365    // If they match, return a new OverloadExpr.
2366    if (ExprsMatchFnType(Args+1, FnType)) {
2367      if (OE)
2368        return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match,
2369                    OE->getFn()->getSourceRange());
2370      // Remember our match, and continue processing the remaining arguments
2371      // to catch any errors.
2372      OE = new OverloadExpr(Args, NumArgs, i, FnType->getResultType(),
2373                            BuiltinLoc, RParenLoc);
2374    }
2375  }
2376  // Return the newly created OverloadExpr node, if we succeded in matching
2377  // exactly one of the candidate functions.
2378  if (OE)
2379    return OE;
2380
2381  // If we didn't find a matching function Expr in the __builtin_overload list
2382  // the return an error.
2383  std::string typeNames;
2384  for (unsigned i = 0; i != NumParams; ++i) {
2385    if (i != 0) typeNames += ", ";
2386    typeNames += Args[i+1]->getType().getAsString();
2387  }
2388
2389  return Diag(BuiltinLoc, diag::err_overload_no_match, typeNames,
2390              SourceRange(BuiltinLoc, RParenLoc));
2391}
2392
2393Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
2394                                  ExprTy *expr, TypeTy *type,
2395                                  SourceLocation RPLoc) {
2396  Expr *E = static_cast<Expr*>(expr);
2397  QualType T = QualType::getFromOpaquePtr(type);
2398
2399  InitBuiltinVaListType();
2400
2401  if (CheckAssignmentConstraints(Context.getBuiltinVaListType(), E->getType())
2402      != Compatible)
2403    return Diag(E->getLocStart(),
2404                diag::err_first_argument_to_va_arg_not_of_type_va_list,
2405                E->getType().getAsString(),
2406                E->getSourceRange());
2407
2408  // FIXME: Warn if a non-POD type is passed in.
2409
2410  return new VAArgExpr(BuiltinLoc, E, T, RPLoc);
2411}
2412
2413bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
2414                                    SourceLocation Loc,
2415                                    QualType DstType, QualType SrcType,
2416                                    Expr *SrcExpr, const char *Flavor) {
2417  // Decode the result (notice that AST's are still created for extensions).
2418  bool isInvalid = false;
2419  unsigned DiagKind;
2420  switch (ConvTy) {
2421  default: assert(0 && "Unknown conversion type");
2422  case Compatible: return false;
2423  case PointerToInt:
2424    DiagKind = diag::ext_typecheck_convert_pointer_int;
2425    break;
2426  case IntToPointer:
2427    DiagKind = diag::ext_typecheck_convert_int_pointer;
2428    break;
2429  case IncompatiblePointer:
2430    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
2431    break;
2432  case FunctionVoidPointer:
2433    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
2434    break;
2435  case CompatiblePointerDiscardsQualifiers:
2436    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
2437    break;
2438  case Incompatible:
2439    DiagKind = diag::err_typecheck_convert_incompatible;
2440    isInvalid = true;
2441    break;
2442  }
2443
2444  Diag(Loc, DiagKind, DstType.getAsString(), SrcType.getAsString(), Flavor,
2445       SrcExpr->getSourceRange());
2446  return isInvalid;
2447}
2448
2449
2450
2451