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