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