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