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