SemaExpr.cpp revision 48a8732ec59331eb3b65d4cefe992cc88c914e48
1//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/Lex/Preprocessor.h"
20#include "clang/Lex/LiteralSupport.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Parse/DeclSpec.h"
24#include "clang/Parse/Designator.h"
25#include "clang/Parse/Scope.h"
26using namespace clang;
27
28//===----------------------------------------------------------------------===//
29//  Standard Promotions and Conversions
30//===----------------------------------------------------------------------===//
31
32/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
33void Sema::DefaultFunctionArrayConversion(Expr *&E) {
34  QualType Ty = E->getType();
35  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
36
37  if (Ty->isFunctionType())
38    ImpCastExprToType(E, Context.getPointerType(Ty));
39  else if (Ty->isArrayType()) {
40    // In C90 mode, arrays only promote to pointers if the array expression is
41    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
42    // type 'array of type' is converted to an expression that has type 'pointer
43    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
44    // that has type 'array of type' ...".  The relevant change is "an lvalue"
45    // (C90) to "an expression" (C99).
46    //
47    // C++ 4.2p1:
48    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
49    // T" can be converted to an rvalue of type "pointer to T".
50    //
51    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
52        E->isLvalue(Context) == Expr::LV_Valid)
53      ImpCastExprToType(E, Context.getArrayDecayedType(Ty));
54  }
55}
56
57/// UsualUnaryConversions - Performs various conversions that are common to most
58/// operators (C99 6.3). The conversions of array and function types are
59/// sometimes surpressed. For example, the array->pointer conversion doesn't
60/// apply if the array is an argument to the sizeof or address (&) operators.
61/// In these instances, this routine should *not* be called.
62Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
63  QualType Ty = Expr->getType();
64  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
65
66  if (Ty->isPromotableIntegerType()) // C99 6.3.1.1p2
67    ImpCastExprToType(Expr, Context.IntTy);
68  else
69    DefaultFunctionArrayConversion(Expr);
70
71  return Expr;
72}
73
74/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
75/// do not have a prototype. Arguments that have type float are promoted to
76/// double. All other argument types are converted by UsualUnaryConversions().
77void Sema::DefaultArgumentPromotion(Expr *&Expr) {
78  QualType Ty = Expr->getType();
79  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
80
81  // If this is a 'float' (CVR qualified or typedef) promote to double.
82  if (const BuiltinType *BT = Ty->getAsBuiltinType())
83    if (BT->getKind() == BuiltinType::Float)
84      return ImpCastExprToType(Expr, Context.DoubleTy);
85
86  UsualUnaryConversions(Expr);
87}
88
89// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
90// will warn if the resulting type is not a POD type.
91void Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT)
92
93{
94  DefaultArgumentPromotion(Expr);
95
96  if (!Expr->getType()->isPODType()) {
97    Diag(Expr->getLocStart(),
98         diag::warn_cannot_pass_non_pod_arg_to_vararg) <<
99    Expr->getType() << CT;
100  }
101}
102
103
104/// UsualArithmeticConversions - Performs various conversions that are common to
105/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
106/// routine returns the first non-arithmetic type found. The client is
107/// responsible for emitting appropriate error diagnostics.
108/// FIXME: verify the conversion rules for "complex int" are consistent with
109/// GCC.
110QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
111                                          bool isCompAssign) {
112  if (!isCompAssign) {
113    UsualUnaryConversions(lhsExpr);
114    UsualUnaryConversions(rhsExpr);
115  }
116
117  // For conversion purposes, we ignore any qualifiers.
118  // For example, "const float" and "float" are equivalent.
119  QualType lhs =
120    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
121  QualType rhs =
122    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
123
124  // If both types are identical, no conversion is needed.
125  if (lhs == rhs)
126    return lhs;
127
128  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
129  // The caller can deal with this (e.g. pointer + int).
130  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
131    return lhs;
132
133  QualType destType = UsualArithmeticConversionsType(lhs, rhs);
134  if (!isCompAssign) {
135    ImpCastExprToType(lhsExpr, destType);
136    ImpCastExprToType(rhsExpr, destType);
137  }
138  return destType;
139}
140
141QualType Sema::UsualArithmeticConversionsType(QualType lhs, QualType rhs) {
142  // Perform the usual unary conversions. We do this early so that
143  // integral promotions to "int" can allow us to exit early, in the
144  // lhs == rhs check. Also, for conversion purposes, we ignore any
145  // qualifiers.  For example, "const float" and "float" are
146  // equivalent.
147  if (lhs->isPromotableIntegerType()) lhs = Context.IntTy;
148  else                                lhs = lhs.getUnqualifiedType();
149  if (rhs->isPromotableIntegerType()) rhs = Context.IntTy;
150  else                                rhs = rhs.getUnqualifiedType();
151
152  // If both types are identical, no conversion is needed.
153  if (lhs == rhs)
154    return lhs;
155
156  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
157  // The caller can deal with this (e.g. pointer + int).
158  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
159    return lhs;
160
161  // At this point, we have two different arithmetic types.
162
163  // Handle complex types first (C99 6.3.1.8p1).
164  if (lhs->isComplexType() || rhs->isComplexType()) {
165    // if we have an integer operand, the result is the complex type.
166    if (rhs->isIntegerType() || rhs->isComplexIntegerType()) {
167      // convert the rhs to the lhs complex type.
168      return lhs;
169    }
170    if (lhs->isIntegerType() || lhs->isComplexIntegerType()) {
171      // convert the lhs to the rhs complex type.
172      return rhs;
173    }
174    // This handles complex/complex, complex/float, or float/complex.
175    // When both operands are complex, the shorter operand is converted to the
176    // type of the longer, and that is the type of the result. This corresponds
177    // to what is done when combining two real floating-point operands.
178    // The fun begins when size promotion occur across type domains.
179    // From H&S 6.3.4: When one operand is complex and the other is a real
180    // floating-point type, the less precise type is converted, within it's
181    // real or complex domain, to the precision of the other type. For example,
182    // when combining a "long double" with a "double _Complex", the
183    // "double _Complex" is promoted to "long double _Complex".
184    int result = Context.getFloatingTypeOrder(lhs, rhs);
185
186    if (result > 0) { // The left side is bigger, convert rhs.
187      rhs = Context.getFloatingTypeOfSizeWithinDomain(lhs, rhs);
188    } else if (result < 0) { // The right side is bigger, convert lhs.
189      lhs = Context.getFloatingTypeOfSizeWithinDomain(rhs, lhs);
190    }
191    // At this point, lhs and rhs have the same rank/size. Now, make sure the
192    // domains match. This is a requirement for our implementation, C99
193    // does not require this promotion.
194    if (lhs != rhs) { // Domains don't match, we have complex/float mix.
195      if (lhs->isRealFloatingType()) { // handle "double, _Complex double".
196        return rhs;
197      } else { // handle "_Complex double, double".
198        return lhs;
199      }
200    }
201    return lhs; // The domain/size match exactly.
202  }
203  // Now handle "real" floating types (i.e. float, double, long double).
204  if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) {
205    // if we have an integer operand, the result is the real floating type.
206    if (rhs->isIntegerType()) {
207      // convert rhs to the lhs floating point type.
208      return lhs;
209    }
210    if (rhs->isComplexIntegerType()) {
211      // convert rhs to the complex floating point type.
212      return Context.getComplexType(lhs);
213    }
214    if (lhs->isIntegerType()) {
215      // convert lhs to the rhs floating point type.
216      return rhs;
217    }
218    if (lhs->isComplexIntegerType()) {
219      // convert lhs to the complex floating point type.
220      return Context.getComplexType(rhs);
221    }
222    // We have two real floating types, float/complex combos were handled above.
223    // Convert the smaller operand to the bigger result.
224    int result = Context.getFloatingTypeOrder(lhs, rhs);
225
226    if (result > 0) { // convert the rhs
227      return lhs;
228    }
229    if (result < 0) { // convert the lhs
230      return rhs;
231    }
232    assert(0 && "Sema::UsualArithmeticConversionsType(): illegal float comparison");
233  }
234  if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) {
235    // Handle GCC complex int extension.
236    const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType();
237    const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType();
238
239    if (lhsComplexInt && rhsComplexInt) {
240      if (Context.getIntegerTypeOrder(lhsComplexInt->getElementType(),
241                                      rhsComplexInt->getElementType()) >= 0) {
242        // convert the rhs
243        return lhs;
244      }
245      return rhs;
246    } else if (lhsComplexInt && rhs->isIntegerType()) {
247      // convert the rhs to the lhs complex type.
248      return lhs;
249    } else if (rhsComplexInt && lhs->isIntegerType()) {
250      // convert the lhs to the rhs complex type.
251      return rhs;
252    }
253  }
254  // Finally, we have two differing integer types.
255  // The rules for this case are in C99 6.3.1.8
256  int compare = Context.getIntegerTypeOrder(lhs, rhs);
257  bool lhsSigned = lhs->isSignedIntegerType(),
258       rhsSigned = rhs->isSignedIntegerType();
259  QualType destType;
260  if (lhsSigned == rhsSigned) {
261    // Same signedness; use the higher-ranked type
262    destType = compare >= 0 ? lhs : rhs;
263  } else if (compare != (lhsSigned ? 1 : -1)) {
264    // The unsigned type has greater than or equal rank to the
265    // signed type, so use the unsigned type
266    destType = lhsSigned ? rhs : lhs;
267  } else if (Context.getIntWidth(lhs) != Context.getIntWidth(rhs)) {
268    // The two types are different widths; if we are here, that
269    // means the signed type is larger than the unsigned type, so
270    // use the signed type.
271    destType = lhsSigned ? lhs : rhs;
272  } else {
273    // The signed type is higher-ranked than the unsigned type,
274    // but isn't actually any bigger (like unsigned int and long
275    // on most 32-bit systems).  Use the unsigned type corresponding
276    // to the signed type.
277    destType = Context.getCorrespondingUnsignedType(lhsSigned ? lhs : rhs);
278  }
279  return destType;
280}
281
282//===----------------------------------------------------------------------===//
283//  Semantic Analysis for various Expression Types
284//===----------------------------------------------------------------------===//
285
286
287/// ActOnStringLiteral - The specified tokens were lexed as pasted string
288/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
289/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
290/// multiple tokens.  However, the common case is that StringToks points to one
291/// string.
292///
293Action::OwningExprResult
294Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
295  assert(NumStringToks && "Must have at least one string!");
296
297  StringLiteralParser Literal(StringToks, NumStringToks, PP);
298  if (Literal.hadError)
299    return ExprError();
300
301  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
302  for (unsigned i = 0; i != NumStringToks; ++i)
303    StringTokLocs.push_back(StringToks[i].getLocation());
304
305  QualType StrTy = Context.CharTy;
306  if (Literal.AnyWide) StrTy = Context.getWCharType();
307  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
308
309  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
310  if (getLangOptions().CPlusPlus)
311    StrTy.addConst();
312
313  // Get an array type for the string, according to C99 6.4.5.  This includes
314  // the nul terminator character as well as the string length for pascal
315  // strings.
316  StrTy = Context.getConstantArrayType(StrTy,
317                                   llvm::APInt(32, Literal.GetStringLength()+1),
318                                       ArrayType::Normal, 0);
319
320  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
321  return Owned(new (Context) StringLiteral(Literal.GetString(),
322                                 Literal.GetStringLength(),
323                                 Literal.AnyWide, StrTy,
324                                 StringToks[0].getLocation(),
325                                 StringToks[NumStringToks-1].getLocation()));
326}
327
328/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
329/// CurBlock to VD should cause it to be snapshotted (as we do for auto
330/// variables defined outside the block) or false if this is not needed (e.g.
331/// for values inside the block or for globals).
332///
333/// FIXME: This will create BlockDeclRefExprs for global variables,
334/// function references, etc which is suboptimal :) and breaks
335/// things like "integer constant expression" tests.
336static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
337                                              ValueDecl *VD) {
338  // If the value is defined inside the block, we couldn't snapshot it even if
339  // we wanted to.
340  if (CurBlock->TheDecl == VD->getDeclContext())
341    return false;
342
343  // If this is an enum constant or function, it is constant, don't snapshot.
344  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
345    return false;
346
347  // If this is a reference to an extern, static, or global variable, no need to
348  // snapshot it.
349  // FIXME: What about 'const' variables in C++?
350  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
351    return Var->hasLocalStorage();
352
353  return true;
354}
355
356
357
358/// ActOnIdentifierExpr - The parser read an identifier in expression context,
359/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
360/// identifier is used in a function call context.
361/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
362/// class or namespace that the identifier must be a member of.
363Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
364                                                 IdentifierInfo &II,
365                                                 bool HasTrailingLParen,
366                                                 const CXXScopeSpec *SS,
367                                                 bool isAddressOfOperand) {
368  return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
369                                  isAddressOfOperand);
370}
371
372/// BuildDeclRefExpr - Build either a DeclRefExpr or a
373/// QualifiedDeclRefExpr based on whether or not SS is a
374/// nested-name-specifier.
375DeclRefExpr *
376Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
377                       bool TypeDependent, bool ValueDependent,
378                       const CXXScopeSpec *SS) {
379  if (SS && !SS->isEmpty())
380    return new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
381                       ValueDependent, SS->getRange().getBegin());
382  else
383    return new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
384}
385
386/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
387/// variable corresponding to the anonymous union or struct whose type
388/// is Record.
389static Decl *getObjectForAnonymousRecordDecl(RecordDecl *Record) {
390  assert(Record->isAnonymousStructOrUnion() &&
391         "Record must be an anonymous struct or union!");
392
393  // FIXME: Once Decls are directly linked together, this will
394  // be an O(1) operation rather than a slow walk through DeclContext's
395  // vector (which itself will be eliminated). DeclGroups might make
396  // this even better.
397  DeclContext *Ctx = Record->getDeclContext();
398  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
399                               DEnd = Ctx->decls_end();
400       D != DEnd; ++D) {
401    if (*D == Record) {
402      // The object for the anonymous struct/union directly
403      // follows its type in the list of declarations.
404      ++D;
405      assert(D != DEnd && "Missing object for anonymous record");
406      assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
407      return *D;
408    }
409  }
410
411  assert(false && "Missing object for anonymous record");
412  return 0;
413}
414
415Sema::OwningExprResult
416Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
417                                               FieldDecl *Field,
418                                               Expr *BaseObjectExpr,
419                                               SourceLocation OpLoc) {
420  assert(Field->getDeclContext()->isRecord() &&
421         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
422         && "Field must be stored inside an anonymous struct or union");
423
424  // Construct the sequence of field member references
425  // we'll have to perform to get to the field in the anonymous
426  // union/struct. The list of members is built from the field
427  // outward, so traverse it backwards to go from an object in
428  // the current context to the field we found.
429  llvm::SmallVector<FieldDecl *, 4> AnonFields;
430  AnonFields.push_back(Field);
431  VarDecl *BaseObject = 0;
432  DeclContext *Ctx = Field->getDeclContext();
433  do {
434    RecordDecl *Record = cast<RecordDecl>(Ctx);
435    Decl *AnonObject = getObjectForAnonymousRecordDecl(Record);
436    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
437      AnonFields.push_back(AnonField);
438    else {
439      BaseObject = cast<VarDecl>(AnonObject);
440      break;
441    }
442    Ctx = Ctx->getParent();
443  } while (Ctx->isRecord() &&
444           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
445
446  // Build the expression that refers to the base object, from
447  // which we will build a sequence of member references to each
448  // of the anonymous union objects and, eventually, the field we
449  // found via name lookup.
450  bool BaseObjectIsPointer = false;
451  unsigned ExtraQuals = 0;
452  if (BaseObject) {
453    // BaseObject is an anonymous struct/union variable (and is,
454    // therefore, not part of another non-anonymous record).
455    delete BaseObjectExpr;
456
457    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
458                                     SourceLocation());
459    ExtraQuals
460      = Context.getCanonicalType(BaseObject->getType()).getCVRQualifiers();
461  } else if (BaseObjectExpr) {
462    // The caller provided the base object expression. Determine
463    // whether its a pointer and whether it adds any qualifiers to the
464    // anonymous struct/union fields we're looking into.
465    QualType ObjectType = BaseObjectExpr->getType();
466    if (const PointerType *ObjectPtr = ObjectType->getAsPointerType()) {
467      BaseObjectIsPointer = true;
468      ObjectType = ObjectPtr->getPointeeType();
469    }
470    ExtraQuals = Context.getCanonicalType(ObjectType).getCVRQualifiers();
471  } else {
472    // We've found a member of an anonymous struct/union that is
473    // inside a non-anonymous struct/union, so in a well-formed
474    // program our base object expression is "this".
475    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
476      if (!MD->isStatic()) {
477        QualType AnonFieldType
478          = Context.getTagDeclType(
479                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
480        QualType ThisType = Context.getTagDeclType(MD->getParent());
481        if ((Context.getCanonicalType(AnonFieldType)
482               == Context.getCanonicalType(ThisType)) ||
483            IsDerivedFrom(ThisType, AnonFieldType)) {
484          // Our base object expression is "this".
485          BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
486                                           MD->getThisType(Context));
487          BaseObjectIsPointer = true;
488        }
489      } else {
490        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
491          << Field->getDeclName());
492      }
493      ExtraQuals = MD->getTypeQualifiers();
494    }
495
496    if (!BaseObjectExpr)
497      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
498        << Field->getDeclName());
499  }
500
501  // Build the implicit member references to the field of the
502  // anonymous struct/union.
503  Expr *Result = BaseObjectExpr;
504  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
505         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
506       FI != FIEnd; ++FI) {
507    QualType MemberType = (*FI)->getType();
508    if (!(*FI)->isMutable()) {
509      unsigned combinedQualifiers
510        = MemberType.getCVRQualifiers() | ExtraQuals;
511      MemberType = MemberType.getQualifiedType(combinedQualifiers);
512    }
513    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
514                                      OpLoc, MemberType);
515    BaseObjectIsPointer = false;
516    ExtraQuals = Context.getCanonicalType(MemberType).getCVRQualifiers();
517    OpLoc = SourceLocation();
518  }
519
520  return Owned(Result);
521}
522
523/// ActOnDeclarationNameExpr - The parser has read some kind of name
524/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
525/// performs lookup on that name and returns an expression that refers
526/// to that name. This routine isn't directly called from the parser,
527/// because the parser doesn't know about DeclarationName. Rather,
528/// this routine is called by ActOnIdentifierExpr,
529/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
530/// which form the DeclarationName from the corresponding syntactic
531/// forms.
532///
533/// HasTrailingLParen indicates whether this identifier is used in a
534/// function call context.  LookupCtx is only used for a C++
535/// qualified-id (foo::bar) to indicate the class or namespace that
536/// the identifier must be a member of.
537///
538/// isAddressOfOperand means that this expression is the direct operand
539/// of an address-of operator. This matters because this is the only
540/// situation where a qualified name referencing a non-static member may
541/// appear outside a member function of this class.
542Sema::OwningExprResult
543Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
544                               DeclarationName Name, bool HasTrailingLParen,
545                               const CXXScopeSpec *SS,
546                               bool isAddressOfOperand) {
547  // Could be enum-constant, value decl, instance variable, etc.
548  if (SS && SS->isInvalid())
549    return ExprError();
550  LookupResult Lookup = LookupParsedName(S, SS, Name, LookupOrdinaryName);
551
552  if (getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
553      HasTrailingLParen && Lookup.getKind() == LookupResult::NotFound) {
554    // We've seen something of the form
555    //
556    //   identifier(
557    //
558    // and we did not find any entity by the name
559    // "identifier". However, this identifier is still subject to
560    // argument-dependent lookup, so keep track of the name.
561    return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
562                                                          Context.OverloadTy,
563                                                          Loc));
564  }
565
566  Decl *D = 0;
567  if (Lookup.isAmbiguous()) {
568    DiagnoseAmbiguousLookup(Lookup, Name, Loc,
569                            SS && SS->isSet() ? SS->getRange()
570                                              : SourceRange());
571    return ExprError();
572  } else
573    D = Lookup.getAsDecl();
574
575  // If this reference is in an Objective-C method, then ivar lookup happens as
576  // well.
577  IdentifierInfo *II = Name.getAsIdentifierInfo();
578  if (II && getCurMethodDecl()) {
579    // There are two cases to handle here.  1) scoped lookup could have failed,
580    // in which case we should look for an ivar.  2) scoped lookup could have
581    // found a decl, but that decl is outside the current method (i.e. a global
582    // variable).  In these two cases, we do a lookup for an ivar with this
583    // name, if the lookup suceeds, we replace it our current decl.
584    if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
585      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
586      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II)) {
587        // FIXME: This should use a new expr for a direct reference, don't turn
588        // this into Self->ivar, just return a BareIVarExpr or something.
589        IdentifierInfo &II = Context.Idents.get("self");
590        OwningExprResult SelfExpr = ActOnIdentifierExpr(S, Loc, II, false);
591        ObjCIvarRefExpr *MRef = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
592                                  Loc, static_cast<Expr*>(SelfExpr.release()),
593                                  true, true);
594        Context.setFieldDecl(IFace, IV, MRef);
595        return Owned(MRef);
596      }
597    }
598    // Needed to implement property "super.method" notation.
599    if (D == 0 && II->isStr("super")) {
600      QualType T = Context.getPointerType(Context.getObjCInterfaceType(
601                     getCurMethodDecl()->getClassInterface()));
602      return Owned(new (Context) ObjCSuperExpr(Loc, T));
603    }
604  }
605  if (D == 0) {
606    // Otherwise, this could be an implicitly declared function reference (legal
607    // in C90, extension in C99).
608    if (HasTrailingLParen && II &&
609        !getLangOptions().CPlusPlus) // Not in C++.
610      D = ImplicitlyDefineFunction(Loc, *II, S);
611    else {
612      // If this name wasn't predeclared and if this is not a function call,
613      // diagnose the problem.
614      if (SS && !SS->isEmpty())
615        return ExprError(Diag(Loc, diag::err_typecheck_no_member)
616          << Name << SS->getRange());
617      else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
618               Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
619        return ExprError(Diag(Loc, diag::err_undeclared_use)
620          << Name.getAsString());
621      else
622        return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
623    }
624  }
625
626  // If this is an expression of the form &Class::member, don't build an
627  // implicit member ref, because we want a pointer to the member in general,
628  // not any specific instance's member.
629  if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
630    NamedDecl *ND = dyn_cast<NamedDecl>(D);
631    DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
632    if (ND && isa<CXXRecordDecl>(DC)) {
633      QualType DType;
634      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
635        DType = FD->getType().getNonReferenceType();
636      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
637        DType = Method->getType();
638      } else if (isa<OverloadedFunctionDecl>(D)) {
639        DType = Context.OverloadTy;
640      }
641      // Could be an inner type. That's diagnosed below, so ignore it here.
642      if (!DType.isNull()) {
643        // The pointer is type- and value-dependent if it points into something
644        // dependent.
645        bool Dependent = false;
646        for (; DC; DC = DC->getParent()) {
647          // FIXME: could stop early at namespace scope.
648          if (DC->isRecord()) {
649            CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
650            if (Context.getTypeDeclType(Record)->isDependentType()) {
651              Dependent = true;
652              break;
653            }
654          }
655        }
656        return Owned(BuildDeclRefExpr(ND, DType, Loc, Dependent, Dependent,SS));
657      }
658    }
659  }
660
661  // We may have found a field within an anonymous union or struct
662  // (C++ [class.union]).
663  if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
664    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
665      return BuildAnonymousStructUnionMemberReference(Loc, FD);
666
667  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
668    if (!MD->isStatic()) {
669      // C++ [class.mfct.nonstatic]p2:
670      //   [...] if name lookup (3.4.1) resolves the name in the
671      //   id-expression to a nonstatic nontype member of class X or of
672      //   a base class of X, the id-expression is transformed into a
673      //   class member access expression (5.2.5) using (*this) (9.3.2)
674      //   as the postfix-expression to the left of the '.' operator.
675      DeclContext *Ctx = 0;
676      QualType MemberType;
677      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
678        Ctx = FD->getDeclContext();
679        MemberType = FD->getType();
680
681        if (const ReferenceType *RefType = MemberType->getAsReferenceType())
682          MemberType = RefType->getPointeeType();
683        else if (!FD->isMutable()) {
684          unsigned combinedQualifiers
685            = MemberType.getCVRQualifiers() | MD->getTypeQualifiers();
686          MemberType = MemberType.getQualifiedType(combinedQualifiers);
687        }
688      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
689        if (!Method->isStatic()) {
690          Ctx = Method->getParent();
691          MemberType = Method->getType();
692        }
693      } else if (OverloadedFunctionDecl *Ovl
694                   = dyn_cast<OverloadedFunctionDecl>(D)) {
695        for (OverloadedFunctionDecl::function_iterator
696               Func = Ovl->function_begin(),
697               FuncEnd = Ovl->function_end();
698             Func != FuncEnd; ++Func) {
699          if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(*Func))
700            if (!DMethod->isStatic()) {
701              Ctx = Ovl->getDeclContext();
702              MemberType = Context.OverloadTy;
703              break;
704            }
705        }
706      }
707
708      if (Ctx && Ctx->isRecord()) {
709        QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
710        QualType ThisType = Context.getTagDeclType(MD->getParent());
711        if ((Context.getCanonicalType(CtxType)
712               == Context.getCanonicalType(ThisType)) ||
713            IsDerivedFrom(ThisType, CtxType)) {
714          // Build the implicit member access expression.
715          Expr *This = new (Context) CXXThisExpr(SourceLocation(),
716                                       MD->getThisType(Context));
717          return Owned(new (Context) MemberExpr(This, true, cast<NamedDecl>(D),
718                                      SourceLocation(), MemberType));
719        }
720      }
721    }
722  }
723
724  if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
725    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
726      if (MD->isStatic())
727        // "invalid use of member 'x' in static member function"
728        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
729          << FD->getDeclName());
730    }
731
732    // Any other ways we could have found the field in a well-formed
733    // program would have been turned into implicit member expressions
734    // above.
735    return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
736      << FD->getDeclName());
737  }
738
739  if (isa<TypedefDecl>(D))
740    return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
741  if (isa<ObjCInterfaceDecl>(D))
742    return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
743  if (isa<NamespaceDecl>(D))
744    return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
745
746  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
747  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
748    return Owned(BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
749                                  false, false, SS));
750
751  ValueDecl *VD = cast<ValueDecl>(D);
752
753  // check if referencing an identifier with __attribute__((deprecated)).
754  if (VD->getAttr<DeprecatedAttr>())
755    ExprError(Diag(Loc, diag::warn_deprecated) << VD->getDeclName());
756
757  if (VarDecl *Var = dyn_cast<VarDecl>(VD)) {
758    if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
759      Scope *CheckS = S;
760      while (CheckS) {
761        if (CheckS->isWithinElse() &&
762            CheckS->getControlParent()->isDeclScope(Var)) {
763          if (Var->getType()->isBooleanType())
764            ExprError(Diag(Loc, diag::warn_value_always_false)
765              << Var->getDeclName());
766          else
767            ExprError(Diag(Loc, diag::warn_value_always_zero)
768              << Var->getDeclName());
769          break;
770        }
771
772        // Move up one more control parent to check again.
773        CheckS = CheckS->getControlParent();
774        if (CheckS)
775          CheckS = CheckS->getParent();
776      }
777    }
778  }
779
780  // Only create DeclRefExpr's for valid Decl's.
781  if (VD->isInvalidDecl())
782    return ExprError();
783
784  // If the identifier reference is inside a block, and it refers to a value
785  // that is outside the block, create a BlockDeclRefExpr instead of a
786  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
787  // the block is formed.
788  //
789  // We do not do this for things like enum constants, global variables, etc,
790  // as they do not get snapshotted.
791  //
792  if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
793    // The BlocksAttr indicates the variable is bound by-reference.
794    if (VD->getAttr<BlocksAttr>())
795      return Owned(new (Context) BlockDeclRefExpr(VD,
796                               VD->getType().getNonReferenceType(), Loc, true));
797
798    // Variable will be bound by-copy, make it const within the closure.
799    VD->getType().addConst();
800    return Owned(new (Context) BlockDeclRefExpr(VD,
801                             VD->getType().getNonReferenceType(), Loc, false));
802  }
803  // If this reference is not in a block or if the referenced variable is
804  // within the block, create a normal DeclRefExpr.
805
806  bool TypeDependent = false;
807  bool ValueDependent = false;
808  if (getLangOptions().CPlusPlus) {
809    // C++ [temp.dep.expr]p3:
810    //   An id-expression is type-dependent if it contains:
811    //     - an identifier that was declared with a dependent type,
812    if (VD->getType()->isDependentType())
813      TypeDependent = true;
814    //     - FIXME: a template-id that is dependent,
815    //     - a conversion-function-id that specifies a dependent type,
816    else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
817             Name.getCXXNameType()->isDependentType())
818      TypeDependent = true;
819    //     - a nested-name-specifier that contains a class-name that
820    //       names a dependent type.
821    else if (SS && !SS->isEmpty()) {
822      for (DeclContext *DC = static_cast<DeclContext*>(SS->getScopeRep());
823           DC; DC = DC->getParent()) {
824        // FIXME: could stop early at namespace scope.
825        if (DC->isRecord()) {
826          CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
827          if (Context.getTypeDeclType(Record)->isDependentType()) {
828            TypeDependent = true;
829            break;
830          }
831        }
832      }
833    }
834
835    // C++ [temp.dep.constexpr]p2:
836    //
837    //   An identifier is value-dependent if it is:
838    //     - a name declared with a dependent type,
839    if (TypeDependent)
840      ValueDependent = true;
841    //     - the name of a non-type template parameter,
842    else if (isa<NonTypeTemplateParmDecl>(VD))
843      ValueDependent = true;
844    //    - a constant with integral or enumeration type and is
845    //      initialized with an expression that is value-dependent
846    //      (FIXME!).
847  }
848
849  return Owned(BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
850                                TypeDependent, ValueDependent, SS));
851}
852
853Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
854                                                 tok::TokenKind Kind) {
855  PredefinedExpr::IdentType IT;
856
857  switch (Kind) {
858  default: assert(0 && "Unknown simple primary expr!");
859  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
860  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
861  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
862  }
863
864  // Pre-defined identifiers are of type char[x], where x is the length of the
865  // string.
866  unsigned Length;
867  if (FunctionDecl *FD = getCurFunctionDecl())
868    Length = FD->getIdentifier()->getLength();
869  else if (ObjCMethodDecl *MD = getCurMethodDecl())
870    Length = MD->getSynthesizedMethodSize();
871  else {
872    Diag(Loc, diag::ext_predef_outside_function);
873    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
874    Length = IT == PredefinedExpr::PrettyFunction ? strlen("top level") : 0;
875  }
876
877
878  llvm::APInt LengthI(32, Length + 1);
879  QualType ResTy = Context.CharTy.getQualifiedType(QualType::Const);
880  ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
881  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
882}
883
884Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
885  llvm::SmallString<16> CharBuffer;
886  CharBuffer.resize(Tok.getLength());
887  const char *ThisTokBegin = &CharBuffer[0];
888  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
889
890  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
891                            Tok.getLocation(), PP);
892  if (Literal.hadError())
893    return ExprError();
894
895  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
896
897  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
898                                              Literal.isWide(),
899                                              type, Tok.getLocation()));
900}
901
902Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
903  // Fast path for a single digit (which is quite common).  A single digit
904  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
905  if (Tok.getLength() == 1) {
906    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
907    unsigned IntSize = Context.Target.getIntWidth();
908    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
909                    Context.IntTy, Tok.getLocation()));
910  }
911
912  llvm::SmallString<512> IntegerBuffer;
913  // Add padding so that NumericLiteralParser can overread by one character.
914  IntegerBuffer.resize(Tok.getLength()+1);
915  const char *ThisTokBegin = &IntegerBuffer[0];
916
917  // Get the spelling of the token, which eliminates trigraphs, etc.
918  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
919
920  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
921                               Tok.getLocation(), PP);
922  if (Literal.hadError)
923    return ExprError();
924
925  Expr *Res;
926
927  if (Literal.isFloatingLiteral()) {
928    QualType Ty;
929    if (Literal.isFloat)
930      Ty = Context.FloatTy;
931    else if (!Literal.isLong)
932      Ty = Context.DoubleTy;
933    else
934      Ty = Context.LongDoubleTy;
935
936    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
937
938    // isExact will be set by GetFloatValue().
939    bool isExact = false;
940    Res = new (Context) FloatingLiteral(Literal.GetFloatValue(Format, &isExact),
941                                        &isExact, Ty, Tok.getLocation());
942
943  } else if (!Literal.isIntegerLiteral()) {
944    return ExprError();
945  } else {
946    QualType Ty;
947
948    // long long is a C99 feature.
949    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
950        Literal.isLongLong)
951      Diag(Tok.getLocation(), diag::ext_longlong);
952
953    // Get the value in the widest-possible width.
954    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
955
956    if (Literal.GetIntegerValue(ResultVal)) {
957      // If this value didn't fit into uintmax_t, warn and force to ull.
958      Diag(Tok.getLocation(), diag::warn_integer_too_large);
959      Ty = Context.UnsignedLongLongTy;
960      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
961             "long long is not intmax_t?");
962    } else {
963      // If this value fits into a ULL, try to figure out what else it fits into
964      // according to the rules of C99 6.4.4.1p5.
965
966      // Octal, Hexadecimal, and integers with a U suffix are allowed to
967      // be an unsigned int.
968      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
969
970      // Check from smallest to largest, picking the smallest type we can.
971      unsigned Width = 0;
972      if (!Literal.isLong && !Literal.isLongLong) {
973        // Are int/unsigned possibilities?
974        unsigned IntSize = Context.Target.getIntWidth();
975
976        // Does it fit in a unsigned int?
977        if (ResultVal.isIntN(IntSize)) {
978          // Does it fit in a signed int?
979          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
980            Ty = Context.IntTy;
981          else if (AllowUnsigned)
982            Ty = Context.UnsignedIntTy;
983          Width = IntSize;
984        }
985      }
986
987      // Are long/unsigned long possibilities?
988      if (Ty.isNull() && !Literal.isLongLong) {
989        unsigned LongSize = Context.Target.getLongWidth();
990
991        // Does it fit in a unsigned long?
992        if (ResultVal.isIntN(LongSize)) {
993          // Does it fit in a signed long?
994          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
995            Ty = Context.LongTy;
996          else if (AllowUnsigned)
997            Ty = Context.UnsignedLongTy;
998          Width = LongSize;
999        }
1000      }
1001
1002      // Finally, check long long if needed.
1003      if (Ty.isNull()) {
1004        unsigned LongLongSize = Context.Target.getLongLongWidth();
1005
1006        // Does it fit in a unsigned long long?
1007        if (ResultVal.isIntN(LongLongSize)) {
1008          // Does it fit in a signed long long?
1009          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1010            Ty = Context.LongLongTy;
1011          else if (AllowUnsigned)
1012            Ty = Context.UnsignedLongLongTy;
1013          Width = LongLongSize;
1014        }
1015      }
1016
1017      // If we still couldn't decide a type, we probably have something that
1018      // does not fit in a signed long long, but has no U suffix.
1019      if (Ty.isNull()) {
1020        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1021        Ty = Context.UnsignedLongLongTy;
1022        Width = Context.Target.getLongLongWidth();
1023      }
1024
1025      if (ResultVal.getBitWidth() != Width)
1026        ResultVal.trunc(Width);
1027    }
1028    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1029  }
1030
1031  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1032  if (Literal.isImaginary)
1033    Res = new (Context) ImaginaryLiteral(Res,
1034                                        Context.getComplexType(Res->getType()));
1035
1036  return Owned(Res);
1037}
1038
1039Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1040                                              SourceLocation R, ExprArg Val) {
1041  Expr *E = (Expr *)Val.release();
1042  assert((E != 0) && "ActOnParenExpr() missing expr");
1043  return Owned(new (Context) ParenExpr(L, R, E));
1044}
1045
1046/// The UsualUnaryConversions() function is *not* called by this routine.
1047/// See C99 6.3.2.1p[2-4] for more details.
1048bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1049                                     SourceLocation OpLoc,
1050                                     const SourceRange &ExprRange,
1051                                     bool isSizeof) {
1052  // C99 6.5.3.4p1:
1053  if (isa<FunctionType>(exprType)) {
1054    // alignof(function) is allowed.
1055    if (isSizeof)
1056      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1057    return false;
1058  }
1059
1060  if (exprType->isVoidType()) {
1061    Diag(OpLoc, diag::ext_sizeof_void_type)
1062      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1063    return false;
1064  }
1065
1066  return DiagnoseIncompleteType(OpLoc, exprType,
1067                                isSizeof ? diag::err_sizeof_incomplete_type :
1068                                           diag::err_alignof_incomplete_type,
1069                                ExprRange);
1070}
1071
1072bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1073                            const SourceRange &ExprRange) {
1074  E = E->IgnoreParens();
1075
1076  // alignof decl is always ok.
1077  if (isa<DeclRefExpr>(E))
1078    return false;
1079
1080  if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
1081    if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
1082      if (FD->isBitField()) {
1083        Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1084        return true;
1085      }
1086      // Other fields are ok.
1087      return false;
1088    }
1089  }
1090  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1091}
1092
1093/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1094/// the same for @c alignof and @c __alignof
1095/// Note that the ArgRange is invalid if isType is false.
1096Action::OwningExprResult
1097Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1098                             void *TyOrEx, const SourceRange &ArgRange) {
1099  // If error parsing type, ignore.
1100  if (TyOrEx == 0) return ExprError();
1101
1102  QualType ArgTy;
1103  SourceRange Range;
1104  if (isType) {
1105    ArgTy = QualType::getFromOpaquePtr(TyOrEx);
1106    Range = ArgRange;
1107
1108    // Verify that the operand is valid.
1109    if (CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, isSizeof))
1110      return ExprError();
1111  } else {
1112    // Get the end location.
1113    Expr *ArgEx = (Expr *)TyOrEx;
1114    Range = ArgEx->getSourceRange();
1115    ArgTy = ArgEx->getType();
1116
1117    // Verify that the operand is valid.
1118    bool isInvalid;
1119    if (!isSizeof) {
1120      isInvalid = CheckAlignOfExpr(ArgEx, OpLoc, Range);
1121    } else if (ArgEx->isBitField()) {  // C99 6.5.3.4p1.
1122      Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1123      isInvalid = true;
1124    } else {
1125      isInvalid = CheckSizeOfAlignOfOperand(ArgTy, OpLoc, Range, true);
1126    }
1127
1128    if (isInvalid) {
1129      DeleteExpr(ArgEx);
1130      return ExprError();
1131    }
1132  }
1133
1134  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1135  return Owned(new (Context) SizeOfAlignOfExpr(isSizeof, isType, TyOrEx,
1136                                               Context.getSizeType(), OpLoc,
1137                                               Range.getEnd()));
1138}
1139
1140QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc) {
1141  DefaultFunctionArrayConversion(V);
1142
1143  // These operators return the element type of a complex type.
1144  if (const ComplexType *CT = V->getType()->getAsComplexType())
1145    return CT->getElementType();
1146
1147  // Otherwise they pass through real integer and floating point types here.
1148  if (V->getType()->isArithmeticType())
1149    return V->getType();
1150
1151  // Reject anything else.
1152  Diag(Loc, diag::err_realimag_invalid_type) << V->getType();
1153  return QualType();
1154}
1155
1156
1157
1158Action::OwningExprResult
1159Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1160                          tok::TokenKind Kind, ExprArg Input) {
1161  Expr *Arg = (Expr *)Input.get();
1162
1163  UnaryOperator::Opcode Opc;
1164  switch (Kind) {
1165  default: assert(0 && "Unknown unary op!");
1166  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1167  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1168  }
1169
1170  if (getLangOptions().CPlusPlus &&
1171      (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1172    // Which overloaded operator?
1173    OverloadedOperatorKind OverOp =
1174      (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1175
1176    // C++ [over.inc]p1:
1177    //
1178    //     [...] If the function is a member function with one
1179    //     parameter (which shall be of type int) or a non-member
1180    //     function with two parameters (the second of which shall be
1181    //     of type int), it defines the postfix increment operator ++
1182    //     for objects of that type. When the postfix increment is
1183    //     called as a result of using the ++ operator, the int
1184    //     argument will have value zero.
1185    Expr *Args[2] = {
1186      Arg,
1187      new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1188                          /*isSigned=*/true), Context.IntTy, SourceLocation())
1189    };
1190
1191    // Build the candidate set for overloading
1192    OverloadCandidateSet CandidateSet;
1193    if (AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet))
1194      return ExprError();
1195
1196    // Perform overload resolution.
1197    OverloadCandidateSet::iterator Best;
1198    switch (BestViableFunction(CandidateSet, Best)) {
1199    case OR_Success: {
1200      // We found a built-in operator or an overloaded operator.
1201      FunctionDecl *FnDecl = Best->Function;
1202
1203      if (FnDecl) {
1204        // We matched an overloaded operator. Build a call to that
1205        // operator.
1206
1207        // Convert the arguments.
1208        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1209          if (PerformObjectArgumentInitialization(Arg, Method))
1210            return ExprError();
1211        } else {
1212          // Convert the arguments.
1213          if (PerformCopyInitialization(Arg,
1214                                        FnDecl->getParamDecl(0)->getType(),
1215                                        "passing"))
1216            return ExprError();
1217        }
1218
1219        // Determine the result type
1220        QualType ResultTy
1221          = FnDecl->getType()->getAsFunctionType()->getResultType();
1222        ResultTy = ResultTy.getNonReferenceType();
1223
1224        // Build the actual expression node.
1225        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1226                                       SourceLocation());
1227        UsualUnaryConversions(FnExpr);
1228
1229        Input.release();
1230        return Owned(new (Context)CXXOperatorCallExpr(FnExpr, Args, 2, ResultTy,
1231                                                   OpLoc));
1232      } else {
1233        // We matched a built-in operator. Convert the arguments, then
1234        // break out so that we will build the appropriate built-in
1235        // operator node.
1236        if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1237                                      "passing"))
1238          return ExprError();
1239
1240        break;
1241      }
1242    }
1243
1244    case OR_No_Viable_Function:
1245      // No viable function; fall through to handling this as a
1246      // built-in operator, which will produce an error message for us.
1247      break;
1248
1249    case OR_Ambiguous:
1250      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1251          << UnaryOperator::getOpcodeStr(Opc)
1252          << Arg->getSourceRange();
1253      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1254      return ExprError();
1255    }
1256
1257    // Either we found no viable overloaded operator or we matched a
1258    // built-in operator. In either case, fall through to trying to
1259    // build a built-in operation.
1260  }
1261
1262  QualType result = CheckIncrementDecrementOperand(Arg, OpLoc,
1263                                                 Opc == UnaryOperator::PostInc);
1264  if (result.isNull())
1265    return ExprError();
1266  Input.release();
1267  return Owned(new (Context) UnaryOperator(Arg, Opc, result, OpLoc));
1268}
1269
1270Action::OwningExprResult
1271Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1272                              ExprArg Idx, SourceLocation RLoc) {
1273  Expr *LHSExp = static_cast<Expr*>(Base.get()),
1274       *RHSExp = static_cast<Expr*>(Idx.get());
1275
1276  if (getLangOptions().CPlusPlus &&
1277      (LHSExp->getType()->isRecordType() ||
1278       LHSExp->getType()->isEnumeralType() ||
1279       RHSExp->getType()->isRecordType() ||
1280       RHSExp->getType()->isEnumeralType())) {
1281    // Add the appropriate overloaded operators (C++ [over.match.oper])
1282    // to the candidate set.
1283    OverloadCandidateSet CandidateSet;
1284    Expr *Args[2] = { LHSExp, RHSExp };
1285    if (AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1286                              SourceRange(LLoc, RLoc)))
1287      return ExprError();
1288
1289    // Perform overload resolution.
1290    OverloadCandidateSet::iterator Best;
1291    switch (BestViableFunction(CandidateSet, Best)) {
1292    case OR_Success: {
1293      // We found a built-in operator or an overloaded operator.
1294      FunctionDecl *FnDecl = Best->Function;
1295
1296      if (FnDecl) {
1297        // We matched an overloaded operator. Build a call to that
1298        // operator.
1299
1300        // Convert the arguments.
1301        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1302          if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1303              PerformCopyInitialization(RHSExp,
1304                                        FnDecl->getParamDecl(0)->getType(),
1305                                        "passing"))
1306            return ExprError();
1307        } else {
1308          // Convert the arguments.
1309          if (PerformCopyInitialization(LHSExp,
1310                                        FnDecl->getParamDecl(0)->getType(),
1311                                        "passing") ||
1312              PerformCopyInitialization(RHSExp,
1313                                        FnDecl->getParamDecl(1)->getType(),
1314                                        "passing"))
1315            return ExprError();
1316        }
1317
1318        // Determine the result type
1319        QualType ResultTy
1320          = FnDecl->getType()->getAsFunctionType()->getResultType();
1321        ResultTy = ResultTy.getNonReferenceType();
1322
1323        // Build the actual expression node.
1324        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1325                                       SourceLocation());
1326        UsualUnaryConversions(FnExpr);
1327
1328        Base.release();
1329        Idx.release();
1330        return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
1331                                                       ResultTy, LLoc));
1332      } else {
1333        // We matched a built-in operator. Convert the arguments, then
1334        // break out so that we will build the appropriate built-in
1335        // operator node.
1336        if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1337                                      "passing") ||
1338            PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1339                                      "passing"))
1340          return ExprError();
1341
1342        break;
1343      }
1344    }
1345
1346    case OR_No_Viable_Function:
1347      // No viable function; fall through to handling this as a
1348      // built-in operator, which will produce an error message for us.
1349      break;
1350
1351    case OR_Ambiguous:
1352      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
1353          << "[]"
1354          << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1355      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1356      return ExprError();
1357    }
1358
1359    // Either we found no viable overloaded operator or we matched a
1360    // built-in operator. In either case, fall through to trying to
1361    // build a built-in operation.
1362  }
1363
1364  // Perform default conversions.
1365  DefaultFunctionArrayConversion(LHSExp);
1366  DefaultFunctionArrayConversion(RHSExp);
1367
1368  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1369
1370  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1371  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1372  // in the subscript position. As a result, we need to derive the array base
1373  // and index from the expression types.
1374  Expr *BaseExpr, *IndexExpr;
1375  QualType ResultType;
1376  if (const PointerType *PTy = LHSTy->getAsPointerType()) {
1377    BaseExpr = LHSExp;
1378    IndexExpr = RHSExp;
1379    // FIXME: need to deal with const...
1380    ResultType = PTy->getPointeeType();
1381  } else if (const PointerType *PTy = RHSTy->getAsPointerType()) {
1382     // Handle the uncommon case of "123[Ptr]".
1383    BaseExpr = RHSExp;
1384    IndexExpr = LHSExp;
1385    // FIXME: need to deal with const...
1386    ResultType = PTy->getPointeeType();
1387  } else if (const VectorType *VTy = LHSTy->getAsVectorType()) {
1388    BaseExpr = LHSExp;    // vectors: V[123]
1389    IndexExpr = RHSExp;
1390
1391    // FIXME: need to deal with const...
1392    ResultType = VTy->getElementType();
1393  } else {
1394    return ExprError(Diag(LHSExp->getLocStart(),
1395      diag::err_typecheck_subscript_value) << RHSExp->getSourceRange());
1396  }
1397  // C99 6.5.2.1p1
1398  if (!IndexExpr->getType()->isIntegerType())
1399    return ExprError(Diag(IndexExpr->getLocStart(),
1400      diag::err_typecheck_subscript) << IndexExpr->getSourceRange());
1401
1402  // C99 6.5.2.1p1: "shall have type "pointer to *object* type".  In practice,
1403  // the following check catches trying to index a pointer to a function (e.g.
1404  // void (*)(int)) and pointers to incomplete types.  Functions are not
1405  // objects in C99.
1406  if (!ResultType->isObjectType())
1407    return ExprError(Diag(BaseExpr->getLocStart(),
1408                diag::err_typecheck_subscript_not_object)
1409      << BaseExpr->getType() << BaseExpr->getSourceRange());
1410
1411  Base.release();
1412  Idx.release();
1413  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1414                                                ResultType, RLoc));
1415}
1416
1417QualType Sema::
1418CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1419                        IdentifierInfo &CompName, SourceLocation CompLoc) {
1420  const ExtVectorType *vecType = baseType->getAsExtVectorType();
1421
1422  // The vector accessor can't exceed the number of elements.
1423  const char *compStr = CompName.getName();
1424
1425  // This flag determines whether or not the component is one of the four
1426  // special names that indicate a subset of exactly half the elements are
1427  // to be selected.
1428  bool HalvingSwizzle = false;
1429
1430  // This flag determines whether or not CompName has an 's' char prefix,
1431  // indicating that it is a string of hex values to be used as vector indices.
1432  bool HexSwizzle = *compStr == 's';
1433
1434  // Check that we've found one of the special components, or that the component
1435  // names must come from the same set.
1436  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1437      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1438    HalvingSwizzle = true;
1439  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1440    do
1441      compStr++;
1442    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1443  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1444    do
1445      compStr++;
1446    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1447  }
1448
1449  if (!HalvingSwizzle && *compStr) {
1450    // We didn't get to the end of the string. This means the component names
1451    // didn't come from the same set *or* we encountered an illegal name.
1452    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1453      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1454    return QualType();
1455  }
1456
1457  // Ensure no component accessor exceeds the width of the vector type it
1458  // operates on.
1459  if (!HalvingSwizzle) {
1460    compStr = CompName.getName();
1461
1462    if (HexSwizzle)
1463      compStr++;
1464
1465    while (*compStr) {
1466      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1467        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1468          << baseType << SourceRange(CompLoc);
1469        return QualType();
1470      }
1471    }
1472  }
1473
1474  // If this is a halving swizzle, verify that the base type has an even
1475  // number of elements.
1476  if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1477    Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1478      << baseType << SourceRange(CompLoc);
1479    return QualType();
1480  }
1481
1482  // The component accessor looks fine - now we need to compute the actual type.
1483  // The vector type is implied by the component accessor. For example,
1484  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1485  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1486  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1487  unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1488                                     : CompName.getLength();
1489  if (HexSwizzle)
1490    CompSize--;
1491
1492  if (CompSize == 1)
1493    return vecType->getElementType();
1494
1495  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1496  // Now look up the TypeDefDecl from the vector type. Without this,
1497  // diagostics look bad. We want extended vector types to appear built-in.
1498  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1499    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1500      return Context.getTypedefType(ExtVectorDecls[i]);
1501  }
1502  return VT; // should never get here (a typedef type should always be found).
1503}
1504
1505/// constructSetterName - Return the setter name for the given
1506/// identifier, i.e. "set" + Name where the initial character of Name
1507/// has been capitalized.
1508// FIXME: Merge with same routine in Parser. But where should this
1509// live?
1510static IdentifierInfo *constructSetterName(IdentifierTable &Idents,
1511                                           const IdentifierInfo *Name) {
1512  llvm::SmallString<100> SelectorName;
1513  SelectorName = "set";
1514  SelectorName.append(Name->getName(), Name->getName()+Name->getLength());
1515  SelectorName[3] = toupper(SelectorName[3]);
1516  return &Idents.get(&SelectorName[0], &SelectorName[SelectorName.size()]);
1517}
1518
1519Action::OwningExprResult
1520Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1521                               tok::TokenKind OpKind, SourceLocation MemberLoc,
1522                               IdentifierInfo &Member) {
1523  Expr *BaseExpr = static_cast<Expr *>(Base.release());
1524  assert(BaseExpr && "no record expression");
1525
1526  // Perform default conversions.
1527  DefaultFunctionArrayConversion(BaseExpr);
1528
1529  QualType BaseType = BaseExpr->getType();
1530  assert(!BaseType.isNull() && "no type for member expression");
1531
1532  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
1533  // must have pointer type, and the accessed type is the pointee.
1534  if (OpKind == tok::arrow) {
1535    if (const PointerType *PT = BaseType->getAsPointerType())
1536      BaseType = PT->getPointeeType();
1537    else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1538      return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1539                                            MemberLoc, Member));
1540    else
1541      return ExprError(Diag(MemberLoc,
1542                            diag::err_typecheck_member_reference_arrow)
1543        << BaseType << BaseExpr->getSourceRange());
1544  }
1545
1546  // Handle field access to simple records.  This also handles access to fields
1547  // of the ObjC 'id' struct.
1548  if (const RecordType *RTy = BaseType->getAsRecordType()) {
1549    RecordDecl *RDecl = RTy->getDecl();
1550    if (DiagnoseIncompleteType(OpLoc, BaseType,
1551                               diag::err_typecheck_incomplete_tag,
1552                               BaseExpr->getSourceRange()))
1553      return ExprError();
1554
1555    // The record definition is complete, now make sure the member is valid.
1556    // FIXME: Qualified name lookup for C++ is a bit more complicated
1557    // than this.
1558    LookupResult Result
1559      = LookupQualifiedName(RDecl, DeclarationName(&Member),
1560                            LookupMemberName, false);
1561
1562    Decl *MemberDecl = 0;
1563    if (!Result)
1564      return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1565               << &Member << BaseExpr->getSourceRange());
1566    else if (Result.isAmbiguous()) {
1567      DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1568                              MemberLoc, BaseExpr->getSourceRange());
1569      return ExprError();
1570    } else
1571      MemberDecl = Result;
1572
1573    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
1574      // We may have found a field within an anonymous union or struct
1575      // (C++ [class.union]).
1576      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1577        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1578                                                        BaseExpr, OpLoc);
1579
1580      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1581      // FIXME: Handle address space modifiers
1582      QualType MemberType = FD->getType();
1583      if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1584        MemberType = Ref->getPointeeType();
1585      else {
1586        unsigned combinedQualifiers =
1587          MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
1588        if (FD->isMutable())
1589          combinedQualifiers &= ~QualType::Const;
1590        MemberType = MemberType.getQualifiedType(combinedQualifiers);
1591      }
1592
1593      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1594                                            MemberLoc, MemberType));
1595    } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
1596      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1597                                  Var, MemberLoc,
1598                                  Var->getType().getNonReferenceType()));
1599    else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
1600      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1601                                  MemberFn, MemberLoc, MemberFn->getType()));
1602    else if (OverloadedFunctionDecl *Ovl
1603             = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
1604      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
1605                                  MemberLoc, Context.OverloadTy));
1606    else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
1607      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Enum,
1608                                  MemberLoc, Enum->getType()));
1609    else if (isa<TypeDecl>(MemberDecl))
1610      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1611        << DeclarationName(&Member) << int(OpKind == tok::arrow));
1612
1613    // We found a declaration kind that we didn't expect. This is a
1614    // generic error message that tells the user that she can't refer
1615    // to this member with '.' or '->'.
1616    return ExprError(Diag(MemberLoc,
1617                          diag::err_typecheck_member_reference_unknown)
1618      << DeclarationName(&Member) << int(OpKind == tok::arrow));
1619  }
1620
1621  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1622  // (*Obj).ivar.
1623  if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1624    if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member)) {
1625      ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1626                                                 MemberLoc, BaseExpr,
1627                                                 OpKind == tok::arrow);
1628      Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1629      return Owned(MRef);
1630    }
1631    return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1632                       << IFTy->getDecl()->getDeclName() << &Member
1633                       << BaseExpr->getSourceRange());
1634  }
1635
1636  // Handle Objective-C property access, which is "Obj.property" where Obj is a
1637  // pointer to a (potentially qualified) interface type.
1638  const PointerType *PTy;
1639  const ObjCInterfaceType *IFTy;
1640  if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1641      (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1642    ObjCInterfaceDecl *IFace = IFTy->getDecl();
1643
1644    // Search for a declared property first.
1645    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member))
1646      return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1647                                           MemberLoc, BaseExpr));
1648
1649    // Check protocols on qualified interfaces.
1650    for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1651         E = IFTy->qual_end(); I != E; ++I)
1652      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1653        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1654                                             MemberLoc, BaseExpr));
1655
1656    // If that failed, look for an "implicit" property by seeing if the nullary
1657    // selector is implemented.
1658
1659    // FIXME: The logic for looking up nullary and unary selectors should be
1660    // shared with the code in ActOnInstanceMessage.
1661
1662    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1663    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1664
1665    // If this reference is in an @implementation, check for 'private' methods.
1666    if (!Getter)
1667      if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1668        if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1669          if (ObjCImplementationDecl *ImpDecl =
1670              ObjCImplementations[ClassDecl->getIdentifier()])
1671            Getter = ImpDecl->getInstanceMethod(Sel);
1672
1673    // Look through local category implementations associated with the class.
1674    if (!Getter) {
1675      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1676        if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1677          Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1678      }
1679    }
1680    if (Getter) {
1681      // If we found a getter then this may be a valid dot-reference, we
1682      // will look for the matching setter, in case it is needed.
1683      IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1684                                                       &Member);
1685      Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1686      ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1687      if (!Setter) {
1688        // If this reference is in an @implementation, also check for 'private'
1689        // methods.
1690        if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1691          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1692            if (ObjCImplementationDecl *ImpDecl =
1693                  ObjCImplementations[ClassDecl->getIdentifier()])
1694              Setter = ImpDecl->getInstanceMethod(SetterSel);
1695      }
1696      // Look through local category implementations associated with the class.
1697      if (!Setter) {
1698        for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1699          if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1700            Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1701        }
1702      }
1703
1704      // FIXME: we must check that the setter has property type.
1705      return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1706                                      Setter, MemberLoc, BaseExpr));
1707    }
1708
1709    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1710      << &Member << BaseType);
1711  }
1712  // Handle properties on qualified "id" protocols.
1713  const ObjCQualifiedIdType *QIdTy;
1714  if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1715    // Check protocols on qualified interfaces.
1716    for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1717         E = QIdTy->qual_end(); I != E; ++I) {
1718      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member))
1719        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1720                                             MemberLoc, BaseExpr));
1721      // Also must look for a getter name which uses property syntax.
1722      Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1723      if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1724        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1725                        OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
1726      }
1727    }
1728
1729    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1730                       << &Member << BaseType);
1731  }
1732  // Handle 'field access' to vectors, such as 'V.xx'.
1733  if (BaseType->isExtVectorType() && OpKind == tok::period) {
1734    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1735    if (ret.isNull())
1736      return ExprError();
1737    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1738                                                    MemberLoc));
1739  }
1740
1741  return ExprError(Diag(MemberLoc,
1742                        diag::err_typecheck_member_reference_struct_union)
1743                     << BaseType << BaseExpr->getSourceRange());
1744}
1745
1746/// ConvertArgumentsForCall - Converts the arguments specified in
1747/// Args/NumArgs to the parameter types of the function FDecl with
1748/// function prototype Proto. Call is the call expression itself, and
1749/// Fn is the function expression. For a C++ member function, this
1750/// routine does not attempt to convert the object argument. Returns
1751/// true if the call is ill-formed.
1752bool
1753Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1754                              FunctionDecl *FDecl,
1755                              const FunctionTypeProto *Proto,
1756                              Expr **Args, unsigned NumArgs,
1757                              SourceLocation RParenLoc) {
1758  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1759  // assignment, to the types of the corresponding parameter, ...
1760  unsigned NumArgsInProto = Proto->getNumArgs();
1761  unsigned NumArgsToCheck = NumArgs;
1762  bool Invalid = false;
1763
1764  // If too few arguments are available (and we don't have default
1765  // arguments for the remaining parameters), don't make the call.
1766  if (NumArgs < NumArgsInProto) {
1767    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1768      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1769        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1770    // Use default arguments for missing arguments
1771    NumArgsToCheck = NumArgsInProto;
1772    Call->setNumArgs(NumArgsInProto);
1773  }
1774
1775  // If too many are passed and not variadic, error on the extras and drop
1776  // them.
1777  if (NumArgs > NumArgsInProto) {
1778    if (!Proto->isVariadic()) {
1779      Diag(Args[NumArgsInProto]->getLocStart(),
1780           diag::err_typecheck_call_too_many_args)
1781        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
1782        << SourceRange(Args[NumArgsInProto]->getLocStart(),
1783                       Args[NumArgs-1]->getLocEnd());
1784      // This deletes the extra arguments.
1785      Call->setNumArgs(NumArgsInProto);
1786      Invalid = true;
1787    }
1788    NumArgsToCheck = NumArgsInProto;
1789  }
1790
1791  // Continue to check argument types (even if we have too few/many args).
1792  for (unsigned i = 0; i != NumArgsToCheck; i++) {
1793    QualType ProtoArgType = Proto->getArgType(i);
1794
1795    Expr *Arg;
1796    if (i < NumArgs) {
1797      Arg = Args[i];
1798
1799      // Pass the argument.
1800      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
1801        return true;
1802    } else
1803      // We already type-checked the argument, so we know it works.
1804      Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
1805    QualType ArgType = Arg->getType();
1806
1807    Call->setArg(i, Arg);
1808  }
1809
1810  // If this is a variadic call, handle args passed through "...".
1811  if (Proto->isVariadic()) {
1812    VariadicCallType CallType = VariadicFunction;
1813    if (Fn->getType()->isBlockPointerType())
1814      CallType = VariadicBlock; // Block
1815    else if (isa<MemberExpr>(Fn))
1816      CallType = VariadicMethod;
1817
1818    // Promote the arguments (C99 6.5.2.2p7).
1819    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
1820      Expr *Arg = Args[i];
1821      DefaultVariadicArgumentPromotion(Arg, CallType);
1822      Call->setArg(i, Arg);
1823    }
1824  }
1825
1826  return Invalid;
1827}
1828
1829/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
1830/// This provides the location of the left/right parens and a list of comma
1831/// locations.
1832Action::OwningExprResult
1833Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
1834                    MultiExprArg args,
1835                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
1836  unsigned NumArgs = args.size();
1837  Expr *Fn = static_cast<Expr *>(fn.release());
1838  Expr **Args = reinterpret_cast<Expr**>(args.release());
1839  assert(Fn && "no function call expression");
1840  FunctionDecl *FDecl = NULL;
1841  DeclarationName UnqualifiedName;
1842
1843  if (getLangOptions().CPlusPlus) {
1844    // Determine whether this is a dependent call inside a C++ template,
1845    // in which case we won't do any semantic analysis now.
1846    // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
1847    bool Dependent = false;
1848    if (Fn->isTypeDependent())
1849      Dependent = true;
1850    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
1851      Dependent = true;
1852
1853    if (Dependent)
1854      return Owned(new (Context) CallExpr(Fn, Args, NumArgs,
1855                                          Context.DependentTy, RParenLoc));
1856
1857    // Determine whether this is a call to an object (C++ [over.call.object]).
1858    if (Fn->getType()->isRecordType())
1859      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
1860                                                CommaLocs, RParenLoc));
1861
1862    // Determine whether this is a call to a member function.
1863    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
1864      if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
1865          isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
1866        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
1867                                               CommaLocs, RParenLoc));
1868  }
1869
1870  // If we're directly calling a function, get the appropriate declaration.
1871  DeclRefExpr *DRExpr = NULL;
1872  Expr *FnExpr = Fn;
1873  bool ADL = true;
1874  while (true) {
1875    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
1876      FnExpr = IcExpr->getSubExpr();
1877    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
1878      // Parentheses around a function disable ADL
1879      // (C++0x [basic.lookup.argdep]p1).
1880      ADL = false;
1881      FnExpr = PExpr->getSubExpr();
1882    } else if (isa<UnaryOperator>(FnExpr) &&
1883               cast<UnaryOperator>(FnExpr)->getOpcode()
1884                 == UnaryOperator::AddrOf) {
1885      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
1886    } else {
1887      if (isa<DeclRefExpr>(FnExpr)) {
1888        DRExpr = cast<DeclRefExpr>(FnExpr);
1889
1890        // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
1891        ADL = ADL && !isa<QualifiedDeclRefExpr>(DRExpr);
1892      }
1893      else if (UnresolvedFunctionNameExpr *DepName
1894                 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr))
1895        UnqualifiedName = DepName->getName();
1896      else {
1897        // Any kind of name that does not refer to a declaration (or
1898        // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
1899        ADL = false;
1900      }
1901      break;
1902    }
1903  }
1904
1905  OverloadedFunctionDecl *Ovl = 0;
1906  if (DRExpr) {
1907    FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
1908    Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
1909  }
1910
1911  if (getLangOptions().CPlusPlus && (FDecl || Ovl || UnqualifiedName)) {
1912    // We don't perform ADL for builtins.
1913    if (FDecl && FDecl->getIdentifier() &&
1914        FDecl->getIdentifier()->getBuiltinID())
1915      ADL = false;
1916
1917    if (Ovl || ADL) {
1918      FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
1919                                      UnqualifiedName, LParenLoc, Args,
1920                                      NumArgs, CommaLocs, RParenLoc, ADL);
1921      if (!FDecl)
1922        return ExprError();
1923
1924      // Update Fn to refer to the actual function selected.
1925      Expr *NewFn = 0;
1926      if (QualifiedDeclRefExpr *QDRExpr
1927            = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
1928        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
1929                                                   QDRExpr->getLocation(),
1930                                                   false, false,
1931                                          QDRExpr->getSourceRange().getBegin());
1932      else
1933        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
1934                                          Fn->getSourceRange().getBegin());
1935      Fn->Destroy(Context);
1936      Fn = NewFn;
1937    }
1938  }
1939
1940  // Promote the function operand.
1941  UsualUnaryConversions(Fn);
1942
1943  // Make the call expr early, before semantic checks.  This guarantees cleanup
1944  // of arguments and function on error.
1945  // FIXME: Except that llvm::OwningPtr uses delete, when it really must be
1946  // Destroy(), or nothing gets cleaned up.
1947  llvm::OwningPtr<CallExpr> TheCall(new (Context) CallExpr(Fn, Args, NumArgs,
1948                                                 Context.BoolTy, RParenLoc));
1949
1950  const FunctionType *FuncT;
1951  if (!Fn->getType()->isBlockPointerType()) {
1952    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
1953    // have type pointer to function".
1954    const PointerType *PT = Fn->getType()->getAsPointerType();
1955    if (PT == 0)
1956      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1957        << Fn->getType() << Fn->getSourceRange());
1958    FuncT = PT->getPointeeType()->getAsFunctionType();
1959  } else { // This is a block call.
1960    FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
1961                getAsFunctionType();
1962  }
1963  if (FuncT == 0)
1964    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
1965      << Fn->getType() << Fn->getSourceRange());
1966
1967  // We know the result type of the call, set it.
1968  TheCall->setType(FuncT->getResultType().getNonReferenceType());
1969
1970  if (const FunctionTypeProto *Proto = dyn_cast<FunctionTypeProto>(FuncT)) {
1971    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
1972                                RParenLoc))
1973      return ExprError();
1974  } else {
1975    assert(isa<FunctionTypeNoProto>(FuncT) && "Unknown FunctionType!");
1976
1977    // Promote the arguments (C99 6.5.2.2p6).
1978    for (unsigned i = 0; i != NumArgs; i++) {
1979      Expr *Arg = Args[i];
1980      DefaultArgumentPromotion(Arg);
1981      TheCall->setArg(i, Arg);
1982    }
1983  }
1984
1985  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
1986    if (!Method->isStatic())
1987      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
1988        << Fn->getSourceRange());
1989
1990  // Do special checking on direct calls to functions.
1991  if (FDecl)
1992    return CheckFunctionCall(FDecl, TheCall.take());
1993
1994  return Owned(TheCall.take());
1995}
1996
1997Action::OwningExprResult
1998Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
1999                           SourceLocation RParenLoc, ExprArg InitExpr) {
2000  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
2001  QualType literalType = QualType::getFromOpaquePtr(Ty);
2002  // FIXME: put back this assert when initializers are worked out.
2003  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
2004  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
2005
2006  if (literalType->isArrayType()) {
2007    if (literalType->isVariableArrayType())
2008      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2009        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
2010  } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2011                                    diag::err_typecheck_decl_incomplete_type,
2012                SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
2013    return ExprError();
2014
2015  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
2016                            DeclarationName(), /*FIXME:DirectInit=*/false))
2017    return ExprError();
2018
2019  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
2020  if (isFileScope) { // 6.5.2.5p3
2021    if (CheckForConstantInitializer(literalExpr, literalType))
2022      return ExprError();
2023  }
2024  InitExpr.release();
2025  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2026                                                 literalExpr, isFileScope));
2027}
2028
2029Action::OwningExprResult
2030Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2031                    InitListDesignations &Designators,
2032                    SourceLocation RBraceLoc) {
2033  unsigned NumInit = initlist.size();
2034  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
2035
2036  // Semantic analysis for initializers is done by ActOnDeclarator() and
2037  // CheckInitializer() - it requires knowledge of the object being intialized.
2038
2039  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
2040                                               RBraceLoc);
2041  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
2042  return Owned(E);
2043}
2044
2045/// CheckCastTypes - Check type constraints for casting between types.
2046bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
2047  UsualUnaryConversions(castExpr);
2048
2049  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2050  // type needs to be scalar.
2051  if (castType->isVoidType()) {
2052    // Cast to void allows any expr type.
2053  } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2054    // We can't check any more until template instantiation time.
2055  } else if (!castType->isScalarType() && !castType->isVectorType()) {
2056    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2057        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2058        (castType->isStructureType() || castType->isUnionType())) {
2059      // GCC struct/union extension: allow cast to self.
2060      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2061        << castType << castExpr->getSourceRange();
2062    } else if (castType->isUnionType()) {
2063      // GCC cast to union extension
2064      RecordDecl *RD = castType->getAsRecordType()->getDecl();
2065      RecordDecl::field_iterator Field, FieldEnd;
2066      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2067           Field != FieldEnd; ++Field) {
2068        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2069            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2070          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2071            << castExpr->getSourceRange();
2072          break;
2073        }
2074      }
2075      if (Field == FieldEnd)
2076        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2077          << castExpr->getType() << castExpr->getSourceRange();
2078    } else {
2079      // Reject any other conversions to non-scalar types.
2080      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
2081        << castType << castExpr->getSourceRange();
2082    }
2083  } else if (!castExpr->getType()->isScalarType() &&
2084             !castExpr->getType()->isVectorType()) {
2085    return Diag(castExpr->getLocStart(),
2086                diag::err_typecheck_expect_scalar_operand)
2087      << castExpr->getType() << castExpr->getSourceRange();
2088  } else if (castExpr->getType()->isVectorType()) {
2089    if (CheckVectorCast(TyR, castExpr->getType(), castType))
2090      return true;
2091  } else if (castType->isVectorType()) {
2092    if (CheckVectorCast(TyR, castType, castExpr->getType()))
2093      return true;
2094  }
2095  return false;
2096}
2097
2098bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
2099  assert(VectorTy->isVectorType() && "Not a vector type!");
2100
2101  if (Ty->isVectorType() || Ty->isIntegerType()) {
2102    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
2103      return Diag(R.getBegin(),
2104                  Ty->isVectorType() ?
2105                  diag::err_invalid_conversion_between_vectors :
2106                  diag::err_invalid_conversion_between_vector_and_integer)
2107        << VectorTy << Ty << R;
2108  } else
2109    return Diag(R.getBegin(),
2110                diag::err_invalid_conversion_between_vector_and_scalar)
2111      << VectorTy << Ty << R;
2112
2113  return false;
2114}
2115
2116Action::OwningExprResult
2117Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2118                    SourceLocation RParenLoc, ExprArg Op) {
2119  assert((Ty != 0) && (Op.get() != 0) &&
2120         "ActOnCastExpr(): missing type or expr");
2121
2122  Expr *castExpr = static_cast<Expr*>(Op.release());
2123  QualType castType = QualType::getFromOpaquePtr(Ty);
2124
2125  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2126    return ExprError();
2127  return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
2128                                  LParenLoc, RParenLoc));
2129}
2130
2131/// Note that lex is not null here, even if this is the gnu "x ?: y" extension.
2132/// In that case, lex = cond.
2133inline QualType Sema::CheckConditionalOperands( // C99 6.5.15
2134  Expr *&cond, Expr *&lex, Expr *&rex, SourceLocation questionLoc) {
2135  UsualUnaryConversions(cond);
2136  UsualUnaryConversions(lex);
2137  UsualUnaryConversions(rex);
2138  QualType condT = cond->getType();
2139  QualType lexT = lex->getType();
2140  QualType rexT = rex->getType();
2141
2142  // first, check the condition.
2143  if (!cond->isTypeDependent()) {
2144    if (!condT->isScalarType()) { // C99 6.5.15p2
2145      Diag(cond->getLocStart(), diag::err_typecheck_cond_expect_scalar) << condT;
2146      return QualType();
2147    }
2148  }
2149
2150  // Now check the two expressions.
2151  if ((lex && lex->isTypeDependent()) || (rex && rex->isTypeDependent()))
2152    return Context.DependentTy;
2153
2154  // If both operands have arithmetic type, do the usual arithmetic conversions
2155  // to find a common type: C99 6.5.15p3,5.
2156  if (lexT->isArithmeticType() && rexT->isArithmeticType()) {
2157    UsualArithmeticConversions(lex, rex);
2158    return lex->getType();
2159  }
2160
2161  // If both operands are the same structure or union type, the result is that
2162  // type.
2163  if (const RecordType *LHSRT = lexT->getAsRecordType()) {    // C99 6.5.15p3
2164    if (const RecordType *RHSRT = rexT->getAsRecordType())
2165      if (LHSRT->getDecl() == RHSRT->getDecl())
2166        // "If both the operands have structure or union type, the result has
2167        // that type."  This implies that CV qualifiers are dropped.
2168        return lexT.getUnqualifiedType();
2169  }
2170
2171  // C99 6.5.15p5: "If both operands have void type, the result has void type."
2172  // The following || allows only one side to be void (a GCC-ism).
2173  if (lexT->isVoidType() || rexT->isVoidType()) {
2174    if (!lexT->isVoidType())
2175      Diag(rex->getLocStart(), diag::ext_typecheck_cond_one_void)
2176        << rex->getSourceRange();
2177    if (!rexT->isVoidType())
2178      Diag(lex->getLocStart(), diag::ext_typecheck_cond_one_void)
2179        << lex->getSourceRange();
2180    ImpCastExprToType(lex, Context.VoidTy);
2181    ImpCastExprToType(rex, Context.VoidTy);
2182    return Context.VoidTy;
2183  }
2184  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2185  // the type of the other operand."
2186  if ((lexT->isPointerType() || lexT->isBlockPointerType() ||
2187       Context.isObjCObjectPointerType(lexT)) &&
2188      rex->isNullPointerConstant(Context)) {
2189    ImpCastExprToType(rex, lexT); // promote the null to a pointer.
2190    return lexT;
2191  }
2192  if ((rexT->isPointerType() || rexT->isBlockPointerType() ||
2193       Context.isObjCObjectPointerType(rexT)) &&
2194      lex->isNullPointerConstant(Context)) {
2195    ImpCastExprToType(lex, rexT); // promote the null to a pointer.
2196    return rexT;
2197  }
2198  // Handle the case where both operands are pointers before we handle null
2199  // pointer constants in case both operands are null pointer constants.
2200  if (const PointerType *LHSPT = lexT->getAsPointerType()) { // C99 6.5.15p3,6
2201    if (const PointerType *RHSPT = rexT->getAsPointerType()) {
2202      // get the "pointed to" types
2203      QualType lhptee = LHSPT->getPointeeType();
2204      QualType rhptee = RHSPT->getPointeeType();
2205
2206      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2207      if (lhptee->isVoidType() &&
2208          rhptee->isIncompleteOrObjectType()) {
2209        // Figure out necessary qualifiers (C99 6.5.15p6)
2210        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2211        QualType destType = Context.getPointerType(destPointee);
2212        ImpCastExprToType(lex, destType); // add qualifiers if necessary
2213        ImpCastExprToType(rex, destType); // promote to void*
2214        return destType;
2215      }
2216      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
2217        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2218        QualType destType = Context.getPointerType(destPointee);
2219        ImpCastExprToType(lex, destType); // add qualifiers if necessary
2220        ImpCastExprToType(rex, destType); // promote to void*
2221        return destType;
2222      }
2223
2224      QualType compositeType = lexT;
2225
2226      // If either type is an Objective-C object type then check
2227      // compatibility according to Objective-C.
2228      if (Context.isObjCObjectPointerType(lexT) ||
2229          Context.isObjCObjectPointerType(rexT)) {
2230        // If both operands are interfaces and either operand can be
2231        // assigned to the other, use that type as the composite
2232        // type. This allows
2233        //   xxx ? (A*) a : (B*) b
2234        // where B is a subclass of A.
2235        //
2236        // Additionally, as for assignment, if either type is 'id'
2237        // allow silent coercion. Finally, if the types are
2238        // incompatible then make sure to use 'id' as the composite
2239        // type so the result is acceptable for sending messages to.
2240
2241        // FIXME: This code should not be localized to here. Also this
2242        // should use a compatible check instead of abusing the
2243        // canAssignObjCInterfaces code.
2244        const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2245        const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2246        if (LHSIface && RHSIface &&
2247            Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2248          compositeType = lexT;
2249        } else if (LHSIface && RHSIface &&
2250                   Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
2251          compositeType = rexT;
2252        } else if (Context.isObjCIdType(lhptee) ||
2253                   Context.isObjCIdType(rhptee)) {
2254          // FIXME: This code looks wrong, because isObjCIdType checks
2255          // the struct but getObjCIdType returns the pointer to
2256          // struct. This is horrible and should be fixed.
2257          compositeType = Context.getObjCIdType();
2258        } else {
2259          QualType incompatTy = Context.getObjCIdType();
2260          ImpCastExprToType(lex, incompatTy);
2261          ImpCastExprToType(rex, incompatTy);
2262          return incompatTy;
2263        }
2264      } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2265                                             rhptee.getUnqualifiedType())) {
2266        Diag(questionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2267          << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
2268        // In this situation, we assume void* type. No especially good
2269        // reason, but this is what gcc does, and we do have to pick
2270        // to get a consistent AST.
2271        QualType incompatTy = Context.getPointerType(Context.VoidTy);
2272        ImpCastExprToType(lex, incompatTy);
2273        ImpCastExprToType(rex, incompatTy);
2274        return incompatTy;
2275      }
2276      // The pointer types are compatible.
2277      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2278      // differently qualified versions of compatible types, the result type is
2279      // a pointer to an appropriately qualified version of the *composite*
2280      // type.
2281      // FIXME: Need to calculate the composite type.
2282      // FIXME: Need to add qualifiers
2283      ImpCastExprToType(lex, compositeType);
2284      ImpCastExprToType(rex, compositeType);
2285      return compositeType;
2286    }
2287  }
2288  // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2289  // evaluates to "struct objc_object *" (and is handled above when comparing
2290  // id with statically typed objects).
2291  if (lexT->isObjCQualifiedIdType() || rexT->isObjCQualifiedIdType()) {
2292    // GCC allows qualified id and any Objective-C type to devolve to
2293    // id. Currently localizing to here until clear this should be
2294    // part of ObjCQualifiedIdTypesAreCompatible.
2295    if (ObjCQualifiedIdTypesAreCompatible(lexT, rexT, true) ||
2296        (lexT->isObjCQualifiedIdType() &&
2297         Context.isObjCObjectPointerType(rexT)) ||
2298        (rexT->isObjCQualifiedIdType() &&
2299         Context.isObjCObjectPointerType(lexT))) {
2300      // FIXME: This is not the correct composite type. This only
2301      // happens to work because id can more or less be used anywhere,
2302      // however this may change the type of method sends.
2303      // FIXME: gcc adds some type-checking of the arguments and emits
2304      // (confusing) incompatible comparison warnings in some
2305      // cases. Investigate.
2306      QualType compositeType = Context.getObjCIdType();
2307      ImpCastExprToType(lex, compositeType);
2308      ImpCastExprToType(rex, compositeType);
2309      return compositeType;
2310    }
2311  }
2312
2313  // Selection between block pointer types is ok as long as they are the same.
2314  if (lexT->isBlockPointerType() && rexT->isBlockPointerType() &&
2315      Context.getCanonicalType(lexT) == Context.getCanonicalType(rexT))
2316    return lexT;
2317
2318  // Otherwise, the operands are not compatible.
2319  Diag(questionLoc, diag::err_typecheck_cond_incompatible_operands)
2320    << lexT << rexT << lex->getSourceRange() << rex->getSourceRange();
2321  return QualType();
2322}
2323
2324/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2325/// in the case of a the GNU conditional expr extension.
2326Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2327                                                  SourceLocation ColonLoc,
2328                                                  ExprArg Cond, ExprArg LHS,
2329                                                  ExprArg RHS) {
2330  Expr *CondExpr = (Expr *) Cond.get();
2331  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
2332
2333  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2334  // was the condition.
2335  bool isLHSNull = LHSExpr == 0;
2336  if (isLHSNull)
2337    LHSExpr = CondExpr;
2338
2339  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2340                                             RHSExpr, QuestionLoc);
2341  if (result.isNull())
2342    return ExprError();
2343
2344  Cond.release();
2345  LHS.release();
2346  RHS.release();
2347  return Owned(new (Context) ConditionalOperator(CondExpr,
2348                                                 isLHSNull ? 0 : LHSExpr,
2349                                                 RHSExpr, result));
2350}
2351
2352
2353// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2354// being closely modeled after the C99 spec:-). The odd characteristic of this
2355// routine is it effectively iqnores the qualifiers on the top level pointee.
2356// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2357// FIXME: add a couple examples in this comment.
2358Sema::AssignConvertType
2359Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2360  QualType lhptee, rhptee;
2361
2362  // get the "pointed to" type (ignoring qualifiers at the top level)
2363  lhptee = lhsType->getAsPointerType()->getPointeeType();
2364  rhptee = rhsType->getAsPointerType()->getPointeeType();
2365
2366  // make sure we operate on the canonical type
2367  lhptee = Context.getCanonicalType(lhptee);
2368  rhptee = Context.getCanonicalType(rhptee);
2369
2370  AssignConvertType ConvTy = Compatible;
2371
2372  // C99 6.5.16.1p1: This following citation is common to constraints
2373  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2374  // qualifiers of the type *pointed to* by the right;
2375  // FIXME: Handle ASQualType
2376  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
2377    ConvTy = CompatiblePointerDiscardsQualifiers;
2378
2379  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2380  // incomplete type and the other is a pointer to a qualified or unqualified
2381  // version of void...
2382  if (lhptee->isVoidType()) {
2383    if (rhptee->isIncompleteOrObjectType())
2384      return ConvTy;
2385
2386    // As an extension, we allow cast to/from void* to function pointer.
2387    assert(rhptee->isFunctionType());
2388    return FunctionVoidPointer;
2389  }
2390
2391  if (rhptee->isVoidType()) {
2392    if (lhptee->isIncompleteOrObjectType())
2393      return ConvTy;
2394
2395    // As an extension, we allow cast to/from void* to function pointer.
2396    assert(lhptee->isFunctionType());
2397    return FunctionVoidPointer;
2398  }
2399
2400  // Check for ObjC interfaces
2401  const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2402  const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2403  if (LHSIface && RHSIface &&
2404      Context.canAssignObjCInterfaces(LHSIface, RHSIface))
2405    return ConvTy;
2406
2407  // ID acts sort of like void* for ObjC interfaces
2408  if (LHSIface && Context.isObjCIdType(rhptee))
2409    return ConvTy;
2410  if (RHSIface && Context.isObjCIdType(lhptee))
2411    return ConvTy;
2412
2413  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2414  // unqualified versions of compatible types, ...
2415  if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2416                                  rhptee.getUnqualifiedType()))
2417    return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
2418  return ConvTy;
2419}
2420
2421/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2422/// block pointer types are compatible or whether a block and normal pointer
2423/// are compatible. It is more restrict than comparing two function pointer
2424// types.
2425Sema::AssignConvertType
2426Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2427                                          QualType rhsType) {
2428  QualType lhptee, rhptee;
2429
2430  // get the "pointed to" type (ignoring qualifiers at the top level)
2431  lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2432  rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2433
2434  // make sure we operate on the canonical type
2435  lhptee = Context.getCanonicalType(lhptee);
2436  rhptee = Context.getCanonicalType(rhptee);
2437
2438  AssignConvertType ConvTy = Compatible;
2439
2440  // For blocks we enforce that qualifiers are identical.
2441  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2442    ConvTy = CompatiblePointerDiscardsQualifiers;
2443
2444  if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2445    return IncompatibleBlockPointer;
2446  return ConvTy;
2447}
2448
2449/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2450/// has code to accommodate several GCC extensions when type checking
2451/// pointers. Here are some objectionable examples that GCC considers warnings:
2452///
2453///  int a, *pint;
2454///  short *pshort;
2455///  struct foo *pfoo;
2456///
2457///  pint = pshort; // warning: assignment from incompatible pointer type
2458///  a = pint; // warning: assignment makes integer from pointer without a cast
2459///  pint = a; // warning: assignment makes pointer from integer without a cast
2460///  pint = pfoo; // warning: assignment from incompatible pointer type
2461///
2462/// As a result, the code for dealing with pointers is more complex than the
2463/// C99 spec dictates.
2464///
2465Sema::AssignConvertType
2466Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
2467  // Get canonical types.  We're not formatting these types, just comparing
2468  // them.
2469  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2470  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
2471
2472  if (lhsType == rhsType)
2473    return Compatible; // Common case: fast path an exact match.
2474
2475  // If the left-hand side is a reference type, then we are in a
2476  // (rare!) case where we've allowed the use of references in C,
2477  // e.g., as a parameter type in a built-in function. In this case,
2478  // just make sure that the type referenced is compatible with the
2479  // right-hand side type. The caller is responsible for adjusting
2480  // lhsType so that the resulting expression does not have reference
2481  // type.
2482  if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2483    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
2484      return Compatible;
2485    return Incompatible;
2486  }
2487
2488  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2489    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
2490      return Compatible;
2491    // Relax integer conversions like we do for pointers below.
2492    if (rhsType->isIntegerType())
2493      return IntToPointer;
2494    if (lhsType->isIntegerType())
2495      return PointerToInt;
2496    return IncompatibleObjCQualifiedId;
2497  }
2498
2499  if (lhsType->isVectorType() || rhsType->isVectorType()) {
2500    // For ExtVector, allow vector splats; float -> <n x float>
2501    if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2502      if (LV->getElementType() == rhsType)
2503        return Compatible;
2504
2505    // If we are allowing lax vector conversions, and LHS and RHS are both
2506    // vectors, the total size only needs to be the same. This is a bitcast;
2507    // no bits are changed but the result type is different.
2508    if (getLangOptions().LaxVectorConversions &&
2509        lhsType->isVectorType() && rhsType->isVectorType()) {
2510      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2511        return IncompatibleVectors;
2512    }
2513    return Incompatible;
2514  }
2515
2516  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
2517    return Compatible;
2518
2519  if (isa<PointerType>(lhsType)) {
2520    if (rhsType->isIntegerType())
2521      return IntToPointer;
2522
2523    if (isa<PointerType>(rhsType))
2524      return CheckPointerTypesForAssignment(lhsType, rhsType);
2525
2526    if (rhsType->getAsBlockPointerType()) {
2527      if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
2528        return Compatible;
2529
2530      // Treat block pointers as objects.
2531      if (getLangOptions().ObjC1 &&
2532          lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2533        return Compatible;
2534    }
2535    return Incompatible;
2536  }
2537
2538  if (isa<BlockPointerType>(lhsType)) {
2539    if (rhsType->isIntegerType())
2540      return IntToPointer;
2541
2542    // Treat block pointers as objects.
2543    if (getLangOptions().ObjC1 &&
2544        rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2545      return Compatible;
2546
2547    if (rhsType->isBlockPointerType())
2548      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2549
2550    if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2551      if (RHSPT->getPointeeType()->isVoidType())
2552        return Compatible;
2553    }
2554    return Incompatible;
2555  }
2556
2557  if (isa<PointerType>(rhsType)) {
2558    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
2559    if (lhsType == Context.BoolTy)
2560      return Compatible;
2561
2562    if (lhsType->isIntegerType())
2563      return PointerToInt;
2564
2565    if (isa<PointerType>(lhsType))
2566      return CheckPointerTypesForAssignment(lhsType, rhsType);
2567
2568    if (isa<BlockPointerType>(lhsType) &&
2569        rhsType->getAsPointerType()->getPointeeType()->isVoidType())
2570      return Compatible;
2571    return Incompatible;
2572  }
2573
2574  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
2575    if (Context.typesAreCompatible(lhsType, rhsType))
2576      return Compatible;
2577  }
2578  return Incompatible;
2579}
2580
2581Sema::AssignConvertType
2582Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
2583  if (getLangOptions().CPlusPlus) {
2584    if (!lhsType->isRecordType()) {
2585      // C++ 5.17p3: If the left operand is not of class type, the
2586      // expression is implicitly converted (C++ 4) to the
2587      // cv-unqualified type of the left operand.
2588      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2589                                    "assigning"))
2590        return Incompatible;
2591      else
2592        return Compatible;
2593    }
2594
2595    // FIXME: Currently, we fall through and treat C++ classes like C
2596    // structures.
2597  }
2598
2599  // C99 6.5.16.1p1: the left operand is a pointer and the right is
2600  // a null pointer constant.
2601  if ((lhsType->isPointerType() || lhsType->isObjCQualifiedIdType() ||
2602       lhsType->isBlockPointerType())
2603      && rExpr->isNullPointerConstant(Context)) {
2604    ImpCastExprToType(rExpr, lhsType);
2605    return Compatible;
2606  }
2607
2608  // We don't allow conversion of non-null-pointer constants to integers.
2609  if (lhsType->isBlockPointerType() && rExpr->getType()->isIntegerType())
2610    return IntToBlockPointer;
2611
2612  // This check seems unnatural, however it is necessary to ensure the proper
2613  // conversion of functions/arrays. If the conversion were done for all
2614  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
2615  // expressions that surpress this implicit conversion (&, sizeof).
2616  //
2617  // Suppress this for references: C++ 8.5.3p5.
2618  if (!lhsType->isReferenceType())
2619    DefaultFunctionArrayConversion(rExpr);
2620
2621  Sema::AssignConvertType result =
2622    CheckAssignmentConstraints(lhsType, rExpr->getType());
2623
2624  // C99 6.5.16.1p2: The value of the right operand is converted to the
2625  // type of the assignment expression.
2626  // CheckAssignmentConstraints allows the left-hand side to be a reference,
2627  // so that we can use references in built-in functions even in C.
2628  // The getNonReferenceType() call makes sure that the resulting expression
2629  // does not have reference type.
2630  if (rExpr->getType() != lhsType)
2631    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
2632  return result;
2633}
2634
2635Sema::AssignConvertType
2636Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2637  return CheckAssignmentConstraints(lhsType, rhsType);
2638}
2639
2640QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
2641  Diag(Loc, diag::err_typecheck_invalid_operands)
2642    << lex->getType() << rex->getType()
2643    << lex->getSourceRange() << rex->getSourceRange();
2644  return QualType();
2645}
2646
2647inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
2648                                                              Expr *&rex) {
2649  // For conversion purposes, we ignore any qualifiers.
2650  // For example, "const float" and "float" are equivalent.
2651  QualType lhsType =
2652    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2653  QualType rhsType =
2654    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
2655
2656  // If the vector types are identical, return.
2657  if (lhsType == rhsType)
2658    return lhsType;
2659
2660  // Handle the case of a vector & extvector type of the same size and element
2661  // type.  It would be nice if we only had one vector type someday.
2662  if (getLangOptions().LaxVectorConversions) {
2663    // FIXME: Should we warn here?
2664    if (const VectorType *LV = lhsType->getAsVectorType()) {
2665      if (const VectorType *RV = rhsType->getAsVectorType())
2666        if (LV->getElementType() == RV->getElementType() &&
2667            LV->getNumElements() == RV->getNumElements()) {
2668          return lhsType->isExtVectorType() ? lhsType : rhsType;
2669        }
2670    }
2671  }
2672
2673  // If the lhs is an extended vector and the rhs is a scalar of the same type
2674  // or a literal, promote the rhs to the vector type.
2675  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
2676    QualType eltType = V->getElementType();
2677
2678    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2679        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2680        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
2681      ImpCastExprToType(rex, lhsType);
2682      return lhsType;
2683    }
2684  }
2685
2686  // If the rhs is an extended vector and the lhs is a scalar of the same type,
2687  // promote the lhs to the vector type.
2688  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
2689    QualType eltType = V->getElementType();
2690
2691    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2692        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2693        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
2694      ImpCastExprToType(lex, rhsType);
2695      return rhsType;
2696    }
2697  }
2698
2699  // You cannot convert between vector values of different size.
2700  Diag(Loc, diag::err_typecheck_vector_not_convertable)
2701    << lex->getType() << rex->getType()
2702    << lex->getSourceRange() << rex->getSourceRange();
2703  return QualType();
2704}
2705
2706inline QualType Sema::CheckMultiplyDivideOperands(
2707  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2708{
2709  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2710    return CheckVectorOperands(Loc, lex, rex);
2711
2712  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2713
2714  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2715    return compType;
2716  return InvalidOperands(Loc, lex, rex);
2717}
2718
2719inline QualType Sema::CheckRemainderOperands(
2720  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2721{
2722  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2723    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2724      return CheckVectorOperands(Loc, lex, rex);
2725    return InvalidOperands(Loc, lex, rex);
2726  }
2727
2728  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2729
2730  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2731    return compType;
2732  return InvalidOperands(Loc, lex, rex);
2733}
2734
2735inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
2736  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2737{
2738  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2739    return CheckVectorOperands(Loc, lex, rex);
2740
2741  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2742
2743  // handle the common case first (both operands are arithmetic).
2744  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2745    return compType;
2746
2747  // Put any potential pointer into PExp
2748  Expr* PExp = lex, *IExp = rex;
2749  if (IExp->getType()->isPointerType())
2750    std::swap(PExp, IExp);
2751
2752  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2753    if (IExp->getType()->isIntegerType()) {
2754      // Check for arithmetic on pointers to incomplete types
2755      if (!PTy->getPointeeType()->isObjectType()) {
2756        if (PTy->getPointeeType()->isVoidType()) {
2757          if (getLangOptions().CPlusPlus) {
2758            Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2759              << lex->getSourceRange() << rex->getSourceRange();
2760            return QualType();
2761          }
2762
2763          // GNU extension: arithmetic on pointer to void
2764          Diag(Loc, diag::ext_gnu_void_ptr)
2765            << lex->getSourceRange() << rex->getSourceRange();
2766        } else if (PTy->getPointeeType()->isFunctionType()) {
2767          if (getLangOptions().CPlusPlus) {
2768            Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2769              << lex->getType() << lex->getSourceRange();
2770            return QualType();
2771          }
2772
2773          // GNU extension: arithmetic on pointer to function
2774          Diag(Loc, diag::ext_gnu_ptr_func_arith)
2775            << lex->getType() << lex->getSourceRange();
2776        } else {
2777          DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2778                                 diag::err_typecheck_arithmetic_incomplete_type,
2779                                 lex->getSourceRange(), SourceRange(),
2780                                 lex->getType());
2781          return QualType();
2782        }
2783      }
2784      return PExp->getType();
2785    }
2786  }
2787
2788  return InvalidOperands(Loc, lex, rex);
2789}
2790
2791// C99 6.5.6
2792QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
2793                                        SourceLocation Loc, bool isCompAssign) {
2794  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2795    return CheckVectorOperands(Loc, lex, rex);
2796
2797  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2798
2799  // Enforce type constraints: C99 6.5.6p3.
2800
2801  // Handle the common case first (both operands are arithmetic).
2802  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2803    return compType;
2804
2805  // Either ptr - int   or   ptr - ptr.
2806  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
2807    QualType lpointee = LHSPTy->getPointeeType();
2808
2809    // The LHS must be an object type, not incomplete, function, etc.
2810    if (!lpointee->isObjectType()) {
2811      // Handle the GNU void* extension.
2812      if (lpointee->isVoidType()) {
2813        Diag(Loc, diag::ext_gnu_void_ptr)
2814          << lex->getSourceRange() << rex->getSourceRange();
2815      } else if (lpointee->isFunctionType()) {
2816        if (getLangOptions().CPlusPlus) {
2817          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2818            << lex->getType() << lex->getSourceRange();
2819          return QualType();
2820        }
2821
2822        // GNU extension: arithmetic on pointer to function
2823        Diag(Loc, diag::ext_gnu_ptr_func_arith)
2824          << lex->getType() << lex->getSourceRange();
2825      } else {
2826        Diag(Loc, diag::err_typecheck_sub_ptr_object)
2827          << lex->getType() << lex->getSourceRange();
2828        return QualType();
2829      }
2830    }
2831
2832    // The result type of a pointer-int computation is the pointer type.
2833    if (rex->getType()->isIntegerType())
2834      return lex->getType();
2835
2836    // Handle pointer-pointer subtractions.
2837    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
2838      QualType rpointee = RHSPTy->getPointeeType();
2839
2840      // RHS must be an object type, unless void (GNU).
2841      if (!rpointee->isObjectType()) {
2842        // Handle the GNU void* extension.
2843        if (rpointee->isVoidType()) {
2844          if (!lpointee->isVoidType())
2845            Diag(Loc, diag::ext_gnu_void_ptr)
2846              << lex->getSourceRange() << rex->getSourceRange();
2847        } else if (rpointee->isFunctionType()) {
2848          if (getLangOptions().CPlusPlus) {
2849            Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2850              << rex->getType() << rex->getSourceRange();
2851            return QualType();
2852          }
2853
2854          // GNU extension: arithmetic on pointer to function
2855          if (!lpointee->isFunctionType())
2856            Diag(Loc, diag::ext_gnu_ptr_func_arith)
2857              << lex->getType() << lex->getSourceRange();
2858        } else {
2859          Diag(Loc, diag::err_typecheck_sub_ptr_object)
2860            << rex->getType() << rex->getSourceRange();
2861          return QualType();
2862        }
2863      }
2864
2865      // Pointee types must be compatible.
2866      if (!Context.typesAreCompatible(
2867              Context.getCanonicalType(lpointee).getUnqualifiedType(),
2868              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
2869        Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
2870          << lex->getType() << rex->getType()
2871          << lex->getSourceRange() << rex->getSourceRange();
2872        return QualType();
2873      }
2874
2875      return Context.getPointerDiffType();
2876    }
2877  }
2878
2879  return InvalidOperands(Loc, lex, rex);
2880}
2881
2882// C99 6.5.7
2883QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
2884                                  bool isCompAssign) {
2885  // C99 6.5.7p2: Each of the operands shall have integer type.
2886  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
2887    return InvalidOperands(Loc, lex, rex);
2888
2889  // Shifts don't perform usual arithmetic conversions, they just do integer
2890  // promotions on each operand. C99 6.5.7p3
2891  if (!isCompAssign)
2892    UsualUnaryConversions(lex);
2893  UsualUnaryConversions(rex);
2894
2895  // "The type of the result is that of the promoted left operand."
2896  return lex->getType();
2897}
2898
2899static bool areComparableObjCInterfaces(QualType LHS, QualType RHS,
2900                                        ASTContext& Context) {
2901  const ObjCInterfaceType* LHSIface = LHS->getAsObjCInterfaceType();
2902  const ObjCInterfaceType* RHSIface = RHS->getAsObjCInterfaceType();
2903  // ID acts sort of like void* for ObjC interfaces
2904  if (LHSIface && Context.isObjCIdType(RHS))
2905    return true;
2906  if (RHSIface && Context.isObjCIdType(LHS))
2907    return true;
2908  if (!LHSIface || !RHSIface)
2909    return false;
2910  return Context.canAssignObjCInterfaces(LHSIface, RHSIface) ||
2911         Context.canAssignObjCInterfaces(RHSIface, LHSIface);
2912}
2913
2914// C99 6.5.8
2915QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
2916                                    bool isRelational) {
2917  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2918    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
2919
2920  // C99 6.5.8p3 / C99 6.5.9p4
2921  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2922    UsualArithmeticConversions(lex, rex);
2923  else {
2924    UsualUnaryConversions(lex);
2925    UsualUnaryConversions(rex);
2926  }
2927  QualType lType = lex->getType();
2928  QualType rType = rex->getType();
2929
2930  // For non-floating point types, check for self-comparisons of the form
2931  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
2932  // often indicate logic errors in the program.
2933  if (!lType->isFloatingType()) {
2934    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
2935      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
2936        if (DRL->getDecl() == DRR->getDecl())
2937          Diag(Loc, diag::warn_selfcomparison);
2938  }
2939
2940  // The result of comparisons is 'bool' in C++, 'int' in C.
2941  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
2942
2943  if (isRelational) {
2944    if (lType->isRealType() && rType->isRealType())
2945      return ResultTy;
2946  } else {
2947    // Check for comparisons of floating point operands using != and ==.
2948    if (lType->isFloatingType()) {
2949      assert (rType->isFloatingType());
2950      CheckFloatComparison(Loc,lex,rex);
2951    }
2952
2953    if (lType->isArithmeticType() && rType->isArithmeticType())
2954      return ResultTy;
2955  }
2956
2957  bool LHSIsNull = lex->isNullPointerConstant(Context);
2958  bool RHSIsNull = rex->isNullPointerConstant(Context);
2959
2960  // All of the following pointer related warnings are GCC extensions, except
2961  // when handling null pointer constants. One day, we can consider making them
2962  // errors (when -pedantic-errors is enabled).
2963  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
2964    QualType LCanPointeeTy =
2965      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
2966    QualType RCanPointeeTy =
2967      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
2968
2969    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
2970        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
2971        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
2972                                    RCanPointeeTy.getUnqualifiedType()) &&
2973        !areComparableObjCInterfaces(LCanPointeeTy, RCanPointeeTy, Context)) {
2974      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
2975        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
2976    }
2977    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2978    return ResultTy;
2979  }
2980  // Handle block pointer types.
2981  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
2982    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
2983    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
2984
2985    if (!LHSIsNull && !RHSIsNull &&
2986        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
2987      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
2988        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
2989    }
2990    ImpCastExprToType(rex, lType); // promote the pointer to pointer
2991    return ResultTy;
2992  }
2993  // Allow block pointers to be compared with null pointer constants.
2994  if ((lType->isBlockPointerType() && rType->isPointerType()) ||
2995      (lType->isPointerType() && rType->isBlockPointerType())) {
2996    if (!LHSIsNull && !RHSIsNull) {
2997      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
2998        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
2999    }
3000    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3001    return ResultTy;
3002  }
3003
3004  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
3005    if (lType->isPointerType() || rType->isPointerType()) {
3006      const PointerType *LPT = lType->getAsPointerType();
3007      const PointerType *RPT = rType->getAsPointerType();
3008      bool LPtrToVoid = LPT ?
3009        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3010      bool RPtrToVoid = RPT ?
3011        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3012
3013      if (!LPtrToVoid && !RPtrToVoid &&
3014          !Context.typesAreCompatible(lType, rType)) {
3015        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
3016          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3017        ImpCastExprToType(rex, lType);
3018        return ResultTy;
3019      }
3020      ImpCastExprToType(rex, lType);
3021      return ResultTy;
3022    }
3023    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3024      ImpCastExprToType(rex, lType);
3025      return ResultTy;
3026    } else {
3027      if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
3028        Diag(Loc, diag::warn_incompatible_qualified_id_operands)
3029          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3030        ImpCastExprToType(rex, lType);
3031        return ResultTy;
3032      }
3033    }
3034  }
3035  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3036       rType->isIntegerType()) {
3037    if (!RHSIsNull)
3038      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3039        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3040    ImpCastExprToType(rex, lType); // promote the integer to pointer
3041    return ResultTy;
3042  }
3043  if (lType->isIntegerType() &&
3044      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
3045    if (!LHSIsNull)
3046      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3047        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3048    ImpCastExprToType(lex, rType); // promote the integer to pointer
3049    return ResultTy;
3050  }
3051  // Handle block pointers.
3052  if (lType->isBlockPointerType() && rType->isIntegerType()) {
3053    if (!RHSIsNull)
3054      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3055        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3056    ImpCastExprToType(rex, lType); // promote the integer to pointer
3057    return ResultTy;
3058  }
3059  if (lType->isIntegerType() && rType->isBlockPointerType()) {
3060    if (!LHSIsNull)
3061      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3062        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3063    ImpCastExprToType(lex, rType); // promote the integer to pointer
3064    return ResultTy;
3065  }
3066  return InvalidOperands(Loc, lex, rex);
3067}
3068
3069/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3070/// operates on extended vector types.  Instead of producing an IntTy result,
3071/// like a scalar comparison, a vector comparison produces a vector of integer
3072/// types.
3073QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
3074                                          SourceLocation Loc,
3075                                          bool isRelational) {
3076  // Check to make sure we're operating on vectors of the same type and width,
3077  // Allowing one side to be a scalar of element type.
3078  QualType vType = CheckVectorOperands(Loc, lex, rex);
3079  if (vType.isNull())
3080    return vType;
3081
3082  QualType lType = lex->getType();
3083  QualType rType = rex->getType();
3084
3085  // For non-floating point types, check for self-comparisons of the form
3086  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
3087  // often indicate logic errors in the program.
3088  if (!lType->isFloatingType()) {
3089    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3090      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3091        if (DRL->getDecl() == DRR->getDecl())
3092          Diag(Loc, diag::warn_selfcomparison);
3093  }
3094
3095  // Check for comparisons of floating point operands using != and ==.
3096  if (!isRelational && lType->isFloatingType()) {
3097    assert (rType->isFloatingType());
3098    CheckFloatComparison(Loc,lex,rex);
3099  }
3100
3101  // Return the type for the comparison, which is the same as vector type for
3102  // integer vectors, or an integer type of identical size and number of
3103  // elements for floating point vectors.
3104  if (lType->isIntegerType())
3105    return lType;
3106
3107  const VectorType *VTy = lType->getAsVectorType();
3108  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
3109  if (TypeSize == Context.getTypeSize(Context.IntTy))
3110    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
3111  else if (TypeSize == Context.getTypeSize(Context.LongTy))
3112    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3113
3114  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3115         "Unhandled vector element size in vector compare");
3116  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3117}
3118
3119inline QualType Sema::CheckBitwiseOperands(
3120  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3121{
3122  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3123    return CheckVectorOperands(Loc, lex, rex);
3124
3125  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3126
3127  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3128    return compType;
3129  return InvalidOperands(Loc, lex, rex);
3130}
3131
3132inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
3133  Expr *&lex, Expr *&rex, SourceLocation Loc)
3134{
3135  UsualUnaryConversions(lex);
3136  UsualUnaryConversions(rex);
3137
3138  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
3139    return Context.IntTy;
3140  return InvalidOperands(Loc, lex, rex);
3141}
3142
3143/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3144/// is a read-only property; return true if so. A readonly property expression
3145/// depends on various declarations and thus must be treated specially.
3146///
3147static bool IsReadonlyProperty(Expr *E, Sema &S)
3148{
3149  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3150    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3151    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3152      QualType BaseType = PropExpr->getBase()->getType();
3153      if (const PointerType *PTy = BaseType->getAsPointerType())
3154        if (const ObjCInterfaceType *IFTy =
3155            PTy->getPointeeType()->getAsObjCInterfaceType())
3156          if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3157            if (S.isPropertyReadonly(PDecl, IFace))
3158              return true;
3159    }
3160  }
3161  return false;
3162}
3163
3164/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
3165/// emit an error and return true.  If so, return false.
3166static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
3167  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3168  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3169    IsLV = Expr::MLV_ReadonlyProperty;
3170  if (IsLV == Expr::MLV_Valid)
3171    return false;
3172
3173  unsigned Diag = 0;
3174  bool NeedType = false;
3175  switch (IsLV) { // C99 6.5.16p2
3176  default: assert(0 && "Unknown result from isModifiableLvalue!");
3177  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
3178  case Expr::MLV_ArrayType:
3179    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3180    NeedType = true;
3181    break;
3182  case Expr::MLV_NotObjectType:
3183    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3184    NeedType = true;
3185    break;
3186  case Expr::MLV_LValueCast:
3187    Diag = diag::err_typecheck_lvalue_casts_not_supported;
3188    break;
3189  case Expr::MLV_InvalidExpression:
3190    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3191    break;
3192  case Expr::MLV_IncompleteType:
3193  case Expr::MLV_IncompleteVoidType:
3194    return S.DiagnoseIncompleteType(Loc, E->getType(),
3195                      diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3196                                    E->getSourceRange());
3197  case Expr::MLV_DuplicateVectorComponents:
3198    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3199    break;
3200  case Expr::MLV_NotBlockQualified:
3201    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3202    break;
3203  case Expr::MLV_ReadonlyProperty:
3204    Diag = diag::error_readonly_property_assignment;
3205    break;
3206  case Expr::MLV_NoSetterProperty:
3207    Diag = diag::error_nosetter_property_assignment;
3208    break;
3209  }
3210
3211  if (NeedType)
3212    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
3213  else
3214    S.Diag(Loc, Diag) << E->getSourceRange();
3215  return true;
3216}
3217
3218
3219
3220// C99 6.5.16.1
3221QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3222                                       SourceLocation Loc,
3223                                       QualType CompoundType) {
3224  // Verify that LHS is a modifiable lvalue, and emit error if not.
3225  if (CheckForModifiableLvalue(LHS, Loc, *this))
3226    return QualType();
3227
3228  QualType LHSType = LHS->getType();
3229  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
3230
3231  AssignConvertType ConvTy;
3232  if (CompoundType.isNull()) {
3233    // Simple assignment "x = y".
3234    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
3235    // Special case of NSObject attributes on c-style pointer types.
3236    if (ConvTy == IncompatiblePointer &&
3237        ((Context.isObjCNSObjectType(LHSType) &&
3238          Context.isObjCObjectPointerType(RHSType)) ||
3239         (Context.isObjCNSObjectType(RHSType) &&
3240          Context.isObjCObjectPointerType(LHSType))))
3241      ConvTy = Compatible;
3242
3243    // If the RHS is a unary plus or minus, check to see if they = and + are
3244    // right next to each other.  If so, the user may have typo'd "x =+ 4"
3245    // instead of "x += 4".
3246    Expr *RHSCheck = RHS;
3247    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3248      RHSCheck = ICE->getSubExpr();
3249    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3250      if ((UO->getOpcode() == UnaryOperator::Plus ||
3251           UO->getOpcode() == UnaryOperator::Minus) &&
3252          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
3253          // Only if the two operators are exactly adjacent.
3254          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
3255        Diag(Loc, diag::warn_not_compound_assign)
3256          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3257          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
3258    }
3259  } else {
3260    // Compound assignment "x += y"
3261    ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
3262  }
3263
3264  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3265                               RHS, "assigning"))
3266    return QualType();
3267
3268  // C99 6.5.16p3: The type of an assignment expression is the type of the
3269  // left operand unless the left operand has qualified type, in which case
3270  // it is the unqualified version of the type of the left operand.
3271  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3272  // is converted to the type of the assignment expression (above).
3273  // C++ 5.17p1: the type of the assignment expression is that of its left
3274  // oprdu.
3275  return LHSType.getUnqualifiedType();
3276}
3277
3278// C99 6.5.17
3279QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3280  // FIXME: what is required for LHS?
3281
3282  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
3283  DefaultFunctionArrayConversion(RHS);
3284  return RHS->getType();
3285}
3286
3287/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3288/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
3289QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3290                                              bool isInc) {
3291  QualType ResType = Op->getType();
3292  assert(!ResType.isNull() && "no type for increment/decrement expression");
3293
3294  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3295    // Decrement of bool is not allowed.
3296    if (!isInc) {
3297      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3298      return QualType();
3299    }
3300    // Increment of bool sets it to true, but is deprecated.
3301    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3302  } else if (ResType->isRealType()) {
3303    // OK!
3304  } else if (const PointerType *PT = ResType->getAsPointerType()) {
3305    // C99 6.5.2.4p2, 6.5.6p2
3306    if (PT->getPointeeType()->isObjectType()) {
3307      // Pointer to object is ok!
3308    } else if (PT->getPointeeType()->isVoidType()) {
3309      if (getLangOptions().CPlusPlus) {
3310        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3311          << Op->getSourceRange();
3312        return QualType();
3313      }
3314
3315      // Pointer to void is a GNU extension in C.
3316      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3317    } else if (PT->getPointeeType()->isFunctionType()) {
3318      if (getLangOptions().CPlusPlus) {
3319        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3320          << Op->getType() << Op->getSourceRange();
3321        return QualType();
3322      }
3323
3324      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
3325        << ResType << Op->getSourceRange();
3326      return QualType();
3327    } else {
3328      DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3329                             diag::err_typecheck_arithmetic_incomplete_type,
3330                             Op->getSourceRange(), SourceRange(),
3331                             ResType);
3332      return QualType();
3333    }
3334  } else if (ResType->isComplexType()) {
3335    // C99 does not support ++/-- on complex types, we allow as an extension.
3336    Diag(OpLoc, diag::ext_integer_increment_complex)
3337      << ResType << Op->getSourceRange();
3338  } else {
3339    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
3340      << ResType << Op->getSourceRange();
3341    return QualType();
3342  }
3343  // At this point, we know we have a real, complex or pointer type.
3344  // Now make sure the operand is a modifiable lvalue.
3345  if (CheckForModifiableLvalue(Op, OpLoc, *this))
3346    return QualType();
3347  return ResType;
3348}
3349
3350/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
3351/// This routine allows us to typecheck complex/recursive expressions
3352/// where the declaration is needed for type checking. We only need to
3353/// handle cases when the expression references a function designator
3354/// or is an lvalue. Here are some examples:
3355///  - &(x) => x
3356///  - &*****f => f for f a function designator.
3357///  - &s.xx => s
3358///  - &s.zz[1].yy -> s, if zz is an array
3359///  - *(x + 1) -> x, if x is an array
3360///  - &"123"[2] -> 0
3361///  - & __real__ x -> x
3362static NamedDecl *getPrimaryDecl(Expr *E) {
3363  switch (E->getStmtClass()) {
3364  case Stmt::DeclRefExprClass:
3365  case Stmt::QualifiedDeclRefExprClass:
3366    return cast<DeclRefExpr>(E)->getDecl();
3367  case Stmt::MemberExprClass:
3368    // Fields cannot be declared with a 'register' storage class.
3369    // &X->f is always ok, even if X is declared register.
3370    if (cast<MemberExpr>(E)->isArrow())
3371      return 0;
3372    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
3373  case Stmt::ArraySubscriptExprClass: {
3374    // &X[4] and &4[X] refers to X if X is not a pointer.
3375
3376    NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
3377    ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3378    if (!VD || VD->getType()->isPointerType())
3379      return 0;
3380    else
3381      return VD;
3382  }
3383  case Stmt::UnaryOperatorClass: {
3384    UnaryOperator *UO = cast<UnaryOperator>(E);
3385
3386    switch(UO->getOpcode()) {
3387    case UnaryOperator::Deref: {
3388      // *(X + 1) refers to X if X is not a pointer.
3389      if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3390        ValueDecl *VD = dyn_cast<ValueDecl>(D);
3391        if (!VD || VD->getType()->isPointerType())
3392          return 0;
3393        return VD;
3394      }
3395      return 0;
3396    }
3397    case UnaryOperator::Real:
3398    case UnaryOperator::Imag:
3399    case UnaryOperator::Extension:
3400      return getPrimaryDecl(UO->getSubExpr());
3401    default:
3402      return 0;
3403    }
3404  }
3405  case Stmt::BinaryOperatorClass: {
3406    BinaryOperator *BO = cast<BinaryOperator>(E);
3407
3408    // Handle cases involving pointer arithmetic. The result of an
3409    // Assign or AddAssign is not an lvalue so they can be ignored.
3410
3411    // (x + n) or (n + x) => x
3412    if (BO->getOpcode() == BinaryOperator::Add) {
3413      if (BO->getLHS()->getType()->isPointerType()) {
3414        return getPrimaryDecl(BO->getLHS());
3415      } else if (BO->getRHS()->getType()->isPointerType()) {
3416        return getPrimaryDecl(BO->getRHS());
3417      }
3418    }
3419
3420    return 0;
3421  }
3422  case Stmt::ParenExprClass:
3423    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
3424  case Stmt::ImplicitCastExprClass:
3425    // &X[4] when X is an array, has an implicit cast from array to pointer.
3426    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
3427  default:
3428    return 0;
3429  }
3430}
3431
3432/// CheckAddressOfOperand - The operand of & must be either a function
3433/// designator or an lvalue designating an object. If it is an lvalue, the
3434/// object cannot be declared with storage class register or be a bit field.
3435/// Note: The usual conversions are *not* applied to the operand of the &
3436/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
3437/// In C++, the operand might be an overloaded function name, in which case
3438/// we allow the '&' but retain the overloaded-function type.
3439QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
3440  if (op->isTypeDependent())
3441    return Context.DependentTy;
3442
3443  if (getLangOptions().C99) {
3444    // Implement C99-only parts of addressof rules.
3445    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3446      if (uOp->getOpcode() == UnaryOperator::Deref)
3447        // Per C99 6.5.3.2, the address of a deref always returns a valid result
3448        // (assuming the deref expression is valid).
3449        return uOp->getSubExpr()->getType();
3450    }
3451    // Technically, there should be a check for array subscript
3452    // expressions here, but the result of one is always an lvalue anyway.
3453  }
3454  NamedDecl *dcl = getPrimaryDecl(op);
3455  Expr::isLvalueResult lval = op->isLvalue(Context);
3456
3457  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
3458    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3459      // FIXME: emit more specific diag...
3460      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3461        << op->getSourceRange();
3462      return QualType();
3463    }
3464  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
3465    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3466      if (Field->isBitField()) {
3467        Diag(OpLoc, diag::err_typecheck_address_of)
3468          << "bit-field" << op->getSourceRange();
3469        return QualType();
3470      }
3471    }
3472  // Check for Apple extension for accessing vector components.
3473  } else if (isa<ArraySubscriptExpr>(op) &&
3474           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType()) {
3475    Diag(OpLoc, diag::err_typecheck_address_of)
3476      << "vector" << op->getSourceRange();
3477    return QualType();
3478  } else if (dcl) { // C99 6.5.3.2p1
3479    // We have an lvalue with a decl. Make sure the decl is not declared
3480    // with the register storage-class specifier.
3481    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3482      if (vd->getStorageClass() == VarDecl::Register) {
3483        Diag(OpLoc, diag::err_typecheck_address_of)
3484          << "register variable" << op->getSourceRange();
3485        return QualType();
3486      }
3487    } else if (isa<OverloadedFunctionDecl>(dcl)) {
3488      return Context.OverloadTy;
3489    } else if (isa<FieldDecl>(dcl)) {
3490      // Okay: we can take the address of a field.
3491      // Could be a pointer to member, though, if there is an explicit
3492      // scope qualifier for the class.
3493      if (isa<QualifiedDeclRefExpr>(op)) {
3494        DeclContext *Ctx = dcl->getDeclContext();
3495        if (Ctx && Ctx->isRecord())
3496          return Context.getMemberPointerType(op->getType(),
3497                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3498      }
3499    } else if (isa<FunctionDecl>(dcl)) {
3500      // Okay: we can take the address of a function.
3501    }
3502    else
3503      assert(0 && "Unknown/unexpected decl type");
3504  }
3505
3506  // If the operand has type "type", the result has type "pointer to type".
3507  return Context.getPointerType(op->getType());
3508}
3509
3510QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3511  UsualUnaryConversions(Op);
3512  QualType Ty = Op->getType();
3513
3514  // Note that per both C89 and C99, this is always legal, even if ptype is an
3515  // incomplete type or void.  It would be possible to warn about dereferencing
3516  // a void pointer, but it's completely well-defined, and such a warning is
3517  // unlikely to catch any mistakes.
3518  if (const PointerType *PT = Ty->getAsPointerType())
3519    return PT->getPointeeType();
3520
3521  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
3522    << Ty << Op->getSourceRange();
3523  return QualType();
3524}
3525
3526static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3527  tok::TokenKind Kind) {
3528  BinaryOperator::Opcode Opc;
3529  switch (Kind) {
3530  default: assert(0 && "Unknown binop!");
3531  case tok::star:                 Opc = BinaryOperator::Mul; break;
3532  case tok::slash:                Opc = BinaryOperator::Div; break;
3533  case tok::percent:              Opc = BinaryOperator::Rem; break;
3534  case tok::plus:                 Opc = BinaryOperator::Add; break;
3535  case tok::minus:                Opc = BinaryOperator::Sub; break;
3536  case tok::lessless:             Opc = BinaryOperator::Shl; break;
3537  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
3538  case tok::lessequal:            Opc = BinaryOperator::LE; break;
3539  case tok::less:                 Opc = BinaryOperator::LT; break;
3540  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
3541  case tok::greater:              Opc = BinaryOperator::GT; break;
3542  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
3543  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
3544  case tok::amp:                  Opc = BinaryOperator::And; break;
3545  case tok::caret:                Opc = BinaryOperator::Xor; break;
3546  case tok::pipe:                 Opc = BinaryOperator::Or; break;
3547  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
3548  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
3549  case tok::equal:                Opc = BinaryOperator::Assign; break;
3550  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
3551  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
3552  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
3553  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
3554  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
3555  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
3556  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
3557  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
3558  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
3559  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
3560  case tok::comma:                Opc = BinaryOperator::Comma; break;
3561  }
3562  return Opc;
3563}
3564
3565static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3566  tok::TokenKind Kind) {
3567  UnaryOperator::Opcode Opc;
3568  switch (Kind) {
3569  default: assert(0 && "Unknown unary op!");
3570  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
3571  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
3572  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
3573  case tok::star:         Opc = UnaryOperator::Deref; break;
3574  case tok::plus:         Opc = UnaryOperator::Plus; break;
3575  case tok::minus:        Opc = UnaryOperator::Minus; break;
3576  case tok::tilde:        Opc = UnaryOperator::Not; break;
3577  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
3578  case tok::kw___real:    Opc = UnaryOperator::Real; break;
3579  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
3580  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3581  }
3582  return Opc;
3583}
3584
3585/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3586/// operator @p Opc at location @c TokLoc. This routine only supports
3587/// built-in operations; ActOnBinOp handles overloaded operators.
3588Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3589                                                  unsigned Op,
3590                                                  Expr *lhs, Expr *rhs) {
3591  QualType ResultTy;  // Result type of the binary operator.
3592  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
3593  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3594
3595  switch (Opc) {
3596  default:
3597    assert(0 && "Unknown binary expr!");
3598  case BinaryOperator::Assign:
3599    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3600    break;
3601  case BinaryOperator::Mul:
3602  case BinaryOperator::Div:
3603    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3604    break;
3605  case BinaryOperator::Rem:
3606    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3607    break;
3608  case BinaryOperator::Add:
3609    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3610    break;
3611  case BinaryOperator::Sub:
3612    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3613    break;
3614  case BinaryOperator::Shl:
3615  case BinaryOperator::Shr:
3616    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3617    break;
3618  case BinaryOperator::LE:
3619  case BinaryOperator::LT:
3620  case BinaryOperator::GE:
3621  case BinaryOperator::GT:
3622    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3623    break;
3624  case BinaryOperator::EQ:
3625  case BinaryOperator::NE:
3626    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3627    break;
3628  case BinaryOperator::And:
3629  case BinaryOperator::Xor:
3630  case BinaryOperator::Or:
3631    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3632    break;
3633  case BinaryOperator::LAnd:
3634  case BinaryOperator::LOr:
3635    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3636    break;
3637  case BinaryOperator::MulAssign:
3638  case BinaryOperator::DivAssign:
3639    CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3640    if (!CompTy.isNull())
3641      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3642    break;
3643  case BinaryOperator::RemAssign:
3644    CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3645    if (!CompTy.isNull())
3646      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3647    break;
3648  case BinaryOperator::AddAssign:
3649    CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3650    if (!CompTy.isNull())
3651      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3652    break;
3653  case BinaryOperator::SubAssign:
3654    CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3655    if (!CompTy.isNull())
3656      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3657    break;
3658  case BinaryOperator::ShlAssign:
3659  case BinaryOperator::ShrAssign:
3660    CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3661    if (!CompTy.isNull())
3662      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3663    break;
3664  case BinaryOperator::AndAssign:
3665  case BinaryOperator::XorAssign:
3666  case BinaryOperator::OrAssign:
3667    CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3668    if (!CompTy.isNull())
3669      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3670    break;
3671  case BinaryOperator::Comma:
3672    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3673    break;
3674  }
3675  if (ResultTy.isNull())
3676    return ExprError();
3677  if (CompTy.isNull())
3678    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3679  else
3680    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
3681                                                  CompTy, OpLoc));
3682}
3683
3684// Binary Operators.  'Tok' is the token for the operator.
3685Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3686                                          tok::TokenKind Kind,
3687                                          ExprArg LHS, ExprArg RHS) {
3688  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3689  Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
3690
3691  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3692  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
3693
3694  // If either expression is type-dependent, just build the AST.
3695  // FIXME: We'll need to perform some caching of the result of name
3696  // lookup for operator+.
3697  if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3698    if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3699      return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
3700                                              Context.DependentTy,
3701                                              Context.DependentTy, TokLoc));
3702    else
3703      return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, Context.DependentTy,
3704                                                TokLoc));
3705  }
3706
3707  if (getLangOptions().CPlusPlus &&
3708      (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3709       rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
3710    // If this is one of the assignment operators, we only perform
3711    // overload resolution if the left-hand side is a class or
3712    // enumeration type (C++ [expr.ass]p3).
3713    if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3714        !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3715      return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3716    }
3717
3718    // Determine which overloaded operator we're dealing with.
3719    static const OverloadedOperatorKind OverOps[] = {
3720      OO_Star, OO_Slash, OO_Percent,
3721      OO_Plus, OO_Minus,
3722      OO_LessLess, OO_GreaterGreater,
3723      OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3724      OO_EqualEqual, OO_ExclaimEqual,
3725      OO_Amp,
3726      OO_Caret,
3727      OO_Pipe,
3728      OO_AmpAmp,
3729      OO_PipePipe,
3730      OO_Equal, OO_StarEqual,
3731      OO_SlashEqual, OO_PercentEqual,
3732      OO_PlusEqual, OO_MinusEqual,
3733      OO_LessLessEqual, OO_GreaterGreaterEqual,
3734      OO_AmpEqual, OO_CaretEqual,
3735      OO_PipeEqual,
3736      OO_Comma
3737    };
3738    OverloadedOperatorKind OverOp = OverOps[Opc];
3739
3740    // Add the appropriate overloaded operators (C++ [over.match.oper])
3741    // to the candidate set.
3742    OverloadCandidateSet CandidateSet;
3743    Expr *Args[2] = { lhs, rhs };
3744    if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3745      return ExprError();
3746
3747    // Perform overload resolution.
3748    OverloadCandidateSet::iterator Best;
3749    switch (BestViableFunction(CandidateSet, Best)) {
3750    case OR_Success: {
3751      // We found a built-in operator or an overloaded operator.
3752      FunctionDecl *FnDecl = Best->Function;
3753
3754      if (FnDecl) {
3755        // We matched an overloaded operator. Build a call to that
3756        // operator.
3757
3758        // Convert the arguments.
3759        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3760          if (PerformObjectArgumentInitialization(lhs, Method) ||
3761              PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3762                                        "passing"))
3763            return ExprError();
3764        } else {
3765          // Convert the arguments.
3766          if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3767                                        "passing") ||
3768              PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3769                                        "passing"))
3770            return ExprError();
3771        }
3772
3773        // Determine the result type
3774        QualType ResultTy
3775          = FnDecl->getType()->getAsFunctionType()->getResultType();
3776        ResultTy = ResultTy.getNonReferenceType();
3777
3778        // Build the actual expression node.
3779        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3780                                                 SourceLocation());
3781        UsualUnaryConversions(FnExpr);
3782
3783        return Owned(new (Context) CXXOperatorCallExpr(FnExpr, Args, 2,
3784                                                       ResultTy, TokLoc));
3785      } else {
3786        // We matched a built-in operator. Convert the arguments, then
3787        // break out so that we will build the appropriate built-in
3788        // operator node.
3789        if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
3790                                      Best->Conversions[0], "passing") ||
3791            PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
3792                                      Best->Conversions[1], "passing"))
3793          return ExprError();
3794
3795        break;
3796      }
3797    }
3798
3799    case OR_No_Viable_Function:
3800      // No viable function; fall through to handling this as a
3801      // built-in operator, which will produce an error message for us.
3802      break;
3803
3804    case OR_Ambiguous:
3805      Diag(TokLoc,  diag::err_ovl_ambiguous_oper)
3806          << BinaryOperator::getOpcodeStr(Opc)
3807          << lhs->getSourceRange() << rhs->getSourceRange();
3808      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3809      return ExprError();
3810    }
3811
3812    // Either we found no viable overloaded operator or we matched a
3813    // built-in operator. In either case, fall through to trying to
3814    // build a built-in operation.
3815  }
3816
3817  // Build a built-in binary operation.
3818  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3819}
3820
3821// Unary Operators.  'Tok' is the token for the operator.
3822Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
3823                                            tok::TokenKind Op, ExprArg input) {
3824  // FIXME: Input is modified later, but smart pointer not reassigned.
3825  Expr *Input = (Expr*)input.get();
3826  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
3827
3828  if (getLangOptions().CPlusPlus &&
3829      (Input->getType()->isRecordType()
3830       || Input->getType()->isEnumeralType())) {
3831    // Determine which overloaded operator we're dealing with.
3832    static const OverloadedOperatorKind OverOps[] = {
3833      OO_None, OO_None,
3834      OO_PlusPlus, OO_MinusMinus,
3835      OO_Amp, OO_Star,
3836      OO_Plus, OO_Minus,
3837      OO_Tilde, OO_Exclaim,
3838      OO_None, OO_None,
3839      OO_None,
3840      OO_None
3841    };
3842    OverloadedOperatorKind OverOp = OverOps[Opc];
3843
3844    // Add the appropriate overloaded operators (C++ [over.match.oper])
3845    // to the candidate set.
3846    OverloadCandidateSet CandidateSet;
3847    if (OverOp != OO_None &&
3848        AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
3849      return ExprError();
3850
3851    // Perform overload resolution.
3852    OverloadCandidateSet::iterator Best;
3853    switch (BestViableFunction(CandidateSet, Best)) {
3854    case OR_Success: {
3855      // We found a built-in operator or an overloaded operator.
3856      FunctionDecl *FnDecl = Best->Function;
3857
3858      if (FnDecl) {
3859        // We matched an overloaded operator. Build a call to that
3860        // operator.
3861
3862        // Convert the arguments.
3863        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3864          if (PerformObjectArgumentInitialization(Input, Method))
3865            return ExprError();
3866        } else {
3867          // Convert the arguments.
3868          if (PerformCopyInitialization(Input,
3869                                        FnDecl->getParamDecl(0)->getType(),
3870                                        "passing"))
3871            return ExprError();
3872        }
3873
3874        // Determine the result type
3875        QualType ResultTy
3876          = FnDecl->getType()->getAsFunctionType()->getResultType();
3877        ResultTy = ResultTy.getNonReferenceType();
3878
3879        // Build the actual expression node.
3880        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
3881                                                 SourceLocation());
3882        UsualUnaryConversions(FnExpr);
3883
3884        input.release();
3885        return Owned(new (Context) CXXOperatorCallExpr(FnExpr, &Input, 1,
3886                                                       ResultTy, OpLoc));
3887      } else {
3888        // We matched a built-in operator. Convert the arguments, then
3889        // break out so that we will build the appropriate built-in
3890        // operator node.
3891        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
3892                                      Best->Conversions[0], "passing"))
3893          return ExprError();
3894
3895        break;
3896      }
3897    }
3898
3899    case OR_No_Viable_Function:
3900      // No viable function; fall through to handling this as a
3901      // built-in operator, which will produce an error message for us.
3902      break;
3903
3904    case OR_Ambiguous:
3905      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
3906          << UnaryOperator::getOpcodeStr(Opc)
3907          << Input->getSourceRange();
3908      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
3909      return ExprError();
3910    }
3911
3912    // Either we found no viable overloaded operator or we matched a
3913    // built-in operator. In either case, fall through to trying to
3914    // build a built-in operation.
3915  }
3916
3917  QualType resultType;
3918  switch (Opc) {
3919  default:
3920    assert(0 && "Unimplemented unary expr!");
3921  case UnaryOperator::PreInc:
3922  case UnaryOperator::PreDec:
3923    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
3924                                                Opc == UnaryOperator::PreInc);
3925    break;
3926  case UnaryOperator::AddrOf:
3927    resultType = CheckAddressOfOperand(Input, OpLoc);
3928    break;
3929  case UnaryOperator::Deref:
3930    DefaultFunctionArrayConversion(Input);
3931    resultType = CheckIndirectionOperand(Input, OpLoc);
3932    break;
3933  case UnaryOperator::Plus:
3934  case UnaryOperator::Minus:
3935    UsualUnaryConversions(Input);
3936    resultType = Input->getType();
3937    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
3938      break;
3939    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
3940             resultType->isEnumeralType())
3941      break;
3942    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
3943             Opc == UnaryOperator::Plus &&
3944             resultType->isPointerType())
3945      break;
3946
3947    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3948      << resultType << Input->getSourceRange());
3949  case UnaryOperator::Not: // bitwise complement
3950    UsualUnaryConversions(Input);
3951    resultType = Input->getType();
3952    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
3953    if (resultType->isComplexType() || resultType->isComplexIntegerType())
3954      // C99 does not support '~' for complex conjugation.
3955      Diag(OpLoc, diag::ext_integer_complement_complex)
3956        << resultType << Input->getSourceRange();
3957    else if (!resultType->isIntegerType())
3958      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3959        << resultType << Input->getSourceRange());
3960    break;
3961  case UnaryOperator::LNot: // logical negation
3962    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
3963    DefaultFunctionArrayConversion(Input);
3964    resultType = Input->getType();
3965    if (!resultType->isScalarType()) // C99 6.5.3.3p1
3966      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
3967        << resultType << Input->getSourceRange());
3968    // LNot always has type int. C99 6.5.3.3p5.
3969    // In C++, it's bool. C++ 5.3.1p8
3970    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
3971    break;
3972  case UnaryOperator::Real:
3973  case UnaryOperator::Imag:
3974    resultType = CheckRealImagOperand(Input, OpLoc);
3975    break;
3976  case UnaryOperator::Extension:
3977    resultType = Input->getType();
3978    break;
3979  }
3980  if (resultType.isNull())
3981    return ExprError();
3982  input.release();
3983  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
3984}
3985
3986/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
3987Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
3988                                      SourceLocation LabLoc,
3989                                      IdentifierInfo *LabelII) {
3990  // Look up the record for this label identifier.
3991  LabelStmt *&LabelDecl = LabelMap[LabelII];
3992
3993  // If we haven't seen this label yet, create a forward reference. It
3994  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
3995  if (LabelDecl == 0)
3996    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
3997
3998  // Create the AST node.  The address of a label always has type 'void*'.
3999  return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4000                                     Context.getPointerType(Context.VoidTy));
4001}
4002
4003Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
4004                                     SourceLocation RPLoc) { // "({..})"
4005  Stmt *SubStmt = static_cast<Stmt*>(substmt);
4006  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4007  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4008
4009  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4010  if (isFileScope) {
4011    return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4012  }
4013
4014  // FIXME: there are a variety of strange constraints to enforce here, for
4015  // example, it is not possible to goto into a stmt expression apparently.
4016  // More semantic analysis is needed.
4017
4018  // FIXME: the last statement in the compount stmt has its value used.  We
4019  // should not warn about it being unused.
4020
4021  // If there are sub stmts in the compound stmt, take the type of the last one
4022  // as the type of the stmtexpr.
4023  QualType Ty = Context.VoidTy;
4024
4025  if (!Compound->body_empty()) {
4026    Stmt *LastStmt = Compound->body_back();
4027    // If LastStmt is a label, skip down through into the body.
4028    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4029      LastStmt = Label->getSubStmt();
4030
4031    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
4032      Ty = LastExpr->getType();
4033  }
4034
4035  return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
4036}
4037
4038Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4039                                            SourceLocation BuiltinLoc,
4040                                            SourceLocation TypeLoc,
4041                                            TypeTy *argty,
4042                                            OffsetOfComponent *CompPtr,
4043                                            unsigned NumComponents,
4044                                            SourceLocation RPLoc) {
4045  QualType ArgTy = QualType::getFromOpaquePtr(argty);
4046  assert(!ArgTy.isNull() && "Missing type argument!");
4047
4048  // We must have at least one component that refers to the type, and the first
4049  // one is known to be a field designator.  Verify that the ArgTy represents
4050  // a struct/union/class.
4051  if (!ArgTy->isRecordType())
4052    return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
4053
4054  // Otherwise, create a compound literal expression as the base, and
4055  // iteratively process the offsetof designators.
4056  InitListExpr *IList =
4057      new (Context) InitListExpr(SourceLocation(), 0, 0, SourceLocation());
4058  IList->setType(ArgTy);
4059  Expr *Res =
4060      new (Context) CompoundLiteralExpr(SourceLocation(), ArgTy, IList, false);
4061
4062  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4063  // GCC extension, diagnose them.
4064  if (NumComponents != 1)
4065    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4066      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
4067
4068  for (unsigned i = 0; i != NumComponents; ++i) {
4069    const OffsetOfComponent &OC = CompPtr[i];
4070    if (OC.isBrackets) {
4071      // Offset of an array sub-field.  TODO: Should we allow vector elements?
4072      const ArrayType *AT = Context.getAsArrayType(Res->getType());
4073      if (!AT) {
4074        delete Res;
4075        return Diag(OC.LocEnd, diag::err_offsetof_array_type) << Res->getType();
4076      }
4077
4078      // FIXME: C++: Verify that operator[] isn't overloaded.
4079
4080      // C99 6.5.2.1p1
4081      Expr *Idx = static_cast<Expr*>(OC.U.E);
4082      if (!Idx->getType()->isIntegerType())
4083        return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4084          << Idx->getSourceRange();
4085
4086      Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4087                                             OC.LocEnd);
4088      continue;
4089    }
4090
4091    const RecordType *RC = Res->getType()->getAsRecordType();
4092    if (!RC) {
4093      delete Res;
4094      return Diag(OC.LocEnd, diag::err_offsetof_record_type) << Res->getType();
4095    }
4096
4097    // Get the decl corresponding to this.
4098    RecordDecl *RD = RC->getDecl();
4099    FieldDecl *MemberDecl
4100      = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4101                                                        LookupMemberName)
4102                                      .getAsDecl());
4103    if (!MemberDecl)
4104      return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4105       << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
4106
4107    // FIXME: C++: Verify that MemberDecl isn't a static field.
4108    // FIXME: Verify that MemberDecl isn't a bitfield.
4109    // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4110    // matter here.
4111    Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4112                                   MemberDecl->getType().getNonReferenceType());
4113  }
4114
4115  return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4116                                     Context.getSizeType(), BuiltinLoc);
4117}
4118
4119
4120Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4121                                                TypeTy *arg1, TypeTy *arg2,
4122                                                SourceLocation RPLoc) {
4123  QualType argT1 = QualType::getFromOpaquePtr(arg1);
4124  QualType argT2 = QualType::getFromOpaquePtr(arg2);
4125
4126  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4127
4128  return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4129                                           argT2, RPLoc);
4130}
4131
4132Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
4133                                       ExprTy *expr1, ExprTy *expr2,
4134                                       SourceLocation RPLoc) {
4135  Expr *CondExpr = static_cast<Expr*>(cond);
4136  Expr *LHSExpr = static_cast<Expr*>(expr1);
4137  Expr *RHSExpr = static_cast<Expr*>(expr2);
4138
4139  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4140
4141  // The conditional expression is required to be a constant expression.
4142  llvm::APSInt condEval(32);
4143  SourceLocation ExpLoc;
4144  if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4145    return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4146      << CondExpr->getSourceRange();
4147
4148  // If the condition is > zero, then the AST type is the same as the LSHExpr.
4149  QualType resType = condEval.getZExtValue() ? LHSExpr->getType() :
4150                                               RHSExpr->getType();
4151  return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4152                                  resType, RPLoc);
4153}
4154
4155//===----------------------------------------------------------------------===//
4156// Clang Extensions.
4157//===----------------------------------------------------------------------===//
4158
4159/// ActOnBlockStart - This callback is invoked when a block literal is started.
4160void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
4161  // Analyze block parameters.
4162  BlockSemaInfo *BSI = new BlockSemaInfo();
4163
4164  // Add BSI to CurBlock.
4165  BSI->PrevBlockInfo = CurBlock;
4166  CurBlock = BSI;
4167
4168  BSI->ReturnType = 0;
4169  BSI->TheScope = BlockScope;
4170
4171  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
4172  PushDeclContext(BlockScope, BSI->TheDecl);
4173}
4174
4175void Sema::ActOnBlockArguments(Declarator &ParamInfo) {
4176  // Analyze arguments to block.
4177  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4178         "Not a function declarator!");
4179  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4180
4181  CurBlock->hasPrototype = FTI.hasPrototype;
4182  CurBlock->isVariadic = true;
4183
4184  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4185  // no arguments, not a function that takes a single void argument.
4186  if (FTI.hasPrototype &&
4187      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4188      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4189        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4190    // empty arg list, don't push any params.
4191    CurBlock->isVariadic = false;
4192  } else if (FTI.hasPrototype) {
4193    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
4194      CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4195    CurBlock->isVariadic = FTI.isVariadic;
4196  }
4197  CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4198
4199  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4200       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4201    // If this has an identifier, add it to the scope stack.
4202    if ((*AI)->getIdentifier())
4203      PushOnScopeChains(*AI, CurBlock->TheScope);
4204}
4205
4206/// ActOnBlockError - If there is an error parsing a block, this callback
4207/// is invoked to pop the information about the block from the action impl.
4208void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4209  // Ensure that CurBlock is deleted.
4210  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4211
4212  // Pop off CurBlock, handle nested blocks.
4213  CurBlock = CurBlock->PrevBlockInfo;
4214
4215  // FIXME: Delete the ParmVarDecl objects as well???
4216
4217}
4218
4219/// ActOnBlockStmtExpr - This is called when the body of a block statement
4220/// literal was successfully completed.  ^(int x){...}
4221Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4222                                          Scope *CurScope) {
4223  // Ensure that CurBlock is deleted.
4224  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4225  llvm::OwningPtr<CompoundStmt> Body(static_cast<CompoundStmt*>(body));
4226
4227  PopDeclContext();
4228
4229  // Pop off CurBlock, handle nested blocks.
4230  CurBlock = CurBlock->PrevBlockInfo;
4231
4232  QualType RetTy = Context.VoidTy;
4233  if (BSI->ReturnType)
4234    RetTy = QualType(BSI->ReturnType, 0);
4235
4236  llvm::SmallVector<QualType, 8> ArgTypes;
4237  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4238    ArgTypes.push_back(BSI->Params[i]->getType());
4239
4240  QualType BlockTy;
4241  if (!BSI->hasPrototype)
4242    BlockTy = Context.getFunctionTypeNoProto(RetTy);
4243  else
4244    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
4245                                      BSI->isVariadic, 0);
4246
4247  BlockTy = Context.getBlockPointerType(BlockTy);
4248
4249  BSI->TheDecl->setBody(Body.take());
4250  return new (Context) BlockExpr(BSI->TheDecl, BlockTy);
4251}
4252
4253/// ExprsMatchFnType - return true if the Exprs in array Args have
4254/// QualTypes that match the QualTypes of the arguments of the FnType.
4255/// The number of arguments has already been validated to match the number of
4256/// arguments in FnType.
4257static bool ExprsMatchFnType(Expr **Args, const FunctionTypeProto *FnType,
4258                             ASTContext &Context) {
4259  unsigned NumParams = FnType->getNumArgs();
4260  for (unsigned i = 0; i != NumParams; ++i) {
4261    QualType ExprTy = Context.getCanonicalType(Args[i]->getType());
4262    QualType ParmTy = Context.getCanonicalType(FnType->getArgType(i));
4263
4264    if (ExprTy.getUnqualifiedType() != ParmTy.getUnqualifiedType())
4265      return false;
4266  }
4267  return true;
4268}
4269
4270Sema::ExprResult Sema::ActOnOverloadExpr(ExprTy **args, unsigned NumArgs,
4271                                         SourceLocation *CommaLocs,
4272                                         SourceLocation BuiltinLoc,
4273                                         SourceLocation RParenLoc) {
4274  // __builtin_overload requires at least 2 arguments
4275  if (NumArgs < 2)
4276    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4277      << SourceRange(BuiltinLoc, RParenLoc);
4278
4279  // The first argument is required to be a constant expression.  It tells us
4280  // the number of arguments to pass to each of the functions to be overloaded.
4281  Expr **Args = reinterpret_cast<Expr**>(args);
4282  Expr *NParamsExpr = Args[0];
4283  llvm::APSInt constEval(32);
4284  SourceLocation ExpLoc;
4285  if (!NParamsExpr->isIntegerConstantExpr(constEval, Context, &ExpLoc))
4286    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4287      << NParamsExpr->getSourceRange();
4288
4289  // Verify that the number of parameters is > 0
4290  unsigned NumParams = constEval.getZExtValue();
4291  if (NumParams == 0)
4292    return Diag(ExpLoc, diag::err_overload_expr_requires_non_zero_constant)
4293      << NParamsExpr->getSourceRange();
4294  // Verify that we have at least 1 + NumParams arguments to the builtin.
4295  if ((NumParams + 1) > NumArgs)
4296    return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
4297      << SourceRange(BuiltinLoc, RParenLoc);
4298
4299  // Figure out the return type, by matching the args to one of the functions
4300  // listed after the parameters.
4301  OverloadExpr *OE = 0;
4302  for (unsigned i = NumParams + 1; i < NumArgs; ++i) {
4303    // UsualUnaryConversions will convert the function DeclRefExpr into a
4304    // pointer to function.
4305    Expr *Fn = UsualUnaryConversions(Args[i]);
4306    const FunctionTypeProto *FnType = 0;
4307    if (const PointerType *PT = Fn->getType()->getAsPointerType())
4308      FnType = PT->getPointeeType()->getAsFunctionTypeProto();
4309
4310    // The Expr type must be FunctionTypeProto, since FunctionTypeProto has no
4311    // parameters, and the number of parameters must match the value passed to
4312    // the builtin.
4313    if (!FnType || (FnType->getNumArgs() != NumParams))
4314      return Diag(Fn->getExprLoc(), diag::err_overload_incorrect_fntype)
4315        << Fn->getSourceRange();
4316
4317    // Scan the parameter list for the FunctionType, checking the QualType of
4318    // each parameter against the QualTypes of the arguments to the builtin.
4319    // If they match, return a new OverloadExpr.
4320    if (ExprsMatchFnType(Args+1, FnType, Context)) {
4321      if (OE)
4322        return Diag(Fn->getExprLoc(), diag::err_overload_multiple_match)
4323          << OE->getFn()->getSourceRange();
4324      // Remember our match, and continue processing the remaining arguments
4325      // to catch any errors.
4326      OE = new (Context) OverloadExpr(Args, NumArgs, i,
4327                            FnType->getResultType().getNonReferenceType(),
4328                            BuiltinLoc, RParenLoc);
4329    }
4330  }
4331  // Return the newly created OverloadExpr node, if we succeded in matching
4332  // exactly one of the candidate functions.
4333  if (OE)
4334    return OE;
4335
4336  // If we didn't find a matching function Expr in the __builtin_overload list
4337  // the return an error.
4338  std::string typeNames;
4339  for (unsigned i = 0; i != NumParams; ++i) {
4340    if (i != 0) typeNames += ", ";
4341    typeNames += Args[i+1]->getType().getAsString();
4342  }
4343
4344  return Diag(BuiltinLoc, diag::err_overload_no_match)
4345    << typeNames << SourceRange(BuiltinLoc, RParenLoc);
4346}
4347
4348Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4349                                  ExprTy *expr, TypeTy *type,
4350                                  SourceLocation RPLoc) {
4351  Expr *E = static_cast<Expr*>(expr);
4352  QualType T = QualType::getFromOpaquePtr(type);
4353
4354  InitBuiltinVaListType();
4355
4356  // Get the va_list type
4357  QualType VaListType = Context.getBuiltinVaListType();
4358  // Deal with implicit array decay; for example, on x86-64,
4359  // va_list is an array, but it's supposed to decay to
4360  // a pointer for va_arg.
4361  if (VaListType->isArrayType())
4362    VaListType = Context.getArrayDecayedType(VaListType);
4363  // Make sure the input expression also decays appropriately.
4364  UsualUnaryConversions(E);
4365
4366  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
4367    return Diag(E->getLocStart(),
4368                diag::err_first_argument_to_va_arg_not_of_type_va_list)
4369      << E->getType() << E->getSourceRange();
4370
4371  // FIXME: Warn if a non-POD type is passed in.
4372
4373  return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
4374}
4375
4376Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4377  // The type of __null will be int or long, depending on the size of
4378  // pointers on the target.
4379  QualType Ty;
4380  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4381    Ty = Context.IntTy;
4382  else
4383    Ty = Context.LongTy;
4384
4385  return new (Context) GNUNullExpr(Ty, TokenLoc);
4386}
4387
4388bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4389                                    SourceLocation Loc,
4390                                    QualType DstType, QualType SrcType,
4391                                    Expr *SrcExpr, const char *Flavor) {
4392  // Decode the result (notice that AST's are still created for extensions).
4393  bool isInvalid = false;
4394  unsigned DiagKind;
4395  switch (ConvTy) {
4396  default: assert(0 && "Unknown conversion type");
4397  case Compatible: return false;
4398  case PointerToInt:
4399    DiagKind = diag::ext_typecheck_convert_pointer_int;
4400    break;
4401  case IntToPointer:
4402    DiagKind = diag::ext_typecheck_convert_int_pointer;
4403    break;
4404  case IncompatiblePointer:
4405    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4406    break;
4407  case FunctionVoidPointer:
4408    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4409    break;
4410  case CompatiblePointerDiscardsQualifiers:
4411    // If the qualifiers lost were because we were applying the
4412    // (deprecated) C++ conversion from a string literal to a char*
4413    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
4414    // Ideally, this check would be performed in
4415    // CheckPointerTypesForAssignment. However, that would require a
4416    // bit of refactoring (so that the second argument is an
4417    // expression, rather than a type), which should be done as part
4418    // of a larger effort to fix CheckPointerTypesForAssignment for
4419    // C++ semantics.
4420    if (getLangOptions().CPlusPlus &&
4421        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4422      return false;
4423    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4424    break;
4425  case IntToBlockPointer:
4426    DiagKind = diag::err_int_to_block_pointer;
4427    break;
4428  case IncompatibleBlockPointer:
4429    DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
4430    break;
4431  case IncompatibleObjCQualifiedId:
4432    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4433    // it can give a more specific diagnostic.
4434    DiagKind = diag::warn_incompatible_qualified_id;
4435    break;
4436  case IncompatibleVectors:
4437    DiagKind = diag::warn_incompatible_vectors;
4438    break;
4439  case Incompatible:
4440    DiagKind = diag::err_typecheck_convert_incompatible;
4441    isInvalid = true;
4442    break;
4443  }
4444
4445  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4446    << SrcExpr->getSourceRange();
4447  return isInvalid;
4448}
4449
4450bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4451{
4452  Expr::EvalResult EvalResult;
4453
4454  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4455      EvalResult.HasSideEffects) {
4456    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4457
4458    if (EvalResult.Diag) {
4459      // We only show the note if it's not the usual "invalid subexpression"
4460      // or if it's actually in a subexpression.
4461      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4462          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4463        Diag(EvalResult.DiagLoc, EvalResult.Diag);
4464    }
4465
4466    return true;
4467  }
4468
4469  if (EvalResult.Diag) {
4470    Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4471      E->getSourceRange();
4472
4473    // Print the reason it's not a constant.
4474    if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4475      Diag(EvalResult.DiagLoc, EvalResult.Diag);
4476  }
4477
4478  if (Result)
4479    *Result = EvalResult.Val.getInt();
4480  return false;
4481}
4482