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