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