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