SemaExpr.cpp revision 8d6d90d5499d4248761251811ebed0ae77665ed7
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/DeclTemplate.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Basic/PartialDiagnostic.h"
21#include "clang/Basic/SourceManager.h"
22#include "clang/Basic/TargetInfo.h"
23#include "clang/Lex/LiteralSupport.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Parse/DeclSpec.h"
26#include "clang/Parse/Designator.h"
27#include "clang/Parse/Scope.h"
28using namespace clang;
29
30
31/// \brief Determine whether the use of this declaration is valid, and
32/// emit any corresponding diagnostics.
33///
34/// This routine diagnoses various problems with referencing
35/// declarations that can occur when using a declaration. For example,
36/// it might warn if a deprecated or unavailable declaration is being
37/// used, or produce an error (and return true) if a C++0x deleted
38/// function is being used.
39///
40/// \returns true if there was an error (this declaration cannot be
41/// referenced), false otherwise.
42bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
43  // See if the decl is deprecated.
44  if (D->getAttr<DeprecatedAttr>()) {
45    // Implementing deprecated stuff requires referencing deprecated
46    // stuff. Don't warn if we are implementing a deprecated
47    // construct.
48    bool isSilenced = false;
49
50    if (NamedDecl *ND = getCurFunctionOrMethodDecl()) {
51      // If this reference happens *in* a deprecated function or method, don't
52      // warn.
53      isSilenced = ND->getAttr<DeprecatedAttr>();
54
55      // If this is an Objective-C method implementation, check to see if the
56      // method was deprecated on the declaration, not the definition.
57      if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(ND)) {
58        // The semantic decl context of a ObjCMethodDecl is the
59        // ObjCImplementationDecl.
60        if (ObjCImplementationDecl *Impl
61              = dyn_cast<ObjCImplementationDecl>(MD->getParent())) {
62
63          MD = Impl->getClassInterface()->getMethod(MD->getSelector(),
64                                                    MD->isInstanceMethod());
65          isSilenced |= MD && MD->getAttr<DeprecatedAttr>();
66        }
67      }
68    }
69
70    if (!isSilenced)
71      Diag(Loc, diag::warn_deprecated) << D->getDeclName();
72  }
73
74  // See if this is a deleted function.
75  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
76    if (FD->isDeleted()) {
77      Diag(Loc, diag::err_deleted_function_use);
78      Diag(D->getLocation(), diag::note_unavailable_here) << true;
79      return true;
80    }
81  }
82
83  // See if the decl is unavailable
84  if (D->getAttr<UnavailableAttr>()) {
85    Diag(Loc, diag::warn_unavailable) << D->getDeclName();
86    Diag(D->getLocation(), diag::note_unavailable_here) << 0;
87  }
88
89  return false;
90}
91
92/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
93/// (and other functions in future), which have been declared with sentinel
94/// attribute. It warns if call does not have the sentinel argument.
95///
96void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
97                                 Expr **Args, unsigned NumArgs) {
98  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
99  if (!attr)
100    return;
101  int sentinelPos = attr->getSentinel();
102  int nullPos = attr->getNullPos();
103
104  // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
105  // base class. Then we won't be needing two versions of the same code.
106  unsigned int i = 0;
107  bool warnNotEnoughArgs = false;
108  int isMethod = 0;
109  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
110    // skip over named parameters.
111    ObjCMethodDecl::param_iterator P, E = MD->param_end();
112    for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
113      if (nullPos)
114        --nullPos;
115      else
116        ++i;
117    }
118    warnNotEnoughArgs = (P != E || i >= NumArgs);
119    isMethod = 1;
120  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
121    // skip over named parameters.
122    ObjCMethodDecl::param_iterator P, E = FD->param_end();
123    for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
124      if (nullPos)
125        --nullPos;
126      else
127        ++i;
128    }
129    warnNotEnoughArgs = (P != E || i >= NumArgs);
130  } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
131    // block or function pointer call.
132    QualType Ty = V->getType();
133    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
134      const FunctionType *FT = Ty->isFunctionPointerType()
135      ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
136      : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
137      if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
138        unsigned NumArgsInProto = Proto->getNumArgs();
139        unsigned k;
140        for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
141          if (nullPos)
142            --nullPos;
143          else
144            ++i;
145        }
146        warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
147      }
148      if (Ty->isBlockPointerType())
149        isMethod = 2;
150    } else
151      return;
152  } else
153    return;
154
155  if (warnNotEnoughArgs) {
156    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
157    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
158    return;
159  }
160  int sentinel = i;
161  while (sentinelPos > 0 && i < NumArgs-1) {
162    --sentinelPos;
163    ++i;
164  }
165  if (sentinelPos > 0) {
166    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
167    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
168    return;
169  }
170  while (i < NumArgs-1) {
171    ++i;
172    ++sentinel;
173  }
174  Expr *sentinelExpr = Args[sentinel];
175  if (sentinelExpr && (!sentinelExpr->getType()->isPointerType() ||
176                       !sentinelExpr->isNullPointerConstant(Context,
177                                            Expr::NPC_ValueDependentIsNull))) {
178    Diag(Loc, diag::warn_missing_sentinel) << isMethod;
179    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
180  }
181  return;
182}
183
184SourceRange Sema::getExprRange(ExprTy *E) const {
185  Expr *Ex = (Expr *)E;
186  return Ex? Ex->getSourceRange() : SourceRange();
187}
188
189//===----------------------------------------------------------------------===//
190//  Standard Promotions and Conversions
191//===----------------------------------------------------------------------===//
192
193/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
194void Sema::DefaultFunctionArrayConversion(Expr *&E) {
195  QualType Ty = E->getType();
196  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
197
198  if (Ty->isFunctionType())
199    ImpCastExprToType(E, Context.getPointerType(Ty),
200                      CastExpr::CK_FunctionToPointerDecay);
201  else if (Ty->isArrayType()) {
202    // In C90 mode, arrays only promote to pointers if the array expression is
203    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
204    // type 'array of type' is converted to an expression that has type 'pointer
205    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
206    // that has type 'array of type' ...".  The relevant change is "an lvalue"
207    // (C90) to "an expression" (C99).
208    //
209    // C++ 4.2p1:
210    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
211    // T" can be converted to an rvalue of type "pointer to T".
212    //
213    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
214        E->isLvalue(Context) == Expr::LV_Valid)
215      ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
216                        CastExpr::CK_ArrayToPointerDecay);
217  }
218}
219
220/// UsualUnaryConversions - Performs various conversions that are common to most
221/// operators (C99 6.3). The conversions of array and function types are
222/// sometimes surpressed. For example, the array->pointer conversion doesn't
223/// apply if the array is an argument to the sizeof or address (&) operators.
224/// In these instances, this routine should *not* be called.
225Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
226  QualType Ty = Expr->getType();
227  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
228
229  // C99 6.3.1.1p2:
230  //
231  //   The following may be used in an expression wherever an int or
232  //   unsigned int may be used:
233  //     - an object or expression with an integer type whose integer
234  //       conversion rank is less than or equal to the rank of int
235  //       and unsigned int.
236  //     - A bit-field of type _Bool, int, signed int, or unsigned int.
237  //
238  //   If an int can represent all values of the original type, the
239  //   value is converted to an int; otherwise, it is converted to an
240  //   unsigned int. These are called the integer promotions. All
241  //   other types are unchanged by the integer promotions.
242  QualType PTy = Context.isPromotableBitField(Expr);
243  if (!PTy.isNull()) {
244    ImpCastExprToType(Expr, PTy);
245    return Expr;
246  }
247  if (Ty->isPromotableIntegerType()) {
248    QualType PT = Context.getPromotedIntegerType(Ty);
249    ImpCastExprToType(Expr, PT);
250    return Expr;
251  }
252
253  DefaultFunctionArrayConversion(Expr);
254  return Expr;
255}
256
257/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
258/// do not have a prototype. Arguments that have type float are promoted to
259/// double. All other argument types are converted by UsualUnaryConversions().
260void Sema::DefaultArgumentPromotion(Expr *&Expr) {
261  QualType Ty = Expr->getType();
262  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
263
264  // If this is a 'float' (CVR qualified or typedef) promote to double.
265  if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
266    if (BT->getKind() == BuiltinType::Float)
267      return ImpCastExprToType(Expr, Context.DoubleTy);
268
269  UsualUnaryConversions(Expr);
270}
271
272/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
273/// will warn if the resulting type is not a POD type, and rejects ObjC
274/// interfaces passed by value.  This returns true if the argument type is
275/// completely illegal.
276bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT) {
277  DefaultArgumentPromotion(Expr);
278
279  if (Expr->getType()->isObjCInterfaceType()) {
280    Diag(Expr->getLocStart(),
281         diag::err_cannot_pass_objc_interface_to_vararg)
282      << Expr->getType() << CT;
283    return true;
284  }
285
286  if (!Expr->getType()->isPODType())
287    Diag(Expr->getLocStart(), diag::warn_cannot_pass_non_pod_arg_to_vararg)
288      << Expr->getType() << CT;
289
290  return false;
291}
292
293
294/// UsualArithmeticConversions - Performs various conversions that are common to
295/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
296/// routine returns the first non-arithmetic type found. The client is
297/// responsible for emitting appropriate error diagnostics.
298/// FIXME: verify the conversion rules for "complex int" are consistent with
299/// GCC.
300QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
301                                          bool isCompAssign) {
302  if (!isCompAssign)
303    UsualUnaryConversions(lhsExpr);
304
305  UsualUnaryConversions(rhsExpr);
306
307  // For conversion purposes, we ignore any qualifiers.
308  // For example, "const float" and "float" are equivalent.
309  QualType lhs =
310    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
311  QualType rhs =
312    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
313
314  // If both types are identical, no conversion is needed.
315  if (lhs == rhs)
316    return lhs;
317
318  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
319  // The caller can deal with this (e.g. pointer + int).
320  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
321    return lhs;
322
323  // Perform bitfield promotions.
324  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
325  if (!LHSBitfieldPromoteTy.isNull())
326    lhs = LHSBitfieldPromoteTy;
327  QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
328  if (!RHSBitfieldPromoteTy.isNull())
329    rhs = RHSBitfieldPromoteTy;
330
331  QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
332  if (!isCompAssign)
333    ImpCastExprToType(lhsExpr, destType);
334  ImpCastExprToType(rhsExpr, destType);
335  return destType;
336}
337
338//===----------------------------------------------------------------------===//
339//  Semantic Analysis for various Expression Types
340//===----------------------------------------------------------------------===//
341
342
343/// ActOnStringLiteral - The specified tokens were lexed as pasted string
344/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
345/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
346/// multiple tokens.  However, the common case is that StringToks points to one
347/// string.
348///
349Action::OwningExprResult
350Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
351  assert(NumStringToks && "Must have at least one string!");
352
353  StringLiteralParser Literal(StringToks, NumStringToks, PP);
354  if (Literal.hadError)
355    return ExprError();
356
357  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
358  for (unsigned i = 0; i != NumStringToks; ++i)
359    StringTokLocs.push_back(StringToks[i].getLocation());
360
361  QualType StrTy = Context.CharTy;
362  if (Literal.AnyWide) StrTy = Context.getWCharType();
363  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
364
365  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
366  if (getLangOptions().CPlusPlus)
367    StrTy.addConst();
368
369  // Get an array type for the string, according to C99 6.4.5.  This includes
370  // the nul terminator character as well as the string length for pascal
371  // strings.
372  StrTy = Context.getConstantArrayType(StrTy,
373                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
374                                       ArrayType::Normal, 0);
375
376  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
377  return Owned(StringLiteral::Create(Context, Literal.GetString(),
378                                     Literal.GetStringLength(),
379                                     Literal.AnyWide, StrTy,
380                                     &StringTokLocs[0],
381                                     StringTokLocs.size()));
382}
383
384/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
385/// CurBlock to VD should cause it to be snapshotted (as we do for auto
386/// variables defined outside the block) or false if this is not needed (e.g.
387/// for values inside the block or for globals).
388///
389/// This also keeps the 'hasBlockDeclRefExprs' in the BlockSemaInfo records
390/// up-to-date.
391///
392static bool ShouldSnapshotBlockValueReference(BlockSemaInfo *CurBlock,
393                                              ValueDecl *VD) {
394  // If the value is defined inside the block, we couldn't snapshot it even if
395  // we wanted to.
396  if (CurBlock->TheDecl == VD->getDeclContext())
397    return false;
398
399  // If this is an enum constant or function, it is constant, don't snapshot.
400  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
401    return false;
402
403  // If this is a reference to an extern, static, or global variable, no need to
404  // snapshot it.
405  // FIXME: What about 'const' variables in C++?
406  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
407    if (!Var->hasLocalStorage())
408      return false;
409
410  // Blocks that have these can't be constant.
411  CurBlock->hasBlockDeclRefExprs = true;
412
413  // If we have nested blocks, the decl may be declared in an outer block (in
414  // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
415  // be defined outside all of the current blocks (in which case the blocks do
416  // all get the bit).  Walk the nesting chain.
417  for (BlockSemaInfo *NextBlock = CurBlock->PrevBlockInfo; NextBlock;
418       NextBlock = NextBlock->PrevBlockInfo) {
419    // If we found the defining block for the variable, don't mark the block as
420    // having a reference outside it.
421    if (NextBlock->TheDecl == VD->getDeclContext())
422      break;
423
424    // Otherwise, the DeclRef from the inner block causes the outer one to need
425    // a snapshot as well.
426    NextBlock->hasBlockDeclRefExprs = true;
427  }
428
429  return true;
430}
431
432
433
434/// ActOnIdentifierExpr - The parser read an identifier in expression context,
435/// validate it per-C99 6.5.1.  HasTrailingLParen indicates whether this
436/// identifier is used in a function call context.
437/// SS is only used for a C++ qualified-id (foo::bar) to indicate the
438/// class or namespace that the identifier must be a member of.
439Sema::OwningExprResult Sema::ActOnIdentifierExpr(Scope *S, SourceLocation Loc,
440                                                 IdentifierInfo &II,
441                                                 bool HasTrailingLParen,
442                                                 const CXXScopeSpec *SS,
443                                                 bool isAddressOfOperand) {
444  return ActOnDeclarationNameExpr(S, Loc, &II, HasTrailingLParen, SS,
445                                  isAddressOfOperand);
446}
447
448/// BuildDeclRefExpr - Build either a DeclRefExpr or a
449/// QualifiedDeclRefExpr based on whether or not SS is a
450/// nested-name-specifier.
451Sema::OwningExprResult
452Sema::BuildDeclRefExpr(NamedDecl *D, QualType Ty, SourceLocation Loc,
453                       bool TypeDependent, bool ValueDependent,
454                       const CXXScopeSpec *SS) {
455  if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
456    Diag(Loc,
457         diag::err_auto_variable_cannot_appear_in_own_initializer)
458      << D->getDeclName();
459    return ExprError();
460  }
461
462  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
463    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
464      if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
465        if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
466          Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
467            << D->getIdentifier() << FD->getDeclName();
468          Diag(D->getLocation(), diag::note_local_variable_declared_here)
469            << D->getIdentifier();
470          return ExprError();
471        }
472      }
473    }
474  }
475
476  MarkDeclarationReferenced(Loc, D);
477
478  Expr *E;
479  if (SS && !SS->isEmpty()) {
480    E = new (Context) QualifiedDeclRefExpr(D, Ty, Loc, TypeDependent,
481                                          ValueDependent, SS->getRange(),
482                  static_cast<NestedNameSpecifier *>(SS->getScopeRep()));
483  } else
484    E = new (Context) DeclRefExpr(D, Ty, Loc, TypeDependent, ValueDependent);
485
486  return Owned(E);
487}
488
489/// getObjectForAnonymousRecordDecl - Retrieve the (unnamed) field or
490/// variable corresponding to the anonymous union or struct whose type
491/// is Record.
492static Decl *getObjectForAnonymousRecordDecl(ASTContext &Context,
493                                             RecordDecl *Record) {
494  assert(Record->isAnonymousStructOrUnion() &&
495         "Record must be an anonymous struct or union!");
496
497  // FIXME: Once Decls are directly linked together, this will be an O(1)
498  // operation rather than a slow walk through DeclContext's vector (which
499  // itself will be eliminated). DeclGroups might make this even better.
500  DeclContext *Ctx = Record->getDeclContext();
501  for (DeclContext::decl_iterator D = Ctx->decls_begin(),
502                               DEnd = Ctx->decls_end();
503       D != DEnd; ++D) {
504    if (*D == Record) {
505      // The object for the anonymous struct/union directly
506      // follows its type in the list of declarations.
507      ++D;
508      assert(D != DEnd && "Missing object for anonymous record");
509      assert(!cast<NamedDecl>(*D)->getDeclName() && "Decl should be unnamed");
510      return *D;
511    }
512  }
513
514  assert(false && "Missing object for anonymous record");
515  return 0;
516}
517
518/// \brief Given a field that represents a member of an anonymous
519/// struct/union, build the path from that field's context to the
520/// actual member.
521///
522/// Construct the sequence of field member references we'll have to
523/// perform to get to the field in the anonymous union/struct. The
524/// list of members is built from the field outward, so traverse it
525/// backwards to go from an object in the current context to the field
526/// we found.
527///
528/// \returns The variable from which the field access should begin,
529/// for an anonymous struct/union that is not a member of another
530/// class. Otherwise, returns NULL.
531VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
532                                   llvm::SmallVectorImpl<FieldDecl *> &Path) {
533  assert(Field->getDeclContext()->isRecord() &&
534         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
535         && "Field must be stored inside an anonymous struct or union");
536
537  Path.push_back(Field);
538  VarDecl *BaseObject = 0;
539  DeclContext *Ctx = Field->getDeclContext();
540  do {
541    RecordDecl *Record = cast<RecordDecl>(Ctx);
542    Decl *AnonObject = getObjectForAnonymousRecordDecl(Context, Record);
543    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
544      Path.push_back(AnonField);
545    else {
546      BaseObject = cast<VarDecl>(AnonObject);
547      break;
548    }
549    Ctx = Ctx->getParent();
550  } while (Ctx->isRecord() &&
551           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
552
553  return BaseObject;
554}
555
556Sema::OwningExprResult
557Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
558                                               FieldDecl *Field,
559                                               Expr *BaseObjectExpr,
560                                               SourceLocation OpLoc) {
561  llvm::SmallVector<FieldDecl *, 4> AnonFields;
562  VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
563                                                            AnonFields);
564
565  // Build the expression that refers to the base object, from
566  // which we will build a sequence of member references to each
567  // of the anonymous union objects and, eventually, the field we
568  // found via name lookup.
569  bool BaseObjectIsPointer = false;
570  Qualifiers BaseQuals;
571  if (BaseObject) {
572    // BaseObject is an anonymous struct/union variable (and is,
573    // therefore, not part of another non-anonymous record).
574    if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
575    MarkDeclarationReferenced(Loc, BaseObject);
576    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
577                                               SourceLocation());
578    BaseQuals
579      = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
580  } else if (BaseObjectExpr) {
581    // The caller provided the base object expression. Determine
582    // whether its a pointer and whether it adds any qualifiers to the
583    // anonymous struct/union fields we're looking into.
584    QualType ObjectType = BaseObjectExpr->getType();
585    if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
586      BaseObjectIsPointer = true;
587      ObjectType = ObjectPtr->getPointeeType();
588    }
589    BaseQuals
590      = Context.getCanonicalType(ObjectType).getQualifiers();
591  } else {
592    // We've found a member of an anonymous struct/union that is
593    // inside a non-anonymous struct/union, so in a well-formed
594    // program our base object expression is "this".
595    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
596      if (!MD->isStatic()) {
597        QualType AnonFieldType
598          = Context.getTagDeclType(
599                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
600        QualType ThisType = Context.getTagDeclType(MD->getParent());
601        if ((Context.getCanonicalType(AnonFieldType)
602               == Context.getCanonicalType(ThisType)) ||
603            IsDerivedFrom(ThisType, AnonFieldType)) {
604          // Our base object expression is "this".
605          BaseObjectExpr = new (Context) CXXThisExpr(SourceLocation(),
606                                                     MD->getThisType(Context));
607          BaseObjectIsPointer = true;
608        }
609      } else {
610        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
611          << Field->getDeclName());
612      }
613      BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
614    }
615
616    if (!BaseObjectExpr)
617      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
618        << Field->getDeclName());
619  }
620
621  // Build the implicit member references to the field of the
622  // anonymous struct/union.
623  Expr *Result = BaseObjectExpr;
624  Qualifiers ResultQuals = BaseQuals;
625  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
626         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
627       FI != FIEnd; ++FI) {
628    QualType MemberType = (*FI)->getType();
629    Qualifiers MemberTypeQuals =
630      Context.getCanonicalType(MemberType).getQualifiers();
631
632    // CVR attributes from the base are picked up by members,
633    // except that 'mutable' members don't pick up 'const'.
634    if ((*FI)->isMutable())
635      ResultQuals.removeConst();
636
637    // GC attributes are never picked up by members.
638    ResultQuals.removeObjCGCAttr();
639
640    // TR 18037 does not allow fields to be declared with address spaces.
641    assert(!MemberTypeQuals.hasAddressSpace());
642
643    Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
644    if (NewQuals != MemberTypeQuals)
645      MemberType = Context.getQualifiedType(MemberType, NewQuals);
646
647    MarkDeclarationReferenced(Loc, *FI);
648    // FIXME: Might this end up being a qualified name?
649    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
650                                      OpLoc, MemberType);
651    BaseObjectIsPointer = false;
652    ResultQuals = NewQuals;
653  }
654
655  return Owned(Result);
656}
657
658/// ActOnDeclarationNameExpr - The parser has read some kind of name
659/// (e.g., a C++ id-expression (C++ [expr.prim]p1)). This routine
660/// performs lookup on that name and returns an expression that refers
661/// to that name. This routine isn't directly called from the parser,
662/// because the parser doesn't know about DeclarationName. Rather,
663/// this routine is called by ActOnIdentifierExpr,
664/// ActOnOperatorFunctionIdExpr, and ActOnConversionFunctionExpr,
665/// which form the DeclarationName from the corresponding syntactic
666/// forms.
667///
668/// HasTrailingLParen indicates whether this identifier is used in a
669/// function call context.  LookupCtx is only used for a C++
670/// qualified-id (foo::bar) to indicate the class or namespace that
671/// the identifier must be a member of.
672///
673/// isAddressOfOperand means that this expression is the direct operand
674/// of an address-of operator. This matters because this is the only
675/// situation where a qualified name referencing a non-static member may
676/// appear outside a member function of this class.
677Sema::OwningExprResult
678Sema::ActOnDeclarationNameExpr(Scope *S, SourceLocation Loc,
679                               DeclarationName Name, bool HasTrailingLParen,
680                               const CXXScopeSpec *SS,
681                               bool isAddressOfOperand) {
682  // Could be enum-constant, value decl, instance variable, etc.
683  if (SS && SS->isInvalid())
684    return ExprError();
685
686  // C++ [temp.dep.expr]p3:
687  //   An id-expression is type-dependent if it contains:
688  //     -- a nested-name-specifier that contains a class-name that
689  //        names a dependent type.
690  // FIXME: Member of the current instantiation.
691  if (SS && isDependentScopeSpecifier(*SS)) {
692    return Owned(new (Context) UnresolvedDeclRefExpr(Name, Context.DependentTy,
693                                                     Loc, SS->getRange(),
694                static_cast<NestedNameSpecifier *>(SS->getScopeRep()),
695                                                     isAddressOfOperand));
696  }
697
698  LookupResult Lookup;
699  LookupParsedName(Lookup, S, SS, Name, LookupOrdinaryName, false, true, Loc);
700
701  if (Lookup.isAmbiguous()) {
702    DiagnoseAmbiguousLookup(Lookup, Name, Loc,
703                            SS && SS->isSet() ? SS->getRange()
704                                              : SourceRange());
705    return ExprError();
706  }
707
708  NamedDecl *D = Lookup.getAsSingleDecl(Context);
709
710  // If this reference is in an Objective-C method, then ivar lookup happens as
711  // well.
712  IdentifierInfo *II = Name.getAsIdentifierInfo();
713  if (II && getCurMethodDecl()) {
714    // There are two cases to handle here.  1) scoped lookup could have failed,
715    // in which case we should look for an ivar.  2) scoped lookup could have
716    // found a decl, but that decl is outside the current instance method (i.e.
717    // a global variable).  In these two cases, we do a lookup for an ivar with
718    // this name, if the lookup sucedes, we replace it our current decl.
719    if (D == 0 || D->isDefinedOutsideFunctionOrMethod()) {
720      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
721      ObjCInterfaceDecl *ClassDeclared;
722      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
723        // Check if referencing a field with __attribute__((deprecated)).
724        if (DiagnoseUseOfDecl(IV, Loc))
725          return ExprError();
726
727        // If we're referencing an invalid decl, just return this as a silent
728        // error node.  The error diagnostic was already emitted on the decl.
729        if (IV->isInvalidDecl())
730          return ExprError();
731
732        bool IsClsMethod = getCurMethodDecl()->isClassMethod();
733        // If a class method attemps to use a free standing ivar, this is
734        // an error.
735        if (IsClsMethod && D && !D->isDefinedOutsideFunctionOrMethod())
736           return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
737                           << IV->getDeclName());
738        // If a class method uses a global variable, even if an ivar with
739        // same name exists, use the global.
740        if (!IsClsMethod) {
741          if (IV->getAccessControl() == ObjCIvarDecl::Private &&
742              ClassDeclared != IFace)
743           Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
744          // FIXME: This should use a new expr for a direct reference, don't
745          // turn this into Self->ivar, just return a BareIVarExpr or something.
746          IdentifierInfo &II = Context.Idents.get("self");
747          OwningExprResult SelfExpr = ActOnIdentifierExpr(S, SourceLocation(),
748                                                          II, false);
749          MarkDeclarationReferenced(Loc, IV);
750          return Owned(new (Context)
751                       ObjCIvarRefExpr(IV, IV->getType(), Loc,
752                                       SelfExpr.takeAs<Expr>(), true, true));
753        }
754      }
755    } else if (getCurMethodDecl()->isInstanceMethod()) {
756      // We should warn if a local variable hides an ivar.
757      ObjCInterfaceDecl *IFace = getCurMethodDecl()->getClassInterface();
758      ObjCInterfaceDecl *ClassDeclared;
759      if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
760        if (IV->getAccessControl() != ObjCIvarDecl::Private ||
761            IFace == ClassDeclared)
762          Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
763      }
764    }
765    // Needed to implement property "super.method" notation.
766    if (D == 0 && II->isStr("super")) {
767      QualType T;
768
769      if (getCurMethodDecl()->isInstanceMethod())
770        T = Context.getObjCObjectPointerType(Context.getObjCInterfaceType(
771                                      getCurMethodDecl()->getClassInterface()));
772      else
773        T = Context.getObjCClassType();
774      return Owned(new (Context) ObjCSuperExpr(Loc, T));
775    }
776  }
777
778  // Determine whether this name might be a candidate for
779  // argument-dependent lookup.
780  bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
781             HasTrailingLParen;
782
783  if (ADL && D == 0) {
784    // We've seen something of the form
785    //
786    //   identifier(
787    //
788    // and we did not find any entity by the name
789    // "identifier". However, this identifier is still subject to
790    // argument-dependent lookup, so keep track of the name.
791    return Owned(new (Context) UnresolvedFunctionNameExpr(Name,
792                                                          Context.OverloadTy,
793                                                          Loc));
794  }
795
796  if (D == 0) {
797    // Otherwise, this could be an implicitly declared function reference (legal
798    // in C90, extension in C99).
799    if (HasTrailingLParen && II &&
800        !getLangOptions().CPlusPlus) // Not in C++.
801      D = ImplicitlyDefineFunction(Loc, *II, S);
802    else {
803      // If this name wasn't predeclared and if this is not a function call,
804      // diagnose the problem.
805      if (SS && !SS->isEmpty())
806        return ExprError(Diag(Loc, diag::err_no_member)
807                           << Name << computeDeclContext(*SS, false)
808                           << SS->getRange());
809      else if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
810               Name.getNameKind() == DeclarationName::CXXConversionFunctionName)
811        return ExprError(Diag(Loc, diag::err_undeclared_use)
812          << Name.getAsString());
813      else
814        return ExprError(Diag(Loc, diag::err_undeclared_var_use) << Name);
815    }
816  }
817
818  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
819    // Warn about constructs like:
820    //   if (void *X = foo()) { ... } else { X }.
821    // In the else block, the pointer is always false.
822
823    // FIXME: In a template instantiation, we don't have scope
824    // information to check this property.
825    if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
826      Scope *CheckS = S;
827      while (CheckS) {
828        if (CheckS->isWithinElse() &&
829            CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
830          if (Var->getType()->isBooleanType())
831            ExprError(Diag(Loc, diag::warn_value_always_false)
832                      << Var->getDeclName());
833          else
834            ExprError(Diag(Loc, diag::warn_value_always_zero)
835                      << Var->getDeclName());
836          break;
837        }
838
839        // Move up one more control parent to check again.
840        CheckS = CheckS->getControlParent();
841        if (CheckS)
842          CheckS = CheckS->getParent();
843      }
844    }
845  } else if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D)) {
846    if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
847      // C99 DR 316 says that, if a function type comes from a
848      // function definition (without a prototype), that type is only
849      // used for checking compatibility. Therefore, when referencing
850      // the function, we pretend that we don't have the full function
851      // type.
852      if (DiagnoseUseOfDecl(Func, Loc))
853        return ExprError();
854
855      QualType T = Func->getType();
856      QualType NoProtoType = T;
857      if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
858        NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType());
859      return BuildDeclRefExpr(Func, NoProtoType, Loc, false, false, SS);
860    }
861  }
862
863  return BuildDeclarationNameExpr(Loc, D, HasTrailingLParen, SS, isAddressOfOperand);
864}
865/// \brief Cast member's object to its own class if necessary.
866bool
867Sema::PerformObjectMemberConversion(Expr *&From, NamedDecl *Member) {
868  if (FieldDecl *FD = dyn_cast<FieldDecl>(Member))
869    if (CXXRecordDecl *RD =
870        dyn_cast<CXXRecordDecl>(FD->getDeclContext())) {
871      QualType DestType =
872        Context.getCanonicalType(Context.getTypeDeclType(RD));
873      if (DestType->isDependentType() || From->getType()->isDependentType())
874        return false;
875      QualType FromRecordType = From->getType();
876      QualType DestRecordType = DestType;
877      if (FromRecordType->getAs<PointerType>()) {
878        DestType = Context.getPointerType(DestType);
879        FromRecordType = FromRecordType->getPointeeType();
880      }
881      if (!Context.hasSameUnqualifiedType(FromRecordType, DestRecordType) &&
882          CheckDerivedToBaseConversion(FromRecordType,
883                                       DestRecordType,
884                                       From->getSourceRange().getBegin(),
885                                       From->getSourceRange()))
886        return true;
887      ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
888                        /*isLvalue=*/true);
889    }
890  return false;
891}
892
893/// \brief Build a MemberExpr AST node.
894static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
895                                   const CXXScopeSpec *SS, NamedDecl *Member,
896                                   SourceLocation Loc, QualType Ty) {
897  if (SS && SS->isSet())
898    return MemberExpr::Create(C, Base, isArrow,
899                              (NestedNameSpecifier *)SS->getScopeRep(),
900                              SS->getRange(), Member, Loc,
901                              // FIXME: Explicit template argument lists
902                              false, SourceLocation(), 0, 0, SourceLocation(),
903                              Ty);
904
905  return new (C) MemberExpr(Base, isArrow, Member, Loc, Ty);
906}
907
908/// \brief Complete semantic analysis for a reference to the given declaration.
909Sema::OwningExprResult
910Sema::BuildDeclarationNameExpr(SourceLocation Loc, NamedDecl *D,
911                               bool HasTrailingLParen,
912                               const CXXScopeSpec *SS,
913                               bool isAddressOfOperand) {
914  assert(D && "Cannot refer to a NULL declaration");
915  DeclarationName Name = D->getDeclName();
916
917  // If this is an expression of the form &Class::member, don't build an
918  // implicit member ref, because we want a pointer to the member in general,
919  // not any specific instance's member.
920  if (isAddressOfOperand && SS && !SS->isEmpty() && !HasTrailingLParen) {
921    DeclContext *DC = computeDeclContext(*SS);
922    if (D && isa<CXXRecordDecl>(DC)) {
923      QualType DType;
924      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
925        DType = FD->getType().getNonReferenceType();
926      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
927        DType = Method->getType();
928      } else if (isa<OverloadedFunctionDecl>(D)) {
929        DType = Context.OverloadTy;
930      }
931      // Could be an inner type. That's diagnosed below, so ignore it here.
932      if (!DType.isNull()) {
933        // The pointer is type- and value-dependent if it points into something
934        // dependent.
935        bool Dependent = DC->isDependentContext();
936        return BuildDeclRefExpr(D, DType, Loc, Dependent, Dependent, SS);
937      }
938    }
939  }
940
941  // We may have found a field within an anonymous union or struct
942  // (C++ [class.union]).
943  if (FieldDecl *FD = dyn_cast<FieldDecl>(D))
944    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
945      return BuildAnonymousStructUnionMemberReference(Loc, FD);
946
947  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
948    if (!MD->isStatic()) {
949      // C++ [class.mfct.nonstatic]p2:
950      //   [...] if name lookup (3.4.1) resolves the name in the
951      //   id-expression to a nonstatic nontype member of class X or of
952      //   a base class of X, the id-expression is transformed into a
953      //   class member access expression (5.2.5) using (*this) (9.3.2)
954      //   as the postfix-expression to the left of the '.' operator.
955      DeclContext *Ctx = 0;
956      QualType MemberType;
957      if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
958        Ctx = FD->getDeclContext();
959        MemberType = FD->getType();
960
961        if (const ReferenceType *RefType = MemberType->getAs<ReferenceType>())
962          MemberType = RefType->getPointeeType();
963        else if (!FD->isMutable())
964          MemberType
965            = Context.getQualifiedType(MemberType,
966                            Qualifiers::fromCVRMask(MD->getTypeQualifiers()));
967      } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
968        if (!Method->isStatic()) {
969          Ctx = Method->getParent();
970          MemberType = Method->getType();
971        }
972      } else if (FunctionTemplateDecl *FunTmpl
973                   = dyn_cast<FunctionTemplateDecl>(D)) {
974        if (CXXMethodDecl *Method
975              = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())) {
976          if (!Method->isStatic()) {
977            Ctx = Method->getParent();
978            MemberType = Context.OverloadTy;
979          }
980        }
981      } else if (OverloadedFunctionDecl *Ovl
982                   = dyn_cast<OverloadedFunctionDecl>(D)) {
983        // FIXME: We need an abstraction for iterating over one or more function
984        // templates or functions. This code is far too repetitive!
985        for (OverloadedFunctionDecl::function_iterator
986               Func = Ovl->function_begin(),
987               FuncEnd = Ovl->function_end();
988             Func != FuncEnd; ++Func) {
989          CXXMethodDecl *DMethod = 0;
990          if (FunctionTemplateDecl *FunTmpl
991                = dyn_cast<FunctionTemplateDecl>(*Func))
992            DMethod = dyn_cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl());
993          else
994            DMethod = dyn_cast<CXXMethodDecl>(*Func);
995
996          if (DMethod && !DMethod->isStatic()) {
997            Ctx = DMethod->getDeclContext();
998            MemberType = Context.OverloadTy;
999            break;
1000          }
1001        }
1002      }
1003
1004      if (Ctx && Ctx->isRecord()) {
1005        QualType CtxType = Context.getTagDeclType(cast<CXXRecordDecl>(Ctx));
1006        QualType ThisType = Context.getTagDeclType(MD->getParent());
1007        if ((Context.getCanonicalType(CtxType)
1008               == Context.getCanonicalType(ThisType)) ||
1009            IsDerivedFrom(ThisType, CtxType)) {
1010          // Build the implicit member access expression.
1011          Expr *This = new (Context) CXXThisExpr(SourceLocation(),
1012                                                 MD->getThisType(Context));
1013          MarkDeclarationReferenced(Loc, D);
1014          if (PerformObjectMemberConversion(This, D))
1015            return ExprError();
1016
1017          bool ShouldCheckUse = true;
1018          if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
1019            // Don't diagnose the use of a virtual member function unless it's
1020            // explicitly qualified.
1021            if (MD->isVirtual() && (!SS || !SS->isSet()))
1022              ShouldCheckUse = false;
1023          }
1024
1025          if (ShouldCheckUse && DiagnoseUseOfDecl(D, Loc))
1026            return ExprError();
1027          return Owned(BuildMemberExpr(Context, This, true, SS, D,
1028                                       Loc, MemberType));
1029        }
1030      }
1031    }
1032  }
1033
1034  if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
1035    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
1036      if (MD->isStatic())
1037        // "invalid use of member 'x' in static member function"
1038        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
1039          << FD->getDeclName());
1040    }
1041
1042    // Any other ways we could have found the field in a well-formed
1043    // program would have been turned into implicit member expressions
1044    // above.
1045    return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
1046      << FD->getDeclName());
1047  }
1048
1049  if (isa<TypedefDecl>(D))
1050    return ExprError(Diag(Loc, diag::err_unexpected_typedef) << Name);
1051  if (isa<ObjCInterfaceDecl>(D))
1052    return ExprError(Diag(Loc, diag::err_unexpected_interface) << Name);
1053  if (isa<NamespaceDecl>(D))
1054    return ExprError(Diag(Loc, diag::err_unexpected_namespace) << Name);
1055
1056  // Make the DeclRefExpr or BlockDeclRefExpr for the decl.
1057  if (OverloadedFunctionDecl *Ovl = dyn_cast<OverloadedFunctionDecl>(D))
1058    return BuildDeclRefExpr(Ovl, Context.OverloadTy, Loc,
1059                           false, false, SS);
1060  else if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D))
1061    return BuildDeclRefExpr(Template, Context.OverloadTy, Loc,
1062                            false, false, SS);
1063  else if (UnresolvedUsingDecl *UD = dyn_cast<UnresolvedUsingDecl>(D))
1064    return BuildDeclRefExpr(UD, Context.DependentTy, Loc,
1065                            /*TypeDependent=*/true,
1066                            /*ValueDependent=*/true, SS);
1067
1068  ValueDecl *VD = cast<ValueDecl>(D);
1069
1070  // Check whether this declaration can be used. Note that we suppress
1071  // this check when we're going to perform argument-dependent lookup
1072  // on this function name, because this might not be the function
1073  // that overload resolution actually selects.
1074  bool ADL = getLangOptions().CPlusPlus && (!SS || !SS->isSet()) &&
1075             HasTrailingLParen;
1076  if (!(ADL && isa<FunctionDecl>(VD)) && DiagnoseUseOfDecl(VD, Loc))
1077    return ExprError();
1078
1079  // Only create DeclRefExpr's for valid Decl's.
1080  if (VD->isInvalidDecl())
1081    return ExprError();
1082
1083  // If the identifier reference is inside a block, and it refers to a value
1084  // that is outside the block, create a BlockDeclRefExpr instead of a
1085  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
1086  // the block is formed.
1087  //
1088  // We do not do this for things like enum constants, global variables, etc,
1089  // as they do not get snapshotted.
1090  //
1091  if (CurBlock && ShouldSnapshotBlockValueReference(CurBlock, VD)) {
1092    MarkDeclarationReferenced(Loc, VD);
1093    QualType ExprTy = VD->getType().getNonReferenceType();
1094    // The BlocksAttr indicates the variable is bound by-reference.
1095    if (VD->getAttr<BlocksAttr>())
1096      return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1097    // This is to record that a 'const' was actually synthesize and added.
1098    bool constAdded = !ExprTy.isConstQualified();
1099    // Variable will be bound by-copy, make it const within the closure.
1100
1101    ExprTy.addConst();
1102    return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, false,
1103                                                constAdded));
1104  }
1105  // If this reference is not in a block or if the referenced variable is
1106  // within the block, create a normal DeclRefExpr.
1107
1108  bool TypeDependent = false;
1109  bool ValueDependent = false;
1110  if (getLangOptions().CPlusPlus) {
1111    // C++ [temp.dep.expr]p3:
1112    //   An id-expression is type-dependent if it contains:
1113    //     - an identifier that was declared with a dependent type,
1114    if (VD->getType()->isDependentType())
1115      TypeDependent = true;
1116    //     - FIXME: a template-id that is dependent,
1117    //     - a conversion-function-id that specifies a dependent type,
1118    else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1119             Name.getCXXNameType()->isDependentType())
1120      TypeDependent = true;
1121    //     - a nested-name-specifier that contains a class-name that
1122    //       names a dependent type.
1123    else if (SS && !SS->isEmpty()) {
1124      for (DeclContext *DC = computeDeclContext(*SS);
1125           DC; DC = DC->getParent()) {
1126        // FIXME: could stop early at namespace scope.
1127        if (DC->isRecord()) {
1128          CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
1129          if (Context.getTypeDeclType(Record)->isDependentType()) {
1130            TypeDependent = true;
1131            break;
1132          }
1133        }
1134      }
1135    }
1136
1137    // C++ [temp.dep.constexpr]p2:
1138    //
1139    //   An identifier is value-dependent if it is:
1140    //     - a name declared with a dependent type,
1141    if (TypeDependent)
1142      ValueDependent = true;
1143    //     - the name of a non-type template parameter,
1144    else if (isa<NonTypeTemplateParmDecl>(VD))
1145      ValueDependent = true;
1146    //    - a constant with integral or enumeration type and is
1147    //      initialized with an expression that is value-dependent
1148    else if (const VarDecl *Dcl = dyn_cast<VarDecl>(VD)) {
1149      if (Dcl->getType().getCVRQualifiers() == Qualifiers::Const &&
1150          Dcl->getInit()) {
1151        ValueDependent = Dcl->getInit()->isValueDependent();
1152      }
1153    }
1154  }
1155
1156  return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc,
1157                          TypeDependent, ValueDependent, SS);
1158}
1159
1160Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1161                                                 tok::TokenKind Kind) {
1162  PredefinedExpr::IdentType IT;
1163
1164  switch (Kind) {
1165  default: assert(0 && "Unknown simple primary expr!");
1166  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1167  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1168  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1169  }
1170
1171  // Pre-defined identifiers are of type char[x], where x is the length of the
1172  // string.
1173
1174  Decl *currentDecl = getCurFunctionOrMethodDecl();
1175  if (!currentDecl) {
1176    Diag(Loc, diag::ext_predef_outside_function);
1177    currentDecl = Context.getTranslationUnitDecl();
1178  }
1179
1180  QualType ResTy;
1181  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1182    ResTy = Context.DependentTy;
1183  } else {
1184    unsigned Length =
1185      PredefinedExpr::ComputeName(Context, IT, currentDecl).length();
1186
1187    llvm::APInt LengthI(32, Length + 1);
1188    ResTy = Context.CharTy.withConst();
1189    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1190  }
1191  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1192}
1193
1194Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1195  llvm::SmallString<16> CharBuffer;
1196  CharBuffer.resize(Tok.getLength());
1197  const char *ThisTokBegin = &CharBuffer[0];
1198  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1199
1200  CharLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1201                            Tok.getLocation(), PP);
1202  if (Literal.hadError())
1203    return ExprError();
1204
1205  QualType type = getLangOptions().CPlusPlus ? Context.CharTy : Context.IntTy;
1206
1207  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1208                                              Literal.isWide(),
1209                                              type, Tok.getLocation()));
1210}
1211
1212Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1213  // Fast path for a single digit (which is quite common).  A single digit
1214  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1215  if (Tok.getLength() == 1) {
1216    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1217    unsigned IntSize = Context.Target.getIntWidth();
1218    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1219                    Context.IntTy, Tok.getLocation()));
1220  }
1221
1222  llvm::SmallString<512> IntegerBuffer;
1223  // Add padding so that NumericLiteralParser can overread by one character.
1224  IntegerBuffer.resize(Tok.getLength()+1);
1225  const char *ThisTokBegin = &IntegerBuffer[0];
1226
1227  // Get the spelling of the token, which eliminates trigraphs, etc.
1228  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin);
1229
1230  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1231                               Tok.getLocation(), PP);
1232  if (Literal.hadError)
1233    return ExprError();
1234
1235  Expr *Res;
1236
1237  if (Literal.isFloatingLiteral()) {
1238    QualType Ty;
1239    if (Literal.isFloat)
1240      Ty = Context.FloatTy;
1241    else if (!Literal.isLong)
1242      Ty = Context.DoubleTy;
1243    else
1244      Ty = Context.LongDoubleTy;
1245
1246    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1247
1248    // isExact will be set by GetFloatValue().
1249    bool isExact = false;
1250    llvm::APFloat Val = Literal.GetFloatValue(Format, &isExact);
1251    Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1252
1253  } else if (!Literal.isIntegerLiteral()) {
1254    return ExprError();
1255  } else {
1256    QualType Ty;
1257
1258    // long long is a C99 feature.
1259    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1260        Literal.isLongLong)
1261      Diag(Tok.getLocation(), diag::ext_longlong);
1262
1263    // Get the value in the widest-possible width.
1264    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1265
1266    if (Literal.GetIntegerValue(ResultVal)) {
1267      // If this value didn't fit into uintmax_t, warn and force to ull.
1268      Diag(Tok.getLocation(), diag::warn_integer_too_large);
1269      Ty = Context.UnsignedLongLongTy;
1270      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1271             "long long is not intmax_t?");
1272    } else {
1273      // If this value fits into a ULL, try to figure out what else it fits into
1274      // according to the rules of C99 6.4.4.1p5.
1275
1276      // Octal, Hexadecimal, and integers with a U suffix are allowed to
1277      // be an unsigned int.
1278      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1279
1280      // Check from smallest to largest, picking the smallest type we can.
1281      unsigned Width = 0;
1282      if (!Literal.isLong && !Literal.isLongLong) {
1283        // Are int/unsigned possibilities?
1284        unsigned IntSize = Context.Target.getIntWidth();
1285
1286        // Does it fit in a unsigned int?
1287        if (ResultVal.isIntN(IntSize)) {
1288          // Does it fit in a signed int?
1289          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1290            Ty = Context.IntTy;
1291          else if (AllowUnsigned)
1292            Ty = Context.UnsignedIntTy;
1293          Width = IntSize;
1294        }
1295      }
1296
1297      // Are long/unsigned long possibilities?
1298      if (Ty.isNull() && !Literal.isLongLong) {
1299        unsigned LongSize = Context.Target.getLongWidth();
1300
1301        // Does it fit in a unsigned long?
1302        if (ResultVal.isIntN(LongSize)) {
1303          // Does it fit in a signed long?
1304          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1305            Ty = Context.LongTy;
1306          else if (AllowUnsigned)
1307            Ty = Context.UnsignedLongTy;
1308          Width = LongSize;
1309        }
1310      }
1311
1312      // Finally, check long long if needed.
1313      if (Ty.isNull()) {
1314        unsigned LongLongSize = Context.Target.getLongLongWidth();
1315
1316        // Does it fit in a unsigned long long?
1317        if (ResultVal.isIntN(LongLongSize)) {
1318          // Does it fit in a signed long long?
1319          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1320            Ty = Context.LongLongTy;
1321          else if (AllowUnsigned)
1322            Ty = Context.UnsignedLongLongTy;
1323          Width = LongLongSize;
1324        }
1325      }
1326
1327      // If we still couldn't decide a type, we probably have something that
1328      // does not fit in a signed long long, but has no U suffix.
1329      if (Ty.isNull()) {
1330        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1331        Ty = Context.UnsignedLongLongTy;
1332        Width = Context.Target.getLongLongWidth();
1333      }
1334
1335      if (ResultVal.getBitWidth() != Width)
1336        ResultVal.trunc(Width);
1337    }
1338    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1339  }
1340
1341  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1342  if (Literal.isImaginary)
1343    Res = new (Context) ImaginaryLiteral(Res,
1344                                        Context.getComplexType(Res->getType()));
1345
1346  return Owned(Res);
1347}
1348
1349Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1350                                              SourceLocation R, ExprArg Val) {
1351  Expr *E = Val.takeAs<Expr>();
1352  assert((E != 0) && "ActOnParenExpr() missing expr");
1353  return Owned(new (Context) ParenExpr(L, R, E));
1354}
1355
1356/// The UsualUnaryConversions() function is *not* called by this routine.
1357/// See C99 6.3.2.1p[2-4] for more details.
1358bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1359                                     SourceLocation OpLoc,
1360                                     const SourceRange &ExprRange,
1361                                     bool isSizeof) {
1362  if (exprType->isDependentType())
1363    return false;
1364
1365  // C99 6.5.3.4p1:
1366  if (isa<FunctionType>(exprType)) {
1367    // alignof(function) is allowed as an extension.
1368    if (isSizeof)
1369      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
1370    return false;
1371  }
1372
1373  // Allow sizeof(void)/alignof(void) as an extension.
1374  if (exprType->isVoidType()) {
1375    Diag(OpLoc, diag::ext_sizeof_void_type)
1376      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
1377    return false;
1378  }
1379
1380  if (RequireCompleteType(OpLoc, exprType,
1381                          isSizeof ? diag::err_sizeof_incomplete_type :
1382                          PDiag(diag::err_alignof_incomplete_type)
1383                            << ExprRange))
1384    return true;
1385
1386  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
1387  if (LangOpts.ObjCNonFragileABI && exprType->isObjCInterfaceType()) {
1388    Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
1389      << exprType << isSizeof << ExprRange;
1390    return true;
1391  }
1392
1393  return false;
1394}
1395
1396bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
1397                            const SourceRange &ExprRange) {
1398  E = E->IgnoreParens();
1399
1400  // alignof decl is always ok.
1401  if (isa<DeclRefExpr>(E))
1402    return false;
1403
1404  // Cannot know anything else if the expression is dependent.
1405  if (E->isTypeDependent())
1406    return false;
1407
1408  if (E->getBitField()) {
1409    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
1410    return true;
1411  }
1412
1413  // Alignment of a field access is always okay, so long as it isn't a
1414  // bit-field.
1415  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
1416    if (isa<FieldDecl>(ME->getMemberDecl()))
1417      return false;
1418
1419  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
1420}
1421
1422/// \brief Build a sizeof or alignof expression given a type operand.
1423Action::OwningExprResult
1424Sema::CreateSizeOfAlignOfExpr(QualType T, SourceLocation OpLoc,
1425                              bool isSizeOf, SourceRange R) {
1426  if (T.isNull())
1427    return ExprError();
1428
1429  if (!T->isDependentType() &&
1430      CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
1431    return ExprError();
1432
1433  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1434  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, T,
1435                                               Context.getSizeType(), OpLoc,
1436                                               R.getEnd()));
1437}
1438
1439/// \brief Build a sizeof or alignof expression given an expression
1440/// operand.
1441Action::OwningExprResult
1442Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
1443                              bool isSizeOf, SourceRange R) {
1444  // Verify that the operand is valid.
1445  bool isInvalid = false;
1446  if (E->isTypeDependent()) {
1447    // Delay type-checking for type-dependent expressions.
1448  } else if (!isSizeOf) {
1449    isInvalid = CheckAlignOfExpr(E, OpLoc, R);
1450  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
1451    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
1452    isInvalid = true;
1453  } else {
1454    isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
1455  }
1456
1457  if (isInvalid)
1458    return ExprError();
1459
1460  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
1461  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
1462                                               Context.getSizeType(), OpLoc,
1463                                               R.getEnd()));
1464}
1465
1466/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
1467/// the same for @c alignof and @c __alignof
1468/// Note that the ArgRange is invalid if isType is false.
1469Action::OwningExprResult
1470Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
1471                             void *TyOrEx, const SourceRange &ArgRange) {
1472  // If error parsing type, ignore.
1473  if (TyOrEx == 0) return ExprError();
1474
1475  if (isType) {
1476    // FIXME: Preserve type source info.
1477    QualType ArgTy = GetTypeFromParser(TyOrEx);
1478    return CreateSizeOfAlignOfExpr(ArgTy, OpLoc, isSizeof, ArgRange);
1479  }
1480
1481  // Get the end location.
1482  Expr *ArgEx = (Expr *)TyOrEx;
1483  Action::OwningExprResult Result
1484    = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
1485
1486  if (Result.isInvalid())
1487    DeleteExpr(ArgEx);
1488
1489  return move(Result);
1490}
1491
1492QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
1493  if (V->isTypeDependent())
1494    return Context.DependentTy;
1495
1496  // These operators return the element type of a complex type.
1497  if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
1498    return CT->getElementType();
1499
1500  // Otherwise they pass through real integer and floating point types here.
1501  if (V->getType()->isArithmeticType())
1502    return V->getType();
1503
1504  // Reject anything else.
1505  Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
1506    << (isReal ? "__real" : "__imag");
1507  return QualType();
1508}
1509
1510
1511
1512Action::OwningExprResult
1513Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
1514                          tok::TokenKind Kind, ExprArg Input) {
1515  // Since this might be a postfix expression, get rid of ParenListExprs.
1516  Input = MaybeConvertParenListExprToParenExpr(S, move(Input));
1517  Expr *Arg = (Expr *)Input.get();
1518
1519  UnaryOperator::Opcode Opc;
1520  switch (Kind) {
1521  default: assert(0 && "Unknown unary op!");
1522  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
1523  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
1524  }
1525
1526  if (getLangOptions().CPlusPlus &&
1527      (Arg->getType()->isRecordType() || Arg->getType()->isEnumeralType())) {
1528    // Which overloaded operator?
1529    OverloadedOperatorKind OverOp =
1530      (Opc == UnaryOperator::PostInc)? OO_PlusPlus : OO_MinusMinus;
1531
1532    // C++ [over.inc]p1:
1533    //
1534    //     [...] If the function is a member function with one
1535    //     parameter (which shall be of type int) or a non-member
1536    //     function with two parameters (the second of which shall be
1537    //     of type int), it defines the postfix increment operator ++
1538    //     for objects of that type. When the postfix increment is
1539    //     called as a result of using the ++ operator, the int
1540    //     argument will have value zero.
1541    Expr *Args[2] = {
1542      Arg,
1543      new (Context) IntegerLiteral(llvm::APInt(Context.Target.getIntWidth(), 0,
1544                          /*isSigned=*/true), Context.IntTy, SourceLocation())
1545    };
1546
1547    // Build the candidate set for overloading
1548    OverloadCandidateSet CandidateSet;
1549    AddOperatorCandidates(OverOp, S, OpLoc, Args, 2, CandidateSet);
1550
1551    // Perform overload resolution.
1552    OverloadCandidateSet::iterator Best;
1553    switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
1554    case OR_Success: {
1555      // We found a built-in operator or an overloaded operator.
1556      FunctionDecl *FnDecl = Best->Function;
1557
1558      if (FnDecl) {
1559        // We matched an overloaded operator. Build a call to that
1560        // operator.
1561
1562        // Convert the arguments.
1563        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1564          if (PerformObjectArgumentInitialization(Arg, Method))
1565            return ExprError();
1566        } else {
1567          // Convert the arguments.
1568          if (PerformCopyInitialization(Arg,
1569                                        FnDecl->getParamDecl(0)->getType(),
1570                                        "passing"))
1571            return ExprError();
1572        }
1573
1574        // Determine the result type
1575        QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
1576
1577        // Build the actual expression node.
1578        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1579                                                 SourceLocation());
1580        UsualUnaryConversions(FnExpr);
1581
1582        Input.release();
1583        Args[0] = Arg;
1584
1585        ExprOwningPtr<CXXOperatorCallExpr>
1586          TheCall(this, new (Context) CXXOperatorCallExpr(Context, OverOp,
1587                                                          FnExpr, Args, 2,
1588                                                          ResultTy, OpLoc));
1589
1590        if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
1591                                FnDecl))
1592          return ExprError();
1593        return Owned(TheCall.release());
1594
1595      } else {
1596        // We matched a built-in operator. Convert the arguments, then
1597        // break out so that we will build the appropriate built-in
1598        // operator node.
1599        if (PerformCopyInitialization(Arg, Best->BuiltinTypes.ParamTypes[0],
1600                                      "passing"))
1601          return ExprError();
1602
1603        break;
1604      }
1605    }
1606
1607    case OR_No_Viable_Function: {
1608      // No viable function; try checking this as a built-in operator, which
1609      // will fail and provide a diagnostic. Then, print the overload
1610      // candidates.
1611      OwningExprResult Result = CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1612      assert(Result.isInvalid() &&
1613             "C++ postfix-unary operator overloading is missing candidates!");
1614      if (Result.isInvalid())
1615        PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1616
1617      return move(Result);
1618    }
1619
1620    case OR_Ambiguous:
1621      Diag(OpLoc,  diag::err_ovl_ambiguous_oper)
1622          << UnaryOperator::getOpcodeStr(Opc)
1623          << Arg->getSourceRange();
1624      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1625      return ExprError();
1626
1627    case OR_Deleted:
1628      Diag(OpLoc, diag::err_ovl_deleted_oper)
1629        << Best->Function->isDeleted()
1630        << UnaryOperator::getOpcodeStr(Opc)
1631        << Arg->getSourceRange();
1632      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1633      return ExprError();
1634    }
1635
1636    // Either we found no viable overloaded operator or we matched a
1637    // built-in operator. In either case, fall through to trying to
1638    // build a built-in operation.
1639  }
1640
1641  Input.release();
1642  Input = Arg;
1643  return CreateBuiltinUnaryOp(OpLoc, Opc, move(Input));
1644}
1645
1646Action::OwningExprResult
1647Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
1648                              ExprArg Idx, SourceLocation RLoc) {
1649  // Since this might be a postfix expression, get rid of ParenListExprs.
1650  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
1651
1652  Expr *LHSExp = static_cast<Expr*>(Base.get()),
1653       *RHSExp = static_cast<Expr*>(Idx.get());
1654
1655  if (getLangOptions().CPlusPlus &&
1656      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
1657    Base.release();
1658    Idx.release();
1659    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1660                                                  Context.DependentTy, RLoc));
1661  }
1662
1663  if (getLangOptions().CPlusPlus &&
1664      (LHSExp->getType()->isRecordType() ||
1665       LHSExp->getType()->isEnumeralType() ||
1666       RHSExp->getType()->isRecordType() ||
1667       RHSExp->getType()->isEnumeralType())) {
1668    // Add the appropriate overloaded operators (C++ [over.match.oper])
1669    // to the candidate set.
1670    OverloadCandidateSet CandidateSet;
1671    Expr *Args[2] = { LHSExp, RHSExp };
1672    AddOperatorCandidates(OO_Subscript, S, LLoc, Args, 2, CandidateSet,
1673                          SourceRange(LLoc, RLoc));
1674
1675    // Perform overload resolution.
1676    OverloadCandidateSet::iterator Best;
1677    switch (BestViableFunction(CandidateSet, LLoc, Best)) {
1678    case OR_Success: {
1679      // We found a built-in operator or an overloaded operator.
1680      FunctionDecl *FnDecl = Best->Function;
1681
1682      if (FnDecl) {
1683        // We matched an overloaded operator. Build a call to that
1684        // operator.
1685
1686        // Convert the arguments.
1687        if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
1688          if (PerformObjectArgumentInitialization(LHSExp, Method) ||
1689              PerformCopyInitialization(RHSExp,
1690                                        FnDecl->getParamDecl(0)->getType(),
1691                                        "passing"))
1692            return ExprError();
1693        } else {
1694          // Convert the arguments.
1695          if (PerformCopyInitialization(LHSExp,
1696                                        FnDecl->getParamDecl(0)->getType(),
1697                                        "passing") ||
1698              PerformCopyInitialization(RHSExp,
1699                                        FnDecl->getParamDecl(1)->getType(),
1700                                        "passing"))
1701            return ExprError();
1702        }
1703
1704        // Determine the result type
1705        QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
1706
1707        // Build the actual expression node.
1708        Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
1709                                                 SourceLocation());
1710        UsualUnaryConversions(FnExpr);
1711
1712        Base.release();
1713        Idx.release();
1714        Args[0] = LHSExp;
1715        Args[1] = RHSExp;
1716
1717        ExprOwningPtr<CXXOperatorCallExpr>
1718          TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
1719                                                          FnExpr, Args, 2,
1720                                                          ResultTy, RLoc));
1721        if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
1722                                FnDecl))
1723          return ExprError();
1724
1725        return Owned(TheCall.release());
1726      } else {
1727        // We matched a built-in operator. Convert the arguments, then
1728        // break out so that we will build the appropriate built-in
1729        // operator node.
1730        if (PerformCopyInitialization(LHSExp, Best->BuiltinTypes.ParamTypes[0],
1731                                      "passing") ||
1732            PerformCopyInitialization(RHSExp, Best->BuiltinTypes.ParamTypes[1],
1733                                      "passing"))
1734          return ExprError();
1735
1736        break;
1737      }
1738    }
1739
1740    case OR_No_Viable_Function:
1741      // No viable function; fall through to handling this as a
1742      // built-in operator, which will produce an error message for us.
1743      break;
1744
1745    case OR_Ambiguous:
1746      Diag(LLoc,  diag::err_ovl_ambiguous_oper)
1747          << "[]"
1748          << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1749      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1750      return ExprError();
1751
1752    case OR_Deleted:
1753      Diag(LLoc, diag::err_ovl_deleted_oper)
1754        << Best->Function->isDeleted()
1755        << "[]"
1756        << LHSExp->getSourceRange() << RHSExp->getSourceRange();
1757      PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
1758      return ExprError();
1759    }
1760
1761    // Either we found no viable overloaded operator or we matched a
1762    // built-in operator. In either case, fall through to trying to
1763    // build a built-in operation.
1764  }
1765
1766  // Perform default conversions.
1767  DefaultFunctionArrayConversion(LHSExp);
1768  DefaultFunctionArrayConversion(RHSExp);
1769
1770  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
1771
1772  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
1773  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
1774  // in the subscript position. As a result, we need to derive the array base
1775  // and index from the expression types.
1776  Expr *BaseExpr, *IndexExpr;
1777  QualType ResultType;
1778  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
1779    BaseExpr = LHSExp;
1780    IndexExpr = RHSExp;
1781    ResultType = Context.DependentTy;
1782  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
1783    BaseExpr = LHSExp;
1784    IndexExpr = RHSExp;
1785    ResultType = PTy->getPointeeType();
1786  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
1787     // Handle the uncommon case of "123[Ptr]".
1788    BaseExpr = RHSExp;
1789    IndexExpr = LHSExp;
1790    ResultType = PTy->getPointeeType();
1791  } else if (const ObjCObjectPointerType *PTy =
1792               LHSTy->getAs<ObjCObjectPointerType>()) {
1793    BaseExpr = LHSExp;
1794    IndexExpr = RHSExp;
1795    ResultType = PTy->getPointeeType();
1796  } else if (const ObjCObjectPointerType *PTy =
1797               RHSTy->getAs<ObjCObjectPointerType>()) {
1798     // Handle the uncommon case of "123[Ptr]".
1799    BaseExpr = RHSExp;
1800    IndexExpr = LHSExp;
1801    ResultType = PTy->getPointeeType();
1802  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
1803    BaseExpr = LHSExp;    // vectors: V[123]
1804    IndexExpr = RHSExp;
1805
1806    // FIXME: need to deal with const...
1807    ResultType = VTy->getElementType();
1808  } else if (LHSTy->isArrayType()) {
1809    // If we see an array that wasn't promoted by
1810    // DefaultFunctionArrayConversion, it must be an array that
1811    // wasn't promoted because of the C90 rule that doesn't
1812    // allow promoting non-lvalue arrays.  Warn, then
1813    // force the promotion here.
1814    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1815        LHSExp->getSourceRange();
1816    ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy));
1817    LHSTy = LHSExp->getType();
1818
1819    BaseExpr = LHSExp;
1820    IndexExpr = RHSExp;
1821    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
1822  } else if (RHSTy->isArrayType()) {
1823    // Same as previous, except for 123[f().a] case
1824    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
1825        RHSExp->getSourceRange();
1826    ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy));
1827    RHSTy = RHSExp->getType();
1828
1829    BaseExpr = RHSExp;
1830    IndexExpr = LHSExp;
1831    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
1832  } else {
1833    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
1834       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
1835  }
1836  // C99 6.5.2.1p1
1837  if (!(IndexExpr->getType()->isIntegerType() &&
1838        IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
1839    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
1840                     << IndexExpr->getSourceRange());
1841
1842  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
1843       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
1844         && !IndexExpr->isTypeDependent())
1845    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
1846
1847  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
1848  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
1849  // type. Note that Functions are not objects, and that (in C99 parlance)
1850  // incomplete types are not object types.
1851  if (ResultType->isFunctionType()) {
1852    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
1853      << ResultType << BaseExpr->getSourceRange();
1854    return ExprError();
1855  }
1856
1857  if (!ResultType->isDependentType() &&
1858      RequireCompleteType(LLoc, ResultType,
1859                          PDiag(diag::err_subscript_incomplete_type)
1860                            << BaseExpr->getSourceRange()))
1861    return ExprError();
1862
1863  // Diagnose bad cases where we step over interface counts.
1864  if (ResultType->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
1865    Diag(LLoc, diag::err_subscript_nonfragile_interface)
1866      << ResultType << BaseExpr->getSourceRange();
1867    return ExprError();
1868  }
1869
1870  Base.release();
1871  Idx.release();
1872  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
1873                                                ResultType, RLoc));
1874}
1875
1876QualType Sema::
1877CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
1878                        const IdentifierInfo *CompName,
1879                        SourceLocation CompLoc) {
1880  const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
1881
1882  // The vector accessor can't exceed the number of elements.
1883  const char *compStr = CompName->getName();
1884
1885  // This flag determines whether or not the component is one of the four
1886  // special names that indicate a subset of exactly half the elements are
1887  // to be selected.
1888  bool HalvingSwizzle = false;
1889
1890  // This flag determines whether or not CompName has an 's' char prefix,
1891  // indicating that it is a string of hex values to be used as vector indices.
1892  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
1893
1894  // Check that we've found one of the special components, or that the component
1895  // names must come from the same set.
1896  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
1897      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
1898    HalvingSwizzle = true;
1899  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
1900    do
1901      compStr++;
1902    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
1903  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
1904    do
1905      compStr++;
1906    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
1907  }
1908
1909  if (!HalvingSwizzle && *compStr) {
1910    // We didn't get to the end of the string. This means the component names
1911    // didn't come from the same set *or* we encountered an illegal name.
1912    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
1913      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
1914    return QualType();
1915  }
1916
1917  // Ensure no component accessor exceeds the width of the vector type it
1918  // operates on.
1919  if (!HalvingSwizzle) {
1920    compStr = CompName->getName();
1921
1922    if (HexSwizzle)
1923      compStr++;
1924
1925    while (*compStr) {
1926      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
1927        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
1928          << baseType << SourceRange(CompLoc);
1929        return QualType();
1930      }
1931    }
1932  }
1933
1934  // If this is a halving swizzle, verify that the base type has an even
1935  // number of elements.
1936  if (HalvingSwizzle && (vecType->getNumElements() & 1U)) {
1937    Diag(OpLoc, diag::err_ext_vector_component_requires_even)
1938      << baseType << SourceRange(CompLoc);
1939    return QualType();
1940  }
1941
1942  // The component accessor looks fine - now we need to compute the actual type.
1943  // The vector type is implied by the component accessor. For example,
1944  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
1945  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
1946  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
1947  unsigned CompSize = HalvingSwizzle ? vecType->getNumElements() / 2
1948                                     : CompName->getLength();
1949  if (HexSwizzle)
1950    CompSize--;
1951
1952  if (CompSize == 1)
1953    return vecType->getElementType();
1954
1955  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
1956  // Now look up the TypeDefDecl from the vector type. Without this,
1957  // diagostics look bad. We want extended vector types to appear built-in.
1958  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
1959    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
1960      return Context.getTypedefType(ExtVectorDecls[i]);
1961  }
1962  return VT; // should never get here (a typedef type should always be found).
1963}
1964
1965static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
1966                                                IdentifierInfo *Member,
1967                                                const Selector &Sel,
1968                                                ASTContext &Context) {
1969
1970  if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
1971    return PD;
1972  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
1973    return OMD;
1974
1975  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
1976       E = PDecl->protocol_end(); I != E; ++I) {
1977    if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
1978                                                     Context))
1979      return D;
1980  }
1981  return 0;
1982}
1983
1984static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
1985                                IdentifierInfo *Member,
1986                                const Selector &Sel,
1987                                ASTContext &Context) {
1988  // Check protocols on qualified interfaces.
1989  Decl *GDecl = 0;
1990  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
1991       E = QIdTy->qual_end(); I != E; ++I) {
1992    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
1993      GDecl = PD;
1994      break;
1995    }
1996    // Also must look for a getter name which uses property syntax.
1997    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
1998      GDecl = OMD;
1999      break;
2000    }
2001  }
2002  if (!GDecl) {
2003    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2004         E = QIdTy->qual_end(); I != E; ++I) {
2005      // Search in the protocol-qualifier list of current protocol.
2006      GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
2007      if (GDecl)
2008        return GDecl;
2009    }
2010  }
2011  return GDecl;
2012}
2013
2014Action::OwningExprResult
2015Sema::BuildMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2016                               tok::TokenKind OpKind, SourceLocation MemberLoc,
2017                               DeclarationName MemberName,
2018                               bool HasExplicitTemplateArgs,
2019                               SourceLocation LAngleLoc,
2020                               const TemplateArgument *ExplicitTemplateArgs,
2021                               unsigned NumExplicitTemplateArgs,
2022                               SourceLocation RAngleLoc,
2023                               DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS,
2024                               NamedDecl *FirstQualifierInScope) {
2025  if (SS && SS->isInvalid())
2026    return ExprError();
2027
2028  // Since this might be a postfix expression, get rid of ParenListExprs.
2029  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2030
2031  Expr *BaseExpr = Base.takeAs<Expr>();
2032  assert(BaseExpr && "no base expression");
2033
2034  // Perform default conversions.
2035  DefaultFunctionArrayConversion(BaseExpr);
2036
2037  QualType BaseType = BaseExpr->getType();
2038  // If this is an Objective-C pseudo-builtin and a definition is provided then
2039  // use that.
2040  if (BaseType->isObjCIdType()) {
2041    // We have an 'id' type. Rather than fall through, we check if this
2042    // is a reference to 'isa'.
2043    if (BaseType != Context.ObjCIdRedefinitionType) {
2044      BaseType = Context.ObjCIdRedefinitionType;
2045      ImpCastExprToType(BaseExpr, BaseType);
2046    }
2047  }
2048  assert(!BaseType.isNull() && "no type for member expression");
2049
2050  // Handle properties on ObjC 'Class' types.
2051  if (OpKind == tok::period && BaseType->isObjCClassType()) {
2052    // Also must look for a getter name which uses property syntax.
2053    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2054    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2055    if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2056      ObjCInterfaceDecl *IFace = MD->getClassInterface();
2057      ObjCMethodDecl *Getter;
2058      // FIXME: need to also look locally in the implementation.
2059      if ((Getter = IFace->lookupClassMethod(Sel))) {
2060        // Check the use of this method.
2061        if (DiagnoseUseOfDecl(Getter, MemberLoc))
2062          return ExprError();
2063      }
2064      // If we found a getter then this may be a valid dot-reference, we
2065      // will look for the matching setter, in case it is needed.
2066      Selector SetterSel =
2067      SelectorTable::constructSetterName(PP.getIdentifierTable(),
2068                                         PP.getSelectorTable(), Member);
2069      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2070      if (!Setter) {
2071        // If this reference is in an @implementation, also check for 'private'
2072        // methods.
2073        Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
2074      }
2075      // Look through local category implementations associated with the class.
2076      if (!Setter)
2077        Setter = IFace->getCategoryClassMethod(SetterSel);
2078
2079      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2080        return ExprError();
2081
2082      if (Getter || Setter) {
2083        QualType PType;
2084
2085        if (Getter)
2086          PType = Getter->getResultType();
2087        else
2088          // Get the expression type from Setter's incoming parameter.
2089          PType = (*(Setter->param_end() -1))->getType();
2090        // FIXME: we must check that the setter has property type.
2091        return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2092                                                  PType,
2093                                                  Setter, MemberLoc, BaseExpr));
2094      }
2095      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2096                       << MemberName << BaseType);
2097    }
2098  }
2099
2100  if (BaseType->isObjCClassType() &&
2101      BaseType != Context.ObjCClassRedefinitionType) {
2102    BaseType = Context.ObjCClassRedefinitionType;
2103    ImpCastExprToType(BaseExpr, BaseType);
2104  }
2105
2106  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
2107  // must have pointer type, and the accessed type is the pointee.
2108  if (OpKind == tok::arrow) {
2109    if (BaseType->isDependentType()) {
2110      NestedNameSpecifier *Qualifier = 0;
2111      if (SS) {
2112        Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2113        if (!FirstQualifierInScope)
2114          FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2115      }
2116
2117      return Owned(CXXUnresolvedMemberExpr::Create(Context, BaseExpr, true,
2118                                                   OpLoc, Qualifier,
2119                                            SS? SS->getRange() : SourceRange(),
2120                                                   FirstQualifierInScope,
2121                                                   MemberName,
2122                                                   MemberLoc,
2123                                                   HasExplicitTemplateArgs,
2124                                                   LAngleLoc,
2125                                                   ExplicitTemplateArgs,
2126                                                   NumExplicitTemplateArgs,
2127                                                   RAngleLoc));
2128    }
2129    else if (const PointerType *PT = BaseType->getAs<PointerType>())
2130      BaseType = PT->getPointeeType();
2131    else if (BaseType->isObjCObjectPointerType())
2132      ;
2133    else
2134      return ExprError(Diag(MemberLoc,
2135                            diag::err_typecheck_member_reference_arrow)
2136        << BaseType << BaseExpr->getSourceRange());
2137  } else if (BaseType->isDependentType()) {
2138      // Require that the base type isn't a pointer type
2139      // (so we'll report an error for)
2140      // T* t;
2141      // t.f;
2142      //
2143      // In Obj-C++, however, the above expression is valid, since it could be
2144      // accessing the 'f' property if T is an Obj-C interface. The extra check
2145      // allows this, while still reporting an error if T is a struct pointer.
2146      const PointerType *PT = BaseType->getAs<PointerType>();
2147
2148      if (!PT || (getLangOptions().ObjC1 &&
2149                  !PT->getPointeeType()->isRecordType())) {
2150        NestedNameSpecifier *Qualifier = 0;
2151        if (SS) {
2152          Qualifier = static_cast<NestedNameSpecifier *>(SS->getScopeRep());
2153          if (!FirstQualifierInScope)
2154            FirstQualifierInScope = FindFirstQualifierInScope(S, Qualifier);
2155        }
2156
2157        return Owned(CXXUnresolvedMemberExpr::Create(Context,
2158                                                     BaseExpr, false,
2159                                                     OpLoc,
2160                                                     Qualifier,
2161                                            SS? SS->getRange() : SourceRange(),
2162                                                     FirstQualifierInScope,
2163                                                     MemberName,
2164                                                     MemberLoc,
2165                                                     HasExplicitTemplateArgs,
2166                                                     LAngleLoc,
2167                                                     ExplicitTemplateArgs,
2168                                                     NumExplicitTemplateArgs,
2169                                                     RAngleLoc));
2170      }
2171    }
2172
2173  // Handle field access to simple records.  This also handles access to fields
2174  // of the ObjC 'id' struct.
2175  if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
2176    RecordDecl *RDecl = RTy->getDecl();
2177    if (RequireCompleteType(OpLoc, BaseType,
2178                            PDiag(diag::err_typecheck_incomplete_tag)
2179                              << BaseExpr->getSourceRange()))
2180      return ExprError();
2181
2182    DeclContext *DC = RDecl;
2183    if (SS && SS->isSet()) {
2184      // If the member name was a qualified-id, look into the
2185      // nested-name-specifier.
2186      DC = computeDeclContext(*SS, false);
2187
2188      // FIXME: If DC is not computable, we should build a
2189      // CXXUnresolvedMemberExpr.
2190      assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2191    }
2192
2193    // The record definition is complete, now make sure the member is valid.
2194    LookupResult Result;
2195    LookupQualifiedName(Result, DC, MemberName, LookupMemberName, false);
2196
2197    if (Result.empty())
2198      return ExprError(Diag(MemberLoc, diag::err_no_member)
2199               << MemberName << DC << BaseExpr->getSourceRange());
2200    if (Result.isAmbiguous()) {
2201      DiagnoseAmbiguousLookup(Result, MemberName, MemberLoc,
2202                              BaseExpr->getSourceRange());
2203      return ExprError();
2204    }
2205
2206    NamedDecl *MemberDecl = Result.getAsSingleDecl(Context);
2207
2208    if (SS && SS->isSet()) {
2209      TypeDecl* TyD = cast<TypeDecl>(MemberDecl->getDeclContext());
2210      QualType BaseTypeCanon
2211        = Context.getCanonicalType(BaseType).getUnqualifiedType();
2212      QualType MemberTypeCanon
2213        = Context.getCanonicalType(Context.getTypeDeclType(TyD));
2214
2215      if (BaseTypeCanon != MemberTypeCanon &&
2216          !IsDerivedFrom(BaseTypeCanon, MemberTypeCanon))
2217        return ExprError(Diag(SS->getBeginLoc(),
2218                              diag::err_not_direct_base_or_virtual)
2219                         << MemberTypeCanon << BaseTypeCanon);
2220    }
2221
2222    // If the decl being referenced had an error, return an error for this
2223    // sub-expr without emitting another error, in order to avoid cascading
2224    // error cases.
2225    if (MemberDecl->isInvalidDecl())
2226      return ExprError();
2227
2228    bool ShouldCheckUse = true;
2229    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2230      // Don't diagnose the use of a virtual member function unless it's
2231      // explicitly qualified.
2232      if (MD->isVirtual() && (!SS || !SS->isSet()))
2233        ShouldCheckUse = false;
2234    }
2235
2236    // Check the use of this field
2237    if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
2238      return ExprError();
2239
2240    if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2241      // We may have found a field within an anonymous union or struct
2242      // (C++ [class.union]).
2243      if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
2244        return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2245                                                        BaseExpr, OpLoc);
2246
2247      // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2248      QualType MemberType = FD->getType();
2249      if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2250        MemberType = Ref->getPointeeType();
2251      else {
2252        Qualifiers BaseQuals = BaseType.getQualifiers();
2253        BaseQuals.removeObjCGCAttr();
2254        if (FD->isMutable()) BaseQuals.removeConst();
2255
2256        Qualifiers MemberQuals
2257          = Context.getCanonicalType(MemberType).getQualifiers();
2258
2259        Qualifiers Combined = BaseQuals + MemberQuals;
2260        if (Combined != MemberQuals)
2261          MemberType = Context.getQualifiedType(MemberType, Combined);
2262      }
2263
2264      MarkDeclarationReferenced(MemberLoc, FD);
2265      if (PerformObjectMemberConversion(BaseExpr, FD))
2266        return ExprError();
2267      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2268                                   FD, MemberLoc, MemberType));
2269    }
2270
2271    if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2272      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2273      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2274                                   Var, MemberLoc,
2275                                   Var->getType().getNonReferenceType()));
2276    }
2277    if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2278      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2279      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2280                                   MemberFn, MemberLoc,
2281                                   MemberFn->getType()));
2282    }
2283    if (FunctionTemplateDecl *FunTmpl
2284          = dyn_cast<FunctionTemplateDecl>(MemberDecl)) {
2285      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2286
2287      if (HasExplicitTemplateArgs)
2288        return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2289                             (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2290                                       SS? SS->getRange() : SourceRange(),
2291                                        FunTmpl, MemberLoc, true,
2292                                        LAngleLoc, ExplicitTemplateArgs,
2293                                        NumExplicitTemplateArgs, RAngleLoc,
2294                                        Context.OverloadTy));
2295
2296      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2297                                   FunTmpl, MemberLoc,
2298                                   Context.OverloadTy));
2299    }
2300    if (OverloadedFunctionDecl *Ovl
2301          = dyn_cast<OverloadedFunctionDecl>(MemberDecl)) {
2302      if (HasExplicitTemplateArgs)
2303        return Owned(MemberExpr::Create(Context, BaseExpr, OpKind == tok::arrow,
2304                             (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2305                                        SS? SS->getRange() : SourceRange(),
2306                                        Ovl, MemberLoc, true,
2307                                        LAngleLoc, ExplicitTemplateArgs,
2308                                        NumExplicitTemplateArgs, RAngleLoc,
2309                                        Context.OverloadTy));
2310
2311      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2312                                   Ovl, MemberLoc, Context.OverloadTy));
2313    }
2314    if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2315      MarkDeclarationReferenced(MemberLoc, MemberDecl);
2316      return Owned(BuildMemberExpr(Context, BaseExpr, OpKind == tok::arrow, SS,
2317                                   Enum, MemberLoc, Enum->getType()));
2318    }
2319    if (isa<TypeDecl>(MemberDecl))
2320      return ExprError(Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2321        << MemberName << int(OpKind == tok::arrow));
2322
2323    // We found a declaration kind that we didn't expect. This is a
2324    // generic error message that tells the user that she can't refer
2325    // to this member with '.' or '->'.
2326    return ExprError(Diag(MemberLoc,
2327                          diag::err_typecheck_member_reference_unknown)
2328      << MemberName << int(OpKind == tok::arrow));
2329  }
2330
2331  // Handle pseudo-destructors (C++ [expr.pseudo]). Since anything referring
2332  // into a record type was handled above, any destructor we see here is a
2333  // pseudo-destructor.
2334  if (MemberName.getNameKind() == DeclarationName::CXXDestructorName) {
2335    // C++ [expr.pseudo]p2:
2336    //   The left hand side of the dot operator shall be of scalar type. The
2337    //   left hand side of the arrow operator shall be of pointer to scalar
2338    //   type.
2339    if (!BaseType->isScalarType())
2340      return Owned(Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
2341                     << BaseType << BaseExpr->getSourceRange());
2342
2343    //   [...] The type designated by the pseudo-destructor-name shall be the
2344    //   same as the object type.
2345    if (!MemberName.getCXXNameType()->isDependentType() &&
2346        !Context.hasSameUnqualifiedType(BaseType, MemberName.getCXXNameType()))
2347      return Owned(Diag(OpLoc, diag::err_pseudo_dtor_type_mismatch)
2348                     << BaseType << MemberName.getCXXNameType()
2349                     << BaseExpr->getSourceRange() << SourceRange(MemberLoc));
2350
2351    //   [...] Furthermore, the two type-names in a pseudo-destructor-name of
2352    //   the form
2353    //
2354    //       ::[opt] nested-name-specifier[opt] type-name ::  ̃ type-name
2355    //
2356    //   shall designate the same scalar type.
2357    //
2358    // FIXME: DPG can't see any way to trigger this particular clause, so it
2359    // isn't checked here.
2360
2361    // FIXME: We've lost the precise spelling of the type by going through
2362    // DeclarationName. Can we do better?
2363    return Owned(new (Context) CXXPseudoDestructorExpr(Context, BaseExpr,
2364                                                       OpKind == tok::arrow,
2365                                                       OpLoc,
2366                            (NestedNameSpecifier *)(SS? SS->getScopeRep() : 0),
2367                                            SS? SS->getRange() : SourceRange(),
2368                                                   MemberName.getCXXNameType(),
2369                                                       MemberLoc));
2370  }
2371
2372  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
2373  // (*Obj).ivar.
2374  if ((OpKind == tok::arrow && BaseType->isObjCObjectPointerType()) ||
2375      (OpKind == tok::period && BaseType->isObjCInterfaceType())) {
2376    const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
2377    const ObjCInterfaceType *IFaceT =
2378      OPT ? OPT->getInterfaceType() : BaseType->getAs<ObjCInterfaceType>();
2379    if (IFaceT) {
2380      IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2381
2382      ObjCInterfaceDecl *IDecl = IFaceT->getDecl();
2383      ObjCInterfaceDecl *ClassDeclared;
2384      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
2385
2386      if (IV) {
2387        // If the decl being referenced had an error, return an error for this
2388        // sub-expr without emitting another error, in order to avoid cascading
2389        // error cases.
2390        if (IV->isInvalidDecl())
2391          return ExprError();
2392
2393        // Check whether we can reference this field.
2394        if (DiagnoseUseOfDecl(IV, MemberLoc))
2395          return ExprError();
2396        if (IV->getAccessControl() != ObjCIvarDecl::Public &&
2397            IV->getAccessControl() != ObjCIvarDecl::Package) {
2398          ObjCInterfaceDecl *ClassOfMethodDecl = 0;
2399          if (ObjCMethodDecl *MD = getCurMethodDecl())
2400            ClassOfMethodDecl =  MD->getClassInterface();
2401          else if (ObjCImpDecl && getCurFunctionDecl()) {
2402            // Case of a c-function declared inside an objc implementation.
2403            // FIXME: For a c-style function nested inside an objc implementation
2404            // class, there is no implementation context available, so we pass
2405            // down the context as argument to this routine. Ideally, this context
2406            // need be passed down in the AST node and somehow calculated from the
2407            // AST for a function decl.
2408            Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
2409            if (ObjCImplementationDecl *IMPD =
2410                dyn_cast<ObjCImplementationDecl>(ImplDecl))
2411              ClassOfMethodDecl = IMPD->getClassInterface();
2412            else if (ObjCCategoryImplDecl* CatImplClass =
2413                        dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
2414              ClassOfMethodDecl = CatImplClass->getClassInterface();
2415          }
2416
2417          if (IV->getAccessControl() == ObjCIvarDecl::Private) {
2418            if (ClassDeclared != IDecl ||
2419                ClassOfMethodDecl != ClassDeclared)
2420              Diag(MemberLoc, diag::error_private_ivar_access)
2421                << IV->getDeclName();
2422          } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
2423            // @protected
2424            Diag(MemberLoc, diag::error_protected_ivar_access)
2425              << IV->getDeclName();
2426        }
2427
2428        return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
2429                                                   MemberLoc, BaseExpr,
2430                                                   OpKind == tok::arrow));
2431      }
2432      return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
2433                         << IDecl->getDeclName() << MemberName
2434                         << BaseExpr->getSourceRange());
2435    }
2436  }
2437  // Handle properties on 'id' and qualified "id".
2438  if (OpKind == tok::period && (BaseType->isObjCIdType() ||
2439                                BaseType->isObjCQualifiedIdType())) {
2440    const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
2441    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2442
2443    // Check protocols on qualified interfaces.
2444    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2445    if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
2446      if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
2447        // Check the use of this declaration
2448        if (DiagnoseUseOfDecl(PD, MemberLoc))
2449          return ExprError();
2450
2451        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2452                                                       MemberLoc, BaseExpr));
2453      }
2454      if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
2455        // Check the use of this method.
2456        if (DiagnoseUseOfDecl(OMD, MemberLoc))
2457          return ExprError();
2458
2459        return Owned(new (Context) ObjCMessageExpr(BaseExpr, Sel,
2460                                                   OMD->getResultType(),
2461                                                   OMD, OpLoc, MemberLoc,
2462                                                   NULL, 0));
2463      }
2464    }
2465
2466    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2467                       << MemberName << BaseType);
2468  }
2469  // Handle Objective-C property access, which is "Obj.property" where Obj is a
2470  // pointer to a (potentially qualified) interface type.
2471  const ObjCObjectPointerType *OPT;
2472  if (OpKind == tok::period &&
2473      (OPT = BaseType->getAsObjCInterfacePointerType())) {
2474    const ObjCInterfaceType *IFaceT = OPT->getInterfaceType();
2475    ObjCInterfaceDecl *IFace = IFaceT->getDecl();
2476    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2477
2478    // Search for a declared property first.
2479    if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) {
2480      // Check whether we can reference this property.
2481      if (DiagnoseUseOfDecl(PD, MemberLoc))
2482        return ExprError();
2483      QualType ResTy = PD->getType();
2484      Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2485      ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2486      if (DiagnosePropertyAccessorMismatch(PD, Getter, MemberLoc))
2487        ResTy = Getter->getResultType();
2488      return Owned(new (Context) ObjCPropertyRefExpr(PD, ResTy,
2489                                                     MemberLoc, BaseExpr));
2490    }
2491    // Check protocols on qualified interfaces.
2492    for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2493         E = OPT->qual_end(); I != E; ++I)
2494      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2495        // Check whether we can reference this property.
2496        if (DiagnoseUseOfDecl(PD, MemberLoc))
2497          return ExprError();
2498
2499        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2500                                                       MemberLoc, BaseExpr));
2501      }
2502    for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(),
2503         E = OPT->qual_end(); I != E; ++I)
2504      if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2505        // Check whether we can reference this property.
2506        if (DiagnoseUseOfDecl(PD, MemberLoc))
2507          return ExprError();
2508
2509        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
2510                                                       MemberLoc, BaseExpr));
2511      }
2512    // If that failed, look for an "implicit" property by seeing if the nullary
2513    // selector is implemented.
2514
2515    // FIXME: The logic for looking up nullary and unary selectors should be
2516    // shared with the code in ActOnInstanceMessage.
2517
2518    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2519    ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel);
2520
2521    // If this reference is in an @implementation, check for 'private' methods.
2522    if (!Getter)
2523      Getter = IFace->lookupPrivateInstanceMethod(Sel);
2524
2525    // Look through local category implementations associated with the class.
2526    if (!Getter)
2527      Getter = IFace->getCategoryInstanceMethod(Sel);
2528    if (Getter) {
2529      // Check if we can reference this property.
2530      if (DiagnoseUseOfDecl(Getter, MemberLoc))
2531        return ExprError();
2532    }
2533    // If we found a getter then this may be a valid dot-reference, we
2534    // will look for the matching setter, in case it is needed.
2535    Selector SetterSel =
2536      SelectorTable::constructSetterName(PP.getIdentifierTable(),
2537                                         PP.getSelectorTable(), Member);
2538    ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel);
2539    if (!Setter) {
2540      // If this reference is in an @implementation, also check for 'private'
2541      // methods.
2542      Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
2543    }
2544    // Look through local category implementations associated with the class.
2545    if (!Setter)
2546      Setter = IFace->getCategoryInstanceMethod(SetterSel);
2547
2548    if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2549      return ExprError();
2550
2551    if (Getter || Setter) {
2552      QualType PType;
2553
2554      if (Getter)
2555        PType = Getter->getResultType();
2556      else
2557        // Get the expression type from Setter's incoming parameter.
2558        PType = (*(Setter->param_end() -1))->getType();
2559      // FIXME: we must check that the setter has property type.
2560      return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter, PType,
2561                                      Setter, MemberLoc, BaseExpr));
2562    }
2563    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2564      << MemberName << BaseType);
2565  }
2566
2567  // Handle the following exceptional case (*Obj).isa.
2568  if (OpKind == tok::period &&
2569      BaseType->isSpecificBuiltinType(BuiltinType::ObjCId) &&
2570      MemberName.getAsIdentifierInfo()->isStr("isa"))
2571    return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
2572                                           Context.getObjCIdType()));
2573
2574  // Handle 'field access' to vectors, such as 'V.xx'.
2575  if (BaseType->isExtVectorType()) {
2576    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2577    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
2578    if (ret.isNull())
2579      return ExprError();
2580    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
2581                                                    MemberLoc));
2582  }
2583
2584  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
2585    << BaseType << BaseExpr->getSourceRange();
2586
2587  // If the user is trying to apply -> or . to a function or function
2588  // pointer, it's probably because they forgot parentheses to call
2589  // the function. Suggest the addition of those parentheses.
2590  if (BaseType == Context.OverloadTy ||
2591      BaseType->isFunctionType() ||
2592      (BaseType->isPointerType() &&
2593       BaseType->getAs<PointerType>()->isFunctionType())) {
2594    SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2595    Diag(Loc, diag::note_member_reference_needs_call)
2596      << CodeModificationHint::CreateInsertion(Loc, "()");
2597  }
2598
2599  return ExprError();
2600}
2601
2602Action::OwningExprResult
2603Sema::ActOnMemberReferenceExpr(Scope *S, ExprArg Base, SourceLocation OpLoc,
2604                               tok::TokenKind OpKind, SourceLocation MemberLoc,
2605                               IdentifierInfo &Member,
2606                               DeclPtrTy ObjCImpDecl, const CXXScopeSpec *SS) {
2607  return BuildMemberReferenceExpr(S, move(Base), OpLoc, OpKind, MemberLoc,
2608                                  DeclarationName(&Member), ObjCImpDecl, SS);
2609}
2610
2611Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
2612                                                    FunctionDecl *FD,
2613                                                    ParmVarDecl *Param) {
2614  if (Param->hasUnparsedDefaultArg()) {
2615    Diag (CallLoc,
2616          diag::err_use_of_default_argument_to_function_declared_later) <<
2617      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
2618    Diag(UnparsedDefaultArgLocs[Param],
2619          diag::note_default_argument_declared_here);
2620  } else {
2621    if (Param->hasUninstantiatedDefaultArg()) {
2622      Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
2623
2624      // Instantiate the expression.
2625      MultiLevelTemplateArgumentList ArgList = getTemplateInstantiationArgs(FD);
2626
2627      InstantiatingTemplate Inst(*this, CallLoc, Param,
2628                                 ArgList.getInnermost().getFlatArgumentList(),
2629                                 ArgList.getInnermost().flat_size());
2630
2631      OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
2632      if (Result.isInvalid())
2633        return ExprError();
2634
2635      if (SetParamDefaultArgument(Param, move(Result),
2636                                  /*FIXME:EqualLoc*/
2637                                  UninstExpr->getSourceRange().getBegin()))
2638        return ExprError();
2639    }
2640
2641    Expr *DefaultExpr = Param->getDefaultArg();
2642
2643    // If the default expression creates temporaries, we need to
2644    // push them to the current stack of expression temporaries so they'll
2645    // be properly destroyed.
2646    if (CXXExprWithTemporaries *E
2647          = dyn_cast_or_null<CXXExprWithTemporaries>(DefaultExpr)) {
2648      assert(!E->shouldDestroyTemporaries() &&
2649             "Can't destroy temporaries in a default argument expr!");
2650      for (unsigned I = 0, N = E->getNumTemporaries(); I != N; ++I)
2651        ExprTemporaries.push_back(E->getTemporary(I));
2652    }
2653  }
2654
2655  // We already type-checked the argument, so we know it works.
2656  return Owned(CXXDefaultArgExpr::Create(Context, Param));
2657}
2658
2659/// ConvertArgumentsForCall - Converts the arguments specified in
2660/// Args/NumArgs to the parameter types of the function FDecl with
2661/// function prototype Proto. Call is the call expression itself, and
2662/// Fn is the function expression. For a C++ member function, this
2663/// routine does not attempt to convert the object argument. Returns
2664/// true if the call is ill-formed.
2665bool
2666Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
2667                              FunctionDecl *FDecl,
2668                              const FunctionProtoType *Proto,
2669                              Expr **Args, unsigned NumArgs,
2670                              SourceLocation RParenLoc) {
2671  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
2672  // assignment, to the types of the corresponding parameter, ...
2673  unsigned NumArgsInProto = Proto->getNumArgs();
2674  unsigned NumArgsToCheck = NumArgs;
2675  bool Invalid = false;
2676
2677  // If too few arguments are available (and we don't have default
2678  // arguments for the remaining parameters), don't make the call.
2679  if (NumArgs < NumArgsInProto) {
2680    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
2681      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
2682        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange();
2683    // Use default arguments for missing arguments
2684    NumArgsToCheck = NumArgsInProto;
2685    Call->setNumArgs(Context, NumArgsInProto);
2686  }
2687
2688  // If too many are passed and not variadic, error on the extras and drop
2689  // them.
2690  if (NumArgs > NumArgsInProto) {
2691    if (!Proto->isVariadic()) {
2692      Diag(Args[NumArgsInProto]->getLocStart(),
2693           diag::err_typecheck_call_too_many_args)
2694        << Fn->getType()->isBlockPointerType() << Fn->getSourceRange()
2695        << SourceRange(Args[NumArgsInProto]->getLocStart(),
2696                       Args[NumArgs-1]->getLocEnd());
2697      // This deletes the extra arguments.
2698      Call->setNumArgs(Context, NumArgsInProto);
2699      Invalid = true;
2700    }
2701    NumArgsToCheck = NumArgsInProto;
2702  }
2703
2704  // Continue to check argument types (even if we have too few/many args).
2705  for (unsigned i = 0; i != NumArgsToCheck; i++) {
2706    QualType ProtoArgType = Proto->getArgType(i);
2707
2708    Expr *Arg;
2709    if (i < NumArgs) {
2710      Arg = Args[i];
2711
2712      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
2713                              ProtoArgType,
2714                              PDiag(diag::err_call_incomplete_argument)
2715                                << Arg->getSourceRange()))
2716        return true;
2717
2718      // Pass the argument.
2719      if (PerformCopyInitialization(Arg, ProtoArgType, "passing"))
2720        return true;
2721    } else {
2722      ParmVarDecl *Param = FDecl->getParamDecl(i);
2723
2724      OwningExprResult ArgExpr =
2725        BuildCXXDefaultArgExpr(Call->getSourceRange().getBegin(),
2726                               FDecl, Param);
2727      if (ArgExpr.isInvalid())
2728        return true;
2729
2730      Arg = ArgExpr.takeAs<Expr>();
2731    }
2732
2733    Call->setArg(i, Arg);
2734  }
2735
2736  // If this is a variadic call, handle args passed through "...".
2737  if (Proto->isVariadic()) {
2738    VariadicCallType CallType = VariadicFunction;
2739    if (Fn->getType()->isBlockPointerType())
2740      CallType = VariadicBlock; // Block
2741    else if (isa<MemberExpr>(Fn))
2742      CallType = VariadicMethod;
2743
2744    // Promote the arguments (C99 6.5.2.2p7).
2745    for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
2746      Expr *Arg = Args[i];
2747      Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType);
2748      Call->setArg(i, Arg);
2749    }
2750  }
2751
2752  return Invalid;
2753}
2754
2755/// \brief "Deconstruct" the function argument of a call expression to find
2756/// the underlying declaration (if any), the name of the called function,
2757/// whether argument-dependent lookup is available, whether it has explicit
2758/// template arguments, etc.
2759void Sema::DeconstructCallFunction(Expr *FnExpr,
2760                                   NamedDecl *&Function,
2761                                   DeclarationName &Name,
2762                                   NestedNameSpecifier *&Qualifier,
2763                                   SourceRange &QualifierRange,
2764                                   bool &ArgumentDependentLookup,
2765                                   bool &HasExplicitTemplateArguments,
2766                                 const TemplateArgument *&ExplicitTemplateArgs,
2767                                   unsigned &NumExplicitTemplateArgs) {
2768  // Set defaults for all of the output parameters.
2769  Function = 0;
2770  Name = DeclarationName();
2771  Qualifier = 0;
2772  QualifierRange = SourceRange();
2773  ArgumentDependentLookup = getLangOptions().CPlusPlus;
2774  HasExplicitTemplateArguments = false;
2775
2776  // If we're directly calling a function, get the appropriate declaration.
2777  // Also, in C++, keep track of whether we should perform argument-dependent
2778  // lookup and whether there were any explicitly-specified template arguments.
2779  while (true) {
2780    if (ImplicitCastExpr *IcExpr = dyn_cast<ImplicitCastExpr>(FnExpr))
2781      FnExpr = IcExpr->getSubExpr();
2782    else if (ParenExpr *PExpr = dyn_cast<ParenExpr>(FnExpr)) {
2783      // Parentheses around a function disable ADL
2784      // (C++0x [basic.lookup.argdep]p1).
2785      ArgumentDependentLookup = false;
2786      FnExpr = PExpr->getSubExpr();
2787    } else if (isa<UnaryOperator>(FnExpr) &&
2788               cast<UnaryOperator>(FnExpr)->getOpcode()
2789               == UnaryOperator::AddrOf) {
2790      FnExpr = cast<UnaryOperator>(FnExpr)->getSubExpr();
2791    } else if (QualifiedDeclRefExpr *QDRExpr
2792                 = dyn_cast<QualifiedDeclRefExpr>(FnExpr)) {
2793      // Qualified names disable ADL (C++0x [basic.lookup.argdep]p1).
2794      ArgumentDependentLookup = false;
2795      Qualifier = QDRExpr->getQualifier();
2796      QualifierRange = QDRExpr->getQualifierRange();
2797      Function = dyn_cast<NamedDecl>(QDRExpr->getDecl());
2798      break;
2799    } else if (DeclRefExpr *DRExpr = dyn_cast<DeclRefExpr>(FnExpr)) {
2800      Function = dyn_cast<NamedDecl>(DRExpr->getDecl());
2801      break;
2802    } else if (UnresolvedFunctionNameExpr *DepName
2803               = dyn_cast<UnresolvedFunctionNameExpr>(FnExpr)) {
2804      Name = DepName->getName();
2805      break;
2806    } else if (TemplateIdRefExpr *TemplateIdRef
2807               = dyn_cast<TemplateIdRefExpr>(FnExpr)) {
2808      Function = TemplateIdRef->getTemplateName().getAsTemplateDecl();
2809      if (!Function)
2810        Function = TemplateIdRef->getTemplateName().getAsOverloadedFunctionDecl();
2811      HasExplicitTemplateArguments = true;
2812      ExplicitTemplateArgs = TemplateIdRef->getTemplateArgs();
2813      NumExplicitTemplateArgs = TemplateIdRef->getNumTemplateArgs();
2814
2815      // C++ [temp.arg.explicit]p6:
2816      //   [Note: For simple function names, argument dependent lookup (3.4.2)
2817      //   applies even when the function name is not visible within the
2818      //   scope of the call. This is because the call still has the syntactic
2819      //   form of a function call (3.4.1). But when a function template with
2820      //   explicit template arguments is used, the call does not have the
2821      //   correct syntactic form unless there is a function template with
2822      //   that name visible at the point of the call. If no such name is
2823      //   visible, the call is not syntactically well-formed and
2824      //   argument-dependent lookup does not apply. If some such name is
2825      //   visible, argument dependent lookup applies and additional function
2826      //   templates may be found in other namespaces.
2827      //
2828      // The summary of this paragraph is that, if we get to this point and the
2829      // template-id was not a qualified name, then argument-dependent lookup
2830      // is still possible.
2831      if ((Qualifier = TemplateIdRef->getQualifier())) {
2832        ArgumentDependentLookup = false;
2833        QualifierRange = TemplateIdRef->getQualifierRange();
2834      }
2835      break;
2836    } else {
2837      // Any kind of name that does not refer to a declaration (or
2838      // set of declarations) disables ADL (C++0x [basic.lookup.argdep]p3).
2839      ArgumentDependentLookup = false;
2840      break;
2841    }
2842  }
2843}
2844
2845/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
2846/// This provides the location of the left/right parens and a list of comma
2847/// locations.
2848Action::OwningExprResult
2849Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
2850                    MultiExprArg args,
2851                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
2852  unsigned NumArgs = args.size();
2853
2854  // Since this might be a postfix expression, get rid of ParenListExprs.
2855  fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
2856
2857  Expr *Fn = fn.takeAs<Expr>();
2858  Expr **Args = reinterpret_cast<Expr**>(args.release());
2859  assert(Fn && "no function call expression");
2860  FunctionDecl *FDecl = NULL;
2861  NamedDecl *NDecl = NULL;
2862  DeclarationName UnqualifiedName;
2863
2864  if (getLangOptions().CPlusPlus) {
2865    // If this is a pseudo-destructor expression, build the call immediately.
2866    if (isa<CXXPseudoDestructorExpr>(Fn)) {
2867      if (NumArgs > 0) {
2868        // Pseudo-destructor calls should not have any arguments.
2869        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
2870          << CodeModificationHint::CreateRemoval(
2871                                    SourceRange(Args[0]->getLocStart(),
2872                                                Args[NumArgs-1]->getLocEnd()));
2873
2874        for (unsigned I = 0; I != NumArgs; ++I)
2875          Args[I]->Destroy(Context);
2876
2877        NumArgs = 0;
2878      }
2879
2880      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
2881                                          RParenLoc));
2882    }
2883
2884    // Determine whether this is a dependent call inside a C++ template,
2885    // in which case we won't do any semantic analysis now.
2886    // FIXME: Will need to cache the results of name lookup (including ADL) in
2887    // Fn.
2888    bool Dependent = false;
2889    if (Fn->isTypeDependent())
2890      Dependent = true;
2891    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
2892      Dependent = true;
2893
2894    if (Dependent)
2895      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
2896                                          Context.DependentTy, RParenLoc));
2897
2898    // Determine whether this is a call to an object (C++ [over.call.object]).
2899    if (Fn->getType()->isRecordType())
2900      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
2901                                                CommaLocs, RParenLoc));
2902
2903    // Determine whether this is a call to a member function.
2904    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(Fn->IgnoreParens())) {
2905      NamedDecl *MemDecl = MemExpr->getMemberDecl();
2906      if (isa<OverloadedFunctionDecl>(MemDecl) ||
2907          isa<CXXMethodDecl>(MemDecl) ||
2908          (isa<FunctionTemplateDecl>(MemDecl) &&
2909           isa<CXXMethodDecl>(
2910                cast<FunctionTemplateDecl>(MemDecl)->getTemplatedDecl())))
2911        return Owned(BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
2912                                               CommaLocs, RParenLoc));
2913    }
2914
2915    // Determine whether this is a call to a pointer-to-member function.
2916    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Fn->IgnoreParens())) {
2917      if (BO->getOpcode() == BinaryOperator::PtrMemD ||
2918          BO->getOpcode() == BinaryOperator::PtrMemI) {
2919        const FunctionProtoType *FPT = cast<FunctionProtoType>(BO->getType());
2920        QualType ResultTy = FPT->getResultType().getNonReferenceType();
2921
2922        ExprOwningPtr<CXXMemberCallExpr>
2923          TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
2924                                                        NumArgs, ResultTy,
2925                                                        RParenLoc));
2926
2927        if (CheckCallReturnType(FPT->getResultType(),
2928                                BO->getRHS()->getSourceRange().getBegin(),
2929                                TheCall.get(), 0))
2930          return ExprError();
2931
2932        if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
2933                                    RParenLoc))
2934          return ExprError();
2935
2936        return Owned(MaybeBindToTemporary(TheCall.release()).release());
2937      }
2938    }
2939  }
2940
2941  // If we're directly calling a function, get the appropriate declaration.
2942  // Also, in C++, keep track of whether we should perform argument-dependent
2943  // lookup and whether there were any explicitly-specified template arguments.
2944  bool ADL = true;
2945  bool HasExplicitTemplateArgs = 0;
2946  const TemplateArgument *ExplicitTemplateArgs = 0;
2947  unsigned NumExplicitTemplateArgs = 0;
2948  NestedNameSpecifier *Qualifier = 0;
2949  SourceRange QualifierRange;
2950  DeconstructCallFunction(Fn, NDecl, UnqualifiedName, Qualifier, QualifierRange,
2951                          ADL,HasExplicitTemplateArgs, ExplicitTemplateArgs,
2952                          NumExplicitTemplateArgs);
2953
2954  OverloadedFunctionDecl *Ovl = 0;
2955  FunctionTemplateDecl *FunctionTemplate = 0;
2956  if (NDecl) {
2957    FDecl = dyn_cast<FunctionDecl>(NDecl);
2958    if ((FunctionTemplate = dyn_cast<FunctionTemplateDecl>(NDecl)))
2959      FDecl = FunctionTemplate->getTemplatedDecl();
2960    else
2961      FDecl = dyn_cast<FunctionDecl>(NDecl);
2962    Ovl = dyn_cast<OverloadedFunctionDecl>(NDecl);
2963  }
2964
2965  if (Ovl || FunctionTemplate ||
2966      (getLangOptions().CPlusPlus && (FDecl || UnqualifiedName))) {
2967    // We don't perform ADL for implicit declarations of builtins.
2968    if (FDecl && FDecl->getBuiltinID() && FDecl->isImplicit())
2969      ADL = false;
2970
2971    // We don't perform ADL in C.
2972    if (!getLangOptions().CPlusPlus)
2973      ADL = false;
2974
2975    if (Ovl || FunctionTemplate || ADL) {
2976      FDecl = ResolveOverloadedCallFn(Fn, NDecl, UnqualifiedName,
2977                                      HasExplicitTemplateArgs,
2978                                      ExplicitTemplateArgs,
2979                                      NumExplicitTemplateArgs,
2980                                      LParenLoc, Args, NumArgs, CommaLocs,
2981                                      RParenLoc, ADL);
2982      if (!FDecl)
2983        return ExprError();
2984
2985      // Update Fn to refer to the actual function selected.
2986      Expr *NewFn = 0;
2987      if (Qualifier)
2988        NewFn = new (Context) QualifiedDeclRefExpr(FDecl, FDecl->getType(),
2989                                                   Fn->getLocStart(),
2990                                                   false, false,
2991                                                   QualifierRange,
2992                                                   Qualifier);
2993      else
2994        NewFn = new (Context) DeclRefExpr(FDecl, FDecl->getType(),
2995                                          Fn->getLocStart());
2996      Fn->Destroy(Context);
2997      Fn = NewFn;
2998    }
2999  }
3000
3001  // Promote the function operand.
3002  UsualUnaryConversions(Fn);
3003
3004  // Make the call expr early, before semantic checks.  This guarantees cleanup
3005  // of arguments and function on error.
3006  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3007                                                               Args, NumArgs,
3008                                                               Context.BoolTy,
3009                                                               RParenLoc));
3010
3011  const FunctionType *FuncT;
3012  if (!Fn->getType()->isBlockPointerType()) {
3013    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3014    // have type pointer to function".
3015    const PointerType *PT = Fn->getType()->getAs<PointerType>();
3016    if (PT == 0)
3017      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3018        << Fn->getType() << Fn->getSourceRange());
3019    FuncT = PT->getPointeeType()->getAs<FunctionType>();
3020  } else { // This is a block call.
3021    FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
3022                getAs<FunctionType>();
3023  }
3024  if (FuncT == 0)
3025    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3026      << Fn->getType() << Fn->getSourceRange());
3027
3028  // Check for a valid return type
3029  if (CheckCallReturnType(FuncT->getResultType(),
3030                          Fn->getSourceRange().getBegin(), TheCall.get(),
3031                          FDecl))
3032    return ExprError();
3033
3034  // We know the result type of the call, set it.
3035  TheCall->setType(FuncT->getResultType().getNonReferenceType());
3036
3037  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
3038    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
3039                                RParenLoc))
3040      return ExprError();
3041  } else {
3042    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3043
3044    if (FDecl) {
3045      // Check if we have too few/too many template arguments, based
3046      // on our knowledge of the function definition.
3047      const FunctionDecl *Def = 0;
3048      if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
3049        const FunctionProtoType *Proto =
3050            Def->getType()->getAs<FunctionProtoType>();
3051        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3052          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3053            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3054        }
3055      }
3056    }
3057
3058    // Promote the arguments (C99 6.5.2.2p6).
3059    for (unsigned i = 0; i != NumArgs; i++) {
3060      Expr *Arg = Args[i];
3061      DefaultArgumentPromotion(Arg);
3062      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3063                              Arg->getType(),
3064                              PDiag(diag::err_call_incomplete_argument)
3065                                << Arg->getSourceRange()))
3066        return ExprError();
3067      TheCall->setArg(i, Arg);
3068    }
3069  }
3070
3071  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3072    if (!Method->isStatic())
3073      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3074        << Fn->getSourceRange());
3075
3076  // Check for sentinels
3077  if (NDecl)
3078    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3079
3080  // Do special checking on direct calls to functions.
3081  if (FDecl) {
3082    if (CheckFunctionCall(FDecl, TheCall.get()))
3083      return ExprError();
3084
3085    if (unsigned BuiltinID = FDecl->getBuiltinID())
3086      return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3087  } else if (NDecl) {
3088    if (CheckBlockCall(NDecl, TheCall.get()))
3089      return ExprError();
3090  }
3091
3092  return MaybeBindToTemporary(TheCall.take());
3093}
3094
3095Action::OwningExprResult
3096Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3097                           SourceLocation RParenLoc, ExprArg InitExpr) {
3098  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3099  //FIXME: Preserve type source info.
3100  QualType literalType = GetTypeFromParser(Ty);
3101  // FIXME: put back this assert when initializers are worked out.
3102  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3103  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
3104
3105  if (literalType->isArrayType()) {
3106    if (literalType->isVariableArrayType())
3107      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3108        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3109  } else if (!literalType->isDependentType() &&
3110             RequireCompleteType(LParenLoc, literalType,
3111                      PDiag(diag::err_typecheck_decl_incomplete_type)
3112                        << SourceRange(LParenLoc,
3113                                       literalExpr->getSourceRange().getEnd())))
3114    return ExprError();
3115
3116  if (CheckInitializerTypes(literalExpr, literalType, LParenLoc,
3117                            DeclarationName(), /*FIXME:DirectInit=*/false))
3118    return ExprError();
3119
3120  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3121  if (isFileScope) { // 6.5.2.5p3
3122    if (CheckForConstantInitializer(literalExpr, literalType))
3123      return ExprError();
3124  }
3125  InitExpr.release();
3126  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, literalType,
3127                                                 literalExpr, isFileScope));
3128}
3129
3130Action::OwningExprResult
3131Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3132                    SourceLocation RBraceLoc) {
3133  unsigned NumInit = initlist.size();
3134  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
3135
3136  // Semantic analysis for initializers is done by ActOnDeclarator() and
3137  // CheckInitializer() - it requires knowledge of the object being intialized.
3138
3139  InitListExpr *E = new (Context) InitListExpr(LBraceLoc, InitList, NumInit,
3140                                               RBraceLoc);
3141  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3142  return Owned(E);
3143}
3144
3145/// CheckCastTypes - Check type constraints for casting between types.
3146bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
3147                          CastExpr::CastKind& Kind,
3148                          CXXMethodDecl *& ConversionDecl,
3149                          bool FunctionalStyle) {
3150  if (getLangOptions().CPlusPlus)
3151    return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, FunctionalStyle,
3152                              ConversionDecl);
3153
3154  DefaultFunctionArrayConversion(castExpr);
3155
3156  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3157  // type needs to be scalar.
3158  if (castType->isVoidType()) {
3159    // Cast to void allows any expr type.
3160  } else if (!castType->isScalarType() && !castType->isVectorType()) {
3161    if (Context.getCanonicalType(castType).getUnqualifiedType() ==
3162        Context.getCanonicalType(castExpr->getType().getUnqualifiedType()) &&
3163        (castType->isStructureType() || castType->isUnionType())) {
3164      // GCC struct/union extension: allow cast to self.
3165      // FIXME: Check that the cast destination type is complete.
3166      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3167        << castType << castExpr->getSourceRange();
3168      Kind = CastExpr::CK_NoOp;
3169    } else if (castType->isUnionType()) {
3170      // GCC cast to union extension
3171      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3172      RecordDecl::field_iterator Field, FieldEnd;
3173      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3174           Field != FieldEnd; ++Field) {
3175        if (Context.getCanonicalType(Field->getType()).getUnqualifiedType() ==
3176            Context.getCanonicalType(castExpr->getType()).getUnqualifiedType()) {
3177          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3178            << castExpr->getSourceRange();
3179          break;
3180        }
3181      }
3182      if (Field == FieldEnd)
3183        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3184          << castExpr->getType() << castExpr->getSourceRange();
3185      Kind = CastExpr::CK_ToUnion;
3186    } else {
3187      // Reject any other conversions to non-scalar types.
3188      return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3189        << castType << castExpr->getSourceRange();
3190    }
3191  } else if (!castExpr->getType()->isScalarType() &&
3192             !castExpr->getType()->isVectorType()) {
3193    return Diag(castExpr->getLocStart(),
3194                diag::err_typecheck_expect_scalar_operand)
3195      << castExpr->getType() << castExpr->getSourceRange();
3196  } else if (castType->isExtVectorType()) {
3197    if (CheckExtVectorCast(TyR, castType, castExpr->getType()))
3198      return true;
3199  } else if (castType->isVectorType()) {
3200    if (CheckVectorCast(TyR, castType, castExpr->getType()))
3201      return true;
3202  } else if (castExpr->getType()->isVectorType()) {
3203    if (CheckVectorCast(TyR, castExpr->getType(), castType))
3204      return true;
3205  } else if (getLangOptions().ObjC1 && isa<ObjCSuperExpr>(castExpr)) {
3206    return Diag(castExpr->getLocStart(), diag::err_illegal_super_cast) << TyR;
3207  } else if (!castType->isArithmeticType()) {
3208    QualType castExprType = castExpr->getType();
3209    if (!castExprType->isIntegralType() && castExprType->isArithmeticType())
3210      return Diag(castExpr->getLocStart(),
3211                  diag::err_cast_pointer_from_non_pointer_int)
3212        << castExprType << castExpr->getSourceRange();
3213  } else if (!castExpr->getType()->isArithmeticType()) {
3214    if (!castType->isIntegralType() && castType->isArithmeticType())
3215      return Diag(castExpr->getLocStart(),
3216                  diag::err_cast_pointer_to_non_pointer_int)
3217        << castType << castExpr->getSourceRange();
3218  }
3219  if (isa<ObjCSelectorExpr>(castExpr))
3220    return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3221  return false;
3222}
3223
3224bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty) {
3225  assert(VectorTy->isVectorType() && "Not a vector type!");
3226
3227  if (Ty->isVectorType() || Ty->isIntegerType()) {
3228    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
3229      return Diag(R.getBegin(),
3230                  Ty->isVectorType() ?
3231                  diag::err_invalid_conversion_between_vectors :
3232                  diag::err_invalid_conversion_between_vector_and_integer)
3233        << VectorTy << Ty << R;
3234  } else
3235    return Diag(R.getBegin(),
3236                diag::err_invalid_conversion_between_vector_and_scalar)
3237      << VectorTy << Ty << R;
3238
3239  return false;
3240}
3241
3242bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, QualType SrcTy) {
3243  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3244
3245  // If SrcTy is a VectorType, the total size must match to explicitly cast to
3246  // an ExtVectorType.
3247  if (SrcTy->isVectorType()) {
3248    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3249      return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3250        << DestTy << SrcTy << R;
3251    return false;
3252  }
3253
3254  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
3255  // conversion will take place first from scalar to elt type, and then
3256  // splat from elt type to vector.
3257  if (SrcTy->isPointerType())
3258    return Diag(R.getBegin(),
3259                diag::err_invalid_conversion_between_vector_and_scalar)
3260      << DestTy << SrcTy << R;
3261  return false;
3262}
3263
3264Action::OwningExprResult
3265Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
3266                    SourceLocation RParenLoc, ExprArg Op) {
3267  CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3268
3269  assert((Ty != 0) && (Op.get() != 0) &&
3270         "ActOnCastExpr(): missing type or expr");
3271
3272  Expr *castExpr = (Expr *)Op.get();
3273  //FIXME: Preserve type source info.
3274  QualType castType = GetTypeFromParser(Ty);
3275
3276  // If the Expr being casted is a ParenListExpr, handle it specially.
3277  if (isa<ParenListExpr>(castExpr))
3278    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),castType);
3279  CXXMethodDecl *Method = 0;
3280  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), castType, castExpr,
3281                     Kind, Method))
3282    return ExprError();
3283
3284  if (Method) {
3285    OwningExprResult CastArg = BuildCXXCastArgument(LParenLoc, castType, Kind,
3286                                                    Method, move(Op));
3287
3288    if (CastArg.isInvalid())
3289      return ExprError();
3290
3291    castExpr = CastArg.takeAs<Expr>();
3292  } else {
3293    Op.release();
3294  }
3295
3296  return Owned(new (Context) CStyleCastExpr(castType.getNonReferenceType(),
3297                                            Kind, castExpr, castType,
3298                                            LParenLoc, RParenLoc));
3299}
3300
3301/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3302/// of comma binary operators.
3303Action::OwningExprResult
3304Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
3305  Expr *expr = EA.takeAs<Expr>();
3306  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
3307  if (!E)
3308    return Owned(expr);
3309
3310  OwningExprResult Result(*this, E->getExpr(0));
3311
3312  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
3313    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
3314                        Owned(E->getExpr(i)));
3315
3316  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
3317}
3318
3319Action::OwningExprResult
3320Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
3321                               SourceLocation RParenLoc, ExprArg Op,
3322                               QualType Ty) {
3323  ParenListExpr *PE = (ParenListExpr *)Op.get();
3324
3325  // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
3326  // then handle it as such.
3327  if (getLangOptions().AltiVec && Ty->isVectorType()) {
3328    if (PE->getNumExprs() == 0) {
3329      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
3330      return ExprError();
3331    }
3332
3333    llvm::SmallVector<Expr *, 8> initExprs;
3334    for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
3335      initExprs.push_back(PE->getExpr(i));
3336
3337    // FIXME: This means that pretty-printing the final AST will produce curly
3338    // braces instead of the original commas.
3339    Op.release();
3340    InitListExpr *E = new (Context) InitListExpr(LParenLoc, &initExprs[0],
3341                                                 initExprs.size(), RParenLoc);
3342    E->setType(Ty);
3343    return ActOnCompoundLiteral(LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,
3344                                Owned(E));
3345  } else {
3346    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
3347    // sequence of BinOp comma operators.
3348    Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
3349    return ActOnCastExpr(S, LParenLoc, Ty.getAsOpaquePtr(), RParenLoc,move(Op));
3350  }
3351}
3352
3353Action::OwningExprResult Sema::ActOnParenListExpr(SourceLocation L,
3354                                                  SourceLocation R,
3355                                                  MultiExprArg Val) {
3356  unsigned nexprs = Val.size();
3357  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
3358  assert((exprs != 0) && "ActOnParenListExpr() missing expr list");
3359  Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
3360  return Owned(expr);
3361}
3362
3363/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
3364/// In that case, lhs = cond.
3365/// C99 6.5.15
3366QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
3367                                        SourceLocation QuestionLoc) {
3368  // C++ is sufficiently different to merit its own checker.
3369  if (getLangOptions().CPlusPlus)
3370    return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
3371
3372  UsualUnaryConversions(Cond);
3373  UsualUnaryConversions(LHS);
3374  UsualUnaryConversions(RHS);
3375  QualType CondTy = Cond->getType();
3376  QualType LHSTy = LHS->getType();
3377  QualType RHSTy = RHS->getType();
3378
3379  // first, check the condition.
3380  if (!CondTy->isScalarType()) { // C99 6.5.15p2
3381    Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
3382      << CondTy;
3383    return QualType();
3384  }
3385
3386  // Now check the two expressions.
3387  if (LHSTy->isVectorType() || RHSTy->isVectorType())
3388    return CheckVectorOperands(QuestionLoc, LHS, RHS);
3389
3390  // If both operands have arithmetic type, do the usual arithmetic conversions
3391  // to find a common type: C99 6.5.15p3,5.
3392  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
3393    UsualArithmeticConversions(LHS, RHS);
3394    return LHS->getType();
3395  }
3396
3397  // If both operands are the same structure or union type, the result is that
3398  // type.
3399  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
3400    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
3401      if (LHSRT->getDecl() == RHSRT->getDecl())
3402        // "If both the operands have structure or union type, the result has
3403        // that type."  This implies that CV qualifiers are dropped.
3404        return LHSTy.getUnqualifiedType();
3405    // FIXME: Type of conditional expression must be complete in C mode.
3406  }
3407
3408  // C99 6.5.15p5: "If both operands have void type, the result has void type."
3409  // The following || allows only one side to be void (a GCC-ism).
3410  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
3411    if (!LHSTy->isVoidType())
3412      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3413        << RHS->getSourceRange();
3414    if (!RHSTy->isVoidType())
3415      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
3416        << LHS->getSourceRange();
3417    ImpCastExprToType(LHS, Context.VoidTy);
3418    ImpCastExprToType(RHS, Context.VoidTy);
3419    return Context.VoidTy;
3420  }
3421  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
3422  // the type of the other operand."
3423  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
3424      RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3425    ImpCastExprToType(RHS, LHSTy); // promote the null to a pointer.
3426    return LHSTy;
3427  }
3428  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
3429      LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
3430    ImpCastExprToType(LHS, RHSTy); // promote the null to a pointer.
3431    return RHSTy;
3432  }
3433  // Handle things like Class and struct objc_class*.  Here we case the result
3434  // to the pseudo-builtin, because that will be implicitly cast back to the
3435  // redefinition type if an attempt is made to access its fields.
3436  if (LHSTy->isObjCClassType() &&
3437      (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3438    ImpCastExprToType(RHS, LHSTy);
3439    return LHSTy;
3440  }
3441  if (RHSTy->isObjCClassType() &&
3442      (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
3443    ImpCastExprToType(LHS, RHSTy);
3444    return RHSTy;
3445  }
3446  // And the same for struct objc_object* / id
3447  if (LHSTy->isObjCIdType() &&
3448      (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3449    ImpCastExprToType(RHS, LHSTy);
3450    return LHSTy;
3451  }
3452  if (RHSTy->isObjCIdType() &&
3453      (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
3454    ImpCastExprToType(LHS, RHSTy);
3455    return RHSTy;
3456  }
3457  // Handle block pointer types.
3458  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
3459    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
3460      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
3461        QualType destType = Context.getPointerType(Context.VoidTy);
3462        ImpCastExprToType(LHS, destType);
3463        ImpCastExprToType(RHS, destType);
3464        return destType;
3465      }
3466      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3467            << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3468      return QualType();
3469    }
3470    // We have 2 block pointer types.
3471    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3472      // Two identical block pointer types are always compatible.
3473      return LHSTy;
3474    }
3475    // The block pointer types aren't identical, continue checking.
3476    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
3477    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
3478
3479    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3480                                    rhptee.getUnqualifiedType())) {
3481      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3482        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3483      // In this situation, we assume void* type. No especially good
3484      // reason, but this is what gcc does, and we do have to pick
3485      // to get a consistent AST.
3486      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3487      ImpCastExprToType(LHS, incompatTy);
3488      ImpCastExprToType(RHS, incompatTy);
3489      return incompatTy;
3490    }
3491    // The block pointer types are compatible.
3492    ImpCastExprToType(LHS, LHSTy);
3493    ImpCastExprToType(RHS, LHSTy);
3494    return LHSTy;
3495  }
3496  // Check constraints for Objective-C object pointers types.
3497  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
3498
3499    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3500      // Two identical object pointer types are always compatible.
3501      return LHSTy;
3502    }
3503    const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
3504    const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
3505    QualType compositeType = LHSTy;
3506
3507    // If both operands are interfaces and either operand can be
3508    // assigned to the other, use that type as the composite
3509    // type. This allows
3510    //   xxx ? (A*) a : (B*) b
3511    // where B is a subclass of A.
3512    //
3513    // Additionally, as for assignment, if either type is 'id'
3514    // allow silent coercion. Finally, if the types are
3515    // incompatible then make sure to use 'id' as the composite
3516    // type so the result is acceptable for sending messages to.
3517
3518    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
3519    // It could return the composite type.
3520    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
3521      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
3522    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
3523      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
3524    } else if ((LHSTy->isObjCQualifiedIdType() ||
3525                RHSTy->isObjCQualifiedIdType()) &&
3526                Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
3527      // Need to handle "id<xx>" explicitly.
3528      // GCC allows qualified id and any Objective-C type to devolve to
3529      // id. Currently localizing to here until clear this should be
3530      // part of ObjCQualifiedIdTypesAreCompatible.
3531      compositeType = Context.getObjCIdType();
3532    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
3533      compositeType = Context.getObjCIdType();
3534    } else {
3535      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
3536        << LHSTy << RHSTy
3537        << LHS->getSourceRange() << RHS->getSourceRange();
3538      QualType incompatTy = Context.getObjCIdType();
3539      ImpCastExprToType(LHS, incompatTy);
3540      ImpCastExprToType(RHS, incompatTy);
3541      return incompatTy;
3542    }
3543    // The object pointer types are compatible.
3544    ImpCastExprToType(LHS, compositeType);
3545    ImpCastExprToType(RHS, compositeType);
3546    return compositeType;
3547  }
3548  // Check Objective-C object pointer types and 'void *'
3549  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
3550    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3551    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
3552    QualType destPointee
3553      = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
3554    QualType destType = Context.getPointerType(destPointee);
3555    ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3556    ImpCastExprToType(RHS, destType); // promote to void*
3557    return destType;
3558  }
3559  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
3560    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
3561    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3562    QualType destPointee
3563      = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
3564    QualType destType = Context.getPointerType(destPointee);
3565    ImpCastExprToType(RHS, destType); // add qualifiers if necessary
3566    ImpCastExprToType(LHS, destType); // promote to void*
3567    return destType;
3568  }
3569  // Check constraints for C object pointers types (C99 6.5.15p3,6).
3570  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
3571    // get the "pointed to" types
3572    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
3573    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
3574
3575    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
3576    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
3577      // Figure out necessary qualifiers (C99 6.5.15p6)
3578      QualType destPointee
3579        = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
3580      QualType destType = Context.getPointerType(destPointee);
3581      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3582      ImpCastExprToType(RHS, destType); // promote to void*
3583      return destType;
3584    }
3585    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
3586      QualType destPointee
3587        = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
3588      QualType destType = Context.getPointerType(destPointee);
3589      ImpCastExprToType(LHS, destType); // add qualifiers if necessary
3590      ImpCastExprToType(RHS, destType); // promote to void*
3591      return destType;
3592    }
3593
3594    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
3595      // Two identical pointer types are always compatible.
3596      return LHSTy;
3597    }
3598    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
3599                                    rhptee.getUnqualifiedType())) {
3600      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
3601        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3602      // In this situation, we assume void* type. No especially good
3603      // reason, but this is what gcc does, and we do have to pick
3604      // to get a consistent AST.
3605      QualType incompatTy = Context.getPointerType(Context.VoidTy);
3606      ImpCastExprToType(LHS, incompatTy);
3607      ImpCastExprToType(RHS, incompatTy);
3608      return incompatTy;
3609    }
3610    // The pointer types are compatible.
3611    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
3612    // differently qualified versions of compatible types, the result type is
3613    // a pointer to an appropriately qualified version of the *composite*
3614    // type.
3615    // FIXME: Need to calculate the composite type.
3616    // FIXME: Need to add qualifiers
3617    ImpCastExprToType(LHS, LHSTy);
3618    ImpCastExprToType(RHS, LHSTy);
3619    return LHSTy;
3620  }
3621
3622  // GCC compatibility: soften pointer/integer mismatch.
3623  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
3624    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3625      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3626    ImpCastExprToType(LHS, RHSTy); // promote the integer to a pointer.
3627    return RHSTy;
3628  }
3629  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
3630    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
3631      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3632    ImpCastExprToType(RHS, LHSTy); // promote the integer to a pointer.
3633    return LHSTy;
3634  }
3635
3636  // Otherwise, the operands are not compatible.
3637  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
3638    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
3639  return QualType();
3640}
3641
3642/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
3643/// in the case of a the GNU conditional expr extension.
3644Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
3645                                                  SourceLocation ColonLoc,
3646                                                  ExprArg Cond, ExprArg LHS,
3647                                                  ExprArg RHS) {
3648  Expr *CondExpr = (Expr *) Cond.get();
3649  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
3650
3651  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
3652  // was the condition.
3653  bool isLHSNull = LHSExpr == 0;
3654  if (isLHSNull)
3655    LHSExpr = CondExpr;
3656
3657  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
3658                                             RHSExpr, QuestionLoc);
3659  if (result.isNull())
3660    return ExprError();
3661
3662  Cond.release();
3663  LHS.release();
3664  RHS.release();
3665  return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
3666                                                 isLHSNull ? 0 : LHSExpr,
3667                                                 ColonLoc, RHSExpr, result));
3668}
3669
3670// CheckPointerTypesForAssignment - This is a very tricky routine (despite
3671// being closely modeled after the C99 spec:-). The odd characteristic of this
3672// routine is it effectively iqnores the qualifiers on the top level pointee.
3673// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
3674// FIXME: add a couple examples in this comment.
3675Sema::AssignConvertType
3676Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
3677  QualType lhptee, rhptee;
3678
3679  if ((lhsType->isObjCClassType() &&
3680       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3681     (rhsType->isObjCClassType() &&
3682       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3683      return Compatible;
3684  }
3685
3686  // get the "pointed to" type (ignoring qualifiers at the top level)
3687  lhptee = lhsType->getAs<PointerType>()->getPointeeType();
3688  rhptee = rhsType->getAs<PointerType>()->getPointeeType();
3689
3690  // make sure we operate on the canonical type
3691  lhptee = Context.getCanonicalType(lhptee);
3692  rhptee = Context.getCanonicalType(rhptee);
3693
3694  AssignConvertType ConvTy = Compatible;
3695
3696  // C99 6.5.16.1p1: This following citation is common to constraints
3697  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
3698  // qualifiers of the type *pointed to* by the right;
3699  // FIXME: Handle ExtQualType
3700  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
3701    ConvTy = CompatiblePointerDiscardsQualifiers;
3702
3703  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
3704  // incomplete type and the other is a pointer to a qualified or unqualified
3705  // version of void...
3706  if (lhptee->isVoidType()) {
3707    if (rhptee->isIncompleteOrObjectType())
3708      return ConvTy;
3709
3710    // As an extension, we allow cast to/from void* to function pointer.
3711    assert(rhptee->isFunctionType());
3712    return FunctionVoidPointer;
3713  }
3714
3715  if (rhptee->isVoidType()) {
3716    if (lhptee->isIncompleteOrObjectType())
3717      return ConvTy;
3718
3719    // As an extension, we allow cast to/from void* to function pointer.
3720    assert(lhptee->isFunctionType());
3721    return FunctionVoidPointer;
3722  }
3723  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
3724  // unqualified versions of compatible types, ...
3725  lhptee = lhptee.getUnqualifiedType();
3726  rhptee = rhptee.getUnqualifiedType();
3727  if (!Context.typesAreCompatible(lhptee, rhptee)) {
3728    // Check if the pointee types are compatible ignoring the sign.
3729    // We explicitly check for char so that we catch "char" vs
3730    // "unsigned char" on systems where "char" is unsigned.
3731    if (lhptee->isCharType()) {
3732      lhptee = Context.UnsignedCharTy;
3733    } else if (lhptee->isSignedIntegerType()) {
3734      lhptee = Context.getCorrespondingUnsignedType(lhptee);
3735    }
3736    if (rhptee->isCharType()) {
3737      rhptee = Context.UnsignedCharTy;
3738    } else if (rhptee->isSignedIntegerType()) {
3739      rhptee = Context.getCorrespondingUnsignedType(rhptee);
3740    }
3741    if (lhptee == rhptee) {
3742      // Types are compatible ignoring the sign. Qualifier incompatibility
3743      // takes priority over sign incompatibility because the sign
3744      // warning can be disabled.
3745      if (ConvTy != Compatible)
3746        return ConvTy;
3747      return IncompatiblePointerSign;
3748    }
3749    // General pointer incompatibility takes priority over qualifiers.
3750    return IncompatiblePointer;
3751  }
3752  return ConvTy;
3753}
3754
3755/// CheckBlockPointerTypesForAssignment - This routine determines whether two
3756/// block pointer types are compatible or whether a block and normal pointer
3757/// are compatible. It is more restrict than comparing two function pointer
3758// types.
3759Sema::AssignConvertType
3760Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
3761                                          QualType rhsType) {
3762  QualType lhptee, rhptee;
3763
3764  // get the "pointed to" type (ignoring qualifiers at the top level)
3765  lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
3766  rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
3767
3768  // make sure we operate on the canonical type
3769  lhptee = Context.getCanonicalType(lhptee);
3770  rhptee = Context.getCanonicalType(rhptee);
3771
3772  AssignConvertType ConvTy = Compatible;
3773
3774  // For blocks we enforce that qualifiers are identical.
3775  if (lhptee.getCVRQualifiers() != rhptee.getCVRQualifiers())
3776    ConvTy = CompatiblePointerDiscardsQualifiers;
3777
3778  if (!Context.typesAreCompatible(lhptee, rhptee))
3779    return IncompatibleBlockPointer;
3780  return ConvTy;
3781}
3782
3783/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
3784/// has code to accommodate several GCC extensions when type checking
3785/// pointers. Here are some objectionable examples that GCC considers warnings:
3786///
3787///  int a, *pint;
3788///  short *pshort;
3789///  struct foo *pfoo;
3790///
3791///  pint = pshort; // warning: assignment from incompatible pointer type
3792///  a = pint; // warning: assignment makes integer from pointer without a cast
3793///  pint = a; // warning: assignment makes pointer from integer without a cast
3794///  pint = pfoo; // warning: assignment from incompatible pointer type
3795///
3796/// As a result, the code for dealing with pointers is more complex than the
3797/// C99 spec dictates.
3798///
3799Sema::AssignConvertType
3800Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
3801  // Get canonical types.  We're not formatting these types, just comparing
3802  // them.
3803  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
3804  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
3805
3806  if (lhsType == rhsType)
3807    return Compatible; // Common case: fast path an exact match.
3808
3809  if ((lhsType->isObjCClassType() &&
3810       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
3811     (rhsType->isObjCClassType() &&
3812       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
3813      return Compatible;
3814  }
3815
3816  // If the left-hand side is a reference type, then we are in a
3817  // (rare!) case where we've allowed the use of references in C,
3818  // e.g., as a parameter type in a built-in function. In this case,
3819  // just make sure that the type referenced is compatible with the
3820  // right-hand side type. The caller is responsible for adjusting
3821  // lhsType so that the resulting expression does not have reference
3822  // type.
3823  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
3824    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
3825      return Compatible;
3826    return Incompatible;
3827  }
3828  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
3829  // to the same ExtVector type.
3830  if (lhsType->isExtVectorType()) {
3831    if (rhsType->isExtVectorType())
3832      return lhsType == rhsType ? Compatible : Incompatible;
3833    if (!rhsType->isVectorType() && rhsType->isArithmeticType())
3834      return Compatible;
3835  }
3836
3837  if (lhsType->isVectorType() || rhsType->isVectorType()) {
3838    // If we are allowing lax vector conversions, and LHS and RHS are both
3839    // vectors, the total size only needs to be the same. This is a bitcast;
3840    // no bits are changed but the result type is different.
3841    if (getLangOptions().LaxVectorConversions &&
3842        lhsType->isVectorType() && rhsType->isVectorType()) {
3843      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
3844        return IncompatibleVectors;
3845    }
3846    return Incompatible;
3847  }
3848
3849  if (lhsType->isArithmeticType() && rhsType->isArithmeticType())
3850    return Compatible;
3851
3852  if (isa<PointerType>(lhsType)) {
3853    if (rhsType->isIntegerType())
3854      return IntToPointer;
3855
3856    if (isa<PointerType>(rhsType))
3857      return CheckPointerTypesForAssignment(lhsType, rhsType);
3858
3859    // In general, C pointers are not compatible with ObjC object pointers.
3860    if (isa<ObjCObjectPointerType>(rhsType)) {
3861      if (lhsType->isVoidPointerType()) // an exception to the rule.
3862        return Compatible;
3863      return IncompatiblePointer;
3864    }
3865    if (rhsType->getAs<BlockPointerType>()) {
3866      if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3867        return Compatible;
3868
3869      // Treat block pointers as objects.
3870      if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
3871        return Compatible;
3872    }
3873    return Incompatible;
3874  }
3875
3876  if (isa<BlockPointerType>(lhsType)) {
3877    if (rhsType->isIntegerType())
3878      return IntToBlockPointer;
3879
3880    // Treat block pointers as objects.
3881    if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
3882      return Compatible;
3883
3884    if (rhsType->isBlockPointerType())
3885      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
3886
3887    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3888      if (RHSPT->getPointeeType()->isVoidType())
3889        return Compatible;
3890    }
3891    return Incompatible;
3892  }
3893
3894  if (isa<ObjCObjectPointerType>(lhsType)) {
3895    if (rhsType->isIntegerType())
3896      return IntToPointer;
3897
3898    // In general, C pointers are not compatible with ObjC object pointers.
3899    if (isa<PointerType>(rhsType)) {
3900      if (rhsType->isVoidPointerType()) // an exception to the rule.
3901        return Compatible;
3902      return IncompatiblePointer;
3903    }
3904    if (rhsType->isObjCObjectPointerType()) {
3905      if (lhsType->isObjCBuiltinType() || rhsType->isObjCBuiltinType())
3906        return Compatible;
3907      if (Context.typesAreCompatible(lhsType, rhsType))
3908        return Compatible;
3909      if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
3910        return IncompatibleObjCQualifiedId;
3911      return IncompatiblePointer;
3912    }
3913    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
3914      if (RHSPT->getPointeeType()->isVoidType())
3915        return Compatible;
3916    }
3917    // Treat block pointers as objects.
3918    if (rhsType->isBlockPointerType())
3919      return Compatible;
3920    return Incompatible;
3921  }
3922  if (isa<PointerType>(rhsType)) {
3923    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3924    if (lhsType == Context.BoolTy)
3925      return Compatible;
3926
3927    if (lhsType->isIntegerType())
3928      return PointerToInt;
3929
3930    if (isa<PointerType>(lhsType))
3931      return CheckPointerTypesForAssignment(lhsType, rhsType);
3932
3933    if (isa<BlockPointerType>(lhsType) &&
3934        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3935      return Compatible;
3936    return Incompatible;
3937  }
3938  if (isa<ObjCObjectPointerType>(rhsType)) {
3939    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
3940    if (lhsType == Context.BoolTy)
3941      return Compatible;
3942
3943    if (lhsType->isIntegerType())
3944      return PointerToInt;
3945
3946    // In general, C pointers are not compatible with ObjC object pointers.
3947    if (isa<PointerType>(lhsType)) {
3948      if (lhsType->isVoidPointerType()) // an exception to the rule.
3949        return Compatible;
3950      return IncompatiblePointer;
3951    }
3952    if (isa<BlockPointerType>(lhsType) &&
3953        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
3954      return Compatible;
3955    return Incompatible;
3956  }
3957
3958  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
3959    if (Context.typesAreCompatible(lhsType, rhsType))
3960      return Compatible;
3961  }
3962  return Incompatible;
3963}
3964
3965/// \brief Constructs a transparent union from an expression that is
3966/// used to initialize the transparent union.
3967static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
3968                                      QualType UnionType, FieldDecl *Field) {
3969  // Build an initializer list that designates the appropriate member
3970  // of the transparent union.
3971  InitListExpr *Initializer = new (C) InitListExpr(SourceLocation(),
3972                                                   &E, 1,
3973                                                   SourceLocation());
3974  Initializer->setType(UnionType);
3975  Initializer->setInitializedFieldInUnion(Field);
3976
3977  // Build a compound literal constructing a value of the transparent
3978  // union type from this initializer list.
3979  E = new (C) CompoundLiteralExpr(SourceLocation(), UnionType, Initializer,
3980                                  false);
3981}
3982
3983Sema::AssignConvertType
3984Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
3985  QualType FromType = rExpr->getType();
3986
3987  // If the ArgType is a Union type, we want to handle a potential
3988  // transparent_union GCC extension.
3989  const RecordType *UT = ArgType->getAsUnionType();
3990  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
3991    return Incompatible;
3992
3993  // The field to initialize within the transparent union.
3994  RecordDecl *UD = UT->getDecl();
3995  FieldDecl *InitField = 0;
3996  // It's compatible if the expression matches any of the fields.
3997  for (RecordDecl::field_iterator it = UD->field_begin(),
3998         itend = UD->field_end();
3999       it != itend; ++it) {
4000    if (it->getType()->isPointerType()) {
4001      // If the transparent union contains a pointer type, we allow:
4002      // 1) void pointer
4003      // 2) null pointer constant
4004      if (FromType->isPointerType())
4005        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
4006          ImpCastExprToType(rExpr, it->getType());
4007          InitField = *it;
4008          break;
4009        }
4010
4011      if (rExpr->isNullPointerConstant(Context,
4012                                       Expr::NPC_ValueDependentIsNull)) {
4013        ImpCastExprToType(rExpr, it->getType());
4014        InitField = *it;
4015        break;
4016      }
4017    }
4018
4019    if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4020          == Compatible) {
4021      InitField = *it;
4022      break;
4023    }
4024  }
4025
4026  if (!InitField)
4027    return Incompatible;
4028
4029  ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4030  return Compatible;
4031}
4032
4033Sema::AssignConvertType
4034Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
4035  if (getLangOptions().CPlusPlus) {
4036    if (!lhsType->isRecordType()) {
4037      // C++ 5.17p3: If the left operand is not of class type, the
4038      // expression is implicitly converted (C++ 4) to the
4039      // cv-unqualified type of the left operand.
4040      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4041                                    "assigning"))
4042        return Incompatible;
4043      return Compatible;
4044    }
4045
4046    // FIXME: Currently, we fall through and treat C++ classes like C
4047    // structures.
4048  }
4049
4050  // C99 6.5.16.1p1: the left operand is a pointer and the right is
4051  // a null pointer constant.
4052  if ((lhsType->isPointerType() ||
4053       lhsType->isObjCObjectPointerType() ||
4054       lhsType->isBlockPointerType())
4055      && rExpr->isNullPointerConstant(Context,
4056                                      Expr::NPC_ValueDependentIsNull)) {
4057    ImpCastExprToType(rExpr, lhsType);
4058    return Compatible;
4059  }
4060
4061  // This check seems unnatural, however it is necessary to ensure the proper
4062  // conversion of functions/arrays. If the conversion were done for all
4063  // DeclExpr's (created by ActOnIdentifierExpr), it would mess up the unary
4064  // expressions that surpress this implicit conversion (&, sizeof).
4065  //
4066  // Suppress this for references: C++ 8.5.3p5.
4067  if (!lhsType->isReferenceType())
4068    DefaultFunctionArrayConversion(rExpr);
4069
4070  Sema::AssignConvertType result =
4071    CheckAssignmentConstraints(lhsType, rExpr->getType());
4072
4073  // C99 6.5.16.1p2: The value of the right operand is converted to the
4074  // type of the assignment expression.
4075  // CheckAssignmentConstraints allows the left-hand side to be a reference,
4076  // so that we can use references in built-in functions even in C.
4077  // The getNonReferenceType() call makes sure that the resulting expression
4078  // does not have reference type.
4079  if (result != Incompatible && rExpr->getType() != lhsType)
4080    ImpCastExprToType(rExpr, lhsType.getNonReferenceType());
4081  return result;
4082}
4083
4084QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4085  Diag(Loc, diag::err_typecheck_invalid_operands)
4086    << lex->getType() << rex->getType()
4087    << lex->getSourceRange() << rex->getSourceRange();
4088  return QualType();
4089}
4090
4091inline QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex,
4092                                                              Expr *&rex) {
4093  // For conversion purposes, we ignore any qualifiers.
4094  // For example, "const float" and "float" are equivalent.
4095  QualType lhsType =
4096    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4097  QualType rhsType =
4098    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
4099
4100  // If the vector types are identical, return.
4101  if (lhsType == rhsType)
4102    return lhsType;
4103
4104  // Handle the case of a vector & extvector type of the same size and element
4105  // type.  It would be nice if we only had one vector type someday.
4106  if (getLangOptions().LaxVectorConversions) {
4107    // FIXME: Should we warn here?
4108    if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4109      if (const VectorType *RV = rhsType->getAs<VectorType>())
4110        if (LV->getElementType() == RV->getElementType() &&
4111            LV->getNumElements() == RV->getNumElements()) {
4112          return lhsType->isExtVectorType() ? lhsType : rhsType;
4113        }
4114    }
4115  }
4116
4117  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4118  // swap back (so that we don't reverse the inputs to a subtract, for instance.
4119  bool swapped = false;
4120  if (rhsType->isExtVectorType()) {
4121    swapped = true;
4122    std::swap(rex, lex);
4123    std::swap(rhsType, lhsType);
4124  }
4125
4126  // Handle the case of an ext vector and scalar.
4127  if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
4128    QualType EltTy = LV->getElementType();
4129    if (EltTy->isIntegralType() && rhsType->isIntegralType()) {
4130      if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
4131        ImpCastExprToType(rex, lhsType);
4132        if (swapped) std::swap(rex, lex);
4133        return lhsType;
4134      }
4135    }
4136    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4137        rhsType->isRealFloatingType()) {
4138      if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
4139        ImpCastExprToType(rex, lhsType);
4140        if (swapped) std::swap(rex, lex);
4141        return lhsType;
4142      }
4143    }
4144  }
4145
4146  // Vectors of different size or scalar and non-ext-vector are errors.
4147  Diag(Loc, diag::err_typecheck_vector_not_convertable)
4148    << lex->getType() << rex->getType()
4149    << lex->getSourceRange() << rex->getSourceRange();
4150  return QualType();
4151}
4152
4153inline QualType Sema::CheckMultiplyDivideOperands(
4154  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4155  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4156    return CheckVectorOperands(Loc, lex, rex);
4157
4158  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4159
4160  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4161    return compType;
4162  return InvalidOperands(Loc, lex, rex);
4163}
4164
4165inline QualType Sema::CheckRemainderOperands(
4166  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4167  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4168    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4169      return CheckVectorOperands(Loc, lex, rex);
4170    return InvalidOperands(Loc, lex, rex);
4171  }
4172
4173  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4174
4175  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4176    return compType;
4177  return InvalidOperands(Loc, lex, rex);
4178}
4179
4180inline QualType Sema::CheckAdditionOperands( // C99 6.5.6
4181  Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
4182  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4183    QualType compType = CheckVectorOperands(Loc, lex, rex);
4184    if (CompLHSTy) *CompLHSTy = compType;
4185    return compType;
4186  }
4187
4188  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4189
4190  // handle the common case first (both operands are arithmetic).
4191  if (lex->getType()->isArithmeticType() &&
4192      rex->getType()->isArithmeticType()) {
4193    if (CompLHSTy) *CompLHSTy = compType;
4194    return compType;
4195  }
4196
4197  // Put any potential pointer into PExp
4198  Expr* PExp = lex, *IExp = rex;
4199  if (IExp->getType()->isAnyPointerType())
4200    std::swap(PExp, IExp);
4201
4202  if (PExp->getType()->isAnyPointerType()) {
4203
4204    if (IExp->getType()->isIntegerType()) {
4205      QualType PointeeTy = PExp->getType()->getPointeeType();
4206
4207      // Check for arithmetic on pointers to incomplete types.
4208      if (PointeeTy->isVoidType()) {
4209        if (getLangOptions().CPlusPlus) {
4210          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4211            << lex->getSourceRange() << rex->getSourceRange();
4212          return QualType();
4213        }
4214
4215        // GNU extension: arithmetic on pointer to void
4216        Diag(Loc, diag::ext_gnu_void_ptr)
4217          << lex->getSourceRange() << rex->getSourceRange();
4218      } else if (PointeeTy->isFunctionType()) {
4219        if (getLangOptions().CPlusPlus) {
4220          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4221            << lex->getType() << lex->getSourceRange();
4222          return QualType();
4223        }
4224
4225        // GNU extension: arithmetic on pointer to function
4226        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4227          << lex->getType() << lex->getSourceRange();
4228      } else {
4229        // Check if we require a complete type.
4230        if (((PExp->getType()->isPointerType() &&
4231              !PExp->getType()->isDependentType()) ||
4232              PExp->getType()->isObjCObjectPointerType()) &&
4233             RequireCompleteType(Loc, PointeeTy,
4234                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
4235                             << PExp->getSourceRange()
4236                             << PExp->getType()))
4237          return QualType();
4238      }
4239      // Diagnose bad cases where we step over interface counts.
4240      if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4241        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4242          << PointeeTy << PExp->getSourceRange();
4243        return QualType();
4244      }
4245
4246      if (CompLHSTy) {
4247        QualType LHSTy = Context.isPromotableBitField(lex);
4248        if (LHSTy.isNull()) {
4249          LHSTy = lex->getType();
4250          if (LHSTy->isPromotableIntegerType())
4251            LHSTy = Context.getPromotedIntegerType(LHSTy);
4252        }
4253        *CompLHSTy = LHSTy;
4254      }
4255      return PExp->getType();
4256    }
4257  }
4258
4259  return InvalidOperands(Loc, lex, rex);
4260}
4261
4262// C99 6.5.6
4263QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
4264                                        SourceLocation Loc, QualType* CompLHSTy) {
4265  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4266    QualType compType = CheckVectorOperands(Loc, lex, rex);
4267    if (CompLHSTy) *CompLHSTy = compType;
4268    return compType;
4269  }
4270
4271  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
4272
4273  // Enforce type constraints: C99 6.5.6p3.
4274
4275  // Handle the common case first (both operands are arithmetic).
4276  if (lex->getType()->isArithmeticType()
4277      && rex->getType()->isArithmeticType()) {
4278    if (CompLHSTy) *CompLHSTy = compType;
4279    return compType;
4280  }
4281
4282  // Either ptr - int   or   ptr - ptr.
4283  if (lex->getType()->isAnyPointerType()) {
4284    QualType lpointee = lex->getType()->getPointeeType();
4285
4286    // The LHS must be an completely-defined object type.
4287
4288    bool ComplainAboutVoid = false;
4289    Expr *ComplainAboutFunc = 0;
4290    if (lpointee->isVoidType()) {
4291      if (getLangOptions().CPlusPlus) {
4292        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4293          << lex->getSourceRange() << rex->getSourceRange();
4294        return QualType();
4295      }
4296
4297      // GNU C extension: arithmetic on pointer to void
4298      ComplainAboutVoid = true;
4299    } else if (lpointee->isFunctionType()) {
4300      if (getLangOptions().CPlusPlus) {
4301        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4302          << lex->getType() << lex->getSourceRange();
4303        return QualType();
4304      }
4305
4306      // GNU C extension: arithmetic on pointer to function
4307      ComplainAboutFunc = lex;
4308    } else if (!lpointee->isDependentType() &&
4309               RequireCompleteType(Loc, lpointee,
4310                                   PDiag(diag::err_typecheck_sub_ptr_object)
4311                                     << lex->getSourceRange()
4312                                     << lex->getType()))
4313      return QualType();
4314
4315    // Diagnose bad cases where we step over interface counts.
4316    if (lpointee->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
4317      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
4318        << lpointee << lex->getSourceRange();
4319      return QualType();
4320    }
4321
4322    // The result type of a pointer-int computation is the pointer type.
4323    if (rex->getType()->isIntegerType()) {
4324      if (ComplainAboutVoid)
4325        Diag(Loc, diag::ext_gnu_void_ptr)
4326          << lex->getSourceRange() << rex->getSourceRange();
4327      if (ComplainAboutFunc)
4328        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4329          << ComplainAboutFunc->getType()
4330          << ComplainAboutFunc->getSourceRange();
4331
4332      if (CompLHSTy) *CompLHSTy = lex->getType();
4333      return lex->getType();
4334    }
4335
4336    // Handle pointer-pointer subtractions.
4337    if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
4338      QualType rpointee = RHSPTy->getPointeeType();
4339
4340      // RHS must be a completely-type object type.
4341      // Handle the GNU void* extension.
4342      if (rpointee->isVoidType()) {
4343        if (getLangOptions().CPlusPlus) {
4344          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
4345            << lex->getSourceRange() << rex->getSourceRange();
4346          return QualType();
4347        }
4348
4349        ComplainAboutVoid = true;
4350      } else if (rpointee->isFunctionType()) {
4351        if (getLangOptions().CPlusPlus) {
4352          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
4353            << rex->getType() << rex->getSourceRange();
4354          return QualType();
4355        }
4356
4357        // GNU extension: arithmetic on pointer to function
4358        if (!ComplainAboutFunc)
4359          ComplainAboutFunc = rex;
4360      } else if (!rpointee->isDependentType() &&
4361                 RequireCompleteType(Loc, rpointee,
4362                                     PDiag(diag::err_typecheck_sub_ptr_object)
4363                                       << rex->getSourceRange()
4364                                       << rex->getType()))
4365        return QualType();
4366
4367      if (getLangOptions().CPlusPlus) {
4368        // Pointee types must be the same: C++ [expr.add]
4369        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
4370          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4371            << lex->getType() << rex->getType()
4372            << lex->getSourceRange() << rex->getSourceRange();
4373          return QualType();
4374        }
4375      } else {
4376        // Pointee types must be compatible C99 6.5.6p3
4377        if (!Context.typesAreCompatible(
4378                Context.getCanonicalType(lpointee).getUnqualifiedType(),
4379                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
4380          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
4381            << lex->getType() << rex->getType()
4382            << lex->getSourceRange() << rex->getSourceRange();
4383          return QualType();
4384        }
4385      }
4386
4387      if (ComplainAboutVoid)
4388        Diag(Loc, diag::ext_gnu_void_ptr)
4389          << lex->getSourceRange() << rex->getSourceRange();
4390      if (ComplainAboutFunc)
4391        Diag(Loc, diag::ext_gnu_ptr_func_arith)
4392          << ComplainAboutFunc->getType()
4393          << ComplainAboutFunc->getSourceRange();
4394
4395      if (CompLHSTy) *CompLHSTy = lex->getType();
4396      return Context.getPointerDiffType();
4397    }
4398  }
4399
4400  return InvalidOperands(Loc, lex, rex);
4401}
4402
4403// C99 6.5.7
4404QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4405                                  bool isCompAssign) {
4406  // C99 6.5.7p2: Each of the operands shall have integer type.
4407  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4408    return InvalidOperands(Loc, lex, rex);
4409
4410  // Shifts don't perform usual arithmetic conversions, they just do integer
4411  // promotions on each operand. C99 6.5.7p3
4412  QualType LHSTy = Context.isPromotableBitField(lex);
4413  if (LHSTy.isNull()) {
4414    LHSTy = lex->getType();
4415    if (LHSTy->isPromotableIntegerType())
4416      LHSTy = Context.getPromotedIntegerType(LHSTy);
4417  }
4418  if (!isCompAssign)
4419    ImpCastExprToType(lex, LHSTy);
4420
4421  UsualUnaryConversions(rex);
4422
4423  // Sanity-check shift operands
4424  llvm::APSInt Right;
4425  // Check right/shifter operand
4426  if (!rex->isValueDependent() &&
4427      rex->isIntegerConstantExpr(Right, Context)) {
4428    if (Right.isNegative())
4429      Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
4430    else {
4431      llvm::APInt LeftBits(Right.getBitWidth(),
4432                          Context.getTypeSize(lex->getType()));
4433      if (Right.uge(LeftBits))
4434        Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
4435    }
4436  }
4437
4438  // "The type of the result is that of the promoted left operand."
4439  return LHSTy;
4440}
4441
4442// C99 6.5.8, C++ [expr.rel]
4443QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
4444                                    unsigned OpaqueOpc, bool isRelational) {
4445  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
4446
4447  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4448    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
4449
4450  // C99 6.5.8p3 / C99 6.5.9p4
4451  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
4452    UsualArithmeticConversions(lex, rex);
4453  else {
4454    UsualUnaryConversions(lex);
4455    UsualUnaryConversions(rex);
4456  }
4457  QualType lType = lex->getType();
4458  QualType rType = rex->getType();
4459
4460  if (!lType->isFloatingType()
4461      && !(lType->isBlockPointerType() && isRelational)) {
4462    // For non-floating point types, check for self-comparisons of the form
4463    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4464    // often indicate logic errors in the program.
4465    // NOTE: Don't warn about comparisons of enum constants. These can arise
4466    //  from macro expansions, and are usually quite deliberate.
4467    Expr *LHSStripped = lex->IgnoreParens();
4468    Expr *RHSStripped = rex->IgnoreParens();
4469    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
4470      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped))
4471        if (DRL->getDecl() == DRR->getDecl() &&
4472            !isa<EnumConstantDecl>(DRL->getDecl()))
4473          Diag(Loc, diag::warn_selfcomparison);
4474
4475    if (isa<CastExpr>(LHSStripped))
4476      LHSStripped = LHSStripped->IgnoreParenCasts();
4477    if (isa<CastExpr>(RHSStripped))
4478      RHSStripped = RHSStripped->IgnoreParenCasts();
4479
4480    // Warn about comparisons against a string constant (unless the other
4481    // operand is null), the user probably wants strcmp.
4482    Expr *literalString = 0;
4483    Expr *literalStringStripped = 0;
4484    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
4485        !RHSStripped->isNullPointerConstant(Context,
4486                                            Expr::NPC_ValueDependentIsNull)) {
4487      literalString = lex;
4488      literalStringStripped = LHSStripped;
4489    } else if ((isa<StringLiteral>(RHSStripped) ||
4490                isa<ObjCEncodeExpr>(RHSStripped)) &&
4491               !LHSStripped->isNullPointerConstant(Context,
4492                                            Expr::NPC_ValueDependentIsNull)) {
4493      literalString = rex;
4494      literalStringStripped = RHSStripped;
4495    }
4496
4497    if (literalString) {
4498      std::string resultComparison;
4499      switch (Opc) {
4500      case BinaryOperator::LT: resultComparison = ") < 0"; break;
4501      case BinaryOperator::GT: resultComparison = ") > 0"; break;
4502      case BinaryOperator::LE: resultComparison = ") <= 0"; break;
4503      case BinaryOperator::GE: resultComparison = ") >= 0"; break;
4504      case BinaryOperator::EQ: resultComparison = ") == 0"; break;
4505      case BinaryOperator::NE: resultComparison = ") != 0"; break;
4506      default: assert(false && "Invalid comparison operator");
4507      }
4508      Diag(Loc, diag::warn_stringcompare)
4509        << isa<ObjCEncodeExpr>(literalStringStripped)
4510        << literalString->getSourceRange()
4511        << CodeModificationHint::CreateReplacement(SourceRange(Loc), ", ")
4512        << CodeModificationHint::CreateInsertion(lex->getLocStart(),
4513                                                 "strcmp(")
4514        << CodeModificationHint::CreateInsertion(
4515                                       PP.getLocForEndOfToken(rex->getLocEnd()),
4516                                       resultComparison);
4517    }
4518  }
4519
4520  // The result of comparisons is 'bool' in C++, 'int' in C.
4521  QualType ResultTy = getLangOptions().CPlusPlus? Context.BoolTy :Context.IntTy;
4522
4523  if (isRelational) {
4524    if (lType->isRealType() && rType->isRealType())
4525      return ResultTy;
4526  } else {
4527    // Check for comparisons of floating point operands using != and ==.
4528    if (lType->isFloatingType()) {
4529      assert(rType->isFloatingType());
4530      CheckFloatComparison(Loc,lex,rex);
4531    }
4532
4533    if (lType->isArithmeticType() && rType->isArithmeticType())
4534      return ResultTy;
4535  }
4536
4537  bool LHSIsNull = lex->isNullPointerConstant(Context,
4538                                              Expr::NPC_ValueDependentIsNull);
4539  bool RHSIsNull = rex->isNullPointerConstant(Context,
4540                                              Expr::NPC_ValueDependentIsNull);
4541
4542  // All of the following pointer related warnings are GCC extensions, except
4543  // when handling null pointer constants. One day, we can consider making them
4544  // errors (when -pedantic-errors is enabled).
4545  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
4546    QualType LCanPointeeTy =
4547      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
4548    QualType RCanPointeeTy =
4549      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
4550
4551    if (getLangOptions().CPlusPlus) {
4552      if (LCanPointeeTy == RCanPointeeTy)
4553        return ResultTy;
4554
4555      // C++ [expr.rel]p2:
4556      //   [...] Pointer conversions (4.10) and qualification
4557      //   conversions (4.4) are performed on pointer operands (or on
4558      //   a pointer operand and a null pointer constant) to bring
4559      //   them to their composite pointer type. [...]
4560      //
4561      // C++ [expr.eq]p1 uses the same notion for (in)equality
4562      // comparisons of pointers.
4563      QualType T = FindCompositePointerType(lex, rex);
4564      if (T.isNull()) {
4565        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4566          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4567        return QualType();
4568      }
4569
4570      ImpCastExprToType(lex, T);
4571      ImpCastExprToType(rex, T);
4572      return ResultTy;
4573    }
4574    // C99 6.5.9p2 and C99 6.5.8p2
4575    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
4576                                   RCanPointeeTy.getUnqualifiedType())) {
4577      // Valid unless a relational comparison of function pointers
4578      if (isRelational && LCanPointeeTy->isFunctionType()) {
4579        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
4580          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4581      }
4582    } else if (!isRelational &&
4583               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
4584      // Valid unless comparison between non-null pointer and function pointer
4585      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
4586          && !LHSIsNull && !RHSIsNull) {
4587        Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
4588          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4589      }
4590    } else {
4591      // Invalid
4592      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4593        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4594    }
4595    if (LCanPointeeTy != RCanPointeeTy)
4596      ImpCastExprToType(rex, lType); // promote the pointer to pointer
4597    return ResultTy;
4598  }
4599
4600  if (getLangOptions().CPlusPlus) {
4601    // Comparison of pointers with null pointer constants and equality
4602    // comparisons of member pointers to null pointer constants.
4603    if (RHSIsNull &&
4604        (lType->isPointerType() ||
4605         (!isRelational && lType->isMemberPointerType()))) {
4606      ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
4607      return ResultTy;
4608    }
4609    if (LHSIsNull &&
4610        (rType->isPointerType() ||
4611         (!isRelational && rType->isMemberPointerType()))) {
4612      ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
4613      return ResultTy;
4614    }
4615
4616    // Comparison of member pointers.
4617    if (!isRelational &&
4618        lType->isMemberPointerType() && rType->isMemberPointerType()) {
4619      // C++ [expr.eq]p2:
4620      //   In addition, pointers to members can be compared, or a pointer to
4621      //   member and a null pointer constant. Pointer to member conversions
4622      //   (4.11) and qualification conversions (4.4) are performed to bring
4623      //   them to a common type. If one operand is a null pointer constant,
4624      //   the common type is the type of the other operand. Otherwise, the
4625      //   common type is a pointer to member type similar (4.4) to the type
4626      //   of one of the operands, with a cv-qualification signature (4.4)
4627      //   that is the union of the cv-qualification signatures of the operand
4628      //   types.
4629      QualType T = FindCompositePointerType(lex, rex);
4630      if (T.isNull()) {
4631        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
4632        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4633        return QualType();
4634      }
4635
4636      ImpCastExprToType(lex, T);
4637      ImpCastExprToType(rex, T);
4638      return ResultTy;
4639    }
4640
4641    // Comparison of nullptr_t with itself.
4642    if (lType->isNullPtrType() && rType->isNullPtrType())
4643      return ResultTy;
4644  }
4645
4646  // Handle block pointer types.
4647  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
4648    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
4649    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
4650
4651    if (!LHSIsNull && !RHSIsNull &&
4652        !Context.typesAreCompatible(lpointee, rpointee)) {
4653      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4654        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4655    }
4656    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4657    return ResultTy;
4658  }
4659  // Allow block pointers to be compared with null pointer constants.
4660  if (!isRelational
4661      && ((lType->isBlockPointerType() && rType->isPointerType())
4662          || (lType->isPointerType() && rType->isBlockPointerType()))) {
4663    if (!LHSIsNull && !RHSIsNull) {
4664      if (!((rType->isPointerType() && rType->getAs<PointerType>()
4665             ->getPointeeType()->isVoidType())
4666            || (lType->isPointerType() && lType->getAs<PointerType>()
4667                ->getPointeeType()->isVoidType())))
4668        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
4669          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4670    }
4671    ImpCastExprToType(rex, lType); // promote the pointer to pointer
4672    return ResultTy;
4673  }
4674
4675  if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
4676    if (lType->isPointerType() || rType->isPointerType()) {
4677      const PointerType *LPT = lType->getAs<PointerType>();
4678      const PointerType *RPT = rType->getAs<PointerType>();
4679      bool LPtrToVoid = LPT ?
4680        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
4681      bool RPtrToVoid = RPT ?
4682        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
4683
4684      if (!LPtrToVoid && !RPtrToVoid &&
4685          !Context.typesAreCompatible(lType, rType)) {
4686        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4687          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4688      }
4689      ImpCastExprToType(rex, lType);
4690      return ResultTy;
4691    }
4692    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
4693      if (!Context.areComparableObjCPointerTypes(lType, rType))
4694        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
4695          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4696      ImpCastExprToType(rex, lType);
4697      return ResultTy;
4698    }
4699  }
4700  if (lType->isAnyPointerType() && rType->isIntegerType()) {
4701    unsigned DiagID = 0;
4702    if (RHSIsNull) {
4703      if (isRelational)
4704        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4705    } else if (isRelational)
4706      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4707    else
4708      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4709
4710    if (DiagID) {
4711      Diag(Loc, DiagID)
4712        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4713    }
4714    ImpCastExprToType(rex, lType); // promote the integer to pointer
4715    return ResultTy;
4716  }
4717  if (lType->isIntegerType() && rType->isAnyPointerType()) {
4718    unsigned DiagID = 0;
4719    if (LHSIsNull) {
4720      if (isRelational)
4721        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
4722    } else if (isRelational)
4723      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
4724    else
4725      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
4726
4727    if (DiagID) {
4728      Diag(Loc, DiagID)
4729        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
4730    }
4731    ImpCastExprToType(lex, rType); // promote the integer to pointer
4732    return ResultTy;
4733  }
4734  // Handle block pointers.
4735  if (!isRelational && RHSIsNull
4736      && lType->isBlockPointerType() && rType->isIntegerType()) {
4737    ImpCastExprToType(rex, lType); // promote the integer to pointer
4738    return ResultTy;
4739  }
4740  if (!isRelational && LHSIsNull
4741      && lType->isIntegerType() && rType->isBlockPointerType()) {
4742    ImpCastExprToType(lex, rType); // promote the integer to pointer
4743    return ResultTy;
4744  }
4745  return InvalidOperands(Loc, lex, rex);
4746}
4747
4748/// CheckVectorCompareOperands - vector comparisons are a clang extension that
4749/// operates on extended vector types.  Instead of producing an IntTy result,
4750/// like a scalar comparison, a vector comparison produces a vector of integer
4751/// types.
4752QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
4753                                          SourceLocation Loc,
4754                                          bool isRelational) {
4755  // Check to make sure we're operating on vectors of the same type and width,
4756  // Allowing one side to be a scalar of element type.
4757  QualType vType = CheckVectorOperands(Loc, lex, rex);
4758  if (vType.isNull())
4759    return vType;
4760
4761  QualType lType = lex->getType();
4762  QualType rType = rex->getType();
4763
4764  // For non-floating point types, check for self-comparisons of the form
4765  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
4766  // often indicate logic errors in the program.
4767  if (!lType->isFloatingType()) {
4768    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
4769      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
4770        if (DRL->getDecl() == DRR->getDecl())
4771          Diag(Loc, diag::warn_selfcomparison);
4772  }
4773
4774  // Check for comparisons of floating point operands using != and ==.
4775  if (!isRelational && lType->isFloatingType()) {
4776    assert (rType->isFloatingType());
4777    CheckFloatComparison(Loc,lex,rex);
4778  }
4779
4780  // Return the type for the comparison, which is the same as vector type for
4781  // integer vectors, or an integer type of identical size and number of
4782  // elements for floating point vectors.
4783  if (lType->isIntegerType())
4784    return lType;
4785
4786  const VectorType *VTy = lType->getAs<VectorType>();
4787  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
4788  if (TypeSize == Context.getTypeSize(Context.IntTy))
4789    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
4790  if (TypeSize == Context.getTypeSize(Context.LongTy))
4791    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
4792
4793  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
4794         "Unhandled vector element size in vector compare");
4795  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
4796}
4797
4798inline QualType Sema::CheckBitwiseOperands(
4799  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4800  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4801    return CheckVectorOperands(Loc, lex, rex);
4802
4803  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4804
4805  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4806    return compType;
4807  return InvalidOperands(Loc, lex, rex);
4808}
4809
4810inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
4811  Expr *&lex, Expr *&rex, SourceLocation Loc) {
4812  UsualUnaryConversions(lex);
4813  UsualUnaryConversions(rex);
4814
4815  if (lex->getType()->isScalarType() && rex->getType()->isScalarType())
4816    return Context.IntTy;
4817  return InvalidOperands(Loc, lex, rex);
4818}
4819
4820/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
4821/// is a read-only property; return true if so. A readonly property expression
4822/// depends on various declarations and thus must be treated specially.
4823///
4824static bool IsReadonlyProperty(Expr *E, Sema &S) {
4825  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
4826    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
4827    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
4828      QualType BaseType = PropExpr->getBase()->getType();
4829      if (const ObjCObjectPointerType *OPT =
4830            BaseType->getAsObjCInterfacePointerType())
4831        if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
4832          if (S.isPropertyReadonly(PDecl, IFace))
4833            return true;
4834    }
4835  }
4836  return false;
4837}
4838
4839/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
4840/// emit an error and return true.  If so, return false.
4841static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
4842  SourceLocation OrigLoc = Loc;
4843  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
4844                                                              &Loc);
4845  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
4846    IsLV = Expr::MLV_ReadonlyProperty;
4847  if (IsLV == Expr::MLV_Valid)
4848    return false;
4849
4850  unsigned Diag = 0;
4851  bool NeedType = false;
4852  switch (IsLV) { // C99 6.5.16p2
4853  default: assert(0 && "Unknown result from isModifiableLvalue!");
4854  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
4855  case Expr::MLV_ArrayType:
4856    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
4857    NeedType = true;
4858    break;
4859  case Expr::MLV_NotObjectType:
4860    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
4861    NeedType = true;
4862    break;
4863  case Expr::MLV_LValueCast:
4864    Diag = diag::err_typecheck_lvalue_casts_not_supported;
4865    break;
4866  case Expr::MLV_InvalidExpression:
4867    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
4868    break;
4869  case Expr::MLV_IncompleteType:
4870  case Expr::MLV_IncompleteVoidType:
4871    return S.RequireCompleteType(Loc, E->getType(),
4872                PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
4873                  << E->getSourceRange());
4874  case Expr::MLV_DuplicateVectorComponents:
4875    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
4876    break;
4877  case Expr::MLV_NotBlockQualified:
4878    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
4879    break;
4880  case Expr::MLV_ReadonlyProperty:
4881    Diag = diag::error_readonly_property_assignment;
4882    break;
4883  case Expr::MLV_NoSetterProperty:
4884    Diag = diag::error_nosetter_property_assignment;
4885    break;
4886  }
4887
4888  SourceRange Assign;
4889  if (Loc != OrigLoc)
4890    Assign = SourceRange(OrigLoc, OrigLoc);
4891  if (NeedType)
4892    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
4893  else
4894    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
4895  return true;
4896}
4897
4898
4899
4900// C99 6.5.16.1
4901QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
4902                                       SourceLocation Loc,
4903                                       QualType CompoundType) {
4904  // Verify that LHS is a modifiable lvalue, and emit error if not.
4905  if (CheckForModifiableLvalue(LHS, Loc, *this))
4906    return QualType();
4907
4908  QualType LHSType = LHS->getType();
4909  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
4910
4911  AssignConvertType ConvTy;
4912  if (CompoundType.isNull()) {
4913    // Simple assignment "x = y".
4914    ConvTy = CheckSingleAssignmentConstraints(LHSType, RHS);
4915    // Special case of NSObject attributes on c-style pointer types.
4916    if (ConvTy == IncompatiblePointer &&
4917        ((Context.isObjCNSObjectType(LHSType) &&
4918          RHSType->isObjCObjectPointerType()) ||
4919         (Context.isObjCNSObjectType(RHSType) &&
4920          LHSType->isObjCObjectPointerType())))
4921      ConvTy = Compatible;
4922
4923    // If the RHS is a unary plus or minus, check to see if they = and + are
4924    // right next to each other.  If so, the user may have typo'd "x =+ 4"
4925    // instead of "x += 4".
4926    Expr *RHSCheck = RHS;
4927    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
4928      RHSCheck = ICE->getSubExpr();
4929    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
4930      if ((UO->getOpcode() == UnaryOperator::Plus ||
4931           UO->getOpcode() == UnaryOperator::Minus) &&
4932          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
4933          // Only if the two operators are exactly adjacent.
4934          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
4935          // And there is a space or other character before the subexpr of the
4936          // unary +/-.  We don't want to warn on "x=-1".
4937          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
4938          UO->getSubExpr()->getLocStart().isFileID()) {
4939        Diag(Loc, diag::warn_not_compound_assign)
4940          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
4941          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
4942      }
4943    }
4944  } else {
4945    // Compound assignment "x += y"
4946    ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
4947  }
4948
4949  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
4950                               RHS, "assigning"))
4951    return QualType();
4952
4953  // C99 6.5.16p3: The type of an assignment expression is the type of the
4954  // left operand unless the left operand has qualified type, in which case
4955  // it is the unqualified version of the type of the left operand.
4956  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
4957  // is converted to the type of the assignment expression (above).
4958  // C++ 5.17p1: the type of the assignment expression is that of its left
4959  // operand.
4960  return LHSType.getUnqualifiedType();
4961}
4962
4963// C99 6.5.17
4964QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
4965  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
4966  DefaultFunctionArrayConversion(RHS);
4967
4968  // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
4969  // incomplete in C++).
4970
4971  return RHS->getType();
4972}
4973
4974/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
4975/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
4976QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
4977                                              bool isInc) {
4978  if (Op->isTypeDependent())
4979    return Context.DependentTy;
4980
4981  QualType ResType = Op->getType();
4982  assert(!ResType.isNull() && "no type for increment/decrement expression");
4983
4984  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
4985    // Decrement of bool is not allowed.
4986    if (!isInc) {
4987      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
4988      return QualType();
4989    }
4990    // Increment of bool sets it to true, but is deprecated.
4991    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
4992  } else if (ResType->isRealType()) {
4993    // OK!
4994  } else if (ResType->isAnyPointerType()) {
4995    QualType PointeeTy = ResType->getPointeeType();
4996
4997    // C99 6.5.2.4p2, 6.5.6p2
4998    if (PointeeTy->isVoidType()) {
4999      if (getLangOptions().CPlusPlus) {
5000        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5001          << Op->getSourceRange();
5002        return QualType();
5003      }
5004
5005      // Pointer to void is a GNU extension in C.
5006      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
5007    } else if (PointeeTy->isFunctionType()) {
5008      if (getLangOptions().CPlusPlus) {
5009        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5010          << Op->getType() << Op->getSourceRange();
5011        return QualType();
5012      }
5013
5014      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
5015        << ResType << Op->getSourceRange();
5016    } else if (RequireCompleteType(OpLoc, PointeeTy,
5017                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5018                             << Op->getSourceRange()
5019                             << ResType))
5020      return QualType();
5021    // Diagnose bad cases where we step over interface counts.
5022    else if (PointeeTy->isObjCInterfaceType() && LangOpts.ObjCNonFragileABI) {
5023      Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5024        << PointeeTy << Op->getSourceRange();
5025      return QualType();
5026    }
5027  } else if (ResType->isComplexType()) {
5028    // C99 does not support ++/-- on complex types, we allow as an extension.
5029    Diag(OpLoc, diag::ext_integer_increment_complex)
5030      << ResType << Op->getSourceRange();
5031  } else {
5032    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
5033      << ResType << Op->getSourceRange();
5034    return QualType();
5035  }
5036  // At this point, we know we have a real, complex or pointer type.
5037  // Now make sure the operand is a modifiable lvalue.
5038  if (CheckForModifiableLvalue(Op, OpLoc, *this))
5039    return QualType();
5040  return ResType;
5041}
5042
5043/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
5044/// This routine allows us to typecheck complex/recursive expressions
5045/// where the declaration is needed for type checking. We only need to
5046/// handle cases when the expression references a function designator
5047/// or is an lvalue. Here are some examples:
5048///  - &(x) => x
5049///  - &*****f => f for f a function designator.
5050///  - &s.xx => s
5051///  - &s.zz[1].yy -> s, if zz is an array
5052///  - *(x + 1) -> x, if x is an array
5053///  - &"123"[2] -> 0
5054///  - & __real__ x -> x
5055static NamedDecl *getPrimaryDecl(Expr *E) {
5056  switch (E->getStmtClass()) {
5057  case Stmt::DeclRefExprClass:
5058  case Stmt::QualifiedDeclRefExprClass:
5059    return cast<DeclRefExpr>(E)->getDecl();
5060  case Stmt::MemberExprClass:
5061    // If this is an arrow operator, the address is an offset from
5062    // the base's value, so the object the base refers to is
5063    // irrelevant.
5064    if (cast<MemberExpr>(E)->isArrow())
5065      return 0;
5066    // Otherwise, the expression refers to a part of the base
5067    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
5068  case Stmt::ArraySubscriptExprClass: {
5069    // FIXME: This code shouldn't be necessary!  We should catch the implicit
5070    // promotion of register arrays earlier.
5071    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
5072    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
5073      if (ICE->getSubExpr()->getType()->isArrayType())
5074        return getPrimaryDecl(ICE->getSubExpr());
5075    }
5076    return 0;
5077  }
5078  case Stmt::UnaryOperatorClass: {
5079    UnaryOperator *UO = cast<UnaryOperator>(E);
5080
5081    switch(UO->getOpcode()) {
5082    case UnaryOperator::Real:
5083    case UnaryOperator::Imag:
5084    case UnaryOperator::Extension:
5085      return getPrimaryDecl(UO->getSubExpr());
5086    default:
5087      return 0;
5088    }
5089  }
5090  case Stmt::ParenExprClass:
5091    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
5092  case Stmt::ImplicitCastExprClass:
5093    // If the result of an implicit cast is an l-value, we care about
5094    // the sub-expression; otherwise, the result here doesn't matter.
5095    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
5096  default:
5097    return 0;
5098  }
5099}
5100
5101/// CheckAddressOfOperand - The operand of & must be either a function
5102/// designator or an lvalue designating an object. If it is an lvalue, the
5103/// object cannot be declared with storage class register or be a bit field.
5104/// Note: The usual conversions are *not* applied to the operand of the &
5105/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
5106/// In C++, the operand might be an overloaded function name, in which case
5107/// we allow the '&' but retain the overloaded-function type.
5108QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
5109  // Make sure to ignore parentheses in subsequent checks
5110  op = op->IgnoreParens();
5111
5112  if (op->isTypeDependent())
5113    return Context.DependentTy;
5114
5115  if (getLangOptions().C99) {
5116    // Implement C99-only parts of addressof rules.
5117    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
5118      if (uOp->getOpcode() == UnaryOperator::Deref)
5119        // Per C99 6.5.3.2, the address of a deref always returns a valid result
5120        // (assuming the deref expression is valid).
5121        return uOp->getSubExpr()->getType();
5122    }
5123    // Technically, there should be a check for array subscript
5124    // expressions here, but the result of one is always an lvalue anyway.
5125  }
5126  NamedDecl *dcl = getPrimaryDecl(op);
5127  Expr::isLvalueResult lval = op->isLvalue(Context);
5128
5129  if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
5130    // C99 6.5.3.2p1
5131    // The operand must be either an l-value or a function designator
5132    if (!op->getType()->isFunctionType()) {
5133      // FIXME: emit more specific diag...
5134      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
5135        << op->getSourceRange();
5136      return QualType();
5137    }
5138  } else if (op->getBitField()) { // C99 6.5.3.2p1
5139    // The operand cannot be a bit-field
5140    Diag(OpLoc, diag::err_typecheck_address_of)
5141      << "bit-field" << op->getSourceRange();
5142        return QualType();
5143  } else if (isa<ExtVectorElementExpr>(op) || (isa<ArraySubscriptExpr>(op) &&
5144           cast<ArraySubscriptExpr>(op)->getBase()->getType()->isVectorType())){
5145    // The operand cannot be an element of a vector
5146    Diag(OpLoc, diag::err_typecheck_address_of)
5147      << "vector element" << op->getSourceRange();
5148    return QualType();
5149  } else if (isa<ObjCPropertyRefExpr>(op)) {
5150    // cannot take address of a property expression.
5151    Diag(OpLoc, diag::err_typecheck_address_of)
5152      << "property expression" << op->getSourceRange();
5153    return QualType();
5154  } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
5155    // FIXME: Can LHS ever be null here?
5156    if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
5157      return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
5158  } else if (dcl) { // C99 6.5.3.2p1
5159    // We have an lvalue with a decl. Make sure the decl is not declared
5160    // with the register storage-class specifier.
5161    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
5162      if (vd->getStorageClass() == VarDecl::Register) {
5163        Diag(OpLoc, diag::err_typecheck_address_of)
5164          << "register variable" << op->getSourceRange();
5165        return QualType();
5166      }
5167    } else if (isa<OverloadedFunctionDecl>(dcl) ||
5168               isa<FunctionTemplateDecl>(dcl)) {
5169      return Context.OverloadTy;
5170    } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
5171      // Okay: we can take the address of a field.
5172      // Could be a pointer to member, though, if there is an explicit
5173      // scope qualifier for the class.
5174      if (isa<QualifiedDeclRefExpr>(op)) {
5175        DeclContext *Ctx = dcl->getDeclContext();
5176        if (Ctx && Ctx->isRecord()) {
5177          if (FD->getType()->isReferenceType()) {
5178            Diag(OpLoc,
5179                 diag::err_cannot_form_pointer_to_member_of_reference_type)
5180              << FD->getDeclName() << FD->getType();
5181            return QualType();
5182          }
5183
5184          return Context.getMemberPointerType(op->getType(),
5185                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
5186        }
5187      }
5188    } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
5189      // Okay: we can take the address of a function.
5190      // As above.
5191      if (isa<QualifiedDeclRefExpr>(op) && MD->isInstance())
5192        return Context.getMemberPointerType(op->getType(),
5193              Context.getTypeDeclType(MD->getParent()).getTypePtr());
5194    } else if (!isa<FunctionDecl>(dcl))
5195      assert(0 && "Unknown/unexpected decl type");
5196  }
5197
5198  if (lval == Expr::LV_IncompleteVoidType) {
5199    // Taking the address of a void variable is technically illegal, but we
5200    // allow it in cases which are otherwise valid.
5201    // Example: "extern void x; void* y = &x;".
5202    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
5203  }
5204
5205  // If the operand has type "type", the result has type "pointer to type".
5206  return Context.getPointerType(op->getType());
5207}
5208
5209QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
5210  if (Op->isTypeDependent())
5211    return Context.DependentTy;
5212
5213  UsualUnaryConversions(Op);
5214  QualType Ty = Op->getType();
5215
5216  // Note that per both C89 and C99, this is always legal, even if ptype is an
5217  // incomplete type or void.  It would be possible to warn about dereferencing
5218  // a void pointer, but it's completely well-defined, and such a warning is
5219  // unlikely to catch any mistakes.
5220  if (const PointerType *PT = Ty->getAs<PointerType>())
5221    return PT->getPointeeType();
5222
5223  if (const ObjCObjectPointerType *OPT = Ty->getAs<ObjCObjectPointerType>())
5224    return OPT->getPointeeType();
5225
5226  Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
5227    << Ty << Op->getSourceRange();
5228  return QualType();
5229}
5230
5231static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
5232  tok::TokenKind Kind) {
5233  BinaryOperator::Opcode Opc;
5234  switch (Kind) {
5235  default: assert(0 && "Unknown binop!");
5236  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
5237  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
5238  case tok::star:                 Opc = BinaryOperator::Mul; break;
5239  case tok::slash:                Opc = BinaryOperator::Div; break;
5240  case tok::percent:              Opc = BinaryOperator::Rem; break;
5241  case tok::plus:                 Opc = BinaryOperator::Add; break;
5242  case tok::minus:                Opc = BinaryOperator::Sub; break;
5243  case tok::lessless:             Opc = BinaryOperator::Shl; break;
5244  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
5245  case tok::lessequal:            Opc = BinaryOperator::LE; break;
5246  case tok::less:                 Opc = BinaryOperator::LT; break;
5247  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
5248  case tok::greater:              Opc = BinaryOperator::GT; break;
5249  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
5250  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
5251  case tok::amp:                  Opc = BinaryOperator::And; break;
5252  case tok::caret:                Opc = BinaryOperator::Xor; break;
5253  case tok::pipe:                 Opc = BinaryOperator::Or; break;
5254  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
5255  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
5256  case tok::equal:                Opc = BinaryOperator::Assign; break;
5257  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
5258  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
5259  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
5260  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
5261  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
5262  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
5263  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
5264  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
5265  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
5266  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
5267  case tok::comma:                Opc = BinaryOperator::Comma; break;
5268  }
5269  return Opc;
5270}
5271
5272static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
5273  tok::TokenKind Kind) {
5274  UnaryOperator::Opcode Opc;
5275  switch (Kind) {
5276  default: assert(0 && "Unknown unary op!");
5277  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
5278  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
5279  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
5280  case tok::star:         Opc = UnaryOperator::Deref; break;
5281  case tok::plus:         Opc = UnaryOperator::Plus; break;
5282  case tok::minus:        Opc = UnaryOperator::Minus; break;
5283  case tok::tilde:        Opc = UnaryOperator::Not; break;
5284  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
5285  case tok::kw___real:    Opc = UnaryOperator::Real; break;
5286  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
5287  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
5288  }
5289  return Opc;
5290}
5291
5292/// CreateBuiltinBinOp - Creates a new built-in binary operation with
5293/// operator @p Opc at location @c TokLoc. This routine only supports
5294/// built-in operations; ActOnBinOp handles overloaded operators.
5295Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
5296                                                  unsigned Op,
5297                                                  Expr *lhs, Expr *rhs) {
5298  QualType ResultTy;     // Result type of the binary operator.
5299  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
5300  // The following two variables are used for compound assignment operators
5301  QualType CompLHSTy;    // Type of LHS after promotions for computation
5302  QualType CompResultTy; // Type of computation result
5303
5304  switch (Opc) {
5305  case BinaryOperator::Assign:
5306    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
5307    break;
5308  case BinaryOperator::PtrMemD:
5309  case BinaryOperator::PtrMemI:
5310    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
5311                                            Opc == BinaryOperator::PtrMemI);
5312    break;
5313  case BinaryOperator::Mul:
5314  case BinaryOperator::Div:
5315    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc);
5316    break;
5317  case BinaryOperator::Rem:
5318    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
5319    break;
5320  case BinaryOperator::Add:
5321    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
5322    break;
5323  case BinaryOperator::Sub:
5324    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
5325    break;
5326  case BinaryOperator::Shl:
5327  case BinaryOperator::Shr:
5328    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
5329    break;
5330  case BinaryOperator::LE:
5331  case BinaryOperator::LT:
5332  case BinaryOperator::GE:
5333  case BinaryOperator::GT:
5334    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
5335    break;
5336  case BinaryOperator::EQ:
5337  case BinaryOperator::NE:
5338    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
5339    break;
5340  case BinaryOperator::And:
5341  case BinaryOperator::Xor:
5342  case BinaryOperator::Or:
5343    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
5344    break;
5345  case BinaryOperator::LAnd:
5346  case BinaryOperator::LOr:
5347    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
5348    break;
5349  case BinaryOperator::MulAssign:
5350  case BinaryOperator::DivAssign:
5351    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true);
5352    CompLHSTy = CompResultTy;
5353    if (!CompResultTy.isNull())
5354      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5355    break;
5356  case BinaryOperator::RemAssign:
5357    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
5358    CompLHSTy = CompResultTy;
5359    if (!CompResultTy.isNull())
5360      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5361    break;
5362  case BinaryOperator::AddAssign:
5363    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5364    if (!CompResultTy.isNull())
5365      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5366    break;
5367  case BinaryOperator::SubAssign:
5368    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
5369    if (!CompResultTy.isNull())
5370      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5371    break;
5372  case BinaryOperator::ShlAssign:
5373  case BinaryOperator::ShrAssign:
5374    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
5375    CompLHSTy = CompResultTy;
5376    if (!CompResultTy.isNull())
5377      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5378    break;
5379  case BinaryOperator::AndAssign:
5380  case BinaryOperator::XorAssign:
5381  case BinaryOperator::OrAssign:
5382    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
5383    CompLHSTy = CompResultTy;
5384    if (!CompResultTy.isNull())
5385      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
5386    break;
5387  case BinaryOperator::Comma:
5388    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
5389    break;
5390  }
5391  if (ResultTy.isNull())
5392    return ExprError();
5393  if (CompResultTy.isNull())
5394    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
5395  else
5396    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
5397                                                      CompLHSTy, CompResultTy,
5398                                                      OpLoc));
5399}
5400
5401// Binary Operators.  'Tok' is the token for the operator.
5402Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
5403                                          tok::TokenKind Kind,
5404                                          ExprArg LHS, ExprArg RHS) {
5405  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
5406  Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
5407
5408  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
5409  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
5410
5411  if (getLangOptions().CPlusPlus &&
5412      (lhs->getType()->isOverloadableType() ||
5413       rhs->getType()->isOverloadableType())) {
5414    // Find all of the overloaded operators visible from this
5415    // point. We perform both an operator-name lookup from the local
5416    // scope and an argument-dependent lookup based on the types of
5417    // the arguments.
5418    FunctionSet Functions;
5419    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
5420    if (OverOp != OO_None) {
5421      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
5422                                   Functions);
5423      Expr *Args[2] = { lhs, rhs };
5424      DeclarationName OpName
5425        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5426      ArgumentDependentLookup(OpName, Args, 2, Functions);
5427    }
5428
5429    // Build the (potentially-overloaded, potentially-dependent)
5430    // binary operation.
5431    return CreateOverloadedBinOp(TokLoc, Opc, Functions, lhs, rhs);
5432  }
5433
5434  // Build a built-in binary operation.
5435  return CreateBuiltinBinOp(TokLoc, Opc, lhs, rhs);
5436}
5437
5438Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
5439                                                    unsigned OpcIn,
5440                                                    ExprArg InputArg) {
5441  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
5442
5443  // FIXME: Input is modified below, but InputArg is not updated appropriately.
5444  Expr *Input = (Expr *)InputArg.get();
5445  QualType resultType;
5446  switch (Opc) {
5447  case UnaryOperator::OffsetOf:
5448    assert(false && "Invalid unary operator");
5449    break;
5450
5451  case UnaryOperator::PreInc:
5452  case UnaryOperator::PreDec:
5453  case UnaryOperator::PostInc:
5454  case UnaryOperator::PostDec:
5455    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
5456                                                Opc == UnaryOperator::PreInc ||
5457                                                Opc == UnaryOperator::PostInc);
5458    break;
5459  case UnaryOperator::AddrOf:
5460    resultType = CheckAddressOfOperand(Input, OpLoc);
5461    break;
5462  case UnaryOperator::Deref:
5463    DefaultFunctionArrayConversion(Input);
5464    resultType = CheckIndirectionOperand(Input, OpLoc);
5465    break;
5466  case UnaryOperator::Plus:
5467  case UnaryOperator::Minus:
5468    UsualUnaryConversions(Input);
5469    resultType = Input->getType();
5470    if (resultType->isDependentType())
5471      break;
5472    if (resultType->isArithmeticType()) // C99 6.5.3.3p1
5473      break;
5474    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
5475             resultType->isEnumeralType())
5476      break;
5477    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
5478             Opc == UnaryOperator::Plus &&
5479             resultType->isPointerType())
5480      break;
5481
5482    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5483      << resultType << Input->getSourceRange());
5484  case UnaryOperator::Not: // bitwise complement
5485    UsualUnaryConversions(Input);
5486    resultType = Input->getType();
5487    if (resultType->isDependentType())
5488      break;
5489    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
5490    if (resultType->isComplexType() || resultType->isComplexIntegerType())
5491      // C99 does not support '~' for complex conjugation.
5492      Diag(OpLoc, diag::ext_integer_complement_complex)
5493        << resultType << Input->getSourceRange();
5494    else if (!resultType->isIntegerType())
5495      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5496        << resultType << Input->getSourceRange());
5497    break;
5498  case UnaryOperator::LNot: // logical negation
5499    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
5500    DefaultFunctionArrayConversion(Input);
5501    resultType = Input->getType();
5502    if (resultType->isDependentType())
5503      break;
5504    if (!resultType->isScalarType()) // C99 6.5.3.3p1
5505      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
5506        << resultType << Input->getSourceRange());
5507    // LNot always has type int. C99 6.5.3.3p5.
5508    // In C++, it's bool. C++ 5.3.1p8
5509    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
5510    break;
5511  case UnaryOperator::Real:
5512  case UnaryOperator::Imag:
5513    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
5514    break;
5515  case UnaryOperator::Extension:
5516    resultType = Input->getType();
5517    break;
5518  }
5519  if (resultType.isNull())
5520    return ExprError();
5521
5522  InputArg.release();
5523  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
5524}
5525
5526// Unary Operators.  'Tok' is the token for the operator.
5527Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
5528                                            tok::TokenKind Op, ExprArg input) {
5529  Expr *Input = (Expr*)input.get();
5530  UnaryOperator::Opcode Opc = ConvertTokenKindToUnaryOpcode(Op);
5531
5532  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType()) {
5533    // Find all of the overloaded operators visible from this
5534    // point. We perform both an operator-name lookup from the local
5535    // scope and an argument-dependent lookup based on the types of
5536    // the arguments.
5537    FunctionSet Functions;
5538    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
5539    if (OverOp != OO_None) {
5540      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
5541                                   Functions);
5542      DeclarationName OpName
5543        = Context.DeclarationNames.getCXXOperatorName(OverOp);
5544      ArgumentDependentLookup(OpName, &Input, 1, Functions);
5545    }
5546
5547    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
5548  }
5549
5550  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
5551}
5552
5553/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
5554Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
5555                                            SourceLocation LabLoc,
5556                                            IdentifierInfo *LabelII) {
5557  // Look up the record for this label identifier.
5558  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
5559
5560  // If we haven't seen this label yet, create a forward reference. It
5561  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
5562  if (LabelDecl == 0)
5563    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
5564
5565  // Create the AST node.  The address of a label always has type 'void*'.
5566  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
5567                                       Context.getPointerType(Context.VoidTy)));
5568}
5569
5570Sema::OwningExprResult
5571Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
5572                    SourceLocation RPLoc) { // "({..})"
5573  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
5574  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
5575  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
5576
5577  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
5578  if (isFileScope)
5579    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
5580
5581  // FIXME: there are a variety of strange constraints to enforce here, for
5582  // example, it is not possible to goto into a stmt expression apparently.
5583  // More semantic analysis is needed.
5584
5585  // If there are sub stmts in the compound stmt, take the type of the last one
5586  // as the type of the stmtexpr.
5587  QualType Ty = Context.VoidTy;
5588
5589  if (!Compound->body_empty()) {
5590    Stmt *LastStmt = Compound->body_back();
5591    // If LastStmt is a label, skip down through into the body.
5592    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
5593      LastStmt = Label->getSubStmt();
5594
5595    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
5596      Ty = LastExpr->getType();
5597  }
5598
5599  // FIXME: Check that expression type is complete/non-abstract; statement
5600  // expressions are not lvalues.
5601
5602  substmt.release();
5603  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
5604}
5605
5606Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
5607                                                  SourceLocation BuiltinLoc,
5608                                                  SourceLocation TypeLoc,
5609                                                  TypeTy *argty,
5610                                                  OffsetOfComponent *CompPtr,
5611                                                  unsigned NumComponents,
5612                                                  SourceLocation RPLoc) {
5613  // FIXME: This function leaks all expressions in the offset components on
5614  // error.
5615  // FIXME: Preserve type source info.
5616  QualType ArgTy = GetTypeFromParser(argty);
5617  assert(!ArgTy.isNull() && "Missing type argument!");
5618
5619  bool Dependent = ArgTy->isDependentType();
5620
5621  // We must have at least one component that refers to the type, and the first
5622  // one is known to be a field designator.  Verify that the ArgTy represents
5623  // a struct/union/class.
5624  if (!Dependent && !ArgTy->isRecordType())
5625    return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
5626
5627  // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
5628  // with an incomplete type would be illegal.
5629
5630  // Otherwise, create a null pointer as the base, and iteratively process
5631  // the offsetof designators.
5632  QualType ArgTyPtr = Context.getPointerType(ArgTy);
5633  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
5634  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
5635                                    ArgTy, SourceLocation());
5636
5637  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
5638  // GCC extension, diagnose them.
5639  // FIXME: This diagnostic isn't actually visible because the location is in
5640  // a system header!
5641  if (NumComponents != 1)
5642    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
5643      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
5644
5645  if (!Dependent) {
5646    bool DidWarnAboutNonPOD = false;
5647
5648    // FIXME: Dependent case loses a lot of information here. And probably
5649    // leaks like a sieve.
5650    for (unsigned i = 0; i != NumComponents; ++i) {
5651      const OffsetOfComponent &OC = CompPtr[i];
5652      if (OC.isBrackets) {
5653        // Offset of an array sub-field.  TODO: Should we allow vector elements?
5654        const ArrayType *AT = Context.getAsArrayType(Res->getType());
5655        if (!AT) {
5656          Res->Destroy(Context);
5657          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
5658            << Res->getType());
5659        }
5660
5661        // FIXME: C++: Verify that operator[] isn't overloaded.
5662
5663        // Promote the array so it looks more like a normal array subscript
5664        // expression.
5665        DefaultFunctionArrayConversion(Res);
5666
5667        // C99 6.5.2.1p1
5668        Expr *Idx = static_cast<Expr*>(OC.U.E);
5669        // FIXME: Leaks Res
5670        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
5671          return ExprError(Diag(Idx->getLocStart(),
5672                                diag::err_typecheck_subscript_not_integer)
5673            << Idx->getSourceRange());
5674
5675        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
5676                                               OC.LocEnd);
5677        continue;
5678      }
5679
5680      const RecordType *RC = Res->getType()->getAs<RecordType>();
5681      if (!RC) {
5682        Res->Destroy(Context);
5683        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
5684          << Res->getType());
5685      }
5686
5687      // Get the decl corresponding to this.
5688      RecordDecl *RD = RC->getDecl();
5689      if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
5690        if (!CRD->isPOD() && !DidWarnAboutNonPOD) {
5691          ExprError(Diag(BuiltinLoc, diag::warn_offsetof_non_pod_type)
5692            << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
5693            << Res->getType());
5694          DidWarnAboutNonPOD = true;
5695        }
5696      }
5697
5698      LookupResult R;
5699      LookupQualifiedName(R, RD, OC.U.IdentInfo, LookupMemberName);
5700
5701      FieldDecl *MemberDecl
5702        = dyn_cast_or_null<FieldDecl>(R.getAsSingleDecl(Context));
5703      // FIXME: Leaks Res
5704      if (!MemberDecl)
5705        return ExprError(Diag(BuiltinLoc, diag::err_no_member)
5706         << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
5707
5708      // FIXME: C++: Verify that MemberDecl isn't a static field.
5709      // FIXME: Verify that MemberDecl isn't a bitfield.
5710      if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
5711        Res = BuildAnonymousStructUnionMemberReference(
5712            SourceLocation(), MemberDecl, Res, SourceLocation()).takeAs<Expr>();
5713      } else {
5714        // MemberDecl->getType() doesn't get the right qualifiers, but it
5715        // doesn't matter here.
5716        Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
5717                MemberDecl->getType().getNonReferenceType());
5718      }
5719    }
5720  }
5721
5722  return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
5723                                           Context.getSizeType(), BuiltinLoc));
5724}
5725
5726
5727Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
5728                                                      TypeTy *arg1,TypeTy *arg2,
5729                                                      SourceLocation RPLoc) {
5730  // FIXME: Preserve type source info.
5731  QualType argT1 = GetTypeFromParser(arg1);
5732  QualType argT2 = GetTypeFromParser(arg2);
5733
5734  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
5735
5736  if (getLangOptions().CPlusPlus) {
5737    Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
5738      << SourceRange(BuiltinLoc, RPLoc);
5739    return ExprError();
5740  }
5741
5742  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
5743                                                 argT1, argT2, RPLoc));
5744}
5745
5746Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
5747                                             ExprArg cond,
5748                                             ExprArg expr1, ExprArg expr2,
5749                                             SourceLocation RPLoc) {
5750  Expr *CondExpr = static_cast<Expr*>(cond.get());
5751  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
5752  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
5753
5754  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
5755
5756  QualType resType;
5757  bool ValueDependent = false;
5758  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
5759    resType = Context.DependentTy;
5760    ValueDependent = true;
5761  } else {
5762    // The conditional expression is required to be a constant expression.
5763    llvm::APSInt condEval(32);
5764    SourceLocation ExpLoc;
5765    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
5766      return ExprError(Diag(ExpLoc,
5767                       diag::err_typecheck_choose_expr_requires_constant)
5768        << CondExpr->getSourceRange());
5769
5770    // If the condition is > zero, then the AST type is the same as the LSHExpr.
5771    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
5772    ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
5773                                             : RHSExpr->isValueDependent();
5774  }
5775
5776  cond.release(); expr1.release(); expr2.release();
5777  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
5778                                        resType, RPLoc,
5779                                        resType->isDependentType(),
5780                                        ValueDependent));
5781}
5782
5783//===----------------------------------------------------------------------===//
5784// Clang Extensions.
5785//===----------------------------------------------------------------------===//
5786
5787/// ActOnBlockStart - This callback is invoked when a block literal is started.
5788void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
5789  // Analyze block parameters.
5790  BlockSemaInfo *BSI = new BlockSemaInfo();
5791
5792  // Add BSI to CurBlock.
5793  BSI->PrevBlockInfo = CurBlock;
5794  CurBlock = BSI;
5795
5796  BSI->ReturnType = QualType();
5797  BSI->TheScope = BlockScope;
5798  BSI->hasBlockDeclRefExprs = false;
5799  BSI->hasPrototype = false;
5800  BSI->SavedFunctionNeedsScopeChecking = CurFunctionNeedsScopeChecking;
5801  CurFunctionNeedsScopeChecking = false;
5802
5803  BSI->TheDecl = BlockDecl::Create(Context, CurContext, CaretLoc);
5804  PushDeclContext(BlockScope, BSI->TheDecl);
5805}
5806
5807void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
5808  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
5809
5810  if (ParamInfo.getNumTypeObjects() == 0
5811      || ParamInfo.getTypeObject(0).Kind != DeclaratorChunk::Function) {
5812    ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5813    QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5814
5815    if (T->isArrayType()) {
5816      Diag(ParamInfo.getSourceRange().getBegin(),
5817           diag::err_block_returns_array);
5818      return;
5819    }
5820
5821    // The parameter list is optional, if there was none, assume ().
5822    if (!T->isFunctionType())
5823      T = Context.getFunctionType(T, NULL, 0, 0, 0);
5824
5825    CurBlock->hasPrototype = true;
5826    CurBlock->isVariadic = false;
5827    // Check for a valid sentinel attribute on this block.
5828    if (CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5829      Diag(ParamInfo.getAttributes()->getLoc(),
5830           diag::warn_attribute_sentinel_not_variadic) << 1;
5831      // FIXME: remove the attribute.
5832    }
5833    QualType RetTy = T.getTypePtr()->getAs<FunctionType>()->getResultType();
5834
5835    // Do not allow returning a objc interface by-value.
5836    if (RetTy->isObjCInterfaceType()) {
5837      Diag(ParamInfo.getSourceRange().getBegin(),
5838           diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5839      return;
5840    }
5841    return;
5842  }
5843
5844  // Analyze arguments to block.
5845  assert(ParamInfo.getTypeObject(0).Kind == DeclaratorChunk::Function &&
5846         "Not a function declarator!");
5847  DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getTypeObject(0).Fun;
5848
5849  CurBlock->hasPrototype = FTI.hasPrototype;
5850  CurBlock->isVariadic = true;
5851
5852  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs function that takes
5853  // no arguments, not a function that takes a single void argument.
5854  if (FTI.hasPrototype &&
5855      FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
5856     (!FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType().getCVRQualifiers()&&
5857        FTI.ArgInfo[0].Param.getAs<ParmVarDecl>()->getType()->isVoidType())) {
5858    // empty arg list, don't push any params.
5859    CurBlock->isVariadic = false;
5860  } else if (FTI.hasPrototype) {
5861    for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
5862      CurBlock->Params.push_back(FTI.ArgInfo[i].Param.getAs<ParmVarDecl>());
5863    CurBlock->isVariadic = FTI.isVariadic;
5864  }
5865  CurBlock->TheDecl->setParams(Context, CurBlock->Params.data(),
5866                               CurBlock->Params.size());
5867  CurBlock->TheDecl->setIsVariadic(CurBlock->isVariadic);
5868  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
5869  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
5870       E = CurBlock->TheDecl->param_end(); AI != E; ++AI)
5871    // If this has an identifier, add it to the scope stack.
5872    if ((*AI)->getIdentifier())
5873      PushOnScopeChains(*AI, CurBlock->TheScope);
5874
5875  // Check for a valid sentinel attribute on this block.
5876  if (!CurBlock->isVariadic &&
5877      CurBlock->TheDecl->getAttr<SentinelAttr>()) {
5878    Diag(ParamInfo.getAttributes()->getLoc(),
5879         diag::warn_attribute_sentinel_not_variadic) << 1;
5880    // FIXME: remove the attribute.
5881  }
5882
5883  // Analyze the return type.
5884  QualType T = GetTypeForDeclarator(ParamInfo, CurScope);
5885  QualType RetTy = T->getAs<FunctionType>()->getResultType();
5886
5887  // Do not allow returning a objc interface by-value.
5888  if (RetTy->isObjCInterfaceType()) {
5889    Diag(ParamInfo.getSourceRange().getBegin(),
5890         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
5891  } else if (!RetTy->isDependentType())
5892    CurBlock->ReturnType = RetTy;
5893}
5894
5895/// ActOnBlockError - If there is an error parsing a block, this callback
5896/// is invoked to pop the information about the block from the action impl.
5897void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
5898  // Ensure that CurBlock is deleted.
5899  llvm::OwningPtr<BlockSemaInfo> CC(CurBlock);
5900
5901  CurFunctionNeedsScopeChecking = CurBlock->SavedFunctionNeedsScopeChecking;
5902
5903  // Pop off CurBlock, handle nested blocks.
5904  PopDeclContext();
5905  CurBlock = CurBlock->PrevBlockInfo;
5906  // FIXME: Delete the ParmVarDecl objects as well???
5907}
5908
5909/// ActOnBlockStmtExpr - This is called when the body of a block statement
5910/// literal was successfully completed.  ^(int x){...}
5911Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
5912                                                StmtArg body, Scope *CurScope) {
5913  // If blocks are disabled, emit an error.
5914  if (!LangOpts.Blocks)
5915    Diag(CaretLoc, diag::err_blocks_disable);
5916
5917  // Ensure that CurBlock is deleted.
5918  llvm::OwningPtr<BlockSemaInfo> BSI(CurBlock);
5919
5920  PopDeclContext();
5921
5922  // Pop off CurBlock, handle nested blocks.
5923  CurBlock = CurBlock->PrevBlockInfo;
5924
5925  QualType RetTy = Context.VoidTy;
5926  if (!BSI->ReturnType.isNull())
5927    RetTy = BSI->ReturnType;
5928
5929  llvm::SmallVector<QualType, 8> ArgTypes;
5930  for (unsigned i = 0, e = BSI->Params.size(); i != e; ++i)
5931    ArgTypes.push_back(BSI->Params[i]->getType());
5932
5933  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
5934  QualType BlockTy;
5935  if (!BSI->hasPrototype)
5936    BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0, false, false, 0, 0,
5937                                      NoReturn);
5938  else
5939    BlockTy = Context.getFunctionType(RetTy, ArgTypes.data(), ArgTypes.size(),
5940                                      BSI->isVariadic, 0, false, false, 0, 0,
5941                                      NoReturn);
5942
5943  // FIXME: Check that return/parameter types are complete/non-abstract
5944  DiagnoseUnusedParameters(BSI->Params.begin(), BSI->Params.end());
5945  BlockTy = Context.getBlockPointerType(BlockTy);
5946
5947  // If needed, diagnose invalid gotos and switches in the block.
5948  if (CurFunctionNeedsScopeChecking)
5949    DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
5950  CurFunctionNeedsScopeChecking = BSI->SavedFunctionNeedsScopeChecking;
5951
5952  BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
5953  CheckFallThroughForBlock(BlockTy, BSI->TheDecl->getBody());
5954  return Owned(new (Context) BlockExpr(BSI->TheDecl, BlockTy,
5955                                       BSI->hasBlockDeclRefExprs));
5956}
5957
5958Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
5959                                        ExprArg expr, TypeTy *type,
5960                                        SourceLocation RPLoc) {
5961  QualType T = GetTypeFromParser(type);
5962  Expr *E = static_cast<Expr*>(expr.get());
5963  Expr *OrigExpr = E;
5964
5965  InitBuiltinVaListType();
5966
5967  // Get the va_list type
5968  QualType VaListType = Context.getBuiltinVaListType();
5969  if (VaListType->isArrayType()) {
5970    // Deal with implicit array decay; for example, on x86-64,
5971    // va_list is an array, but it's supposed to decay to
5972    // a pointer for va_arg.
5973    VaListType = Context.getArrayDecayedType(VaListType);
5974    // Make sure the input expression also decays appropriately.
5975    UsualUnaryConversions(E);
5976  } else {
5977    // Otherwise, the va_list argument must be an l-value because
5978    // it is modified by va_arg.
5979    if (!E->isTypeDependent() &&
5980        CheckForModifiableLvalue(E, BuiltinLoc, *this))
5981      return ExprError();
5982  }
5983
5984  if (!E->isTypeDependent() &&
5985      !Context.hasSameType(VaListType, E->getType())) {
5986    return ExprError(Diag(E->getLocStart(),
5987                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
5988      << OrigExpr->getType() << E->getSourceRange());
5989  }
5990
5991  // FIXME: Check that type is complete/non-abstract
5992  // FIXME: Warn if a non-POD type is passed in.
5993
5994  expr.release();
5995  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
5996                                       RPLoc));
5997}
5998
5999Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
6000  // The type of __null will be int or long, depending on the size of
6001  // pointers on the target.
6002  QualType Ty;
6003  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
6004    Ty = Context.IntTy;
6005  else
6006    Ty = Context.LongTy;
6007
6008  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
6009}
6010
6011bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
6012                                    SourceLocation Loc,
6013                                    QualType DstType, QualType SrcType,
6014                                    Expr *SrcExpr, const char *Flavor) {
6015  // Decode the result (notice that AST's are still created for extensions).
6016  bool isInvalid = false;
6017  unsigned DiagKind;
6018  switch (ConvTy) {
6019  default: assert(0 && "Unknown conversion type");
6020  case Compatible: return false;
6021  case PointerToInt:
6022    DiagKind = diag::ext_typecheck_convert_pointer_int;
6023    break;
6024  case IntToPointer:
6025    DiagKind = diag::ext_typecheck_convert_int_pointer;
6026    break;
6027  case IncompatiblePointer:
6028    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
6029    break;
6030  case IncompatiblePointerSign:
6031    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
6032    break;
6033  case FunctionVoidPointer:
6034    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
6035    break;
6036  case CompatiblePointerDiscardsQualifiers:
6037    // If the qualifiers lost were because we were applying the
6038    // (deprecated) C++ conversion from a string literal to a char*
6039    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
6040    // Ideally, this check would be performed in
6041    // CheckPointerTypesForAssignment. However, that would require a
6042    // bit of refactoring (so that the second argument is an
6043    // expression, rather than a type), which should be done as part
6044    // of a larger effort to fix CheckPointerTypesForAssignment for
6045    // C++ semantics.
6046    if (getLangOptions().CPlusPlus &&
6047        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
6048      return false;
6049    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
6050    break;
6051  case IntToBlockPointer:
6052    DiagKind = diag::err_int_to_block_pointer;
6053    break;
6054  case IncompatibleBlockPointer:
6055    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
6056    break;
6057  case IncompatibleObjCQualifiedId:
6058    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
6059    // it can give a more specific diagnostic.
6060    DiagKind = diag::warn_incompatible_qualified_id;
6061    break;
6062  case IncompatibleVectors:
6063    DiagKind = diag::warn_incompatible_vectors;
6064    break;
6065  case Incompatible:
6066    DiagKind = diag::err_typecheck_convert_incompatible;
6067    isInvalid = true;
6068    break;
6069  }
6070
6071  Diag(Loc, DiagKind) << DstType << SrcType << Flavor
6072    << SrcExpr->getSourceRange();
6073  return isInvalid;
6074}
6075
6076bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
6077  llvm::APSInt ICEResult;
6078  if (E->isIntegerConstantExpr(ICEResult, Context)) {
6079    if (Result)
6080      *Result = ICEResult;
6081    return false;
6082  }
6083
6084  Expr::EvalResult EvalResult;
6085
6086  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
6087      EvalResult.HasSideEffects) {
6088    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
6089
6090    if (EvalResult.Diag) {
6091      // We only show the note if it's not the usual "invalid subexpression"
6092      // or if it's actually in a subexpression.
6093      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
6094          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
6095        Diag(EvalResult.DiagLoc, EvalResult.Diag);
6096    }
6097
6098    return true;
6099  }
6100
6101  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
6102    E->getSourceRange();
6103
6104  if (EvalResult.Diag &&
6105      Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
6106    Diag(EvalResult.DiagLoc, EvalResult.Diag);
6107
6108  if (Result)
6109    *Result = EvalResult.Val.getInt();
6110  return false;
6111}
6112
6113Sema::ExpressionEvaluationContext
6114Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
6115  // Introduce a new set of potentially referenced declarations to the stack.
6116  if (NewContext == PotentiallyPotentiallyEvaluated)
6117    PotentiallyReferencedDeclStack.push_back(PotentiallyReferencedDecls());
6118
6119  std::swap(ExprEvalContext, NewContext);
6120  return NewContext;
6121}
6122
6123void
6124Sema::PopExpressionEvaluationContext(ExpressionEvaluationContext OldContext,
6125                                     ExpressionEvaluationContext NewContext) {
6126  ExprEvalContext = NewContext;
6127
6128  if (OldContext == PotentiallyPotentiallyEvaluated) {
6129    // Mark any remaining declarations in the current position of the stack
6130    // as "referenced". If they were not meant to be referenced, semantic
6131    // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
6132    PotentiallyReferencedDecls RemainingDecls;
6133    RemainingDecls.swap(PotentiallyReferencedDeclStack.back());
6134    PotentiallyReferencedDeclStack.pop_back();
6135
6136    for (PotentiallyReferencedDecls::iterator I = RemainingDecls.begin(),
6137                                           IEnd = RemainingDecls.end();
6138         I != IEnd; ++I)
6139      MarkDeclarationReferenced(I->first, I->second);
6140  }
6141}
6142
6143/// \brief Note that the given declaration was referenced in the source code.
6144///
6145/// This routine should be invoke whenever a given declaration is referenced
6146/// in the source code, and where that reference occurred. If this declaration
6147/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
6148/// C99 6.9p3), then the declaration will be marked as used.
6149///
6150/// \param Loc the location where the declaration was referenced.
6151///
6152/// \param D the declaration that has been referenced by the source code.
6153void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
6154  assert(D && "No declaration?");
6155
6156  if (D->isUsed())
6157    return;
6158
6159  // Mark a parameter or variable declaration "used", regardless of whether we're in a
6160  // template or not. The reason for this is that unevaluated expressions
6161  // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
6162  // -Wunused-parameters)
6163  if (isa<ParmVarDecl>(D) ||
6164      (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod()))
6165    D->setUsed(true);
6166
6167  // Do not mark anything as "used" within a dependent context; wait for
6168  // an instantiation.
6169  if (CurContext->isDependentContext())
6170    return;
6171
6172  switch (ExprEvalContext) {
6173    case Unevaluated:
6174      // We are in an expression that is not potentially evaluated; do nothing.
6175      return;
6176
6177    case PotentiallyEvaluated:
6178      // We are in a potentially-evaluated expression, so this declaration is
6179      // "used"; handle this below.
6180      break;
6181
6182    case PotentiallyPotentiallyEvaluated:
6183      // We are in an expression that may be potentially evaluated; queue this
6184      // declaration reference until we know whether the expression is
6185      // potentially evaluated.
6186      PotentiallyReferencedDeclStack.back().push_back(std::make_pair(Loc, D));
6187      return;
6188  }
6189
6190  // Note that this declaration has been used.
6191  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
6192    unsigned TypeQuals;
6193    if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
6194        if (!Constructor->isUsed())
6195          DefineImplicitDefaultConstructor(Loc, Constructor);
6196    } else if (Constructor->isImplicit() &&
6197               Constructor->isCopyConstructor(Context, TypeQuals)) {
6198      if (!Constructor->isUsed())
6199        DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
6200    }
6201  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
6202    if (Destructor->isImplicit() && !Destructor->isUsed())
6203      DefineImplicitDestructor(Loc, Destructor);
6204
6205  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
6206    if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
6207        MethodDecl->getOverloadedOperator() == OO_Equal) {
6208      if (!MethodDecl->isUsed())
6209        DefineImplicitOverloadedAssign(Loc, MethodDecl);
6210    }
6211  }
6212  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
6213    // Implicit instantiation of function templates and member functions of
6214    // class templates.
6215    if (!Function->getBody() &&
6216        Function->getTemplateSpecializationKind()
6217                                                == TSK_ImplicitInstantiation) {
6218      bool AlreadyInstantiated = false;
6219      if (FunctionTemplateSpecializationInfo *SpecInfo
6220                                = Function->getTemplateSpecializationInfo()) {
6221        if (SpecInfo->getPointOfInstantiation().isInvalid())
6222          SpecInfo->setPointOfInstantiation(Loc);
6223        else
6224          AlreadyInstantiated = true;
6225      } else if (MemberSpecializationInfo *MSInfo
6226                                  = Function->getMemberSpecializationInfo()) {
6227        if (MSInfo->getPointOfInstantiation().isInvalid())
6228          MSInfo->setPointOfInstantiation(Loc);
6229        else
6230          AlreadyInstantiated = true;
6231      }
6232
6233      if (!AlreadyInstantiated)
6234        PendingImplicitInstantiations.push_back(std::make_pair(Function, Loc));
6235    }
6236
6237    // FIXME: keep track of references to static functions
6238    Function->setUsed(true);
6239    return;
6240  }
6241
6242  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
6243    // Implicit instantiation of static data members of class templates.
6244    if (Var->isStaticDataMember() &&
6245        Var->getInstantiatedFromStaticDataMember()) {
6246      MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
6247      assert(MSInfo && "Missing member specialization information?");
6248      if (MSInfo->getPointOfInstantiation().isInvalid() &&
6249          MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
6250        MSInfo->setPointOfInstantiation(Loc);
6251        PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
6252      }
6253    }
6254
6255    // FIXME: keep track of references to static data?
6256
6257    D->setUsed(true);
6258    return;
6259  }
6260}
6261
6262bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
6263                               CallExpr *CE, FunctionDecl *FD) {
6264  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
6265    return false;
6266
6267  PartialDiagnostic Note =
6268    FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
6269    << FD->getDeclName() : PDiag();
6270  SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
6271
6272  if (RequireCompleteType(Loc, ReturnType,
6273                          FD ?
6274                          PDiag(diag::err_call_function_incomplete_return)
6275                            << CE->getSourceRange() << FD->getDeclName() :
6276                          PDiag(diag::err_call_incomplete_return)
6277                            << CE->getSourceRange(),
6278                          std::make_pair(NoteLoc, Note)))
6279    return true;
6280
6281  return false;
6282}
6283
6284// Diagnose the common s/=/==/ typo.  Note that adding parentheses
6285// will prevent this condition from triggering, which is what we want.
6286void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
6287  SourceLocation Loc;
6288
6289  if (isa<BinaryOperator>(E)) {
6290    BinaryOperator *Op = cast<BinaryOperator>(E);
6291    if (Op->getOpcode() != BinaryOperator::Assign)
6292      return;
6293
6294    Loc = Op->getOperatorLoc();
6295  } else if (isa<CXXOperatorCallExpr>(E)) {
6296    CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
6297    if (Op->getOperator() != OO_Equal)
6298      return;
6299
6300    Loc = Op->getOperatorLoc();
6301  } else {
6302    // Not an assignment.
6303    return;
6304  }
6305
6306  SourceLocation Open = E->getSourceRange().getBegin();
6307  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
6308
6309  Diag(Loc, diag::warn_condition_is_assignment)
6310    << E->getSourceRange()
6311    << CodeModificationHint::CreateInsertion(Open, "(")
6312    << CodeModificationHint::CreateInsertion(Close, ")");
6313}
6314
6315bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
6316  DiagnoseAssignmentAsCondition(E);
6317
6318  if (!E->isTypeDependent()) {
6319    DefaultFunctionArrayConversion(E);
6320
6321    QualType T = E->getType();
6322
6323    if (getLangOptions().CPlusPlus) {
6324      if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
6325        return true;
6326    } else if (!T->isScalarType()) { // C99 6.8.4.1p1
6327      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
6328        << T << E->getSourceRange();
6329      return true;
6330    }
6331  }
6332
6333  return false;
6334}
6335