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