SemaExpr.cpp revision f96065763cd39674635dc75b2441e5391ded8f94
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
1669ObjCImplementationDecl *getCurImplementationDecl(DeclContext *DC) {
1670  while (DC && !isa<ObjCImplementationDecl>(DC))
1671    DC = DC->getParent();
1672  return dyn_cast_or_null<ObjCImplementationDecl>(DC);
1673}
1674
1675Action::OwningExprResult
1676Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
1677                               tok::TokenKind OpKind, SourceLocation MemberLoc,
1678                               IdentifierInfo &Member) {
1679  Expr *BaseExpr = static_cast<Expr *>(Base.release());
1680  assert(BaseExpr && "no record expression");
1681
1682  // Perform default conversions.
1683  DefaultFunctionArrayConversion(BaseExpr);
1684
1685  QualType BaseType = BaseExpr->getType();
1686  assert(!BaseType.isNull() && "no type for member expression");
1687
1688  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
1689  // must have pointer type, and the accessed type is the pointee.
1690  if (OpKind == tok::arrow) {
1691    if (const PointerType *PT = BaseType->getAsPointerType())
1692      BaseType = PT->getPointeeType();
1693    else if (getLangOptions().CPlusPlus && BaseType->isRecordType())
1694      return Owned(BuildOverloadedArrowExpr(S, BaseExpr, OpLoc,
1695                                            MemberLoc, Member));
1696    else
1697      return ExprError(Diag(MemberLoc,
1698                            diag::err_typecheck_member_reference_arrow)
1699        << BaseType << BaseExpr->getSourceRange());
1700  }
1701
1702  // Handle field access to simple records.  This also handles access to fields
1703  // of the ObjC 'id' struct.
1704  if (const RecordType *RTy = BaseType->getAsRecordType()) {
1705    RecordDecl *RDecl = RTy->getDecl();
1706    if (DiagnoseIncompleteType(OpLoc, BaseType,
1707                               diag::err_typecheck_incomplete_tag,
1708                               BaseExpr->getSourceRange()))
1709      return ExprError();
1710
1711    // The record definition is complete, now make sure the member is valid.
1712    // FIXME: Qualified name lookup for C++ is a bit more complicated
1713    // than this.
1714    LookupResult Result
1715      = LookupQualifiedName(RDecl, DeclarationName(&Member),
1716                            LookupMemberName, false);
1717
1718    NamedDecl *MemberDecl = 0;
1719    if (!Result)
1720      return ExprError(Diag(MemberLoc, diag::err_typecheck_no_member)
1721               << &Member << BaseExpr->getSourceRange());
1722    else if (Result.isAmbiguous()) {
1723      DiagnoseAmbiguousLookup(Result, DeclarationName(&Member),
1724                              MemberLoc, BaseExpr->getSourceRange());
1725      return ExprError();
1726    } else
1727      MemberDecl = Result;
1728
1729    // If the decl being referenced had an error, return an error for this
1730    // sub-expr without emitting another error, in order to avoid cascading
1731    // error cases.
1732    if (MemberDecl->isInvalidDecl())
1733      return ExprError();
1734
1735    // Check the use of this field
1736    if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1737      return ExprError();
1738
1739    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
1740      // We may have found a field within an anonymous union or struct
1741      // (C++ [class.union]).
1742      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1743        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
1744                                                        BaseExpr, OpLoc);
1745
1746      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1747      // FIXME: Handle address space modifiers
1748      QualType MemberType = FD->getType();
1749      if (const ReferenceType *Ref = MemberType->getAsReferenceType())
1750        MemberType = Ref->getPointeeType();
1751      else {
1752        unsigned combinedQualifiers =
1753          MemberType.getCVRQualifiers() | BaseType.getCVRQualifiers();
1754        if (FD->isMutable())
1755          combinedQualifiers &= ~QualType::Const;
1756        MemberType = MemberType.getQualifiedType(combinedQualifiers);
1757      }
1758
1759      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, FD,
1760                                            MemberLoc, MemberType));
1761    } else if (CXXClassVarDecl *Var = dyn_cast<CXXClassVarDecl>(MemberDecl))
1762      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1763                                  Var, MemberLoc,
1764                                  Var->getType().getNonReferenceType()));
1765    else if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl))
1766      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1767                                  MemberFn, MemberLoc, MemberFn->getType()));
1768    else if (OverloadedFunctionDecl *Ovl
1769             = dyn_cast<OverloadedFunctionDecl>(MemberDecl))
1770      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow, Ovl,
1771                                  MemberLoc, Context.OverloadTy));
1772    else if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl))
1773      return Owned(new (Context) MemberExpr(BaseExpr, OpKind == tok::arrow,
1774                                            Enum, MemberLoc, Enum->getType()));
1775    else if (isa<TypeDecl>(MemberDecl))
1776      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
1777        << DeclarationName(&Member) << int(OpKind == tok::arrow));
1778
1779    // We found a declaration kind that we didn't expect. This is a
1780    // generic error message that tells the user that she can't refer
1781    // to this member with '.' or '->'.
1782    return ExprError(Diag(MemberLoc,
1783                          diag::err_typecheck_member_reference_unknown)
1784      << DeclarationName(&Member) << int(OpKind == tok::arrow));
1785  }
1786
1787  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
1788  // (*Obj).ivar.
1789  if (const ObjCInterfaceType *IFTy = BaseType->getAsObjCInterfaceType()) {
1790    ObjCInterfaceDecl *ClassDeclared;
1791    if (ObjCIvarDecl *IV = IFTy->getDecl()->lookupInstanceVariable(&Member,
1792                                                             ClassDeclared)) {
1793      // If the decl being referenced had an error, return an error for this
1794      // sub-expr without emitting another error, in order to avoid cascading
1795      // error cases.
1796      if (IV->isInvalidDecl())
1797        return ExprError();
1798
1799      // Check whether we can reference this field.
1800      if (DiagnoseUseOfDecl(IV, MemberLoc))
1801        return ExprError();
1802      if (IV->getAccessControl() != ObjCIvarDecl::Public) {
1803        ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1804        if (ObjCMethodDecl *MD = getCurMethodDecl())
1805          ClassOfMethodDecl =  MD->getClassInterface();
1806        else if (FunctionDecl *FD = getCurFunctionDecl()) {
1807          // FIXME: This isn't working yet. Will discuss with Fariborz.
1808          // FIXME: Should be ObjCImplDecl, so categories can work.
1809          // Need to fiddle with castToDeclContext/castFromDeclContext.
1810          ObjCImplementationDecl *ImpDecl = getCurImplementationDecl(FD);
1811          if (ImpDecl)
1812            ClassOfMethodDecl = ImpDecl->getClassInterface();
1813        }
1814        if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1815          if (ClassDeclared != IFTy->getDecl() ||
1816              (ClassOfMethodDecl && (ClassOfMethodDecl != ClassDeclared)))
1817            Diag(MemberLoc, diag::error_private_ivar_access) << IV->getDeclName();
1818        }
1819        // @protected
1820        else if (!IFTy->getDecl()->isSuperClassOf(ClassOfMethodDecl))
1821          Diag(MemberLoc, diag::error_protected_ivar_access) << IV->getDeclName();
1822      }
1823
1824      ObjCIvarRefExpr *MRef= new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1825                                                 MemberLoc, BaseExpr,
1826                                                 OpKind == tok::arrow);
1827      Context.setFieldDecl(IFTy->getDecl(), IV, MRef);
1828      return Owned(MRef);
1829    }
1830    return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1831                       << IFTy->getDecl()->getDeclName() << &Member
1832                       << BaseExpr->getSourceRange());
1833  }
1834
1835  // Handle Objective-C property access, which is "Obj.property" where Obj is a
1836  // pointer to a (potentially qualified) interface type.
1837  const PointerType *PTy;
1838  const ObjCInterfaceType *IFTy;
1839  if (OpKind == tok::period && (PTy = BaseType->getAsPointerType()) &&
1840      (IFTy = PTy->getPointeeType()->getAsObjCInterfaceType())) {
1841    ObjCInterfaceDecl *IFace = IFTy->getDecl();
1842
1843    // Search for a declared property first.
1844    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(&Member)) {
1845      // Check whether we can reference this property.
1846      if (DiagnoseUseOfDecl(PD, MemberLoc))
1847        return ExprError();
1848
1849      return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1850                                                     MemberLoc, BaseExpr));
1851    }
1852
1853    // Check protocols on qualified interfaces.
1854    for (ObjCInterfaceType::qual_iterator I = IFTy->qual_begin(),
1855         E = IFTy->qual_end(); I != E; ++I)
1856      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1857        // Check whether we can reference this property.
1858        if (DiagnoseUseOfDecl(PD, MemberLoc))
1859          return ExprError();
1860
1861        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1862                                                       MemberLoc, BaseExpr));
1863      }
1864
1865    // If that failed, look for an "implicit" property by seeing if the nullary
1866    // selector is implemented.
1867
1868    // FIXME: The logic for looking up nullary and unary selectors should be
1869    // shared with the code in ActOnInstanceMessage.
1870
1871    Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1872    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
1873
1874    // If this reference is in an @implementation, check for 'private' methods.
1875    if (!Getter)
1876      if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1877        if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1878          if (ObjCImplementationDecl *ImpDecl =
1879              ObjCImplementations[ClassDecl->getIdentifier()])
1880            Getter = ImpDecl->getInstanceMethod(Sel);
1881
1882    // Look through local category implementations associated with the class.
1883    if (!Getter) {
1884      for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Getter; i++) {
1885        if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1886          Getter = ObjCCategoryImpls[i]->getInstanceMethod(Sel);
1887      }
1888    }
1889    if (Getter) {
1890      // Check if we can reference this property.
1891      if (DiagnoseUseOfDecl(Getter, MemberLoc))
1892        return ExprError();
1893
1894      // If we found a getter then this may be a valid dot-reference, we
1895      // will look for the matching setter, in case it is needed.
1896      IdentifierInfo *SetterName = constructSetterName(PP.getIdentifierTable(),
1897                                                       &Member);
1898      Selector SetterSel = PP.getSelectorTable().getUnarySelector(SetterName);
1899      ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
1900      if (!Setter) {
1901        // If this reference is in an @implementation, also check for 'private'
1902        // methods.
1903        if (ObjCMethodDecl *CurMeth = getCurMethodDecl())
1904          if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface())
1905            if (ObjCImplementationDecl *ImpDecl =
1906                  ObjCImplementations[ClassDecl->getIdentifier()])
1907              Setter = ImpDecl->getInstanceMethod(SetterSel);
1908      }
1909      // Look through local category implementations associated with the class.
1910      if (!Setter) {
1911        for (unsigned i = 0; i < ObjCCategoryImpls.size() && !Setter; i++) {
1912          if (ObjCCategoryImpls[i]->getClassInterface() == IFace)
1913            Setter = ObjCCategoryImpls[i]->getInstanceMethod(SetterSel);
1914        }
1915      }
1916
1917      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1918        return ExprError();
1919
1920      // FIXME: we must check that the setter has property type.
1921      return Owned(new (Context) ObjCKVCRefExpr(Getter, Getter->getResultType(),
1922                                      Setter, MemberLoc, BaseExpr));
1923    }
1924
1925    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1926      << &Member << BaseType);
1927  }
1928  // Handle properties on qualified "id" protocols.
1929  const ObjCQualifiedIdType *QIdTy;
1930  if (OpKind == tok::period && (QIdTy = BaseType->getAsObjCQualifiedIdType())) {
1931    // Check protocols on qualified interfaces.
1932    for (ObjCQualifiedIdType::qual_iterator I = QIdTy->qual_begin(),
1933         E = QIdTy->qual_end(); I != E; ++I) {
1934      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(&Member)) {
1935        // Check the use of this declaration
1936        if (DiagnoseUseOfDecl(PD, MemberLoc))
1937          return ExprError();
1938
1939        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
1940                                                       MemberLoc, BaseExpr));
1941      }
1942      // Also must look for a getter name which uses property syntax.
1943      Selector Sel = PP.getSelectorTable().getNullarySelector(&Member);
1944      if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1945        // Check the use of this method.
1946        if (DiagnoseUseOfDecl(OMD, MemberLoc))
1947          return ExprError();
1948
1949        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
1950                        OMD->getResultType(), OMD, OpLoc, MemberLoc, NULL, 0));
1951      }
1952    }
1953
1954    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1955                       << &Member << BaseType);
1956  }
1957  // Handle 'field access' to vectors, such as 'V.xx'.
1958  if (BaseType->isExtVectorType()) {
1959    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
1960    if (ret.isNull())
1961      return ExprError();
1962    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, Member,
1963                                                    MemberLoc));
1964  }
1965
1966  return ExprError(Diag(MemberLoc,
1967                        diag::err_typecheck_member_reference_struct_union)
1968                     << BaseType << BaseExpr->getSourceRange());
1969}
1970
1971/// ConvertArgumentsForCall - Converts the arguments specified in
1972/// Args/NumArgs to the parameter types of the function FDecl with
1973/// function prototype Proto. Call is the call expression itself, and
1974/// Fn is the function expression. For a C++ member function, this
1975/// routine does not attempt to convert the object argument. Returns
1976/// true if the call is ill-formed.
1977bool
1978Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
1979                              FunctionDecl *FDecl,
1980                              const FunctionProtoType *Proto,
1981                              Expr **Args, unsigned NumArgs,
1982                              SourceLocation RParenLoc) {
1983  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
1984  // assignment, to the types of the corresponding parameter, ...
1985  unsigned NumArgsInProto = Proto->getNumArgs();
1986  unsigned NumArgsToCheck = NumArgs;
1987  bool Invalid = false;
1988
1989  // If too few arguments are available (and we don't have default
1990  // arguments for the remaining parameters), don't make the call.
1991  if (NumArgs < NumArgsInProto) {
1992    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
1993      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
1994        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
1995    // Use default arguments for missing arguments
1996    NumArgsToCheck = NumArgsInProto;
1997    Call->setNumArgs(Context, NumArgsInProto);
1998  }
1999
2000  // If too many are passed and not variadic, error on the extras and drop
2001  // them.
2002  if (NumArgs > NumArgsInProto) {
2003    if (!Proto->isVariadic()) {
2004      Diag(Args[NumArgsInProto]->getLocStart(),
2005           diag::err_typecheck_call_too_many_args)
2006        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2007        << SourceRange(Args[NumArgsInProto]->getLocStart(),
2008                       Args[NumArgs-1]->getLocEnd());
2009      // This deletes the extra arguments.
2010      Call->setNumArgs(Context, NumArgsInProto);
2011      Invalid = true;
2012    }
2013    NumArgsToCheck = NumArgsInProto;
2014  }
2015
2016  // Continue to check argument types (even if we have too few/many args).
2017  for (unsigned i = 0; i != NumArgsToCheck; i++) {
2018    QualType ProtoArgType = Proto->getArgType(i);
2019
2020    Expr *Arg;
2021    if (i < NumArgs) {
2022      Arg = Args[i];
2023
2024      // Pass the argument.
2025      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2026        return true;
2027    } else
2028      // We already type-checked the argument, so we know it works.
2029      Arg = new (Context) CXXDefaultArgExpr(FDecl->getParamDecl(i));
2030    QualType ArgType = Arg->getType();
2031
2032    Call->setArg(i, Arg);
2033  }
2034
2035  // If this is a variadic call, handle args passed through "...".
2036  if (Proto->isVariadic()) {
2037    VariadicCallType CallType = VariadicFunction;
2038    if (Fn->getType()->isBlockPointerType())
2039      CallType = VariadicBlock; // Block
2040    else if (isa<MemberExpr>(Fn))
2041      CallType = VariadicMethod;
2042
2043    // Promote the arguments (C99 6.5.2.2p7).
2044    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2045      Expr *Arg = Args[i];
2046      DefaultVariadicArgumentPromotion(Arg, CallType);
2047      Call->setArg(i, Arg);
2048    }
2049  }
2050
2051  return Invalid;
2052}
2053
2054/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2055/// This provides the location of the left/right parens and a list of comma
2056/// locations.
2057Action::OwningExprResult
2058Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2059                    MultiExprArg args,
2060                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2061  unsigned NumArgs = args.size();
2062  Expr *Fn = static_cast<Expr *>(fn.release());
2063  Expr **Args = reinterpret_cast<Expr**>(args.release());
2064  assert(Fn && "no function call expression");
2065  FunctionDecl *FDecl = NULL;
2066  DeclarationName UnqualifiedName;
2067
2068  if (getLangOptions().CPlusPlus) {
2069    // Determine whether this is a dependent call inside a C++ template,
2070    // in which case we won't do any semantic analysis now.
2071    // FIXME: Will need to cache the results of name lookup (including ADL) in Fn.
2072    bool Dependent = false;
2073    if (Fn->isTypeDependent())
2074      Dependent = true;
2075    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2076      Dependent = true;
2077
2078    if (Dependent)
2079      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2080                                          Context.DependentTy, RParenLoc));
2081
2082    // Determine whether this is a call to an object (C++ [over.call.object]).
2083    if (Fn->getType()->isRecordType())
2084      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2085                                                CommaLocs, RParenLoc));
2086
2087    // Determine whether this is a call to a member function.
2088    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens()))
2089      if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
2090          isa<CXXMethodDecl>(MemExpr->getMemberDecl()))
2091        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2092                                               CommaLocs, RParenLoc));
2093  }
2094
2095  // If we're directly calling a function, get the appropriate declaration.
2096  DeclRefExpr *DRExpr = NULL;
2097  Expr *FnExpr = Fn;
2098  bool ADL = true;
2099  while (true) {
2100    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2101      FnExpr = IcExpr->getSubExpr();
2102    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2103      // Parentheses around a function disable ADL
2104      // (C++0x [basic.lookup.argdep]p1).
2105      ADL = false;
2106      FnExpr = PExpr->getSubExpr();
2107    } else if (isa<UnaryOperator>(FnExpr) &&
2108               cast<UnaryOperator>(FnExpr)->getOpcode()
2109                 == UnaryOperator::AddrOf) {
2110      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2111    } else if ((DRExpr = dyn_cast<DeclRefExpr>(FnExpr))) {
2112      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2113      ADL &= !isa<QualifiedDeclRefExpr>(DRExpr);
2114      break;
2115    } else if (UnresolvedFunctionNameExpr *DepName
2116                 = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2117      UnqualifiedName = DepName->getName();
2118      break;
2119    } else {
2120      // Any kind of name that does not refer to a declaration (or
2121      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2122      ADL = false;
2123      break;
2124    }
2125  }
2126
2127  OverloadedFunctionDecl *Ovl = 0;
2128  if (DRExpr) {
2129    FDecl = dyn_cast<FunctionDecl>(DRExpr->getDecl());
2130    Ovl = dyn_cast<OverloadedFunctionDecl>(DRExpr->getDecl());
2131  }
2132
2133  if (Ovl || (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2134    // We don't perform ADL for implicit declarations of builtins.
2135    if (FDecl && FDecl->getBuiltinID(Context) && FDecl->isImplicit())
2136      ADL = false;
2137
2138    // We don't perform ADL in C.
2139    if (!getLangOptions().CPlusPlus)
2140      ADL = false;
2141
2142    if (Ovl || ADL) {
2143      FDecl = ResolveOverloadedCallFn(Fn, DRExpr? DRExpr->getDecl() : 0,
2144                                      UnqualifiedName, LParenLoc, Args,
2145                                      NumArgs, CommaLocs, RParenLoc, ADL);
2146      if (!FDecl)
2147        return ExprError();
2148
2149      // Update Fn to refer to the actual function selected.
2150      Expr *NewFn = 0;
2151      if (QualifiedDeclRefExpr *QDRExpr
2152            = dyn_cast_or_null<QualifiedDeclRefExpr>(DRExpr))
2153        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2154                                                   QDRExpr->getLocation(),
2155                                                   false, false,
2156                                          QDRExpr->getSourceRange().getBegin());
2157      else
2158        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2159                                          Fn->getSourceRange().getBegin());
2160      Fn->Destroy(Context);
2161      Fn = NewFn;
2162    }
2163  }
2164
2165  // Promote the function operand.
2166  UsualUnaryConversions(Fn);
2167
2168  // Make the call expr early, before semantic checks.  This guarantees cleanup
2169  // of arguments and function on error.
2170  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
2171                                                               Args, NumArgs,
2172                                                               Context.BoolTy,
2173                                                               RParenLoc));
2174
2175  const FunctionType *FuncT;
2176  if (!Fn->getType()->isBlockPointerType()) {
2177    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
2178    // have type pointer to function".
2179    const PointerType *PT = Fn->getType()->getAsPointerType();
2180    if (PT == 0)
2181      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2182        << Fn->getType() << Fn->getSourceRange());
2183    FuncT = PT->getPointeeType()->getAsFunctionType();
2184  } else { // This is a block call.
2185    FuncT = Fn->getType()->getAsBlockPointerType()->getPointeeType()->
2186                getAsFunctionType();
2187  }
2188  if (FuncT == 0)
2189    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
2190      << Fn->getType() << Fn->getSourceRange());
2191
2192  // We know the result type of the call, set it.
2193  TheCall->setType(FuncT->getResultType().getNonReferenceType());
2194
2195  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
2196    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
2197                                RParenLoc))
2198      return ExprError();
2199  } else {
2200    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
2201
2202    // Promote the arguments (C99 6.5.2.2p6).
2203    for (unsigned i = 0; i != NumArgs; i++) {
2204      Expr *Arg = Args[i];
2205      DefaultArgumentPromotion(Arg);
2206      TheCall->setArg(i, Arg);
2207    }
2208  }
2209
2210  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
2211    if (!Method->isStatic())
2212      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
2213        << Fn->getSourceRange());
2214
2215  // Do special checking on direct calls to functions.
2216  if (FDecl)
2217    return CheckFunctionCall(FDecl, TheCall.take());
2218
2219  return Owned(TheCall.take());
2220}
2221
2222Action::OwningExprResult
2223Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
2224                           SourceLocation RParenLoc, ExprArg InitExpr) {
2225  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
2226  QualType literalType = QualType::getFromOpaquePtr(Ty);
2227  // FIXME: put back this assert when initializers are worked out.
2228  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
2229  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
2230
2231  if (literalType->isArrayType()) {
2232    if (literalType->isVariableArrayType())
2233      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
2234        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
2235  } else if (DiagnoseIncompleteType(LParenLoc, literalType,
2236                                    diag::err_typecheck_decl_incomplete_type,
2237                SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd())))
2238    return ExprError();
2239
2240  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
2241                            DeclarationName(), /*FIXME:DirectInit=*/false))
2242    return ExprError();
2243
2244  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
2245  if (isFileScope) { // 6.5.2.5p3
2246    if (CheckForConstantInitializer(literalExpr, literalType))
2247      return ExprError();
2248  }
2249  InitExpr.release();
2250  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
2251                                                 literalExpr, isFileScope));
2252}
2253
2254Action::OwningExprResult
2255Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
2256                    InitListDesignations &Designators,
2257                    SourceLocation RBraceLoc) {
2258  unsigned NumInit = initlist.size();
2259  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
2260
2261  // Semantic analysis for initializers is done by ActOnDeclarator() and
2262  // CheckInitializer() - it requires knowledge of the object being intialized.
2263
2264  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
2265                                               RBraceLoc);
2266  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
2267  return Owned(E);
2268}
2269
2270/// CheckCastTypes - Check type constraints for casting between types.
2271bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr) {
2272  UsualUnaryConversions(castExpr);
2273
2274  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2275  // type needs to be scalar.
2276  if (castType->isVoidType()) {
2277    // Cast to void allows any expr type.
2278  } else if (castType->isDependentType() || castExpr->isTypeDependent()) {
2279    // We can't check any more until template instantiation time.
2280  } else if (!castType->isScalarType() && !castType->isVectorType()) {
2281    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
2282        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
2283        (castType->isStructureType() || castType->isUnionType())) {
2284      // GCC struct/union extension: allow cast to self.
2285      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
2286        << castType << castExpr->getSourceRange();
2287    } else if (castType->isUnionType()) {
2288      // GCC cast to union extension
2289      RecordDecl *RD = castType->getAsRecordType()->getDecl();
2290      RecordDecl::field_iterator Field, FieldEnd;
2291      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2292           Field != FieldEnd; ++Field) {
2293        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
2294            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
2295          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
2296            << castExpr->getSourceRange();
2297          break;
2298        }
2299      }
2300      if (Field == FieldEnd)
2301        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2302          << castExpr->getType() << castExpr->getSourceRange();
2303    } else {
2304      // Reject any other conversions to non-scalar types.
2305      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
2306        << castType << castExpr->getSourceRange();
2307    }
2308  } else if (!castExpr->getType()->isScalarType() &&
2309             !castExpr->getType()->isVectorType()) {
2310    return Diag(castExpr->getLocStart(),
2311                diag::err_typecheck_expect_scalar_operand)
2312      << castExpr->getType() << castExpr->getSourceRange();
2313  } else if (castExpr->getType()->isVectorType()) {
2314    if (CheckVectorCast(TyR, castExpr->getType(), castType))
2315      return true;
2316  } else if (castType->isVectorType()) {
2317    if (CheckVectorCast(TyR, castType, castExpr->getType()))
2318      return true;
2319  } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
2320    return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast);
2321  }
2322  return false;
2323}
2324
2325bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
2326  assert(VectorTy->isVectorType() && "Not a vector type!");
2327
2328  if (Ty->isVectorType() || Ty->isIntegerType()) {
2329    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
2330      return Diag(R.getBegin(),
2331                  Ty->isVectorType() ?
2332                  diag::err_invalid_conversion_between_vectors :
2333                  diag::err_invalid_conversion_between_vector_and_integer)
2334        << VectorTy << Ty << R;
2335  } else
2336    return Diag(R.getBegin(),
2337                diag::err_invalid_conversion_between_vector_and_scalar)
2338      << VectorTy << Ty << R;
2339
2340  return false;
2341}
2342
2343Action::OwningExprResult
2344Sema::ActOnCastExpr(SourceLocation LParenLoc, TypeTy *Ty,
2345                    SourceLocation RParenLoc, ExprArg Op) {
2346  assert((Ty != 0) && (Op.get() != 0) &&
2347         "ActOnCastExpr(): missing type or expr");
2348
2349  Expr *castExpr = static_cast<Expr*>(Op.release());
2350  QualType castType = QualType::getFromOpaquePtr(Ty);
2351
2352  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr))
2353    return ExprError();
2354  return Owned(new (Context) CStyleCastExpr(castType, castExpr, castType,
2355                                            LParenLoc, RParenLoc));
2356}
2357
2358/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
2359/// In that case, lhs = cond.
2360/// C99 6.5.15
2361QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
2362                                        SourceLocation QuestionLoc) {
2363  UsualUnaryConversions(Cond);
2364  UsualUnaryConversions(LHS);
2365  UsualUnaryConversions(RHS);
2366  QualType CondTy = Cond->getType();
2367  QualType LHSTy = LHS->getType();
2368  QualType RHSTy = RHS->getType();
2369
2370  // first, check the condition.
2371  if (!Cond->isTypeDependent()) {
2372    if (!CondTy->isScalarType()) { // C99 6.5.15p2
2373      Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
2374        << CondTy;
2375      return QualType();
2376    }
2377  }
2378
2379  // Now check the two expressions.
2380  if ((LHS && LHS->isTypeDependent()) || (RHS && RHS->isTypeDependent()))
2381    return Context.DependentTy;
2382
2383  // If both operands have arithmetic type, do the usual arithmetic conversions
2384  // to find a common type: C99 6.5.15p3,5.
2385  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
2386    UsualArithmeticConversions(LHS, RHS);
2387    return LHS->getType();
2388  }
2389
2390  // If both operands are the same structure or union type, the result is that
2391  // type.
2392  if (const RecordType *LHSRT = LHSTy->getAsRecordType()) {    // C99 6.5.15p3
2393    if (const RecordType *RHSRT = RHSTy->getAsRecordType())
2394      if (LHSRT->getDecl() == RHSRT->getDecl())
2395        // "If both the operands have structure or union type, the result has
2396        // that type."  This implies that CV qualifiers are dropped.
2397        return LHSTy.getUnqualifiedType();
2398  }
2399
2400  // C99 6.5.15p5: "If both operands have void type, the result has void type."
2401  // The following || allows only one side to be void (a GCC-ism).
2402  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
2403    if (!LHSTy->isVoidType())
2404      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2405        << RHS->getSourceRange();
2406    if (!RHSTy->isVoidType())
2407      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
2408        << LHS->getSourceRange();
2409    ImpCastExprToType(LHS, Context.VoidTy);
2410    ImpCastExprToType(RHS, Context.VoidTy);
2411    return Context.VoidTy;
2412  }
2413  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
2414  // the type of the other operand."
2415  if ((LHSTy->isPointerType() || LHSTy->isBlockPointerType() ||
2416       Context.isObjCObjectPointerType(LHSTy)) &&
2417      RHS->isNullPointerConstant(Context)) {
2418    ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
2419    return LHSTy;
2420  }
2421  if ((RHSTy->isPointerType() || RHSTy->isBlockPointerType() ||
2422       Context.isObjCObjectPointerType(RHSTy)) &&
2423      LHS->isNullPointerConstant(Context)) {
2424    ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
2425    return RHSTy;
2426  }
2427
2428  // Handle the case where both operands are pointers before we handle null
2429  // pointer constants in case both operands are null pointer constants.
2430  if (const PointerType *LHSPT = LHSTy->getAsPointerType()) { // C99 6.5.15p3,6
2431    if (const PointerType *RHSPT = RHSTy->getAsPointerType()) {
2432      // get the "pointed to" types
2433      QualType lhptee = LHSPT->getPointeeType();
2434      QualType rhptee = RHSPT->getPointeeType();
2435
2436      // ignore qualifiers on void (C99 6.5.15p3, clause 6)
2437      if (lhptee->isVoidType() &&
2438          rhptee->isIncompleteOrObjectType()) {
2439        // Figure out necessary qualifiers (C99 6.5.15p6)
2440        QualType destPointee=lhptee.getQualifiedType(rhptee.getCVRQualifiers());
2441        QualType destType = Context.getPointerType(destPointee);
2442        ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2443        ImpCastExprToType(RHS, destType); // promote to void*
2444        return destType;
2445      }
2446      if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
2447        QualType destPointee=rhptee.getQualifiedType(lhptee.getCVRQualifiers());
2448        QualType destType = Context.getPointerType(destPointee);
2449        ImpCastExprToType(LHS, destType); // add qualifiers if necessary
2450        ImpCastExprToType(RHS, destType); // promote to void*
2451        return destType;
2452      }
2453
2454      if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
2455        // Two identical pointer types are always compatible.
2456        return LHSTy;
2457      }
2458
2459      QualType compositeType = LHSTy;
2460
2461      // If either type is an Objective-C object type then check
2462      // compatibility according to Objective-C.
2463      if (Context.isObjCObjectPointerType(LHSTy) ||
2464          Context.isObjCObjectPointerType(RHSTy)) {
2465        // If both operands are interfaces and either operand can be
2466        // assigned to the other, use that type as the composite
2467        // type. This allows
2468        //   xxx ? (A*) a : (B*) b
2469        // where B is a subclass of A.
2470        //
2471        // Additionally, as for assignment, if either type is 'id'
2472        // allow silent coercion. Finally, if the types are
2473        // incompatible then make sure to use 'id' as the composite
2474        // type so the result is acceptable for sending messages to.
2475
2476        // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
2477        // It could return the composite type.
2478        const ObjCInterfaceType* LHSIface = lhptee->getAsObjCInterfaceType();
2479        const ObjCInterfaceType* RHSIface = rhptee->getAsObjCInterfaceType();
2480        if (LHSIface && RHSIface &&
2481            Context.canAssignObjCInterfaces(LHSIface, RHSIface)) {
2482          compositeType = LHSTy;
2483        } else if (LHSIface && RHSIface &&
2484                   Context.canAssignObjCInterfaces(RHSIface, LHSIface)) {
2485          compositeType = RHSTy;
2486        } else if (Context.isObjCIdStructType(lhptee) ||
2487                   Context.isObjCIdStructType(rhptee)) {
2488          compositeType = Context.getObjCIdType();
2489        } else {
2490          Diag(QuestionLoc, diag::ext_typecheck_comparison_of_distinct_pointers)
2491               << LHSTy << RHSTy
2492               << LHS->getSourceRange() << RHS->getSourceRange();
2493          QualType incompatTy = Context.getObjCIdType();
2494          ImpCastExprToType(LHS, incompatTy);
2495          ImpCastExprToType(RHS, incompatTy);
2496          return incompatTy;
2497        }
2498      } else if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2499                                             rhptee.getUnqualifiedType())) {
2500        Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
2501          << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2502        // In this situation, we assume void* type. No especially good
2503        // reason, but this is what gcc does, and we do have to pick
2504        // to get a consistent AST.
2505        QualType incompatTy = Context.getPointerType(Context.VoidTy);
2506        ImpCastExprToType(LHS, incompatTy);
2507        ImpCastExprToType(RHS, incompatTy);
2508        return incompatTy;
2509      }
2510      // The pointer types are compatible.
2511      // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
2512      // differently qualified versions of compatible types, the result type is
2513      // a pointer to an appropriately qualified version of the *composite*
2514      // type.
2515      // FIXME: Need to calculate the composite type.
2516      // FIXME: Need to add qualifiers
2517      ImpCastExprToType(LHS, compositeType);
2518      ImpCastExprToType(RHS, compositeType);
2519      return compositeType;
2520    }
2521  }
2522
2523  // Selection between block pointer types is ok as long as they are the same.
2524  if (LHSTy->isBlockPointerType() && RHSTy->isBlockPointerType() &&
2525      Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy))
2526    return LHSTy;
2527
2528  // Need to handle "id<xx>" explicitly. Unlike "id", whose canonical type
2529  // evaluates to "struct objc_object *" (and is handled above when comparing
2530  // id with statically typed objects).
2531  if (LHSTy->isObjCQualifiedIdType() || RHSTy->isObjCQualifiedIdType()) {
2532    // GCC allows qualified id and any Objective-C type to devolve to
2533    // id. Currently localizing to here until clear this should be
2534    // part of ObjCQualifiedIdTypesAreCompatible.
2535    if (ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true) ||
2536        (LHSTy->isObjCQualifiedIdType() &&
2537         Context.isObjCObjectPointerType(RHSTy)) ||
2538        (RHSTy->isObjCQualifiedIdType() &&
2539         Context.isObjCObjectPointerType(LHSTy))) {
2540      // FIXME: This is not the correct composite type. This only
2541      // happens to work because id can more or less be used anywhere,
2542      // however this may change the type of method sends.
2543      // FIXME: gcc adds some type-checking of the arguments and emits
2544      // (confusing) incompatible comparison warnings in some
2545      // cases. Investigate.
2546      QualType compositeType = Context.getObjCIdType();
2547      ImpCastExprToType(LHS, compositeType);
2548      ImpCastExprToType(RHS, compositeType);
2549      return compositeType;
2550    }
2551  }
2552
2553  // Otherwise, the operands are not compatible.
2554  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
2555    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
2556  return QualType();
2557}
2558
2559/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
2560/// in the case of a the GNU conditional expr extension.
2561Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
2562                                                  SourceLocation ColonLoc,
2563                                                  ExprArg Cond, ExprArg LHS,
2564                                                  ExprArg RHS) {
2565  Expr *CondExpr = (Expr *) Cond.get();
2566  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
2567
2568  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
2569  // was the condition.
2570  bool isLHSNull = LHSExpr == 0;
2571  if (isLHSNull)
2572    LHSExpr = CondExpr;
2573
2574  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
2575                                             RHSExpr, QuestionLoc);
2576  if (result.isNull())
2577    return ExprError();
2578
2579  Cond.release();
2580  LHS.release();
2581  RHS.release();
2582  return Owned(new (Context) ConditionalOperator(CondExpr,
2583                                                 isLHSNull ? 0 : LHSExpr,
2584                                                 RHSExpr, result));
2585}
2586
2587
2588// CheckPointerTypesForAssignment - This is a very tricky routine (despite
2589// being closely modeled after the C99 spec:-). The odd characteristic of this
2590// routine is it effectively iqnores the qualifiers on the top level pointee.
2591// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
2592// FIXME: add a couple examples in this comment.
2593Sema::AssignConvertType
2594Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
2595  QualType lhptee, rhptee;
2596
2597  // get the "pointed to" type (ignoring qualifiers at the top level)
2598  lhptee = lhsType->getAsPointerType()->getPointeeType();
2599  rhptee = rhsType->getAsPointerType()->getPointeeType();
2600
2601  // make sure we operate on the canonical type
2602  lhptee = Context.getCanonicalType(lhptee);
2603  rhptee = Context.getCanonicalType(rhptee);
2604
2605  AssignConvertType ConvTy = Compatible;
2606
2607  // C99 6.5.16.1p1: This following citation is common to constraints
2608  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
2609  // qualifiers of the type *pointed to* by the right;
2610  // FIXME: Handle ExtQualType
2611  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
2612    ConvTy = CompatiblePointerDiscardsQualifiers;
2613
2614  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
2615  // incomplete type and the other is a pointer to a qualified or unqualified
2616  // version of void...
2617  if (lhptee->isVoidType()) {
2618    if (rhptee->isIncompleteOrObjectType())
2619      return ConvTy;
2620
2621    // As an extension, we allow cast to/from void* to function pointer.
2622    assert(rhptee->isFunctionType());
2623    return FunctionVoidPointer;
2624  }
2625
2626  if (rhptee->isVoidType()) {
2627    if (lhptee->isIncompleteOrObjectType())
2628      return ConvTy;
2629
2630    // As an extension, we allow cast to/from void* to function pointer.
2631    assert(lhptee->isFunctionType());
2632    return FunctionVoidPointer;
2633  }
2634  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
2635  // unqualified versions of compatible types, ...
2636  if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
2637                                  rhptee.getUnqualifiedType()))
2638    return IncompatiblePointer; // this "trumps" PointerAssignDiscardsQualifiers
2639  return ConvTy;
2640}
2641
2642/// CheckBlockPointerTypesForAssignment - This routine determines whether two
2643/// block pointer types are compatible or whether a block and normal pointer
2644/// are compatible. It is more restrict than comparing two function pointer
2645// types.
2646Sema::AssignConvertType
2647Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
2648                                          QualType rhsType) {
2649  QualType lhptee, rhptee;
2650
2651  // get the "pointed to" type (ignoring qualifiers at the top level)
2652  lhptee = lhsType->getAsBlockPointerType()->getPointeeType();
2653  rhptee = rhsType->getAsBlockPointerType()->getPointeeType();
2654
2655  // make sure we operate on the canonical type
2656  lhptee = Context.getCanonicalType(lhptee);
2657  rhptee = Context.getCanonicalType(rhptee);
2658
2659  AssignConvertType ConvTy = Compatible;
2660
2661  // For blocks we enforce that qualifiers are identical.
2662  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
2663    ConvTy = CompatiblePointerDiscardsQualifiers;
2664
2665  if (!Context.typesAreBlockCompatible(lhptee, rhptee))
2666    return IncompatibleBlockPointer;
2667  return ConvTy;
2668}
2669
2670/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
2671/// has code to accommodate several GCC extensions when type checking
2672/// pointers. Here are some objectionable examples that GCC considers warnings:
2673///
2674///  int a, *pint;
2675///  short *pshort;
2676///  struct foo *pfoo;
2677///
2678///  pint = pshort; // warning: assignment from incompatible pointer type
2679///  a = pint; // warning: assignment makes integer from pointer without a cast
2680///  pint = a; // warning: assignment makes pointer from integer without a cast
2681///  pint = pfoo; // warning: assignment from incompatible pointer type
2682///
2683/// As a result, the code for dealing with pointers is more complex than the
2684/// C99 spec dictates.
2685///
2686Sema::AssignConvertType
2687Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
2688  // Get canonical types.  We're not formatting these types, just comparing
2689  // them.
2690  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
2691  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
2692
2693  if (lhsType == rhsType)
2694    return Compatible; // Common case: fast path an exact match.
2695
2696  // If the left-hand side is a reference type, then we are in a
2697  // (rare!) case where we've allowed the use of references in C,
2698  // e.g., as a parameter type in a built-in function. In this case,
2699  // just make sure that the type referenced is compatible with the
2700  // right-hand side type. The caller is responsible for adjusting
2701  // lhsType so that the resulting expression does not have reference
2702  // type.
2703  if (const ReferenceType *lhsTypeRef = lhsType->getAsReferenceType()) {
2704    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
2705      return Compatible;
2706    return Incompatible;
2707  }
2708
2709  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType()) {
2710    if (ObjCQualifiedIdTypesAreCompatible(lhsType, rhsType, false))
2711      return Compatible;
2712    // Relax integer conversions like we do for pointers below.
2713    if (rhsType->isIntegerType())
2714      return IntToPointer;
2715    if (lhsType->isIntegerType())
2716      return PointerToInt;
2717    return IncompatibleObjCQualifiedId;
2718  }
2719
2720  if (lhsType->isVectorType() || rhsType->isVectorType()) {
2721    // For ExtVector, allow vector splats; float -> <n x float>
2722    if (const ExtVectorType *LV = lhsType->getAsExtVectorType())
2723      if (LV->getElementType() == rhsType)
2724        return Compatible;
2725
2726    // If we are allowing lax vector conversions, and LHS and RHS are both
2727    // vectors, the total size only needs to be the same. This is a bitcast;
2728    // no bits are changed but the result type is different.
2729    if (getLangOptions().LaxVectorConversions &&
2730        lhsType->isVectorType() && rhsType->isVectorType()) {
2731      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
2732        return IncompatibleVectors;
2733    }
2734    return Incompatible;
2735  }
2736
2737  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
2738    return Compatible;
2739
2740  if (isa<PointerType>(lhsType)) {
2741    if (rhsType->isIntegerType())
2742      return IntToPointer;
2743
2744    if (isa<PointerType>(rhsType))
2745      return CheckPointerTypesForAssignment(lhsType, rhsType);
2746
2747    if (rhsType->getAsBlockPointerType()) {
2748      if (lhsType->getAsPointerType()->getPointeeType()->isVoidType())
2749        return Compatible;
2750
2751      // Treat block pointers as objects.
2752      if (getLangOptions().ObjC1 &&
2753          lhsType == Context.getCanonicalType(Context.getObjCIdType()))
2754        return Compatible;
2755    }
2756    return Incompatible;
2757  }
2758
2759  if (isa<BlockPointerType>(lhsType)) {
2760    if (rhsType->isIntegerType())
2761      return IntToBlockPointer;
2762
2763    // Treat block pointers as objects.
2764    if (getLangOptions().ObjC1 &&
2765        rhsType == Context.getCanonicalType(Context.getObjCIdType()))
2766      return Compatible;
2767
2768    if (rhsType->isBlockPointerType())
2769      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
2770
2771    if (const PointerType *RHSPT = rhsType->getAsPointerType()) {
2772      if (RHSPT->getPointeeType()->isVoidType())
2773        return Compatible;
2774    }
2775    return Incompatible;
2776  }
2777
2778  if (isa<PointerType>(rhsType)) {
2779    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
2780    if (lhsType == Context.BoolTy)
2781      return Compatible;
2782
2783    if (lhsType->isIntegerType())
2784      return PointerToInt;
2785
2786    if (isa<PointerType>(lhsType))
2787      return CheckPointerTypesForAssignment(lhsType, rhsType);
2788
2789    if (isa<BlockPointerType>(lhsType) &&
2790        rhsType->getAsPointerType()->getPointeeType()->isVoidType())
2791      return Compatible;
2792    return Incompatible;
2793  }
2794
2795  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
2796    if (Context.typesAreCompatible(lhsType, rhsType))
2797      return Compatible;
2798  }
2799  return Incompatible;
2800}
2801
2802Sema::AssignConvertType
2803Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
2804  if (getLangOptions().CPlusPlus) {
2805    if (!lhsType->isRecordType()) {
2806      // C++ 5.17p3: If the left operand is not of class type, the
2807      // expression is implicitly converted (C++ 4) to the
2808      // cv-unqualified type of the left operand.
2809      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
2810                                    "assigning"))
2811        return Incompatible;
2812      else
2813        return Compatible;
2814    }
2815
2816    // FIXME: Currently, we fall through and treat C++ classes like C
2817    // structures.
2818  }
2819
2820  // C99 6.5.16.1p1: the left operand is a pointer and the right is
2821  // a null pointer constant.
2822  if ((lhsType->isPointerType() ||
2823       lhsType->isObjCQualifiedIdType() ||
2824       lhsType->isBlockPointerType())
2825      && rExpr->isNullPointerConstant(Context)) {
2826    ImpCastExprToType(rExpr, lhsType);
2827    return Compatible;
2828  }
2829
2830  // This check seems unnatural, however it is necessary to ensure the proper
2831  // conversion of functions/arrays. If the conversion were done for all
2832  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
2833  // expressions that surpress this implicit conversion (&, sizeof).
2834  //
2835  // Suppress this for references: C++ 8.5.3p5.
2836  if (!lhsType->isReferenceType())
2837    DefaultFunctionArrayConversion(rExpr);
2838
2839  Sema::AssignConvertType result =
2840    CheckAssignmentConstraints(lhsType, rExpr->getType());
2841
2842  // C99 6.5.16.1p2: The value of the right operand is converted to the
2843  // type of the assignment expression.
2844  // CheckAssignmentConstraints allows the left-hand side to be a reference,
2845  // so that we can use references in built-in functions even in C.
2846  // The getNonReferenceType() call makes sure that the resulting expression
2847  // does not have reference type.
2848  if (rExpr->getType() != lhsType)
2849    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
2850  return result;
2851}
2852
2853Sema::AssignConvertType
2854Sema::CheckCompoundAssignmentConstraints(QualType lhsType, QualType rhsType) {
2855  return CheckAssignmentConstraints(lhsType, rhsType);
2856}
2857
2858QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
2859  Diag(Loc, diag::err_typecheck_invalid_operands)
2860    << lex->getType() << rex->getType()
2861    << lex->getSourceRange() << rex->getSourceRange();
2862  return QualType();
2863}
2864
2865inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
2866                                                              Expr *&rex) {
2867  // For conversion purposes, we ignore any qualifiers.
2868  // For example, "const float" and "float" are equivalent.
2869  QualType lhsType =
2870    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
2871  QualType rhsType =
2872    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
2873
2874  // If the vector types are identical, return.
2875  if (lhsType == rhsType)
2876    return lhsType;
2877
2878  // Handle the case of a vector & extvector type of the same size and element
2879  // type.  It would be nice if we only had one vector type someday.
2880  if (getLangOptions().LaxVectorConversions) {
2881    // FIXME: Should we warn here?
2882    if (const VectorType *LV = lhsType->getAsVectorType()) {
2883      if (const VectorType *RV = rhsType->getAsVectorType())
2884        if (LV->getElementType() == RV->getElementType() &&
2885            LV->getNumElements() == RV->getNumElements()) {
2886          return lhsType->isExtVectorType() ? lhsType : rhsType;
2887        }
2888    }
2889  }
2890
2891  // If the lhs is an extended vector and the rhs is a scalar of the same type
2892  // or a literal, promote the rhs to the vector type.
2893  if (const ExtVectorType *V = lhsType->getAsExtVectorType()) {
2894    QualType eltType = V->getElementType();
2895
2896    if ((eltType->getAsBuiltinType() == rhsType->getAsBuiltinType()) ||
2897        (eltType->isIntegerType() && isa<IntegerLiteral>(rex)) ||
2898        (eltType->isFloatingType() && isa<FloatingLiteral>(rex))) {
2899      ImpCastExprToType(rex, lhsType);
2900      return lhsType;
2901    }
2902  }
2903
2904  // If the rhs is an extended vector and the lhs is a scalar of the same type,
2905  // promote the lhs to the vector type.
2906  if (const ExtVectorType *V = rhsType->getAsExtVectorType()) {
2907    QualType eltType = V->getElementType();
2908
2909    if ((eltType->getAsBuiltinType() == lhsType->getAsBuiltinType()) ||
2910        (eltType->isIntegerType() && isa<IntegerLiteral>(lex)) ||
2911        (eltType->isFloatingType() && isa<FloatingLiteral>(lex))) {
2912      ImpCastExprToType(lex, rhsType);
2913      return rhsType;
2914    }
2915  }
2916
2917  // You cannot convert between vector values of different size.
2918  Diag(Loc, diag::err_typecheck_vector_not_convertable)
2919    << lex->getType() << rex->getType()
2920    << lex->getSourceRange() << rex->getSourceRange();
2921  return QualType();
2922}
2923
2924inline QualType Sema::CheckMultiplyDivideOperands(
2925  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2926{
2927  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2928    return CheckVectorOperands(Loc, lex, rex);
2929
2930  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2931
2932  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2933    return compType;
2934  return InvalidOperands(Loc, lex, rex);
2935}
2936
2937inline QualType Sema::CheckRemainderOperands(
2938  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2939{
2940  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
2941    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2942      return CheckVectorOperands(Loc, lex, rex);
2943    return InvalidOperands(Loc, lex, rex);
2944  }
2945
2946  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2947
2948  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
2949    return compType;
2950  return InvalidOperands(Loc, lex, rex);
2951}
2952
2953inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
2954  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
2955{
2956  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
2957    return CheckVectorOperands(Loc, lex, rex);
2958
2959  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
2960
2961  // handle the common case first (both operands are arithmetic).
2962  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
2963    return compType;
2964
2965  // Put any potential pointer into PExp
2966  Expr* PExp = lex, *IExp = rex;
2967  if (IExp->getType()->isPointerType())
2968    std::swap(PExp, IExp);
2969
2970  if (const PointerType* PTy = PExp->getType()->getAsPointerType()) {
2971    if (IExp->getType()->isIntegerType()) {
2972      // Check for arithmetic on pointers to incomplete types
2973      if (!PTy->getPointeeType()->isObjectType()) {
2974        if (PTy->getPointeeType()->isVoidType()) {
2975          if (getLangOptions().CPlusPlus) {
2976            Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
2977              << lex->getSourceRange() << rex->getSourceRange();
2978            return QualType();
2979          }
2980
2981          // GNU extension: arithmetic on pointer to void
2982          Diag(Loc, diag::ext_gnu_void_ptr)
2983            << lex->getSourceRange() << rex->getSourceRange();
2984        } else if (PTy->getPointeeType()->isFunctionType()) {
2985          if (getLangOptions().CPlusPlus) {
2986            Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
2987              << lex->getType() << lex->getSourceRange();
2988            return QualType();
2989          }
2990
2991          // GNU extension: arithmetic on pointer to function
2992          Diag(Loc, diag::ext_gnu_ptr_func_arith)
2993            << lex->getType() << lex->getSourceRange();
2994        } else {
2995          DiagnoseIncompleteType(Loc, PTy->getPointeeType(),
2996                                 diag::err_typecheck_arithmetic_incomplete_type,
2997                                 lex->getSourceRange(), SourceRange(),
2998                                 lex->getType());
2999          return QualType();
3000        }
3001      }
3002      return PExp->getType();
3003    }
3004  }
3005
3006  return InvalidOperands(Loc, lex, rex);
3007}
3008
3009// C99 6.5.6
3010QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
3011                                        SourceLocation Loc, bool isCompAssign) {
3012  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3013    return CheckVectorOperands(Loc, lex, rex);
3014
3015  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3016
3017  // Enforce type constraints: C99 6.5.6p3.
3018
3019  // Handle the common case first (both operands are arithmetic).
3020  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3021    return compType;
3022
3023  // Either ptr - int   or   ptr - ptr.
3024  if (const PointerType *LHSPTy = lex->getType()->getAsPointerType()) {
3025    QualType lpointee = LHSPTy->getPointeeType();
3026
3027    // The LHS must be an object type, not incomplete, function, etc.
3028    if (!lpointee->isObjectType()) {
3029      // Handle the GNU void* extension.
3030      if (lpointee->isVoidType()) {
3031        Diag(Loc, diag::ext_gnu_void_ptr)
3032          << lex->getSourceRange() << rex->getSourceRange();
3033      } else if (lpointee->isFunctionType()) {
3034        if (getLangOptions().CPlusPlus) {
3035          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3036            << lex->getType() << lex->getSourceRange();
3037          return QualType();
3038        }
3039
3040        // GNU extension: arithmetic on pointer to function
3041        Diag(Loc, diag::ext_gnu_ptr_func_arith)
3042          << lex->getType() << lex->getSourceRange();
3043      } else {
3044        Diag(Loc, diag::err_typecheck_sub_ptr_object)
3045          << lex->getType() << lex->getSourceRange();
3046        return QualType();
3047      }
3048    }
3049
3050    // The result type of a pointer-int computation is the pointer type.
3051    if (rex->getType()->isIntegerType())
3052      return lex->getType();
3053
3054    // Handle pointer-pointer subtractions.
3055    if (const PointerType *RHSPTy = rex->getType()->getAsPointerType()) {
3056      QualType rpointee = RHSPTy->getPointeeType();
3057
3058      // RHS must be an object type, unless void (GNU).
3059      if (!rpointee->isObjectType()) {
3060        // Handle the GNU void* extension.
3061        if (rpointee->isVoidType()) {
3062          if (!lpointee->isVoidType())
3063            Diag(Loc, diag::ext_gnu_void_ptr)
3064              << lex->getSourceRange() << rex->getSourceRange();
3065        } else if (rpointee->isFunctionType()) {
3066          if (getLangOptions().CPlusPlus) {
3067            Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
3068              << rex->getType() << rex->getSourceRange();
3069            return QualType();
3070          }
3071
3072          // GNU extension: arithmetic on pointer to function
3073          if (!lpointee->isFunctionType())
3074            Diag(Loc, diag::ext_gnu_ptr_func_arith)
3075              << lex->getType() << lex->getSourceRange();
3076        } else {
3077          Diag(Loc, diag::err_typecheck_sub_ptr_object)
3078            << rex->getType() << rex->getSourceRange();
3079          return QualType();
3080        }
3081      }
3082
3083      // Pointee types must be compatible.
3084      if (!Context.typesAreCompatible(
3085              Context.getCanonicalType(lpointee).getUnqualifiedType(),
3086              Context.getCanonicalType(rpointee).getUnqualifiedType())) {
3087        Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
3088          << lex->getType() << rex->getType()
3089          << lex->getSourceRange() << rex->getSourceRange();
3090        return QualType();
3091      }
3092
3093      return Context.getPointerDiffType();
3094    }
3095  }
3096
3097  return InvalidOperands(Loc, lex, rex);
3098}
3099
3100// C99 6.5.7
3101QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
3102                                  bool isCompAssign) {
3103  // C99 6.5.7p2: Each of the operands shall have integer type.
3104  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
3105    return InvalidOperands(Loc, lex, rex);
3106
3107  // Shifts don't perform usual arithmetic conversions, they just do integer
3108  // promotions on each operand. C99 6.5.7p3
3109  if (!isCompAssign)
3110    UsualUnaryConversions(lex);
3111  UsualUnaryConversions(rex);
3112
3113  // "The type of the result is that of the promoted left operand."
3114  return lex->getType();
3115}
3116
3117// C99 6.5.8
3118QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
3119                                    bool isRelational) {
3120  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3121    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
3122
3123  // C99 6.5.8p3 / C99 6.5.9p4
3124  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
3125    UsualArithmeticConversions(lex, rex);
3126  else {
3127    UsualUnaryConversions(lex);
3128    UsualUnaryConversions(rex);
3129  }
3130  QualType lType = lex->getType();
3131  QualType rType = rex->getType();
3132
3133  // For non-floating point types, check for self-comparisons of the form
3134  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
3135  // often indicate logic errors in the program.
3136  if (!lType->isFloatingType()) {
3137    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3138      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3139        if (DRL->getDecl() == DRR->getDecl())
3140          Diag(Loc, diag::warn_selfcomparison);
3141  }
3142
3143  // The result of comparisons is 'bool' in C++, 'int' in C.
3144  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy : Context.IntTy;
3145
3146  if (isRelational) {
3147    if (lType->isRealType() && rType->isRealType())
3148      return ResultTy;
3149  } else {
3150    // Check for comparisons of floating point operands using != and ==.
3151    if (lType->isFloatingType()) {
3152      assert (rType->isFloatingType());
3153      CheckFloatComparison(Loc,lex,rex);
3154    }
3155
3156    if (lType->isArithmeticType() && rType->isArithmeticType())
3157      return ResultTy;
3158  }
3159
3160  bool LHSIsNull = lex->isNullPointerConstant(Context);
3161  bool RHSIsNull = rex->isNullPointerConstant(Context);
3162
3163  // All of the following pointer related warnings are GCC extensions, except
3164  // when handling null pointer constants. One day, we can consider making them
3165  // errors (when -pedantic-errors is enabled).
3166  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
3167    QualType LCanPointeeTy =
3168      Context.getCanonicalType(lType->getAsPointerType()->getPointeeType());
3169    QualType RCanPointeeTy =
3170      Context.getCanonicalType(rType->getAsPointerType()->getPointeeType());
3171
3172    if (!LHSIsNull && !RHSIsNull &&                       // C99 6.5.9p2
3173        !LCanPointeeTy->isVoidType() && !RCanPointeeTy->isVoidType() &&
3174        !Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
3175                                    RCanPointeeTy.getUnqualifiedType()) &&
3176        !Context.areComparableObjCPointerTypes(lType, rType)) {
3177      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
3178        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3179    }
3180    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3181    return ResultTy;
3182  }
3183  // Handle block pointer types.
3184  if (lType->isBlockPointerType() && rType->isBlockPointerType()) {
3185    QualType lpointee = lType->getAsBlockPointerType()->getPointeeType();
3186    QualType rpointee = rType->getAsBlockPointerType()->getPointeeType();
3187
3188    if (!LHSIsNull && !RHSIsNull &&
3189        !Context.typesAreBlockCompatible(lpointee, rpointee)) {
3190      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3191        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3192    }
3193    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3194    return ResultTy;
3195  }
3196  // Allow block pointers to be compared with null pointer constants.
3197  if ((lType->isBlockPointerType() && rType->isPointerType()) ||
3198      (lType->isPointerType() && rType->isBlockPointerType())) {
3199    if (!LHSIsNull && !RHSIsNull) {
3200      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
3201        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3202    }
3203    ImpCastExprToType(rex, lType); // promote the pointer to pointer
3204    return ResultTy;
3205  }
3206
3207  if ((lType->isObjCQualifiedIdType() || rType->isObjCQualifiedIdType())) {
3208    if (lType->isPointerType() || rType->isPointerType()) {
3209      const PointerType *LPT = lType->getAsPointerType();
3210      const PointerType *RPT = rType->getAsPointerType();
3211      bool LPtrToVoid = LPT ?
3212        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
3213      bool RPtrToVoid = RPT ?
3214        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
3215
3216      if (!LPtrToVoid && !RPtrToVoid &&
3217          !Context.typesAreCompatible(lType, rType)) {
3218        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
3219          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3220        ImpCastExprToType(rex, lType);
3221        return ResultTy;
3222      }
3223      ImpCastExprToType(rex, lType);
3224      return ResultTy;
3225    }
3226    if (ObjCQualifiedIdTypesAreCompatible(lType, rType, true)) {
3227      ImpCastExprToType(rex, lType);
3228      return ResultTy;
3229    } else {
3230      if ((lType->isObjCQualifiedIdType() && rType->isObjCQualifiedIdType())) {
3231        Diag(Loc, diag::warn_incompatible_qualified_id_operands)
3232          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3233        ImpCastExprToType(rex, lType);
3234        return ResultTy;
3235      }
3236    }
3237  }
3238  if ((lType->isPointerType() || lType->isObjCQualifiedIdType()) &&
3239       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() &&
3247      (rType->isPointerType() || rType->isObjCQualifiedIdType())) {
3248    if (!LHSIsNull)
3249      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3250        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3251    ImpCastExprToType(lex, rType); // promote the integer to pointer
3252    return ResultTy;
3253  }
3254  // Handle block pointers.
3255  if (lType->isBlockPointerType() && rType->isIntegerType()) {
3256    if (!RHSIsNull)
3257      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3258        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3259    ImpCastExprToType(rex, lType); // promote the integer to pointer
3260    return ResultTy;
3261  }
3262  if (lType->isIntegerType() && rType->isBlockPointerType()) {
3263    if (!LHSIsNull)
3264      Diag(Loc, diag::ext_typecheck_comparison_of_pointer_integer)
3265        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
3266    ImpCastExprToType(lex, rType); // promote the integer to pointer
3267    return ResultTy;
3268  }
3269  return InvalidOperands(Loc, lex, rex);
3270}
3271
3272/// CheckVectorCompareOperands - vector comparisons are a clang extension that
3273/// operates on extended vector types.  Instead of producing an IntTy result,
3274/// like a scalar comparison, a vector comparison produces a vector of integer
3275/// types.
3276QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
3277                                          SourceLocation Loc,
3278                                          bool isRelational) {
3279  // Check to make sure we're operating on vectors of the same type and width,
3280  // Allowing one side to be a scalar of element type.
3281  QualType vType = CheckVectorOperands(Loc, lex, rex);
3282  if (vType.isNull())
3283    return vType;
3284
3285  QualType lType = lex->getType();
3286  QualType rType = rex->getType();
3287
3288  // For non-floating point types, check for self-comparisons of the form
3289  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
3290  // often indicate logic errors in the program.
3291  if (!lType->isFloatingType()) {
3292    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
3293      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
3294        if (DRL->getDecl() == DRR->getDecl())
3295          Diag(Loc, diag::warn_selfcomparison);
3296  }
3297
3298  // Check for comparisons of floating point operands using != and ==.
3299  if (!isRelational && lType->isFloatingType()) {
3300    assert (rType->isFloatingType());
3301    CheckFloatComparison(Loc,lex,rex);
3302  }
3303
3304  // Return the type for the comparison, which is the same as vector type for
3305  // integer vectors, or an integer type of identical size and number of
3306  // elements for floating point vectors.
3307  if (lType->isIntegerType())
3308    return lType;
3309
3310  const VectorType *VTy = lType->getAsVectorType();
3311  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
3312  if (TypeSize == Context.getTypeSize(Context.IntTy))
3313    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
3314  else if (TypeSize == Context.getTypeSize(Context.LongTy))
3315    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
3316
3317  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
3318         "Unhandled vector element size in vector compare");
3319  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
3320}
3321
3322inline QualType Sema::CheckBitwiseOperands(
3323  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign)
3324{
3325  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
3326    return CheckVectorOperands(Loc, lex, rex);
3327
3328  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
3329
3330  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
3331    return compType;
3332  return InvalidOperands(Loc, lex, rex);
3333}
3334
3335inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
3336  Expr *&lex, Expr *&rex, SourceLocation Loc)
3337{
3338  UsualUnaryConversions(lex);
3339  UsualUnaryConversions(rex);
3340
3341  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
3342    return Context.IntTy;
3343  return InvalidOperands(Loc, lex, rex);
3344}
3345
3346/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
3347/// is a read-only property; return true if so. A readonly property expression
3348/// depends on various declarations and thus must be treated specially.
3349///
3350static bool IsReadonlyProperty(Expr *E, Sema &S)
3351{
3352  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
3353    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
3354    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
3355      QualType BaseType = PropExpr->getBase()->getType();
3356      if (const PointerType *PTy = BaseType->getAsPointerType())
3357        if (const ObjCInterfaceType *IFTy =
3358            PTy->getPointeeType()->getAsObjCInterfaceType())
3359          if (ObjCInterfaceDecl *IFace = IFTy->getDecl())
3360            if (S.isPropertyReadonly(PDecl, IFace))
3361              return true;
3362    }
3363  }
3364  return false;
3365}
3366
3367/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
3368/// emit an error and return true.  If so, return false.
3369static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
3370  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context);
3371  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
3372    IsLV = Expr::MLV_ReadonlyProperty;
3373  if (IsLV == Expr::MLV_Valid)
3374    return false;
3375
3376  unsigned Diag = 0;
3377  bool NeedType = false;
3378  switch (IsLV) { // C99 6.5.16p2
3379  default: assert(0 && "Unknown result from isModifiableLvalue!");
3380  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
3381  case Expr::MLV_ArrayType:
3382    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
3383    NeedType = true;
3384    break;
3385  case Expr::MLV_NotObjectType:
3386    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
3387    NeedType = true;
3388    break;
3389  case Expr::MLV_LValueCast:
3390    Diag = diag::err_typecheck_lvalue_casts_not_supported;
3391    break;
3392  case Expr::MLV_InvalidExpression:
3393    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
3394    break;
3395  case Expr::MLV_IncompleteType:
3396  case Expr::MLV_IncompleteVoidType:
3397    return S.DiagnoseIncompleteType(Loc, E->getType(),
3398                      diag::err_typecheck_incomplete_type_not_modifiable_lvalue,
3399                                    E->getSourceRange());
3400  case Expr::MLV_DuplicateVectorComponents:
3401    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
3402    break;
3403  case Expr::MLV_NotBlockQualified:
3404    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
3405    break;
3406  case Expr::MLV_ReadonlyProperty:
3407    Diag = diag::error_readonly_property_assignment;
3408    break;
3409  case Expr::MLV_NoSetterProperty:
3410    Diag = diag::error_nosetter_property_assignment;
3411    break;
3412  }
3413
3414  if (NeedType)
3415    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange();
3416  else
3417    S.Diag(Loc, Diag) << E->getSourceRange();
3418  return true;
3419}
3420
3421
3422
3423// C99 6.5.16.1
3424QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
3425                                       SourceLocation Loc,
3426                                       QualType CompoundType) {
3427  // Verify that LHS is a modifiable lvalue, and emit error if not.
3428  if (CheckForModifiableLvalue(LHS, Loc, *this))
3429    return QualType();
3430
3431  QualType LHSType = LHS->getType();
3432  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
3433
3434  AssignConvertType ConvTy;
3435  if (CompoundType.isNull()) {
3436    // Simple assignment "x = y".
3437    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
3438    // Special case of NSObject attributes on c-style pointer types.
3439    if (ConvTy == IncompatiblePointer &&
3440        ((Context.isObjCNSObjectType(LHSType) &&
3441          Context.isObjCObjectPointerType(RHSType)) ||
3442         (Context.isObjCNSObjectType(RHSType) &&
3443          Context.isObjCObjectPointerType(LHSType))))
3444      ConvTy = Compatible;
3445
3446    // If the RHS is a unary plus or minus, check to see if they = and + are
3447    // right next to each other.  If so, the user may have typo'd "x =+ 4"
3448    // instead of "x += 4".
3449    Expr *RHSCheck = RHS;
3450    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
3451      RHSCheck = ICE->getSubExpr();
3452    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
3453      if ((UO->getOpcode() == UnaryOperator::Plus ||
3454           UO->getOpcode() == UnaryOperator::Minus) &&
3455          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
3456          // Only if the two operators are exactly adjacent.
3457          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc())
3458        Diag(Loc, diag::warn_not_compound_assign)
3459          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
3460          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
3461    }
3462  } else {
3463    // Compound assignment "x += y"
3464    ConvTy = CheckCompoundAssignmentConstraints(LHSType, RHSType);
3465  }
3466
3467  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
3468                               RHS, "assigning"))
3469    return QualType();
3470
3471  // C99 6.5.16p3: The type of an assignment expression is the type of the
3472  // left operand unless the left operand has qualified type, in which case
3473  // it is the unqualified version of the type of the left operand.
3474  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
3475  // is converted to the type of the assignment expression (above).
3476  // C++ 5.17p1: the type of the assignment expression is that of its left
3477  // oprdu.
3478  return LHSType.getUnqualifiedType();
3479}
3480
3481// C99 6.5.17
3482QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
3483  // FIXME: what is required for LHS?
3484
3485  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
3486  DefaultFunctionArrayConversion(RHS);
3487  return RHS->getType();
3488}
3489
3490/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
3491/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
3492QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
3493                                              bool isInc) {
3494  if (Op->isTypeDependent())
3495    return Context.DependentTy;
3496
3497  QualType ResType = Op->getType();
3498  assert(!ResType.isNull() && "no type for increment/decrement expression");
3499
3500  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
3501    // Decrement of bool is not allowed.
3502    if (!isInc) {
3503      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
3504      return QualType();
3505    }
3506    // Increment of bool sets it to true, but is deprecated.
3507    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
3508  } else if (ResType->isRealType()) {
3509    // OK!
3510  } else if (const PointerType *PT = ResType->getAsPointerType()) {
3511    // C99 6.5.2.4p2, 6.5.6p2
3512    if (PT->getPointeeType()->isObjectType()) {
3513      // Pointer to object is ok!
3514    } else if (PT->getPointeeType()->isVoidType()) {
3515      if (getLangOptions().CPlusPlus) {
3516        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
3517          << Op->getSourceRange();
3518        return QualType();
3519      }
3520
3521      // Pointer to void is a GNU extension in C.
3522      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
3523    } else if (PT->getPointeeType()->isFunctionType()) {
3524      if (getLangOptions().CPlusPlus) {
3525        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
3526          << Op->getType() << Op->getSourceRange();
3527        return QualType();
3528      }
3529
3530      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
3531        << ResType << Op->getSourceRange();
3532      return QualType();
3533    } else {
3534      DiagnoseIncompleteType(OpLoc, PT->getPointeeType(),
3535                             diag::err_typecheck_arithmetic_incomplete_type,
3536                             Op->getSourceRange(), SourceRange(),
3537                             ResType);
3538      return QualType();
3539    }
3540  } else if (ResType->isComplexType()) {
3541    // C99 does not support ++/-- on complex types, we allow as an extension.
3542    Diag(OpLoc, diag::ext_integer_increment_complex)
3543      << ResType << Op->getSourceRange();
3544  } else {
3545    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
3546      << ResType << Op->getSourceRange();
3547    return QualType();
3548  }
3549  // At this point, we know we have a real, complex or pointer type.
3550  // Now make sure the operand is a modifiable lvalue.
3551  if (CheckForModifiableLvalue(Op, OpLoc, *this))
3552    return QualType();
3553  return ResType;
3554}
3555
3556/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
3557/// This routine allows us to typecheck complex/recursive expressions
3558/// where the declaration is needed for type checking. We only need to
3559/// handle cases when the expression references a function designator
3560/// or is an lvalue. Here are some examples:
3561///  - &(x) => x
3562///  - &*****f => f for f a function designator.
3563///  - &s.xx => s
3564///  - &s.zz[1].yy -> s, if zz is an array
3565///  - *(x + 1) -> x, if x is an array
3566///  - &"123"[2] -> 0
3567///  - & __real__ x -> x
3568static NamedDecl *getPrimaryDecl(Expr *E) {
3569  switch (E->getStmtClass()) {
3570  case Stmt::DeclRefExprClass:
3571  case Stmt::QualifiedDeclRefExprClass:
3572    return cast<DeclRefExpr>(E)->getDecl();
3573  case Stmt::MemberExprClass:
3574    // Fields cannot be declared with a 'register' storage class.
3575    // &X->f is always ok, even if X is declared register.
3576    if (cast<MemberExpr>(E)->isArrow())
3577      return 0;
3578    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
3579  case Stmt::ArraySubscriptExprClass: {
3580    // &X[4] and &4[X] refers to X if X is not a pointer.
3581
3582    NamedDecl *D = getPrimaryDecl(cast<ArraySubscriptExpr>(E)->getBase());
3583    ValueDecl *VD = dyn_cast_or_null<ValueDecl>(D);
3584    if (!VD || VD->getType()->isPointerType())
3585      return 0;
3586    else
3587      return VD;
3588  }
3589  case Stmt::UnaryOperatorClass: {
3590    UnaryOperator *UO = cast<UnaryOperator>(E);
3591
3592    switch(UO->getOpcode()) {
3593    case UnaryOperator::Deref: {
3594      // *(X + 1) refers to X if X is not a pointer.
3595      if (NamedDecl *D = getPrimaryDecl(UO->getSubExpr())) {
3596        ValueDecl *VD = dyn_cast<ValueDecl>(D);
3597        if (!VD || VD->getType()->isPointerType())
3598          return 0;
3599        return VD;
3600      }
3601      return 0;
3602    }
3603    case UnaryOperator::Real:
3604    case UnaryOperator::Imag:
3605    case UnaryOperator::Extension:
3606      return getPrimaryDecl(UO->getSubExpr());
3607    default:
3608      return 0;
3609    }
3610  }
3611  case Stmt::BinaryOperatorClass: {
3612    BinaryOperator *BO = cast<BinaryOperator>(E);
3613
3614    // Handle cases involving pointer arithmetic. The result of an
3615    // Assign or AddAssign is not an lvalue so they can be ignored.
3616
3617    // (x + n) or (n + x) => x
3618    if (BO->getOpcode() == BinaryOperator::Add) {
3619      if (BO->getLHS()->getType()->isPointerType()) {
3620        return getPrimaryDecl(BO->getLHS());
3621      } else if (BO->getRHS()->getType()->isPointerType()) {
3622        return getPrimaryDecl(BO->getRHS());
3623      }
3624    }
3625
3626    return 0;
3627  }
3628  case Stmt::ParenExprClass:
3629    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
3630  case Stmt::ImplicitCastExprClass:
3631    // &X[4] when X is an array, has an implicit cast from array to pointer.
3632    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
3633  default:
3634    return 0;
3635  }
3636}
3637
3638/// CheckAddressOfOperand - The operand of & must be either a function
3639/// designator or an lvalue designating an object. If it is an lvalue, the
3640/// object cannot be declared with storage class register or be a bit field.
3641/// Note: The usual conversions are *not* applied to the operand of the &
3642/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
3643/// In C++, the operand might be an overloaded function name, in which case
3644/// we allow the '&' but retain the overloaded-function type.
3645QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
3646  if (op->isTypeDependent())
3647    return Context.DependentTy;
3648
3649  if (getLangOptions().C99) {
3650    // Implement C99-only parts of addressof rules.
3651    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
3652      if (uOp->getOpcode() == UnaryOperator::Deref)
3653        // Per C99 6.5.3.2, the address of a deref always returns a valid result
3654        // (assuming the deref expression is valid).
3655        return uOp->getSubExpr()->getType();
3656    }
3657    // Technically, there should be a check for array subscript
3658    // expressions here, but the result of one is always an lvalue anyway.
3659  }
3660  NamedDecl *dcl = getPrimaryDecl(op);
3661  Expr::isLvalueResult lval = op->isLvalue(Context);
3662
3663  if (lval != Expr::LV_Valid) { // C99 6.5.3.2p1
3664    if (!dcl || !isa<FunctionDecl>(dcl)) {// allow function designators
3665      // FIXME: emit more specific diag...
3666      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
3667        << op->getSourceRange();
3668      return QualType();
3669    }
3670  } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(op)) { // C99 6.5.3.2p1
3671    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemExpr->getMemberDecl())) {
3672      if (Field->isBitField()) {
3673        Diag(OpLoc, diag::err_typecheck_address_of)
3674          << "bit-field" << op->getSourceRange();
3675        return QualType();
3676      }
3677    }
3678  // Check for Apple extension for accessing vector components.
3679  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
3680           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
3681    Diag(OpLoc, diag::err_typecheck_address_of)
3682      << "vector element" << op->getSourceRange();
3683    return QualType();
3684  } else if (dcl) { // C99 6.5.3.2p1
3685    // We have an lvalue with a decl. Make sure the decl is not declared
3686    // with the register storage-class specifier.
3687    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
3688      if (vd->getStorageClass() == VarDecl::Register) {
3689        Diag(OpLoc, diag::err_typecheck_address_of)
3690          << "register variable" << op->getSourceRange();
3691        return QualType();
3692      }
3693    } else if (isa<OverloadedFunctionDecl>(dcl)) {
3694      return Context.OverloadTy;
3695    } else if (isa<FieldDecl>(dcl)) {
3696      // Okay: we can take the address of a field.
3697      // Could be a pointer to member, though, if there is an explicit
3698      // scope qualifier for the class.
3699      if (isa<QualifiedDeclRefExpr>(op)) {
3700        DeclContext *Ctx = dcl->getDeclContext();
3701        if (Ctx && Ctx->isRecord())
3702          return Context.getMemberPointerType(op->getType(),
3703                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3704      }
3705    } else if (isa<FunctionDecl>(dcl)) {
3706      // Okay: we can take the address of a function.
3707      // As above.
3708      if (isa<QualifiedDeclRefExpr>(op)) {
3709        DeclContext *Ctx = dcl->getDeclContext();
3710        if (Ctx && Ctx->isRecord())
3711          return Context.getMemberPointerType(op->getType(),
3712                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
3713      }
3714    }
3715    else
3716      assert(0 && "Unknown/unexpected decl type");
3717  }
3718
3719  // If the operand has type "type", the result has type "pointer to type".
3720  return Context.getPointerType(op->getType());
3721}
3722
3723QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
3724  if (Op->isTypeDependent())
3725    return Context.DependentTy;
3726
3727  UsualUnaryConversions(Op);
3728  QualType Ty = Op->getType();
3729
3730  // Note that per both C89 and C99, this is always legal, even if ptype is an
3731  // incomplete type or void.  It would be possible to warn about dereferencing
3732  // a void pointer, but it's completely well-defined, and such a warning is
3733  // unlikely to catch any mistakes.
3734  if (const PointerType *PT = Ty->getAsPointerType())
3735    return PT->getPointeeType();
3736
3737  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
3738    << Ty << Op->getSourceRange();
3739  return QualType();
3740}
3741
3742static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
3743  tok::TokenKind Kind) {
3744  BinaryOperator::Opcode Opc;
3745  switch (Kind) {
3746  default: assert(0 && "Unknown binop!");
3747  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
3748  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
3749  case tok::star:                 Opc = BinaryOperator::Mul; break;
3750  case tok::slash:                Opc = BinaryOperator::Div; break;
3751  case tok::percent:              Opc = BinaryOperator::Rem; break;
3752  case tok::plus:                 Opc = BinaryOperator::Add; break;
3753  case tok::minus:                Opc = BinaryOperator::Sub; break;
3754  case tok::lessless:             Opc = BinaryOperator::Shl; break;
3755  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
3756  case tok::lessequal:            Opc = BinaryOperator::LE; break;
3757  case tok::less:                 Opc = BinaryOperator::LT; break;
3758  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
3759  case tok::greater:              Opc = BinaryOperator::GT; break;
3760  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
3761  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
3762  case tok::amp:                  Opc = BinaryOperator::And; break;
3763  case tok::caret:                Opc = BinaryOperator::Xor; break;
3764  case tok::pipe:                 Opc = BinaryOperator::Or; break;
3765  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
3766  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
3767  case tok::equal:                Opc = BinaryOperator::Assign; break;
3768  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
3769  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
3770  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
3771  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
3772  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
3773  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
3774  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
3775  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
3776  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
3777  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
3778  case tok::comma:                Opc = BinaryOperator::Comma; break;
3779  }
3780  return Opc;
3781}
3782
3783static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
3784  tok::TokenKind Kind) {
3785  UnaryOperator::Opcode Opc;
3786  switch (Kind) {
3787  default: assert(0 && "Unknown unary op!");
3788  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
3789  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
3790  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
3791  case tok::star:         Opc = UnaryOperator::Deref; break;
3792  case tok::plus:         Opc = UnaryOperator::Plus; break;
3793  case tok::minus:        Opc = UnaryOperator::Minus; break;
3794  case tok::tilde:        Opc = UnaryOperator::Not; break;
3795  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
3796  case tok::kw___real:    Opc = UnaryOperator::Real; break;
3797  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
3798  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
3799  }
3800  return Opc;
3801}
3802
3803/// CreateBuiltinBinOp - Creates a new built-in binary operation with
3804/// operator @p Opc at location @c TokLoc. This routine only supports
3805/// built-in operations; ActOnBinOp handles overloaded operators.
3806Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
3807                                                  unsigned Op,
3808                                                  Expr *lhs, Expr *rhs) {
3809  QualType ResultTy;  // Result type of the binary operator.
3810  QualType CompTy;    // Computation type for compound assignments (e.g. '+=')
3811  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
3812
3813  switch (Opc) {
3814  default:
3815    assert(0 && "Unknown binary expr!");
3816  case BinaryOperator::Assign:
3817    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
3818    break;
3819  case BinaryOperator::PtrMemD:
3820  case BinaryOperator::PtrMemI:
3821    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
3822                                            Opc == BinaryOperator::PtrMemI);
3823    break;
3824  case BinaryOperator::Mul:
3825  case BinaryOperator::Div:
3826    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
3827    break;
3828  case BinaryOperator::Rem:
3829    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
3830    break;
3831  case BinaryOperator::Add:
3832    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
3833    break;
3834  case BinaryOperator::Sub:
3835    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
3836    break;
3837  case BinaryOperator::Shl:
3838  case BinaryOperator::Shr:
3839    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
3840    break;
3841  case BinaryOperator::LE:
3842  case BinaryOperator::LT:
3843  case BinaryOperator::GE:
3844  case BinaryOperator::GT:
3845    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, true);
3846    break;
3847  case BinaryOperator::EQ:
3848  case BinaryOperator::NE:
3849    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, false);
3850    break;
3851  case BinaryOperator::And:
3852  case BinaryOperator::Xor:
3853  case BinaryOperator::Or:
3854    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
3855    break;
3856  case BinaryOperator::LAnd:
3857  case BinaryOperator::LOr:
3858    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
3859    break;
3860  case BinaryOperator::MulAssign:
3861  case BinaryOperator::DivAssign:
3862    CompTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
3863    if (!CompTy.isNull())
3864      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3865    break;
3866  case BinaryOperator::RemAssign:
3867    CompTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
3868    if (!CompTy.isNull())
3869      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3870    break;
3871  case BinaryOperator::AddAssign:
3872    CompTy = CheckAdditionOperands(lhs, rhs, OpLoc, true);
3873    if (!CompTy.isNull())
3874      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3875    break;
3876  case BinaryOperator::SubAssign:
3877    CompTy = CheckSubtractionOperands(lhs, rhs, OpLoc, true);
3878    if (!CompTy.isNull())
3879      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3880    break;
3881  case BinaryOperator::ShlAssign:
3882  case BinaryOperator::ShrAssign:
3883    CompTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
3884    if (!CompTy.isNull())
3885      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3886    break;
3887  case BinaryOperator::AndAssign:
3888  case BinaryOperator::XorAssign:
3889  case BinaryOperator::OrAssign:
3890    CompTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
3891    if (!CompTy.isNull())
3892      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompTy);
3893    break;
3894  case BinaryOperator::Comma:
3895    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
3896    break;
3897  }
3898  if (ResultTy.isNull())
3899    return ExprError();
3900  if (CompTy.isNull())
3901    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
3902  else
3903    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
3904                                                      CompTy, OpLoc));
3905}
3906
3907// Binary Operators.  'Tok' is the token for the operator.
3908Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
3909                                          tok::TokenKind Kind,
3910                                          ExprArg LHS, ExprArg RHS) {
3911  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
3912  Expr *lhs = (Expr *)LHS.release(), *rhs = (Expr*)RHS.release();
3913
3914  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
3915  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
3916
3917  // If either expression is type-dependent, just build the AST.
3918  // FIXME: We'll need to perform some caching of the result of name
3919  // lookup for operator+.
3920  if (lhs->isTypeDependent() || rhs->isTypeDependent()) {
3921    if (Opc > BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign)
3922      return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc,
3923                                              Context.DependentTy,
3924                                              Context.DependentTy, TokLoc));
3925    else
3926      return Owned(new (Context) BinaryOperator(lhs, rhs, Opc,
3927                                                Context.DependentTy, TokLoc));
3928  }
3929
3930  if (getLangOptions().CPlusPlus && Opc != BinaryOperator::PtrMemD &&
3931      (lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType() ||
3932       rhs->getType()->isRecordType() || rhs->getType()->isEnumeralType())) {
3933    // If this is one of the assignment operators, we only perform
3934    // overload resolution if the left-hand side is a class or
3935    // enumeration type (C++ [expr.ass]p3).
3936    if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
3937        !(lhs->getType()->isRecordType() || lhs->getType()->isEnumeralType())) {
3938      return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
3939    }
3940
3941    // Determine which overloaded operator we're dealing with.
3942    static const OverloadedOperatorKind OverOps[] = {
3943      // Overloading .* is not possible.
3944      static_cast<OverloadedOperatorKind>(0), OO_ArrowStar,
3945      OO_Star, OO_Slash, OO_Percent,
3946      OO_Plus, OO_Minus,
3947      OO_LessLess, OO_GreaterGreater,
3948      OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
3949      OO_EqualEqual, OO_ExclaimEqual,
3950      OO_Amp,
3951      OO_Caret,
3952      OO_Pipe,
3953      OO_AmpAmp,
3954      OO_PipePipe,
3955      OO_Equal, OO_StarEqual,
3956      OO_SlashEqual, OO_PercentEqual,
3957      OO_PlusEqual, OO_MinusEqual,
3958      OO_LessLessEqual, OO_GreaterGreaterEqual,
3959      OO_AmpEqual, OO_CaretEqual,
3960      OO_PipeEqual,
3961      OO_Comma
3962    };
3963    OverloadedOperatorKind OverOp = OverOps[Opc];
3964
3965    // Add the appropriate overloaded operators (C++ [over.match.oper])
3966    // to the candidate set.
3967    OverloadCandidateSet CandidateSet;
3968    Expr *Args[2] = { lhs, rhs };
3969    if (AddOperatorCandidates(OverOp, S, TokLoc, Args, 2, CandidateSet))
3970      return ExprError();
3971
3972    // Perform overload resolution.
3973    OverloadCandidateSet::iterator Best;
3974    switch (BestViableFunction(CandidateSet, Best)) {
3975    case OR_Success: {
3976      // We found a built-in operator or an overloaded operator.
3977      FunctionDecl *FnDecl = Best->Function;
3978
3979      if (FnDecl) {
3980        // We matched an overloaded operator. Build a call to that
3981        // operator.
3982
3983        // Convert the arguments.
3984        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
3985          if (PerformObjectArgumentInitialization(lhs, Method) ||
3986              PerformCopyInitialization(rhs, FnDecl->getParamDecl(0)->getType(),
3987                                        "passing"))
3988            return ExprError();
3989        } else {
3990          // Convert the arguments.
3991          if (PerformCopyInitialization(lhs, FnDecl->getParamDecl(0)->getType(),
3992                                        "passing") ||
3993              PerformCopyInitialization(rhs, FnDecl->getParamDecl(1)->getType(),
3994                                        "passing"))
3995            return ExprError();
3996        }
3997
3998        // Determine the result type
3999        QualType ResultTy
4000          = FnDecl->getType()->getAsFunctionType()->getResultType();
4001        ResultTy = ResultTy.getNonReferenceType();
4002
4003        // Build the actual expression node.
4004        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4005                                                 SourceLocation());
4006        UsualUnaryConversions(FnExpr);
4007
4008        return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, Args, 2,
4009                                                       ResultTy, TokLoc));
4010      } else {
4011        // We matched a built-in operator. Convert the arguments, then
4012        // break out so that we will build the appropriate built-in
4013        // operator node.
4014        if (PerformImplicitConversion(lhs, Best->BuiltinTypes.ParamTypes[0],
4015                                      Best->Conversions[0], "passing") ||
4016            PerformImplicitConversion(rhs, Best->BuiltinTypes.ParamTypes[1],
4017                                      Best->Conversions[1], "passing"))
4018          return ExprError();
4019
4020        break;
4021      }
4022    }
4023
4024    case OR_No_Viable_Function:
4025      // No viable function; fall through to handling this as a
4026      // built-in operator, which will produce an error message for us.
4027      break;
4028
4029    case OR_Ambiguous:
4030      Diag(TokLoc,  diag::err_ovl_ambiguous_oper)
4031          << BinaryOperator::getOpcodeStr(Opc)
4032          << lhs->getSourceRange() << rhs->getSourceRange();
4033      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4034      return ExprError();
4035
4036    case OR_Deleted:
4037      Diag(TokLoc, diag::err_ovl_deleted_oper)
4038        << Best->Function->isDeleted()
4039        << BinaryOperator::getOpcodeStr(Opc)
4040        << lhs->getSourceRange() << rhs->getSourceRange();
4041      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4042      return ExprError();
4043    }
4044
4045    // Either we found no viable overloaded operator or we matched a
4046    // built-in operator. In either case, fall through to trying to
4047    // build a built-in operation.
4048  }
4049
4050  // Build a built-in binary operation.
4051  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
4052}
4053
4054// Unary Operators.  'Tok' is the token for the operator.
4055Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
4056                                            tok::TokenKind Op, ExprArg input) {
4057  // FIXME: Input is modified later, but smart pointer not reassigned.
4058  Expr *Input = (Expr*)input.get();
4059  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
4060
4061  if (getLangOptions().CPlusPlus &&
4062      (Input->getType()->isRecordType()
4063       || Input->getType()->isEnumeralType())) {
4064    // Determine which overloaded operator we're dealing with.
4065    static const OverloadedOperatorKind OverOps[] = {
4066      OO_None, OO_None,
4067      OO_PlusPlus, OO_MinusMinus,
4068      OO_Amp, OO_Star,
4069      OO_Plus, OO_Minus,
4070      OO_Tilde, OO_Exclaim,
4071      OO_None, OO_None,
4072      OO_None,
4073      OO_None
4074    };
4075    OverloadedOperatorKind OverOp = OverOps[Opc];
4076
4077    // Add the appropriate overloaded operators (C++ [over.match.oper])
4078    // to the candidate set.
4079    OverloadCandidateSet CandidateSet;
4080    if (OverOp != OO_None &&
4081        AddOperatorCandidates(OverOp, S, OpLoc, &Input, 1, CandidateSet))
4082      return ExprError();
4083
4084    // Perform overload resolution.
4085    OverloadCandidateSet::iterator Best;
4086    switch (BestViableFunction(CandidateSet, Best)) {
4087    case OR_Success: {
4088      // We found a built-in operator or an overloaded operator.
4089      FunctionDecl *FnDecl = Best->Function;
4090
4091      if (FnDecl) {
4092        // We matched an overloaded operator. Build a call to that
4093        // operator.
4094
4095        // Convert the arguments.
4096        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4097          if (PerformObjectArgumentInitialization(Input, Method))
4098            return ExprError();
4099        } else {
4100          // Convert the arguments.
4101          if (PerformCopyInitialization(Input,
4102                                        FnDecl->getParamDecl(0)->getType(),
4103                                        "passing"))
4104            return ExprError();
4105        }
4106
4107        // Determine the result type
4108        QualType ResultTy
4109          = FnDecl->getType()->getAsFunctionType()->getResultType();
4110        ResultTy = ResultTy.getNonReferenceType();
4111
4112        // Build the actual expression node.
4113        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4114                                                 SourceLocation());
4115        UsualUnaryConversions(FnExpr);
4116
4117        input.release();
4118        return Owned(new (Context) CXXOperatorCallExpr(Context, FnExpr, &Input,
4119                                                       1, ResultTy, OpLoc));
4120      } else {
4121        // We matched a built-in operator. Convert the arguments, then
4122        // break out so that we will build the appropriate built-in
4123        // operator node.
4124        if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4125                                      Best->Conversions[0], "passing"))
4126          return ExprError();
4127
4128        break;
4129      }
4130    }
4131
4132    case OR_No_Viable_Function:
4133      // No viable function; fall through to handling this as a
4134      // built-in operator, which will produce an error message for us.
4135      break;
4136
4137    case OR_Ambiguous:
4138      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
4139          << UnaryOperator::getOpcodeStr(Opc)
4140          << Input->getSourceRange();
4141      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4142      return ExprError();
4143
4144    case OR_Deleted:
4145      Diag(OpLoc, diag::err_ovl_deleted_oper)
4146        << Best->Function->isDeleted()
4147        << UnaryOperator::getOpcodeStr(Opc)
4148        << Input->getSourceRange();
4149      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4150      return ExprError();
4151    }
4152
4153    // Either we found no viable overloaded operator or we matched a
4154    // built-in operator. In either case, fall through to trying to
4155    // build a built-in operation.
4156  }
4157
4158  QualType resultType;
4159  switch (Opc) {
4160  default:
4161    assert(0 && "Unimplemented unary expr!");
4162  case UnaryOperator::PreInc:
4163  case UnaryOperator::PreDec:
4164    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
4165                                                Opc == UnaryOperator::PreInc);
4166    break;
4167  case UnaryOperator::AddrOf:
4168    resultType = CheckAddressOfOperand(Input, OpLoc);
4169    break;
4170  case UnaryOperator::Deref:
4171    DefaultFunctionArrayConversion(Input);
4172    resultType = CheckIndirectionOperand(Input, OpLoc);
4173    break;
4174  case UnaryOperator::Plus:
4175  case UnaryOperator::Minus:
4176    UsualUnaryConversions(Input);
4177    resultType = Input->getType();
4178    if (resultType->isDependentType())
4179      break;
4180    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
4181      break;
4182    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
4183             resultType->isEnumeralType())
4184      break;
4185    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
4186             Opc == UnaryOperator::Plus &&
4187             resultType->isPointerType())
4188      break;
4189
4190    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4191      << resultType << Input->getSourceRange());
4192  case UnaryOperator::Not: // bitwise complement
4193    UsualUnaryConversions(Input);
4194    resultType = Input->getType();
4195    if (resultType->isDependentType())
4196      break;
4197    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
4198    if (resultType->isComplexType() || resultType->isComplexIntegerType())
4199      // C99 does not support '~' for complex conjugation.
4200      Diag(OpLoc, diag::ext_integer_complement_complex)
4201        << resultType << Input->getSourceRange();
4202    else if (!resultType->isIntegerType())
4203      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4204        << resultType << Input->getSourceRange());
4205    break;
4206  case UnaryOperator::LNot: // logical negation
4207    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
4208    DefaultFunctionArrayConversion(Input);
4209    resultType = Input->getType();
4210    if (resultType->isDependentType())
4211      break;
4212    if (!resultType->isScalarType()) // C99 6.5.3.3p1
4213      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
4214        << resultType << Input->getSourceRange());
4215    // LNot always has type int. C99 6.5.3.3p5.
4216    // In C++, it's bool. C++ 5.3.1p8
4217    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
4218    break;
4219  case UnaryOperator::Real:
4220  case UnaryOperator::Imag:
4221    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
4222    break;
4223  case UnaryOperator::Extension:
4224    resultType = Input->getType();
4225    break;
4226  }
4227  if (resultType.isNull())
4228    return ExprError();
4229  input.release();
4230  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
4231}
4232
4233/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
4234Sema::ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
4235                                      SourceLocation LabLoc,
4236                                      IdentifierInfo *LabelII) {
4237  // Look up the record for this label identifier.
4238  llvm::DenseMap<IdentifierInfo*, Action::StmtTy*>::iterator I =
4239    ActiveScope->LabelMap.find(LabelII);
4240
4241  LabelStmt *LabelDecl;
4242
4243  // If we haven't seen this label yet, create a forward reference. It
4244  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
4245  if (I == ActiveScope->LabelMap.end()) {
4246    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
4247
4248    ActiveScope->LabelMap.insert(std::make_pair(LabelII, LabelDecl));
4249  } else
4250    LabelDecl = static_cast<LabelStmt *>(I->second);
4251
4252  // Create the AST node.  The address of a label always has type 'void*'.
4253  return new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
4254                                     Context.getPointerType(Context.VoidTy));
4255}
4256
4257Sema::ExprResult Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtTy *substmt,
4258                                     SourceLocation RPLoc) { // "({..})"
4259  Stmt *SubStmt = static_cast<Stmt*>(substmt);
4260  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
4261  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
4262
4263  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
4264  if (isFileScope) {
4265    return Diag(LPLoc, diag::err_stmtexpr_file_scope);
4266  }
4267
4268  // FIXME: there are a variety of strange constraints to enforce here, for
4269  // example, it is not possible to goto into a stmt expression apparently.
4270  // More semantic analysis is needed.
4271
4272  // FIXME: the last statement in the compount stmt has its value used.  We
4273  // should not warn about it being unused.
4274
4275  // If there are sub stmts in the compound stmt, take the type of the last one
4276  // as the type of the stmtexpr.
4277  QualType Ty = Context.VoidTy;
4278
4279  if (!Compound->body_empty()) {
4280    Stmt *LastStmt = Compound->body_back();
4281    // If LastStmt is a label, skip down through into the body.
4282    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
4283      LastStmt = Label->getSubStmt();
4284
4285    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
4286      Ty = LastExpr->getType();
4287  }
4288
4289  return new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
4290}
4291
4292Sema::ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
4293                                            SourceLocation BuiltinLoc,
4294                                            SourceLocation TypeLoc,
4295                                            TypeTy *argty,
4296                                            OffsetOfComponent *CompPtr,
4297                                            unsigned NumComponents,
4298                                            SourceLocation RPLoc) {
4299  QualType ArgTy = QualType::getFromOpaquePtr(argty);
4300  assert(!ArgTy.isNull() && "Missing type argument!");
4301
4302  bool Dependent = ArgTy->isDependentType();
4303
4304  // We must have at least one component that refers to the type, and the first
4305  // one is known to be a field designator.  Verify that the ArgTy represents
4306  // a struct/union/class.
4307  if (!Dependent && !ArgTy->isRecordType())
4308    return Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy;
4309
4310  // Otherwise, create a null pointer as the base, and iteratively process
4311  // the offsetof designators.
4312  QualType ArgTyPtr = Context.getPointerType(ArgTy);
4313  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
4314  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
4315                                    ArgTy, SourceLocation());
4316
4317  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
4318  // GCC extension, diagnose them.
4319  // FIXME: This diagnostic isn't actually visible because the location is in
4320  // a system header!
4321  if (NumComponents != 1)
4322    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
4323      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
4324
4325  if (!Dependent) {
4326    // FIXME: Dependent case loses a lot of information here. And probably
4327    // leaks like a sieve.
4328    for (unsigned i = 0; i != NumComponents; ++i) {
4329      const OffsetOfComponent &OC = CompPtr[i];
4330      if (OC.isBrackets) {
4331        // Offset of an array sub-field.  TODO: Should we allow vector elements?
4332        const ArrayType *AT = Context.getAsArrayType(Res->getType());
4333        if (!AT) {
4334          Res->Destroy(Context);
4335          return Diag(OC.LocEnd, diag::err_offsetof_array_type)
4336            << Res->getType();
4337        }
4338
4339        // FIXME: C++: Verify that operator[] isn't overloaded.
4340
4341        // Promote the array so it looks more like a normal array subscript
4342        // expression.
4343        DefaultFunctionArrayConversion(Res);
4344
4345        // C99 6.5.2.1p1
4346        Expr *Idx = static_cast<Expr*>(OC.U.E);
4347        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
4348          return Diag(Idx->getLocStart(), diag::err_typecheck_subscript)
4349            << Idx->getSourceRange();
4350
4351        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
4352                                               OC.LocEnd);
4353        continue;
4354      }
4355
4356      const RecordType *RC = Res->getType()->getAsRecordType();
4357      if (!RC) {
4358        Res->Destroy(Context);
4359        return Diag(OC.LocEnd, diag::err_offsetof_record_type)
4360          << Res->getType();
4361      }
4362
4363      // Get the decl corresponding to this.
4364      RecordDecl *RD = RC->getDecl();
4365      FieldDecl *MemberDecl
4366        = dyn_cast_or_null<FieldDecl>(LookupQualifiedName(RD, OC.U.IdentInfo,
4367                                                          LookupMemberName)
4368                                        .getAsDecl());
4369      if (!MemberDecl)
4370        return Diag(BuiltinLoc, diag::err_typecheck_no_member)
4371         << OC.U.IdentInfo << SourceRange(OC.LocStart, OC.LocEnd);
4372
4373      // FIXME: C++: Verify that MemberDecl isn't a static field.
4374      // FIXME: Verify that MemberDecl isn't a bitfield.
4375      // MemberDecl->getType() doesn't get the right qualifiers, but it doesn't
4376      // matter here.
4377      Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
4378                                   MemberDecl->getType().getNonReferenceType());
4379    }
4380  }
4381
4382  return new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
4383                                     Context.getSizeType(), BuiltinLoc);
4384}
4385
4386
4387Sema::ExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
4388                                                TypeTy *arg1, TypeTy *arg2,
4389                                                SourceLocation RPLoc) {
4390  QualType argT1 = QualType::getFromOpaquePtr(arg1);
4391  QualType argT2 = QualType::getFromOpaquePtr(arg2);
4392
4393  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
4394
4395  return new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc, argT1,
4396                                           argT2, RPLoc);
4397}
4398
4399Sema::ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc, ExprTy *cond,
4400                                       ExprTy *expr1, ExprTy *expr2,
4401                                       SourceLocation RPLoc) {
4402  Expr *CondExpr = static_cast<Expr*>(cond);
4403  Expr *LHSExpr = static_cast<Expr*>(expr1);
4404  Expr *RHSExpr = static_cast<Expr*>(expr2);
4405
4406  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
4407
4408  QualType resType;
4409  if (CondExpr->isValueDependent()) {
4410    resType = Context.DependentTy;
4411  } else {
4412    // The conditional expression is required to be a constant expression.
4413    llvm::APSInt condEval(32);
4414    SourceLocation ExpLoc;
4415    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
4416      return Diag(ExpLoc, diag::err_typecheck_choose_expr_requires_constant)
4417        << CondExpr->getSourceRange();
4418
4419    // If the condition is > zero, then the AST type is the same as the LSHExpr.
4420    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
4421  }
4422
4423  return new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
4424                                  resType, RPLoc);
4425}
4426
4427//===----------------------------------------------------------------------===//
4428// Clang Extensions.
4429//===----------------------------------------------------------------------===//
4430
4431/// ActOnBlockStart - This callback is invoked when a block literal is started.
4432void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
4433  // Analyze block parameters.
4434  BlockSemaInfo *BSI = new BlockSemaInfo();
4435
4436  // Add BSI to CurBlock.
4437  BSI->PrevBlockInfo = CurBlock;
4438  CurBlock = BSI;
4439  ActiveScope = BlockScope;
4440
4441  BSI->ReturnType = 0;
4442  BSI->TheScope = BlockScope;
4443  BSI->hasBlockDeclRefExprs = false;
4444
4445  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
4446  PushDeclContext(BlockScope, BSI->TheDecl);
4447}
4448
4449void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
4450  assert(ParamInfo.getIdentifier() == 0 && "block-id should have no identifier!");
4451
4452  if (ParamInfo.getNumTypeObjects() == 0
4453      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
4454    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
4455
4456    // The type is entirely optional as well, if none, use DependentTy.
4457    if (T.isNull())
4458      T = Context.DependentTy;
4459
4460    // The parameter list is optional, if there was none, assume ().
4461    if (!T->isFunctionType())
4462      T = Context.getFunctionType(T, NULL, 0, 0, 0);
4463
4464    CurBlock->hasPrototype = true;
4465    CurBlock->isVariadic = false;
4466    Type *RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4467      .getTypePtr();
4468
4469    if (!RetTy->isDependentType())
4470      CurBlock->ReturnType = RetTy;
4471    return;
4472  }
4473
4474  // Analyze arguments to block.
4475  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
4476         "Not a function declarator!");
4477  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
4478
4479  CurBlock->hasPrototype = FTI.hasPrototype;
4480  CurBlock->isVariadic = true;
4481
4482  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
4483  // no arguments, not a function that takes a single void argument.
4484  if (FTI.hasPrototype &&
4485      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
4486      (!((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType().getCVRQualifiers() &&
4487        ((ParmVarDecl *)FTI.ArgInfo[0].Param)->getType()->isVoidType())) {
4488    // empty arg list, don't push any params.
4489    CurBlock->isVariadic = false;
4490  } else if (FTI.hasPrototype) {
4491    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
4492      CurBlock->Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
4493    CurBlock->isVariadic = FTI.isVariadic;
4494    QualType T = GetTypeForDeclarator (ParamInfo, CurScope);
4495
4496    Type* RetTy = T.getTypePtr()->getAsFunctionType()->getResultType()
4497      .getTypePtr();
4498
4499    if (!RetTy->isDependentType())
4500      CurBlock->ReturnType = RetTy;
4501  }
4502  CurBlock->TheDecl->setArgs(&CurBlock->Params[0], CurBlock->Params.size());
4503
4504  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
4505       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
4506    // If this has an identifier, add it to the scope stack.
4507    if ((*AI)->getIdentifier())
4508      PushOnScopeChains(*AI, CurBlock->TheScope);
4509}
4510
4511/// ActOnBlockError - If there is an error parsing a block, this callback
4512/// is invoked to pop the information about the block from the action impl.
4513void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
4514  // Ensure that CurBlock is deleted.
4515  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
4516
4517  // Pop off CurBlock, handle nested blocks.
4518  CurBlock = CurBlock->PrevBlockInfo;
4519
4520  // FIXME: Delete the ParmVarDecl objects as well???
4521
4522}
4523
4524/// ActOnBlockStmtExpr - This is called when the body of a block statement
4525/// literal was successfully completed.  ^(int x){...}
4526Sema::ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc, StmtTy *body,
4527                                          Scope *CurScope) {
4528  // Ensure that CurBlock is deleted.
4529  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
4530  ExprOwningPtr<CompoundStmt> Body(this, static_cast<CompoundStmt*>(body));
4531
4532  PopDeclContext();
4533
4534  // Before poping CurBlock, set ActiveScope to this scopes parent.
4535  ActiveScope = CurBlock->TheScope->getParent();
4536
4537  // Pop off CurBlock, handle nested blocks.
4538  CurBlock = CurBlock->PrevBlockInfo;
4539
4540  QualType RetTy = Context.VoidTy;
4541  if (BSI->ReturnType)
4542    RetTy = QualType(BSI->ReturnType, 0);
4543
4544  llvm::SmallVector<QualType, 8> ArgTypes;
4545  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
4546    ArgTypes.push_back(BSI->Params[i]->getType());
4547
4548  QualType BlockTy;
4549  if (!BSI->hasPrototype)
4550    BlockTy = Context.getFunctionNoProtoType(RetTy);
4551  else
4552    BlockTy = Context.getFunctionType(RetTy, &ArgTypes[0], ArgTypes.size(),
4553                                      BSI->isVariadic, 0);
4554
4555  BlockTy = Context.getBlockPointerType(BlockTy);
4556
4557  BSI->TheDecl->setBody(Body.take());
4558  return new (Context) BlockExpr(BSI->TheDecl, BlockTy, BSI->hasBlockDeclRefExprs);
4559}
4560
4561Sema::ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
4562                                  ExprTy *expr, TypeTy *type,
4563                                  SourceLocation RPLoc) {
4564  Expr *E = static_cast<Expr*>(expr);
4565  QualType T = QualType::getFromOpaquePtr(type);
4566
4567  InitBuiltinVaListType();
4568
4569  // Get the va_list type
4570  QualType VaListType = Context.getBuiltinVaListType();
4571  // Deal with implicit array decay; for example, on x86-64,
4572  // va_list is an array, but it's supposed to decay to
4573  // a pointer for va_arg.
4574  if (VaListType->isArrayType())
4575    VaListType = Context.getArrayDecayedType(VaListType);
4576  // Make sure the input expression also decays appropriately.
4577  UsualUnaryConversions(E);
4578
4579  if (CheckAssignmentConstraints(VaListType, E->getType()) != Compatible)
4580    return Diag(E->getLocStart(),
4581                diag::err_first_argument_to_va_arg_not_of_type_va_list)
4582      << E->getType() << E->getSourceRange();
4583
4584  // FIXME: Warn if a non-POD type is passed in.
4585
4586  return new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(), RPLoc);
4587}
4588
4589Sema::ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
4590  // The type of __null will be int or long, depending on the size of
4591  // pointers on the target.
4592  QualType Ty;
4593  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
4594    Ty = Context.IntTy;
4595  else
4596    Ty = Context.LongTy;
4597
4598  return new (Context) GNUNullExpr(Ty, TokenLoc);
4599}
4600
4601bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
4602                                    SourceLocation Loc,
4603                                    QualType DstType, QualType SrcType,
4604                                    Expr *SrcExpr, const char *Flavor) {
4605  // Decode the result (notice that AST's are still created for extensions).
4606  bool isInvalid = false;
4607  unsigned DiagKind;
4608  switch (ConvTy) {
4609  default: assert(0 && "Unknown conversion type");
4610  case Compatible: return false;
4611  case PointerToInt:
4612    DiagKind = diag::ext_typecheck_convert_pointer_int;
4613    break;
4614  case IntToPointer:
4615    DiagKind = diag::ext_typecheck_convert_int_pointer;
4616    break;
4617  case IncompatiblePointer:
4618    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
4619    break;
4620  case FunctionVoidPointer:
4621    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
4622    break;
4623  case CompatiblePointerDiscardsQualifiers:
4624    // If the qualifiers lost were because we were applying the
4625    // (deprecated) C++ conversion from a string literal to a char*
4626    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
4627    // Ideally, this check would be performed in
4628    // CheckPointerTypesForAssignment. However, that would require a
4629    // bit of refactoring (so that the second argument is an
4630    // expression, rather than a type), which should be done as part
4631    // of a larger effort to fix CheckPointerTypesForAssignment for
4632    // C++ semantics.
4633    if (getLangOptions().CPlusPlus &&
4634        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
4635      return false;
4636    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
4637    break;
4638  case IntToBlockPointer:
4639    DiagKind = diag::err_int_to_block_pointer;
4640    break;
4641  case IncompatibleBlockPointer:
4642    DiagKind = diag::ext_typecheck_convert_incompatible_block_pointer;
4643    break;
4644  case IncompatibleObjCQualifiedId:
4645    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
4646    // it can give a more specific diagnostic.
4647    DiagKind = diag::warn_incompatible_qualified_id;
4648    break;
4649  case IncompatibleVectors:
4650    DiagKind = diag::warn_incompatible_vectors;
4651    break;
4652  case Incompatible:
4653    DiagKind = diag::err_typecheck_convert_incompatible;
4654    isInvalid = true;
4655    break;
4656  }
4657
4658  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
4659    << SrcExpr->getSourceRange();
4660  return isInvalid;
4661}
4662
4663bool Sema::VerifyIntegerConstantExpression(const Expr* E, llvm::APSInt *Result)
4664{
4665  Expr::EvalResult EvalResult;
4666
4667  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
4668      EvalResult.HasSideEffects) {
4669    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
4670
4671    if (EvalResult.Diag) {
4672      // We only show the note if it's not the usual "invalid subexpression"
4673      // or if it's actually in a subexpression.
4674      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
4675          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
4676        Diag(EvalResult.DiagLoc, EvalResult.Diag);
4677    }
4678
4679    return true;
4680  }
4681
4682  if (EvalResult.Diag) {
4683    Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
4684      E->getSourceRange();
4685
4686    // Print the reason it's not a constant.
4687    if (Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
4688      Diag(EvalResult.DiagLoc, EvalResult.Diag);
4689  }
4690
4691  if (Result)
4692    *Result = EvalResult.Val.getInt();
4693  return false;
4694}
4695