SemaExpr.cpp revision 8f33423d3428ad03cfa698bbdeabeaa09510016e
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 "SemaInit.h"
16#include "Lookup.h"
17#include "AnalysisBasedWarnings.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Parse/DeclSpec.h"
33#include "clang/Parse/Designator.h"
34#include "clang/Parse/Scope.h"
35#include "clang/Parse/Template.h"
36using namespace clang;
37
38
39/// \brief Determine whether the use of this declaration is valid, and
40/// emit any corresponding diagnostics.
41///
42/// This routine diagnoses various problems with referencing
43/// declarations that can occur when using a declaration. For example,
44/// it might warn if a deprecated or unavailable declaration is being
45/// used, or produce an error (and return true) if a C++0x deleted
46/// function is being used.
47///
48/// If IgnoreDeprecated is set to true, this should not want about deprecated
49/// decls.
50///
51/// \returns true if there was an error (this declaration cannot be
52/// referenced), false otherwise.
53///
54bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc) {
55  // See if the decl is deprecated.
56  if (D->getAttr<DeprecatedAttr>()) {
57    EmitDeprecationWarning(D, Loc);
58  }
59
60  // See if the decl is unavailable
61  if (D->getAttr<UnavailableAttr>()) {
62    Diag(Loc, diag::warn_unavailable) << D->getDeclName();
63    Diag(D->getLocation(), diag::note_unavailable_here) << 0;
64  }
65
66  // See if this is a deleted function.
67  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
68    if (FD->isDeleted()) {
69      Diag(Loc, diag::err_deleted_function_use);
70      Diag(D->getLocation(), diag::note_unavailable_here) << true;
71      return true;
72    }
73  }
74
75  return false;
76}
77
78/// DiagnoseSentinelCalls - This routine checks on method dispatch calls
79/// (and other functions in future), which have been declared with sentinel
80/// attribute. It warns if call does not have the sentinel argument.
81///
82void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
83                                 Expr **Args, unsigned NumArgs) {
84  const SentinelAttr *attr = D->getAttr<SentinelAttr>();
85  if (!attr)
86    return;
87
88  // FIXME: In C++0x, if any of the arguments are parameter pack
89  // expansions, we can't check for the sentinel now.
90  int sentinelPos = attr->getSentinel();
91  int nullPos = attr->getNullPos();
92
93  // FIXME. ObjCMethodDecl and FunctionDecl need be derived from the same common
94  // base class. Then we won't be needing two versions of the same code.
95  unsigned int i = 0;
96  bool warnNotEnoughArgs = false;
97  int isMethod = 0;
98  if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
99    // skip over named parameters.
100    ObjCMethodDecl::param_iterator P, E = MD->param_end();
101    for (P = MD->param_begin(); (P != E && i < NumArgs); ++P) {
102      if (nullPos)
103        --nullPos;
104      else
105        ++i;
106    }
107    warnNotEnoughArgs = (P != E || i >= NumArgs);
108    isMethod = 1;
109  } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
110    // skip over named parameters.
111    ObjCMethodDecl::param_iterator P, E = FD->param_end();
112    for (P = FD->param_begin(); (P != E && i < NumArgs); ++P) {
113      if (nullPos)
114        --nullPos;
115      else
116        ++i;
117    }
118    warnNotEnoughArgs = (P != E || i >= NumArgs);
119  } else if (VarDecl *V = dyn_cast<VarDecl>(D)) {
120    // block or function pointer call.
121    QualType Ty = V->getType();
122    if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
123      const FunctionType *FT = Ty->isFunctionPointerType()
124      ? Ty->getAs<PointerType>()->getPointeeType()->getAs<FunctionType>()
125      : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
126      if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FT)) {
127        unsigned NumArgsInProto = Proto->getNumArgs();
128        unsigned k;
129        for (k = 0; (k != NumArgsInProto && i < NumArgs); k++) {
130          if (nullPos)
131            --nullPos;
132          else
133            ++i;
134        }
135        warnNotEnoughArgs = (k != NumArgsInProto || i >= NumArgs);
136      }
137      if (Ty->isBlockPointerType())
138        isMethod = 2;
139    } else
140      return;
141  } else
142    return;
143
144  if (warnNotEnoughArgs) {
145    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
146    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
147    return;
148  }
149  int sentinel = i;
150  while (sentinelPos > 0 && i < NumArgs-1) {
151    --sentinelPos;
152    ++i;
153  }
154  if (sentinelPos > 0) {
155    Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
156    Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
157    return;
158  }
159  while (i < NumArgs-1) {
160    ++i;
161    ++sentinel;
162  }
163  Expr *sentinelExpr = Args[sentinel];
164  if (!sentinelExpr) return;
165  if (sentinelExpr->isTypeDependent()) return;
166  if (sentinelExpr->isValueDependent()) return;
167  if (sentinelExpr->getType()->isPointerType() &&
168      sentinelExpr->IgnoreParenCasts()->isNullPointerConstant(Context,
169                                            Expr::NPC_ValueDependentIsNull))
170    return;
171
172  // Unfortunately, __null has type 'int'.
173  if (isa<GNUNullExpr>(sentinelExpr)) return;
174
175  Diag(Loc, diag::warn_missing_sentinel) << isMethod;
176  Diag(D->getLocation(), diag::note_sentinel_here) << isMethod;
177}
178
179SourceRange Sema::getExprRange(ExprTy *E) const {
180  Expr *Ex = (Expr *)E;
181  return Ex? Ex->getSourceRange() : SourceRange();
182}
183
184//===----------------------------------------------------------------------===//
185//  Standard Promotions and Conversions
186//===----------------------------------------------------------------------===//
187
188/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
189void Sema::DefaultFunctionArrayConversion(Expr *&E) {
190  QualType Ty = E->getType();
191  assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
192
193  if (Ty->isFunctionType())
194    ImpCastExprToType(E, Context.getPointerType(Ty),
195                      CastExpr::CK_FunctionToPointerDecay);
196  else if (Ty->isArrayType()) {
197    // In C90 mode, arrays only promote to pointers if the array expression is
198    // an lvalue.  The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
199    // type 'array of type' is converted to an expression that has type 'pointer
200    // to type'...".  In C99 this was changed to: C99 6.3.2.1p3: "an expression
201    // that has type 'array of type' ...".  The relevant change is "an lvalue"
202    // (C90) to "an expression" (C99).
203    //
204    // C++ 4.2p1:
205    // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
206    // T" can be converted to an rvalue of type "pointer to T".
207    //
208    if (getLangOptions().C99 || getLangOptions().CPlusPlus ||
209        E->isLvalue(Context) == Expr::LV_Valid)
210      ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
211                        CastExpr::CK_ArrayToPointerDecay);
212  }
213}
214
215void Sema::DefaultFunctionArrayLvalueConversion(Expr *&E) {
216  DefaultFunctionArrayConversion(E);
217
218  QualType Ty = E->getType();
219  assert(!Ty.isNull() && "DefaultFunctionArrayLvalueConversion - missing type");
220  if (!Ty->isDependentType() && Ty.hasQualifiers() &&
221      (!getLangOptions().CPlusPlus || !Ty->isRecordType()) &&
222      E->isLvalue(Context) == Expr::LV_Valid) {
223    // C++ [conv.lval]p1:
224    //   [...] If T is a non-class type, the type of the rvalue is the
225    //   cv-unqualified version of T. Otherwise, the type of the
226    //   rvalue is T
227    //
228    // C99 6.3.2.1p2:
229    //   If the lvalue has qualified type, the value has the unqualified
230    //   version of the type of the lvalue; otherwise, the value has the
231    //   type of the lvalue.
232    ImpCastExprToType(E, Ty.getUnqualifiedType(), CastExpr::CK_NoOp);
233  }
234}
235
236
237/// UsualUnaryConversions - Performs various conversions that are common to most
238/// operators (C99 6.3). The conversions of array and function types are
239/// sometimes surpressed. For example, the array->pointer conversion doesn't
240/// apply if the array is an argument to the sizeof or address (&) operators.
241/// In these instances, this routine should *not* be called.
242Expr *Sema::UsualUnaryConversions(Expr *&Expr) {
243  QualType Ty = Expr->getType();
244  assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
245
246  // C99 6.3.1.1p2:
247  //
248  //   The following may be used in an expression wherever an int or
249  //   unsigned int may be used:
250  //     - an object or expression with an integer type whose integer
251  //       conversion rank is less than or equal to the rank of int
252  //       and unsigned int.
253  //     - A bit-field of type _Bool, int, signed int, or unsigned int.
254  //
255  //   If an int can represent all values of the original type, the
256  //   value is converted to an int; otherwise, it is converted to an
257  //   unsigned int. These are called the integer promotions. All
258  //   other types are unchanged by the integer promotions.
259  QualType PTy = Context.isPromotableBitField(Expr);
260  if (!PTy.isNull()) {
261    ImpCastExprToType(Expr, PTy, CastExpr::CK_IntegralCast);
262    return Expr;
263  }
264  if (Ty->isPromotableIntegerType()) {
265    QualType PT = Context.getPromotedIntegerType(Ty);
266    ImpCastExprToType(Expr, PT, CastExpr::CK_IntegralCast);
267    return Expr;
268  }
269
270  DefaultFunctionArrayLvalueConversion(Expr);
271  return Expr;
272}
273
274/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
275/// do not have a prototype. Arguments that have type float are promoted to
276/// double. All other argument types are converted by UsualUnaryConversions().
277void Sema::DefaultArgumentPromotion(Expr *&Expr) {
278  QualType Ty = Expr->getType();
279  assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
280
281  // If this is a 'float' (CVR qualified or typedef) promote to double.
282  if (Ty->isSpecificBuiltinType(BuiltinType::Float))
283    return ImpCastExprToType(Expr, Context.DoubleTy,
284                             CastExpr::CK_FloatingCast);
285
286  UsualUnaryConversions(Expr);
287}
288
289/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
290/// will warn if the resulting type is not a POD type, and rejects ObjC
291/// interfaces passed by value.  This returns true if the argument type is
292/// completely illegal.
293bool Sema::DefaultVariadicArgumentPromotion(Expr *&Expr, VariadicCallType CT,
294                                            FunctionDecl *FDecl) {
295  DefaultArgumentPromotion(Expr);
296
297  // __builtin_va_start takes the second argument as a "varargs" argument, but
298  // it doesn't actually do anything with it.  It doesn't need to be non-pod
299  // etc.
300  if (FDecl && FDecl->getBuiltinID() == Builtin::BI__builtin_va_start)
301    return false;
302
303  if (Expr->getType()->isObjCObjectType() &&
304      DiagRuntimeBehavior(Expr->getLocStart(),
305        PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
306          << Expr->getType() << CT))
307    return true;
308
309  if (!Expr->getType()->isPODType() &&
310      DiagRuntimeBehavior(Expr->getLocStart(),
311                          PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
312                            << Expr->getType() << CT))
313    return true;
314
315  return false;
316}
317
318
319/// UsualArithmeticConversions - Performs various conversions that are common to
320/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
321/// routine returns the first non-arithmetic type found. The client is
322/// responsible for emitting appropriate error diagnostics.
323/// FIXME: verify the conversion rules for "complex int" are consistent with
324/// GCC.
325QualType Sema::UsualArithmeticConversions(Expr *&lhsExpr, Expr *&rhsExpr,
326                                          bool isCompAssign) {
327  if (!isCompAssign)
328    UsualUnaryConversions(lhsExpr);
329
330  UsualUnaryConversions(rhsExpr);
331
332  // For conversion purposes, we ignore any qualifiers.
333  // For example, "const float" and "float" are equivalent.
334  QualType lhs =
335    Context.getCanonicalType(lhsExpr->getType()).getUnqualifiedType();
336  QualType rhs =
337    Context.getCanonicalType(rhsExpr->getType()).getUnqualifiedType();
338
339  // If both types are identical, no conversion is needed.
340  if (lhs == rhs)
341    return lhs;
342
343  // If either side is a non-arithmetic type (e.g. a pointer), we are done.
344  // The caller can deal with this (e.g. pointer + int).
345  if (!lhs->isArithmeticType() || !rhs->isArithmeticType())
346    return lhs;
347
348  // Perform bitfield promotions.
349  QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(lhsExpr);
350  if (!LHSBitfieldPromoteTy.isNull())
351    lhs = LHSBitfieldPromoteTy;
352  QualType RHSBitfieldPromoteTy = Context.isPromotableBitField(rhsExpr);
353  if (!RHSBitfieldPromoteTy.isNull())
354    rhs = RHSBitfieldPromoteTy;
355
356  QualType destType = Context.UsualArithmeticConversionsType(lhs, rhs);
357  if (!isCompAssign)
358    ImpCastExprToType(lhsExpr, destType, CastExpr::CK_Unknown);
359  ImpCastExprToType(rhsExpr, destType, CastExpr::CK_Unknown);
360  return destType;
361}
362
363//===----------------------------------------------------------------------===//
364//  Semantic Analysis for various Expression Types
365//===----------------------------------------------------------------------===//
366
367
368/// ActOnStringLiteral - The specified tokens were lexed as pasted string
369/// fragments (e.g. "foo" "bar" L"baz").  The result string has to handle string
370/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
371/// multiple tokens.  However, the common case is that StringToks points to one
372/// string.
373///
374Action::OwningExprResult
375Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
376  assert(NumStringToks && "Must have at least one string!");
377
378  StringLiteralParser Literal(StringToks, NumStringToks, PP);
379  if (Literal.hadError)
380    return ExprError();
381
382  llvm::SmallVector<SourceLocation, 4> StringTokLocs;
383  for (unsigned i = 0; i != NumStringToks; ++i)
384    StringTokLocs.push_back(StringToks[i].getLocation());
385
386  QualType StrTy = Context.CharTy;
387  if (Literal.AnyWide) StrTy = Context.getWCharType();
388  if (Literal.Pascal) StrTy = Context.UnsignedCharTy;
389
390  // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
391  if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
392    StrTy.addConst();
393
394  // Get an array type for the string, according to C99 6.4.5.  This includes
395  // the nul terminator character as well as the string length for pascal
396  // strings.
397  StrTy = Context.getConstantArrayType(StrTy,
398                                 llvm::APInt(32, Literal.GetNumStringChars()+1),
399                                       ArrayType::Normal, 0);
400
401  // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
402  return Owned(StringLiteral::Create(Context, Literal.GetString(),
403                                     Literal.GetStringLength(),
404                                     Literal.AnyWide, StrTy,
405                                     &StringTokLocs[0],
406                                     StringTokLocs.size()));
407}
408
409/// ShouldSnapshotBlockValueReference - Return true if a reference inside of
410/// CurBlock to VD should cause it to be snapshotted (as we do for auto
411/// variables defined outside the block) or false if this is not needed (e.g.
412/// for values inside the block or for globals).
413///
414/// This also keeps the 'hasBlockDeclRefExprs' in the BlockScopeInfo records
415/// up-to-date.
416///
417static bool ShouldSnapshotBlockValueReference(Sema &S, BlockScopeInfo *CurBlock,
418                                              ValueDecl *VD) {
419  // If the value is defined inside the block, we couldn't snapshot it even if
420  // we wanted to.
421  if (CurBlock->TheDecl == VD->getDeclContext())
422    return false;
423
424  // If this is an enum constant or function, it is constant, don't snapshot.
425  if (isa<EnumConstantDecl>(VD) || isa<FunctionDecl>(VD))
426    return false;
427
428  // If this is a reference to an extern, static, or global variable, no need to
429  // snapshot it.
430  // FIXME: What about 'const' variables in C++?
431  if (const VarDecl *Var = dyn_cast<VarDecl>(VD))
432    if (!Var->hasLocalStorage())
433      return false;
434
435  // Blocks that have these can't be constant.
436  CurBlock->hasBlockDeclRefExprs = true;
437
438  // If we have nested blocks, the decl may be declared in an outer block (in
439  // which case that outer block doesn't get "hasBlockDeclRefExprs") or it may
440  // be defined outside all of the current blocks (in which case the blocks do
441  // all get the bit).  Walk the nesting chain.
442  for (unsigned I = S.FunctionScopes.size() - 1; I; --I) {
443    BlockScopeInfo *NextBlock = dyn_cast<BlockScopeInfo>(S.FunctionScopes[I]);
444
445    if (!NextBlock)
446      continue;
447
448    // If we found the defining block for the variable, don't mark the block as
449    // having a reference outside it.
450    if (NextBlock->TheDecl == VD->getDeclContext())
451      break;
452
453    // Otherwise, the DeclRef from the inner block causes the outer one to need
454    // a snapshot as well.
455    NextBlock->hasBlockDeclRefExprs = true;
456  }
457
458  return true;
459}
460
461
462
463/// BuildDeclRefExpr - Build a DeclRefExpr.
464Sema::OwningExprResult
465Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, SourceLocation Loc,
466                       const CXXScopeSpec *SS) {
467  if (Context.getCanonicalType(Ty) == Context.UndeducedAutoTy) {
468    Diag(Loc,
469         diag::err_auto_variable_cannot_appear_in_own_initializer)
470      << D->getDeclName();
471    return ExprError();
472  }
473
474  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
475    if (isa<NonTypeTemplateParmDecl>(VD)) {
476      // Non-type template parameters can be referenced anywhere they are
477      // visible.
478    } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(CurContext)) {
479      if (const FunctionDecl *FD = MD->getParent()->isLocalClass()) {
480        if (VD->hasLocalStorage() && VD->getDeclContext() != CurContext) {
481          Diag(Loc, diag::err_reference_to_local_var_in_enclosing_function)
482            << D->getIdentifier() << FD->getDeclName();
483          Diag(D->getLocation(), diag::note_local_variable_declared_here)
484            << D->getIdentifier();
485          return ExprError();
486        }
487      }
488    }
489  }
490
491  MarkDeclarationReferenced(Loc, D);
492
493  return Owned(DeclRefExpr::Create(Context,
494                              SS? (NestedNameSpecifier *)SS->getScopeRep() : 0,
495                                   SS? SS->getRange() : SourceRange(),
496                                   D, Loc, Ty));
497}
498
499/// \brief Given a field that represents a member of an anonymous
500/// struct/union, build the path from that field's context to the
501/// actual member.
502///
503/// Construct the sequence of field member references we'll have to
504/// perform to get to the field in the anonymous union/struct. The
505/// list of members is built from the field outward, so traverse it
506/// backwards to go from an object in the current context to the field
507/// we found.
508///
509/// \returns The variable from which the field access should begin,
510/// for an anonymous struct/union that is not a member of another
511/// class. Otherwise, returns NULL.
512VarDecl *Sema::BuildAnonymousStructUnionMemberPath(FieldDecl *Field,
513                                   llvm::SmallVectorImpl<FieldDecl *> &Path) {
514  assert(Field->getDeclContext()->isRecord() &&
515         cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()
516         && "Field must be stored inside an anonymous struct or union");
517
518  Path.push_back(Field);
519  VarDecl *BaseObject = 0;
520  DeclContext *Ctx = Field->getDeclContext();
521  do {
522    RecordDecl *Record = cast<RecordDecl>(Ctx);
523    ValueDecl *AnonObject = Record->getAnonymousStructOrUnionObject();
524    if (FieldDecl *AnonField = dyn_cast<FieldDecl>(AnonObject))
525      Path.push_back(AnonField);
526    else {
527      BaseObject = cast<VarDecl>(AnonObject);
528      break;
529    }
530    Ctx = Ctx->getParent();
531  } while (Ctx->isRecord() &&
532           cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion());
533
534  return BaseObject;
535}
536
537Sema::OwningExprResult
538Sema::BuildAnonymousStructUnionMemberReference(SourceLocation Loc,
539                                               FieldDecl *Field,
540                                               Expr *BaseObjectExpr,
541                                               SourceLocation OpLoc) {
542  llvm::SmallVector<FieldDecl *, 4> AnonFields;
543  VarDecl *BaseObject = BuildAnonymousStructUnionMemberPath(Field,
544                                                            AnonFields);
545
546  // Build the expression that refers to the base object, from
547  // which we will build a sequence of member references to each
548  // of the anonymous union objects and, eventually, the field we
549  // found via name lookup.
550  bool BaseObjectIsPointer = false;
551  Qualifiers BaseQuals;
552  if (BaseObject) {
553    // BaseObject is an anonymous struct/union variable (and is,
554    // therefore, not part of another non-anonymous record).
555    if (BaseObjectExpr) BaseObjectExpr->Destroy(Context);
556    MarkDeclarationReferenced(Loc, BaseObject);
557    BaseObjectExpr = new (Context) DeclRefExpr(BaseObject,BaseObject->getType(),
558                                               SourceLocation());
559    BaseQuals
560      = Context.getCanonicalType(BaseObject->getType()).getQualifiers();
561  } else if (BaseObjectExpr) {
562    // The caller provided the base object expression. Determine
563    // whether its a pointer and whether it adds any qualifiers to the
564    // anonymous struct/union fields we're looking into.
565    QualType ObjectType = BaseObjectExpr->getType();
566    if (const PointerType *ObjectPtr = ObjectType->getAs<PointerType>()) {
567      BaseObjectIsPointer = true;
568      ObjectType = ObjectPtr->getPointeeType();
569    }
570    BaseQuals
571      = Context.getCanonicalType(ObjectType).getQualifiers();
572  } else {
573    // We've found a member of an anonymous struct/union that is
574    // inside a non-anonymous struct/union, so in a well-formed
575    // program our base object expression is "this".
576    DeclContext *DC = getFunctionLevelDeclContext();
577    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
578      if (!MD->isStatic()) {
579        QualType AnonFieldType
580          = Context.getTagDeclType(
581                     cast<RecordDecl>(AnonFields.back()->getDeclContext()));
582        QualType ThisType = Context.getTagDeclType(MD->getParent());
583        if ((Context.getCanonicalType(AnonFieldType)
584               == Context.getCanonicalType(ThisType)) ||
585            IsDerivedFrom(ThisType, AnonFieldType)) {
586          // Our base object expression is "this".
587          BaseObjectExpr = new (Context) CXXThisExpr(Loc,
588                                                     MD->getThisType(Context),
589                                                     /*isImplicit=*/true);
590          BaseObjectIsPointer = true;
591        }
592      } else {
593        return ExprError(Diag(Loc,diag::err_invalid_member_use_in_static_method)
594          << Field->getDeclName());
595      }
596      BaseQuals = Qualifiers::fromCVRMask(MD->getTypeQualifiers());
597    }
598
599    if (!BaseObjectExpr)
600      return ExprError(Diag(Loc, diag::err_invalid_non_static_member_use)
601        << Field->getDeclName());
602  }
603
604  // Build the implicit member references to the field of the
605  // anonymous struct/union.
606  Expr *Result = BaseObjectExpr;
607  Qualifiers ResultQuals = BaseQuals;
608  for (llvm::SmallVector<FieldDecl *, 4>::reverse_iterator
609         FI = AnonFields.rbegin(), FIEnd = AnonFields.rend();
610       FI != FIEnd; ++FI) {
611    QualType MemberType = (*FI)->getType();
612    Qualifiers MemberTypeQuals =
613      Context.getCanonicalType(MemberType).getQualifiers();
614
615    // CVR attributes from the base are picked up by members,
616    // except that 'mutable' members don't pick up 'const'.
617    if ((*FI)->isMutable())
618      ResultQuals.removeConst();
619
620    // GC attributes are never picked up by members.
621    ResultQuals.removeObjCGCAttr();
622
623    // TR 18037 does not allow fields to be declared with address spaces.
624    assert(!MemberTypeQuals.hasAddressSpace());
625
626    Qualifiers NewQuals = ResultQuals + MemberTypeQuals;
627    if (NewQuals != MemberTypeQuals)
628      MemberType = Context.getQualifiedType(MemberType, NewQuals);
629
630    MarkDeclarationReferenced(Loc, *FI);
631    PerformObjectMemberConversion(Result, /*FIXME:Qualifier=*/0, *FI, *FI);
632    // FIXME: Might this end up being a qualified name?
633    Result = new (Context) MemberExpr(Result, BaseObjectIsPointer, *FI,
634                                      OpLoc, MemberType);
635    BaseObjectIsPointer = false;
636    ResultQuals = NewQuals;
637  }
638
639  return Owned(Result);
640}
641
642/// Decomposes the given name into a DeclarationName, its location, and
643/// possibly a list of template arguments.
644///
645/// If this produces template arguments, it is permitted to call
646/// DecomposeTemplateName.
647///
648/// This actually loses a lot of source location information for
649/// non-standard name kinds; we should consider preserving that in
650/// some way.
651static void DecomposeUnqualifiedId(Sema &SemaRef,
652                                   const UnqualifiedId &Id,
653                                   TemplateArgumentListInfo &Buffer,
654                                   DeclarationName &Name,
655                                   SourceLocation &NameLoc,
656                             const TemplateArgumentListInfo *&TemplateArgs) {
657  if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
658    Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
659    Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
660
661    ASTTemplateArgsPtr TemplateArgsPtr(SemaRef,
662                                       Id.TemplateId->getTemplateArgs(),
663                                       Id.TemplateId->NumArgs);
664    SemaRef.translateTemplateArguments(TemplateArgsPtr, Buffer);
665    TemplateArgsPtr.release();
666
667    TemplateName TName =
668      Sema::TemplateTy::make(Id.TemplateId->Template).getAsVal<TemplateName>();
669
670    Name = SemaRef.Context.getNameForTemplate(TName);
671    NameLoc = Id.TemplateId->TemplateNameLoc;
672    TemplateArgs = &Buffer;
673  } else {
674    Name = SemaRef.GetNameFromUnqualifiedId(Id);
675    NameLoc = Id.StartLocation;
676    TemplateArgs = 0;
677  }
678}
679
680/// Determines whether the given record is "fully-formed" at the given
681/// location, i.e. whether a qualified lookup into it is assured of
682/// getting consistent results already.
683static bool IsFullyFormedScope(Sema &SemaRef, CXXRecordDecl *Record) {
684  if (!Record->hasDefinition())
685    return false;
686
687  for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
688         E = Record->bases_end(); I != E; ++I) {
689    CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
690    CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
691    if (!BaseRT) return false;
692
693    CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
694    if (!BaseRecord->hasDefinition() ||
695        !IsFullyFormedScope(SemaRef, BaseRecord))
696      return false;
697  }
698
699  return true;
700}
701
702/// Determines whether we can lookup this id-expression now or whether
703/// we have to wait until template instantiation is complete.
704static bool IsDependentIdExpression(Sema &SemaRef, const CXXScopeSpec &SS) {
705  DeclContext *DC = SemaRef.computeDeclContext(SS, false);
706
707  // If the qualifier scope isn't computable, it's definitely dependent.
708  if (!DC) return true;
709
710  // If the qualifier scope doesn't name a record, we can always look into it.
711  if (!isa<CXXRecordDecl>(DC)) return false;
712
713  // We can't look into record types unless they're fully-formed.
714  if (!IsFullyFormedScope(SemaRef, cast<CXXRecordDecl>(DC))) return true;
715
716  return false;
717}
718
719/// Determines if the given class is provably not derived from all of
720/// the prospective base classes.
721static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
722                                     CXXRecordDecl *Record,
723                            const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
724  if (Bases.count(Record->getCanonicalDecl()))
725    return false;
726
727  RecordDecl *RD = Record->getDefinition();
728  if (!RD) return false;
729  Record = cast<CXXRecordDecl>(RD);
730
731  for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
732         E = Record->bases_end(); I != E; ++I) {
733    CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
734    CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
735    if (!BaseRT) return false;
736
737    CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
738    if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
739      return false;
740  }
741
742  return true;
743}
744
745enum IMAKind {
746  /// The reference is definitely not an instance member access.
747  IMA_Static,
748
749  /// The reference may be an implicit instance member access.
750  IMA_Mixed,
751
752  /// The reference may be to an instance member, but it is invalid if
753  /// so, because the context is not an instance method.
754  IMA_Mixed_StaticContext,
755
756  /// The reference may be to an instance member, but it is invalid if
757  /// so, because the context is from an unrelated class.
758  IMA_Mixed_Unrelated,
759
760  /// The reference is definitely an implicit instance member access.
761  IMA_Instance,
762
763  /// The reference may be to an unresolved using declaration.
764  IMA_Unresolved,
765
766  /// The reference may be to an unresolved using declaration and the
767  /// context is not an instance method.
768  IMA_Unresolved_StaticContext,
769
770  /// The reference is to a member of an anonymous structure in a
771  /// non-class context.
772  IMA_AnonymousMember,
773
774  /// All possible referrents are instance members and the current
775  /// context is not an instance method.
776  IMA_Error_StaticContext,
777
778  /// All possible referrents are instance members of an unrelated
779  /// class.
780  IMA_Error_Unrelated
781};
782
783/// The given lookup names class member(s) and is not being used for
784/// an address-of-member expression.  Classify the type of access
785/// according to whether it's possible that this reference names an
786/// instance member.  This is best-effort; it is okay to
787/// conservatively answer "yes", in which case some errors will simply
788/// not be caught until template-instantiation.
789static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
790                                            const LookupResult &R) {
791  assert(!R.empty() && (*R.begin())->isCXXClassMember());
792
793  DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
794  bool isStaticContext =
795    (!isa<CXXMethodDecl>(DC) ||
796     cast<CXXMethodDecl>(DC)->isStatic());
797
798  if (R.isUnresolvableResult())
799    return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
800
801  // Collect all the declaring classes of instance members we find.
802  bool hasNonInstance = false;
803  llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
804  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
805    NamedDecl *D = *I;
806    if (D->isCXXInstanceMember()) {
807      CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
808
809      // If this is a member of an anonymous record, move out to the
810      // innermost non-anonymous struct or union.  If there isn't one,
811      // that's a special case.
812      while (R->isAnonymousStructOrUnion()) {
813        R = dyn_cast<CXXRecordDecl>(R->getParent());
814        if (!R) return IMA_AnonymousMember;
815      }
816      Classes.insert(R->getCanonicalDecl());
817    }
818    else
819      hasNonInstance = true;
820  }
821
822  // If we didn't find any instance members, it can't be an implicit
823  // member reference.
824  if (Classes.empty())
825    return IMA_Static;
826
827  // If the current context is not an instance method, it can't be
828  // an implicit member reference.
829  if (isStaticContext)
830    return (hasNonInstance ? IMA_Mixed_StaticContext : IMA_Error_StaticContext);
831
832  // If we can prove that the current context is unrelated to all the
833  // declaring classes, it can't be an implicit member reference (in
834  // which case it's an error if any of those members are selected).
835  if (IsProvablyNotDerivedFrom(SemaRef,
836                               cast<CXXMethodDecl>(DC)->getParent(),
837                               Classes))
838    return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
839
840  return (hasNonInstance ? IMA_Mixed : IMA_Instance);
841}
842
843/// Diagnose a reference to a field with no object available.
844static void DiagnoseInstanceReference(Sema &SemaRef,
845                                      const CXXScopeSpec &SS,
846                                      const LookupResult &R) {
847  SourceLocation Loc = R.getNameLoc();
848  SourceRange Range(Loc);
849  if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
850
851  if (R.getAsSingle<FieldDecl>()) {
852    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
853      if (MD->isStatic()) {
854        // "invalid use of member 'x' in static member function"
855        SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
856          << Range << R.getLookupName();
857        return;
858      }
859    }
860
861    SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
862      << R.getLookupName() << Range;
863    return;
864  }
865
866  SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
867}
868
869/// Diagnose an empty lookup.
870///
871/// \return false if new lookup candidates were found
872bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS,
873                               LookupResult &R, CorrectTypoContext CTC) {
874  DeclarationName Name = R.getLookupName();
875
876  unsigned diagnostic = diag::err_undeclared_var_use;
877  unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
878  if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
879      Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
880      Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
881    diagnostic = diag::err_undeclared_use;
882    diagnostic_suggest = diag::err_undeclared_use_suggest;
883  }
884
885  // If the original lookup was an unqualified lookup, fake an
886  // unqualified lookup.  This is useful when (for example) the
887  // original lookup would not have found something because it was a
888  // dependent name.
889  for (DeclContext *DC = SS.isEmpty()? CurContext : 0;
890       DC; DC = DC->getParent()) {
891    if (isa<CXXRecordDecl>(DC)) {
892      LookupQualifiedName(R, DC);
893
894      if (!R.empty()) {
895        // Don't give errors about ambiguities in this lookup.
896        R.suppressDiagnostics();
897
898        CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
899        bool isInstance = CurMethod &&
900                          CurMethod->isInstance() &&
901                          DC == CurMethod->getParent();
902
903        // Give a code modification hint to insert 'this->'.
904        // TODO: fixit for inserting 'Base<T>::' in the other cases.
905        // Actually quite difficult!
906        if (isInstance)
907          Diag(R.getNameLoc(), diagnostic) << Name
908            << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
909        else
910          Diag(R.getNameLoc(), diagnostic) << Name;
911
912        // Do we really want to note all of these?
913        for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
914          Diag((*I)->getLocation(), diag::note_dependent_var_use);
915
916        // Tell the callee to try to recover.
917        return false;
918      }
919    }
920  }
921
922  // We didn't find anything, so try to correct for a typo.
923  DeclarationName Corrected;
924  if (S && (Corrected = CorrectTypo(R, S, &SS, 0, false, CTC))) {
925    if (!R.empty()) {
926      if (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin())) {
927        if (SS.isEmpty())
928          Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName()
929            << FixItHint::CreateReplacement(R.getNameLoc(),
930                                            R.getLookupName().getAsString());
931        else
932          Diag(R.getNameLoc(), diag::err_no_member_suggest)
933            << Name << computeDeclContext(SS, false) << R.getLookupName()
934            << SS.getRange()
935            << FixItHint::CreateReplacement(R.getNameLoc(),
936                                            R.getLookupName().getAsString());
937        if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
938          Diag(ND->getLocation(), diag::note_previous_decl)
939            << ND->getDeclName();
940
941        // Tell the callee to try to recover.
942        return false;
943      }
944
945      if (isa<TypeDecl>(*R.begin()) || isa<ObjCInterfaceDecl>(*R.begin())) {
946        // FIXME: If we ended up with a typo for a type name or
947        // Objective-C class name, we're in trouble because the parser
948        // is in the wrong place to recover. Suggest the typo
949        // correction, but don't make it a fix-it since we're not going
950        // to recover well anyway.
951        if (SS.isEmpty())
952          Diag(R.getNameLoc(), diagnostic_suggest) << Name << R.getLookupName();
953        else
954          Diag(R.getNameLoc(), diag::err_no_member_suggest)
955            << Name << computeDeclContext(SS, false) << R.getLookupName()
956            << SS.getRange();
957
958        // Don't try to recover; it won't work.
959        return true;
960      }
961    } else {
962      // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
963      // because we aren't able to recover.
964      if (SS.isEmpty())
965        Diag(R.getNameLoc(), diagnostic_suggest) << Name << Corrected;
966      else
967        Diag(R.getNameLoc(), diag::err_no_member_suggest)
968        << Name << computeDeclContext(SS, false) << Corrected
969        << SS.getRange();
970      return true;
971    }
972    R.clear();
973  }
974
975  // Emit a special diagnostic for failed member lookups.
976  // FIXME: computing the declaration context might fail here (?)
977  if (!SS.isEmpty()) {
978    Diag(R.getNameLoc(), diag::err_no_member)
979      << Name << computeDeclContext(SS, false)
980      << SS.getRange();
981    return true;
982  }
983
984  // Give up, we can't recover.
985  Diag(R.getNameLoc(), diagnostic) << Name;
986  return true;
987}
988
989Sema::OwningExprResult Sema::ActOnIdExpression(Scope *S,
990                                               CXXScopeSpec &SS,
991                                               UnqualifiedId &Id,
992                                               bool HasTrailingLParen,
993                                               bool isAddressOfOperand) {
994  assert(!(isAddressOfOperand && HasTrailingLParen) &&
995         "cannot be direct & operand and have a trailing lparen");
996
997  if (SS.isInvalid())
998    return ExprError();
999
1000  TemplateArgumentListInfo TemplateArgsBuffer;
1001
1002  // Decompose the UnqualifiedId into the following data.
1003  DeclarationName Name;
1004  SourceLocation NameLoc;
1005  const TemplateArgumentListInfo *TemplateArgs;
1006  DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
1007                         Name, NameLoc, TemplateArgs);
1008
1009  IdentifierInfo *II = Name.getAsIdentifierInfo();
1010
1011  // C++ [temp.dep.expr]p3:
1012  //   An id-expression is type-dependent if it contains:
1013  //     -- an identifier that was declared with a dependent type,
1014  //        (note: handled after lookup)
1015  //     -- a template-id that is dependent,
1016  //        (note: handled in BuildTemplateIdExpr)
1017  //     -- a conversion-function-id that specifies a dependent type,
1018  //     -- a nested-name-specifier that contains a class-name that
1019  //        names a dependent type.
1020  // Determine whether this is a member of an unknown specialization;
1021  // we need to handle these differently.
1022  if ((Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1023       Name.getCXXNameType()->isDependentType()) ||
1024      (SS.isSet() && IsDependentIdExpression(*this, SS))) {
1025    return ActOnDependentIdExpression(SS, Name, NameLoc,
1026                                      isAddressOfOperand,
1027                                      TemplateArgs);
1028  }
1029
1030  // Perform the required lookup.
1031  LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1032  if (TemplateArgs) {
1033    // Lookup the template name again to correctly establish the context in
1034    // which it was found. This is really unfortunate as we already did the
1035    // lookup to determine that it was a template name in the first place. If
1036    // this becomes a performance hit, we can work harder to preserve those
1037    // results until we get here but it's likely not worth it.
1038    bool MemberOfUnknownSpecialization;
1039    LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1040                       MemberOfUnknownSpecialization);
1041  } else {
1042    bool IvarLookupFollowUp = (!SS.isSet() && II && getCurMethodDecl());
1043    LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
1044
1045    // If this reference is in an Objective-C method, then we need to do
1046    // some special Objective-C lookup, too.
1047    if (IvarLookupFollowUp) {
1048      OwningExprResult E(LookupInObjCMethod(R, S, II, true));
1049      if (E.isInvalid())
1050        return ExprError();
1051
1052      Expr *Ex = E.takeAs<Expr>();
1053      if (Ex) return Owned(Ex);
1054    }
1055  }
1056
1057  if (R.isAmbiguous())
1058    return ExprError();
1059
1060  // Determine whether this name might be a candidate for
1061  // argument-dependent lookup.
1062  bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
1063
1064  if (R.empty() && !ADL) {
1065    // Otherwise, this could be an implicitly declared function reference (legal
1066    // in C90, extension in C99, forbidden in C++).
1067    if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1068      NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1069      if (D) R.addDecl(D);
1070    }
1071
1072    // If this name wasn't predeclared and if this is not a function
1073    // call, diagnose the problem.
1074    if (R.empty()) {
1075      if (DiagnoseEmptyLookup(S, SS, R, CTC_Unknown))
1076        return ExprError();
1077
1078      assert(!R.empty() &&
1079             "DiagnoseEmptyLookup returned false but added no results");
1080
1081      // If we found an Objective-C instance variable, let
1082      // LookupInObjCMethod build the appropriate expression to
1083      // reference the ivar.
1084      if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1085        R.clear();
1086        OwningExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
1087        assert(E.isInvalid() || E.get());
1088        return move(E);
1089      }
1090    }
1091  }
1092
1093  // This is guaranteed from this point on.
1094  assert(!R.empty() || ADL);
1095
1096  if (VarDecl *Var = R.getAsSingle<VarDecl>()) {
1097    // Warn about constructs like:
1098    //   if (void *X = foo()) { ... } else { X }.
1099    // In the else block, the pointer is always false.
1100    if (Var->isDeclaredInCondition() && Var->getType()->isScalarType()) {
1101      Scope *CheckS = S;
1102      while (CheckS && CheckS->getControlParent()) {
1103        if ((CheckS->getFlags() & Scope::ElseScope) &&
1104            CheckS->getControlParent()->isDeclScope(DeclPtrTy::make(Var))) {
1105          ExprError(Diag(NameLoc, diag::warn_value_always_zero)
1106            << Var->getDeclName()
1107            << (Var->getType()->isPointerType() ? 2 :
1108                Var->getType()->isBooleanType() ? 1 : 0));
1109          break;
1110        }
1111
1112        // Move to the parent of this scope.
1113        CheckS = CheckS->getParent();
1114      }
1115    }
1116  } else if (FunctionDecl *Func = R.getAsSingle<FunctionDecl>()) {
1117    if (!getLangOptions().CPlusPlus && !Func->hasPrototype()) {
1118      // C99 DR 316 says that, if a function type comes from a
1119      // function definition (without a prototype), that type is only
1120      // used for checking compatibility. Therefore, when referencing
1121      // the function, we pretend that we don't have the full function
1122      // type.
1123      if (DiagnoseUseOfDecl(Func, NameLoc))
1124        return ExprError();
1125
1126      QualType T = Func->getType();
1127      QualType NoProtoType = T;
1128      if (const FunctionProtoType *Proto = T->getAs<FunctionProtoType>())
1129        NoProtoType = Context.getFunctionNoProtoType(Proto->getResultType(),
1130                                                     Proto->getExtInfo());
1131      return BuildDeclRefExpr(Func, NoProtoType, NameLoc, &SS);
1132    }
1133  }
1134
1135  // Check whether this might be a C++ implicit instance member access.
1136  // C++ [expr.prim.general]p6:
1137  //   Within the definition of a non-static member function, an
1138  //   identifier that names a non-static member is transformed to a
1139  //   class member access expression.
1140  // But note that &SomeClass::foo is grammatically distinct, even
1141  // though we don't parse it that way.
1142  if (!R.empty() && (*R.begin())->isCXXClassMember()) {
1143    bool isAbstractMemberPointer = (isAddressOfOperand && !SS.isEmpty());
1144    if (!isAbstractMemberPointer)
1145      return BuildPossibleImplicitMemberExpr(SS, R, TemplateArgs);
1146  }
1147
1148  if (TemplateArgs)
1149    return BuildTemplateIdExpr(SS, R, ADL, *TemplateArgs);
1150
1151  return BuildDeclarationNameExpr(SS, R, ADL);
1152}
1153
1154/// Builds an expression which might be an implicit member expression.
1155Sema::OwningExprResult
1156Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
1157                                      LookupResult &R,
1158                                const TemplateArgumentListInfo *TemplateArgs) {
1159  switch (ClassifyImplicitMemberAccess(*this, R)) {
1160  case IMA_Instance:
1161    return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
1162
1163  case IMA_AnonymousMember:
1164    assert(R.isSingleResult());
1165    return BuildAnonymousStructUnionMemberReference(R.getNameLoc(),
1166                                                    R.getAsSingle<FieldDecl>());
1167
1168  case IMA_Mixed:
1169  case IMA_Mixed_Unrelated:
1170  case IMA_Unresolved:
1171    return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
1172
1173  case IMA_Static:
1174  case IMA_Mixed_StaticContext:
1175  case IMA_Unresolved_StaticContext:
1176    if (TemplateArgs)
1177      return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
1178    return BuildDeclarationNameExpr(SS, R, false);
1179
1180  case IMA_Error_StaticContext:
1181  case IMA_Error_Unrelated:
1182    DiagnoseInstanceReference(*this, SS, R);
1183    return ExprError();
1184  }
1185
1186  llvm_unreachable("unexpected instance member access kind");
1187  return ExprError();
1188}
1189
1190/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1191/// declaration name, generally during template instantiation.
1192/// There's a large number of things which don't need to be done along
1193/// this path.
1194Sema::OwningExprResult
1195Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
1196                                        DeclarationName Name,
1197                                        SourceLocation NameLoc) {
1198  DeclContext *DC;
1199  if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
1200    return BuildDependentDeclRefExpr(SS, Name, NameLoc, 0);
1201
1202  if (RequireCompleteDeclContext(SS, DC))
1203    return ExprError();
1204
1205  LookupResult R(*this, Name, NameLoc, LookupOrdinaryName);
1206  LookupQualifiedName(R, DC);
1207
1208  if (R.isAmbiguous())
1209    return ExprError();
1210
1211  if (R.empty()) {
1212    Diag(NameLoc, diag::err_no_member) << Name << DC << SS.getRange();
1213    return ExprError();
1214  }
1215
1216  return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1217}
1218
1219/// LookupInObjCMethod - The parser has read a name in, and Sema has
1220/// detected that we're currently inside an ObjC method.  Perform some
1221/// additional lookup.
1222///
1223/// Ideally, most of this would be done by lookup, but there's
1224/// actually quite a lot of extra work involved.
1225///
1226/// Returns a null sentinel to indicate trivial success.
1227Sema::OwningExprResult
1228Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
1229                         IdentifierInfo *II, bool AllowBuiltinCreation) {
1230  SourceLocation Loc = Lookup.getNameLoc();
1231  ObjCMethodDecl *CurMethod = getCurMethodDecl();
1232
1233  // There are two cases to handle here.  1) scoped lookup could have failed,
1234  // in which case we should look for an ivar.  2) scoped lookup could have
1235  // found a decl, but that decl is outside the current instance method (i.e.
1236  // a global variable).  In these two cases, we do a lookup for an ivar with
1237  // this name, if the lookup sucedes, we replace it our current decl.
1238
1239  // If we're in a class method, we don't normally want to look for
1240  // ivars.  But if we don't find anything else, and there's an
1241  // ivar, that's an error.
1242  bool IsClassMethod = CurMethod->isClassMethod();
1243
1244  bool LookForIvars;
1245  if (Lookup.empty())
1246    LookForIvars = true;
1247  else if (IsClassMethod)
1248    LookForIvars = false;
1249  else
1250    LookForIvars = (Lookup.isSingleResult() &&
1251                    Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
1252  ObjCInterfaceDecl *IFace = 0;
1253  if (LookForIvars) {
1254    IFace = CurMethod->getClassInterface();
1255    ObjCInterfaceDecl *ClassDeclared;
1256    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1257      // Diagnose using an ivar in a class method.
1258      if (IsClassMethod)
1259        return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1260                         << IV->getDeclName());
1261
1262      // If we're referencing an invalid decl, just return this as a silent
1263      // error node.  The error diagnostic was already emitted on the decl.
1264      if (IV->isInvalidDecl())
1265        return ExprError();
1266
1267      // Check if referencing a field with __attribute__((deprecated)).
1268      if (DiagnoseUseOfDecl(IV, Loc))
1269        return ExprError();
1270
1271      // Diagnose the use of an ivar outside of the declaring class.
1272      if (IV->getAccessControl() == ObjCIvarDecl::Private &&
1273          ClassDeclared != IFace)
1274        Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1275
1276      // FIXME: This should use a new expr for a direct reference, don't
1277      // turn this into Self->ivar, just return a BareIVarExpr or something.
1278      IdentifierInfo &II = Context.Idents.get("self");
1279      UnqualifiedId SelfName;
1280      SelfName.setIdentifier(&II, SourceLocation());
1281      CXXScopeSpec SelfScopeSpec;
1282      OwningExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec,
1283                                                    SelfName, false, false);
1284      MarkDeclarationReferenced(Loc, IV);
1285      return Owned(new (Context)
1286                   ObjCIvarRefExpr(IV, IV->getType(), Loc,
1287                                   SelfExpr.takeAs<Expr>(), true, true));
1288    }
1289  } else if (CurMethod->isInstanceMethod()) {
1290    // We should warn if a local variable hides an ivar.
1291    ObjCInterfaceDecl *IFace = CurMethod->getClassInterface();
1292    ObjCInterfaceDecl *ClassDeclared;
1293    if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1294      if (IV->getAccessControl() != ObjCIvarDecl::Private ||
1295          IFace == ClassDeclared)
1296        Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1297    }
1298  }
1299
1300  if (Lookup.empty() && II && AllowBuiltinCreation) {
1301    // FIXME. Consolidate this with similar code in LookupName.
1302    if (unsigned BuiltinID = II->getBuiltinID()) {
1303      if (!(getLangOptions().CPlusPlus &&
1304            Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1305        NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1306                                           S, Lookup.isForRedeclaration(),
1307                                           Lookup.getNameLoc());
1308        if (D) Lookup.addDecl(D);
1309      }
1310    }
1311  }
1312  // Sentinel value saying that we didn't do anything special.
1313  return Owned((Expr*) 0);
1314}
1315
1316/// \brief Cast a base object to a member's actual type.
1317///
1318/// Logically this happens in three phases:
1319///
1320/// * First we cast from the base type to the naming class.
1321///   The naming class is the class into which we were looking
1322///   when we found the member;  it's the qualifier type if a
1323///   qualifier was provided, and otherwise it's the base type.
1324///
1325/// * Next we cast from the naming class to the declaring class.
1326///   If the member we found was brought into a class's scope by
1327///   a using declaration, this is that class;  otherwise it's
1328///   the class declaring the member.
1329///
1330/// * Finally we cast from the declaring class to the "true"
1331///   declaring class of the member.  This conversion does not
1332///   obey access control.
1333bool
1334Sema::PerformObjectMemberConversion(Expr *&From,
1335                                    NestedNameSpecifier *Qualifier,
1336                                    NamedDecl *FoundDecl,
1337                                    NamedDecl *Member) {
1338  CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1339  if (!RD)
1340    return false;
1341
1342  QualType DestRecordType;
1343  QualType DestType;
1344  QualType FromRecordType;
1345  QualType FromType = From->getType();
1346  bool PointerConversions = false;
1347  if (isa<FieldDecl>(Member)) {
1348    DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
1349
1350    if (FromType->getAs<PointerType>()) {
1351      DestType = Context.getPointerType(DestRecordType);
1352      FromRecordType = FromType->getPointeeType();
1353      PointerConversions = true;
1354    } else {
1355      DestType = DestRecordType;
1356      FromRecordType = FromType;
1357    }
1358  } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1359    if (Method->isStatic())
1360      return false;
1361
1362    DestType = Method->getThisType(Context);
1363    DestRecordType = DestType->getPointeeType();
1364
1365    if (FromType->getAs<PointerType>()) {
1366      FromRecordType = FromType->getPointeeType();
1367      PointerConversions = true;
1368    } else {
1369      FromRecordType = FromType;
1370      DestType = DestRecordType;
1371    }
1372  } else {
1373    // No conversion necessary.
1374    return false;
1375  }
1376
1377  if (DestType->isDependentType() || FromType->isDependentType())
1378    return false;
1379
1380  // If the unqualified types are the same, no conversion is necessary.
1381  if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1382    return false;
1383
1384  SourceRange FromRange = From->getSourceRange();
1385  SourceLocation FromLoc = FromRange.getBegin();
1386
1387  bool isLvalue
1388    = (From->isLvalue(Context) == Expr::LV_Valid) && !PointerConversions;
1389
1390  // C++ [class.member.lookup]p8:
1391  //   [...] Ambiguities can often be resolved by qualifying a name with its
1392  //   class name.
1393  //
1394  // If the member was a qualified name and the qualified referred to a
1395  // specific base subobject type, we'll cast to that intermediate type
1396  // first and then to the object in which the member is declared. That allows
1397  // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1398  //
1399  //   class Base { public: int x; };
1400  //   class Derived1 : public Base { };
1401  //   class Derived2 : public Base { };
1402  //   class VeryDerived : public Derived1, public Derived2 { void f(); };
1403  //
1404  //   void VeryDerived::f() {
1405  //     x = 17; // error: ambiguous base subobjects
1406  //     Derived1::x = 17; // okay, pick the Base subobject of Derived1
1407  //   }
1408  if (Qualifier) {
1409    QualType QType = QualType(Qualifier->getAsType(), 0);
1410    assert(!QType.isNull() && "lookup done with dependent qualifier?");
1411    assert(QType->isRecordType() && "lookup done with non-record type");
1412
1413    QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1414
1415    // In C++98, the qualifier type doesn't actually have to be a base
1416    // type of the object type, in which case we just ignore it.
1417    // Otherwise build the appropriate casts.
1418    if (IsDerivedFrom(FromRecordType, QRecordType)) {
1419      CXXBaseSpecifierArray BasePath;
1420      if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
1421                                       FromLoc, FromRange, &BasePath))
1422        return true;
1423
1424      if (PointerConversions)
1425        QType = Context.getPointerType(QType);
1426      ImpCastExprToType(From, QType, CastExpr::CK_UncheckedDerivedToBase,
1427                        isLvalue, BasePath);
1428
1429      FromType = QType;
1430      FromRecordType = QRecordType;
1431
1432      // If the qualifier type was the same as the destination type,
1433      // we're done.
1434      if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
1435        return false;
1436    }
1437  }
1438
1439  bool IgnoreAccess = false;
1440
1441  // If we actually found the member through a using declaration, cast
1442  // down to the using declaration's type.
1443  //
1444  // Pointer equality is fine here because only one declaration of a
1445  // class ever has member declarations.
1446  if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1447    assert(isa<UsingShadowDecl>(FoundDecl));
1448    QualType URecordType = Context.getTypeDeclType(
1449                           cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1450
1451    // We only need to do this if the naming-class to declaring-class
1452    // conversion is non-trivial.
1453    if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1454      assert(IsDerivedFrom(FromRecordType, URecordType));
1455      CXXBaseSpecifierArray BasePath;
1456      if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
1457                                       FromLoc, FromRange, &BasePath))
1458        return true;
1459
1460      QualType UType = URecordType;
1461      if (PointerConversions)
1462        UType = Context.getPointerType(UType);
1463      ImpCastExprToType(From, UType, CastExpr::CK_UncheckedDerivedToBase,
1464                        isLvalue, BasePath);
1465      FromType = UType;
1466      FromRecordType = URecordType;
1467    }
1468
1469    // We don't do access control for the conversion from the
1470    // declaring class to the true declaring class.
1471    IgnoreAccess = true;
1472  }
1473
1474  CXXBaseSpecifierArray BasePath;
1475  if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1476                                   FromLoc, FromRange, &BasePath,
1477                                   IgnoreAccess))
1478    return true;
1479
1480  ImpCastExprToType(From, DestType, CastExpr::CK_UncheckedDerivedToBase,
1481                    isLvalue, BasePath);
1482  return false;
1483}
1484
1485/// \brief Build a MemberExpr AST node.
1486static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
1487                                   const CXXScopeSpec &SS, ValueDecl *Member,
1488                                   DeclAccessPair FoundDecl,
1489                                   SourceLocation Loc, QualType Ty,
1490                          const TemplateArgumentListInfo *TemplateArgs = 0) {
1491  NestedNameSpecifier *Qualifier = 0;
1492  SourceRange QualifierRange;
1493  if (SS.isSet()) {
1494    Qualifier = (NestedNameSpecifier *) SS.getScopeRep();
1495    QualifierRange = SS.getRange();
1496  }
1497
1498  return MemberExpr::Create(C, Base, isArrow, Qualifier, QualifierRange,
1499                            Member, FoundDecl, Loc, TemplateArgs, Ty);
1500}
1501
1502/// Builds an implicit member access expression.  The current context
1503/// is known to be an instance method, and the given unqualified lookup
1504/// set is known to contain only instance members, at least one of which
1505/// is from an appropriate type.
1506Sema::OwningExprResult
1507Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1508                              LookupResult &R,
1509                              const TemplateArgumentListInfo *TemplateArgs,
1510                              bool IsKnownInstance) {
1511  assert(!R.empty() && !R.isAmbiguous());
1512
1513  SourceLocation Loc = R.getNameLoc();
1514
1515  // We may have found a field within an anonymous union or struct
1516  // (C++ [class.union]).
1517  // FIXME: This needs to happen post-isImplicitMemberReference?
1518  // FIXME: template-ids inside anonymous structs?
1519  if (FieldDecl *FD = R.getAsSingle<FieldDecl>())
1520    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion())
1521      return BuildAnonymousStructUnionMemberReference(Loc, FD);
1522
1523  // If this is known to be an instance access, go ahead and build a
1524  // 'this' expression now.
1525  DeclContext *DC = getFunctionLevelDeclContext();
1526  QualType ThisType = cast<CXXMethodDecl>(DC)->getThisType(Context);
1527  Expr *This = 0; // null signifies implicit access
1528  if (IsKnownInstance) {
1529    SourceLocation Loc = R.getNameLoc();
1530    if (SS.getRange().isValid())
1531      Loc = SS.getRange().getBegin();
1532    This = new (Context) CXXThisExpr(Loc, ThisType, /*isImplicit=*/true);
1533  }
1534
1535  return BuildMemberReferenceExpr(ExprArg(*this, This), ThisType,
1536                                  /*OpLoc*/ SourceLocation(),
1537                                  /*IsArrow*/ true,
1538                                  SS,
1539                                  /*FirstQualifierInScope*/ 0,
1540                                  R, TemplateArgs);
1541}
1542
1543bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
1544                                      const LookupResult &R,
1545                                      bool HasTrailingLParen) {
1546  // Only when used directly as the postfix-expression of a call.
1547  if (!HasTrailingLParen)
1548    return false;
1549
1550  // Never if a scope specifier was provided.
1551  if (SS.isSet())
1552    return false;
1553
1554  // Only in C++ or ObjC++.
1555  if (!getLangOptions().CPlusPlus)
1556    return false;
1557
1558  // Turn off ADL when we find certain kinds of declarations during
1559  // normal lookup:
1560  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1561    NamedDecl *D = *I;
1562
1563    // C++0x [basic.lookup.argdep]p3:
1564    //     -- a declaration of a class member
1565    // Since using decls preserve this property, we check this on the
1566    // original decl.
1567    if (D->isCXXClassMember())
1568      return false;
1569
1570    // C++0x [basic.lookup.argdep]p3:
1571    //     -- a block-scope function declaration that is not a
1572    //        using-declaration
1573    // NOTE: we also trigger this for function templates (in fact, we
1574    // don't check the decl type at all, since all other decl types
1575    // turn off ADL anyway).
1576    if (isa<UsingShadowDecl>(D))
1577      D = cast<UsingShadowDecl>(D)->getTargetDecl();
1578    else if (D->getDeclContext()->isFunctionOrMethod())
1579      return false;
1580
1581    // C++0x [basic.lookup.argdep]p3:
1582    //     -- a declaration that is neither a function or a function
1583    //        template
1584    // And also for builtin functions.
1585    if (isa<FunctionDecl>(D)) {
1586      FunctionDecl *FDecl = cast<FunctionDecl>(D);
1587
1588      // But also builtin functions.
1589      if (FDecl->getBuiltinID() && FDecl->isImplicit())
1590        return false;
1591    } else if (!isa<FunctionTemplateDecl>(D))
1592      return false;
1593  }
1594
1595  return true;
1596}
1597
1598
1599/// Diagnoses obvious problems with the use of the given declaration
1600/// as an expression.  This is only actually called for lookups that
1601/// were not overloaded, and it doesn't promise that the declaration
1602/// will in fact be used.
1603static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
1604  if (isa<TypedefDecl>(D)) {
1605    S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
1606    return true;
1607  }
1608
1609  if (isa<ObjCInterfaceDecl>(D)) {
1610    S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
1611    return true;
1612  }
1613
1614  if (isa<NamespaceDecl>(D)) {
1615    S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
1616    return true;
1617  }
1618
1619  return false;
1620}
1621
1622Sema::OwningExprResult
1623Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
1624                               LookupResult &R,
1625                               bool NeedsADL) {
1626  // If this is a single, fully-resolved result and we don't need ADL,
1627  // just build an ordinary singleton decl ref.
1628  if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
1629    return BuildDeclarationNameExpr(SS, R.getNameLoc(), R.getFoundDecl());
1630
1631  // We only need to check the declaration if there's exactly one
1632  // result, because in the overloaded case the results can only be
1633  // functions and function templates.
1634  if (R.isSingleResult() &&
1635      CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
1636    return ExprError();
1637
1638  // Otherwise, just build an unresolved lookup expression.  Suppress
1639  // any lookup-related diagnostics; we'll hash these out later, when
1640  // we've picked a target.
1641  R.suppressDiagnostics();
1642
1643  bool Dependent
1644    = UnresolvedLookupExpr::ComputeDependence(R.begin(), R.end(), 0);
1645  UnresolvedLookupExpr *ULE
1646    = UnresolvedLookupExpr::Create(Context, Dependent, R.getNamingClass(),
1647                                   (NestedNameSpecifier*) SS.getScopeRep(),
1648                                   SS.getRange(),
1649                                   R.getLookupName(), R.getNameLoc(),
1650                                   NeedsADL, R.isOverloadedResult(),
1651                                   R.begin(), R.end());
1652
1653  return Owned(ULE);
1654}
1655
1656
1657/// \brief Complete semantic analysis for a reference to the given declaration.
1658Sema::OwningExprResult
1659Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
1660                               SourceLocation Loc, NamedDecl *D) {
1661  assert(D && "Cannot refer to a NULL declaration");
1662  assert(!isa<FunctionTemplateDecl>(D) &&
1663         "Cannot refer unambiguously to a function template");
1664
1665  if (CheckDeclInExpr(*this, Loc, D))
1666    return ExprError();
1667
1668  if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
1669    // Specifically diagnose references to class templates that are missing
1670    // a template argument list.
1671    Diag(Loc, diag::err_template_decl_ref)
1672      << Template << SS.getRange();
1673    Diag(Template->getLocation(), diag::note_template_decl_here);
1674    return ExprError();
1675  }
1676
1677  // Make sure that we're referring to a value.
1678  ValueDecl *VD = dyn_cast<ValueDecl>(D);
1679  if (!VD) {
1680    Diag(Loc, diag::err_ref_non_value)
1681      << D << SS.getRange();
1682    Diag(D->getLocation(), diag::note_declared_at);
1683    return ExprError();
1684  }
1685
1686  // Check whether this declaration can be used. Note that we suppress
1687  // this check when we're going to perform argument-dependent lookup
1688  // on this function name, because this might not be the function
1689  // that overload resolution actually selects.
1690  if (DiagnoseUseOfDecl(VD, Loc))
1691    return ExprError();
1692
1693  // Only create DeclRefExpr's for valid Decl's.
1694  if (VD->isInvalidDecl())
1695    return ExprError();
1696
1697  // If the identifier reference is inside a block, and it refers to a value
1698  // that is outside the block, create a BlockDeclRefExpr instead of a
1699  // DeclRefExpr.  This ensures the value is treated as a copy-in snapshot when
1700  // the block is formed.
1701  //
1702  // We do not do this for things like enum constants, global variables, etc,
1703  // as they do not get snapshotted.
1704  //
1705  if (getCurBlock() &&
1706      ShouldSnapshotBlockValueReference(*this, getCurBlock(), VD)) {
1707    if (VD->getType().getTypePtr()->isVariablyModifiedType()) {
1708      Diag(Loc, diag::err_ref_vm_type);
1709      Diag(D->getLocation(), diag::note_declared_at);
1710      return ExprError();
1711    }
1712
1713    if (VD->getType()->isArrayType()) {
1714      Diag(Loc, diag::err_ref_array_type);
1715      Diag(D->getLocation(), diag::note_declared_at);
1716      return ExprError();
1717    }
1718
1719    MarkDeclarationReferenced(Loc, VD);
1720    QualType ExprTy = VD->getType().getNonReferenceType();
1721    // The BlocksAttr indicates the variable is bound by-reference.
1722    if (VD->getAttr<BlocksAttr>())
1723      return Owned(new (Context) BlockDeclRefExpr(VD, ExprTy, Loc, true));
1724    // This is to record that a 'const' was actually synthesize and added.
1725    bool constAdded = !ExprTy.isConstQualified();
1726    // Variable will be bound by-copy, make it const within the closure.
1727
1728    ExprTy.addConst();
1729    BlockDeclRefExpr *BDRE = new (Context) BlockDeclRefExpr(VD,
1730                                                            ExprTy, Loc, false,
1731                                                            constAdded);
1732    QualType T = VD->getType();
1733    if (getLangOptions().CPlusPlus && !T->isDependentType() &&
1734        !T->isReferenceType()) {
1735      Expr *E = new (Context)
1736                  DeclRefExpr(const_cast<ValueDecl*>(BDRE->getDecl()), T,
1737                                         SourceLocation());
1738
1739      OwningExprResult Res = PerformCopyInitialization(
1740                      InitializedEntity::InitializeBlock(VD->getLocation(),
1741                                                         T, false),
1742                      SourceLocation(),
1743                      Owned(E));
1744      if (!Res.isInvalid()) {
1745        Res = MaybeCreateCXXExprWithTemporaries(move(Res));
1746        Expr *Init = Res.takeAs<Expr>();
1747        BDRE->setCopyConstructorExpr(Init);
1748      }
1749    }
1750    return Owned(BDRE);
1751  }
1752  // If this reference is not in a block or if the referenced variable is
1753  // within the block, create a normal DeclRefExpr.
1754
1755  return BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), Loc, &SS);
1756}
1757
1758Sema::OwningExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc,
1759                                                 tok::TokenKind Kind) {
1760  PredefinedExpr::IdentType IT;
1761
1762  switch (Kind) {
1763  default: assert(0 && "Unknown simple primary expr!");
1764  case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
1765  case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
1766  case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
1767  }
1768
1769  // Pre-defined identifiers are of type char[x], where x is the length of the
1770  // string.
1771
1772  Decl *currentDecl = getCurFunctionOrMethodDecl();
1773  if (!currentDecl) {
1774    Diag(Loc, diag::ext_predef_outside_function);
1775    currentDecl = Context.getTranslationUnitDecl();
1776  }
1777
1778  QualType ResTy;
1779  if (cast<DeclContext>(currentDecl)->isDependentContext()) {
1780    ResTy = Context.DependentTy;
1781  } else {
1782    unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
1783
1784    llvm::APInt LengthI(32, Length + 1);
1785    ResTy = Context.CharTy.withConst();
1786    ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
1787  }
1788  return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
1789}
1790
1791Sema::OwningExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
1792  llvm::SmallString<16> CharBuffer;
1793  bool Invalid = false;
1794  llvm::StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
1795  if (Invalid)
1796    return ExprError();
1797
1798  CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
1799                            PP);
1800  if (Literal.hadError())
1801    return ExprError();
1802
1803  QualType Ty;
1804  if (!getLangOptions().CPlusPlus)
1805    Ty = Context.IntTy;   // 'x' and L'x' -> int in C.
1806  else if (Literal.isWide())
1807    Ty = Context.WCharTy; // L'x' -> wchar_t in C++.
1808  else if (Literal.isMultiChar())
1809    Ty = Context.IntTy;   // 'wxyz' -> int in C++.
1810  else
1811    Ty = Context.CharTy;  // 'x' -> char in C++
1812
1813  return Owned(new (Context) CharacterLiteral(Literal.getValue(),
1814                                              Literal.isWide(),
1815                                              Ty, Tok.getLocation()));
1816}
1817
1818Action::OwningExprResult Sema::ActOnNumericConstant(const Token &Tok) {
1819  // Fast path for a single digit (which is quite common).  A single digit
1820  // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
1821  if (Tok.getLength() == 1) {
1822    const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
1823    unsigned IntSize = Context.Target.getIntWidth();
1824    return Owned(new (Context) IntegerLiteral(llvm::APInt(IntSize, Val-'0'),
1825                    Context.IntTy, Tok.getLocation()));
1826  }
1827
1828  llvm::SmallString<512> IntegerBuffer;
1829  // Add padding so that NumericLiteralParser can overread by one character.
1830  IntegerBuffer.resize(Tok.getLength()+1);
1831  const char *ThisTokBegin = &IntegerBuffer[0];
1832
1833  // Get the spelling of the token, which eliminates trigraphs, etc.
1834  bool Invalid = false;
1835  unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
1836  if (Invalid)
1837    return ExprError();
1838
1839  NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
1840                               Tok.getLocation(), PP);
1841  if (Literal.hadError)
1842    return ExprError();
1843
1844  Expr *Res;
1845
1846  if (Literal.isFloatingLiteral()) {
1847    QualType Ty;
1848    if (Literal.isFloat)
1849      Ty = Context.FloatTy;
1850    else if (!Literal.isLong)
1851      Ty = Context.DoubleTy;
1852    else
1853      Ty = Context.LongDoubleTy;
1854
1855    const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
1856
1857    using llvm::APFloat;
1858    APFloat Val(Format);
1859
1860    APFloat::opStatus result = Literal.GetFloatValue(Val);
1861
1862    // Overflow is always an error, but underflow is only an error if
1863    // we underflowed to zero (APFloat reports denormals as underflow).
1864    if ((result & APFloat::opOverflow) ||
1865        ((result & APFloat::opUnderflow) && Val.isZero())) {
1866      unsigned diagnostic;
1867      llvm::SmallString<20> buffer;
1868      if (result & APFloat::opOverflow) {
1869        diagnostic = diag::warn_float_overflow;
1870        APFloat::getLargest(Format).toString(buffer);
1871      } else {
1872        diagnostic = diag::warn_float_underflow;
1873        APFloat::getSmallest(Format).toString(buffer);
1874      }
1875
1876      Diag(Tok.getLocation(), diagnostic)
1877        << Ty
1878        << llvm::StringRef(buffer.data(), buffer.size());
1879    }
1880
1881    bool isExact = (result == APFloat::opOK);
1882    Res = new (Context) FloatingLiteral(Val, isExact, Ty, Tok.getLocation());
1883
1884  } else if (!Literal.isIntegerLiteral()) {
1885    return ExprError();
1886  } else {
1887    QualType Ty;
1888
1889    // long long is a C99 feature.
1890    if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
1891        Literal.isLongLong)
1892      Diag(Tok.getLocation(), diag::ext_longlong);
1893
1894    // Get the value in the widest-possible width.
1895    llvm::APInt ResultVal(Context.Target.getIntMaxTWidth(), 0);
1896
1897    if (Literal.GetIntegerValue(ResultVal)) {
1898      // If this value didn't fit into uintmax_t, warn and force to ull.
1899      Diag(Tok.getLocation(), diag::warn_integer_too_large);
1900      Ty = Context.UnsignedLongLongTy;
1901      assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
1902             "long long is not intmax_t?");
1903    } else {
1904      // If this value fits into a ULL, try to figure out what else it fits into
1905      // according to the rules of C99 6.4.4.1p5.
1906
1907      // Octal, Hexadecimal, and integers with a U suffix are allowed to
1908      // be an unsigned int.
1909      bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
1910
1911      // Check from smallest to largest, picking the smallest type we can.
1912      unsigned Width = 0;
1913      if (!Literal.isLong && !Literal.isLongLong) {
1914        // Are int/unsigned possibilities?
1915        unsigned IntSize = Context.Target.getIntWidth();
1916
1917        // Does it fit in a unsigned int?
1918        if (ResultVal.isIntN(IntSize)) {
1919          // Does it fit in a signed int?
1920          if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
1921            Ty = Context.IntTy;
1922          else if (AllowUnsigned)
1923            Ty = Context.UnsignedIntTy;
1924          Width = IntSize;
1925        }
1926      }
1927
1928      // Are long/unsigned long possibilities?
1929      if (Ty.isNull() && !Literal.isLongLong) {
1930        unsigned LongSize = Context.Target.getLongWidth();
1931
1932        // Does it fit in a unsigned long?
1933        if (ResultVal.isIntN(LongSize)) {
1934          // Does it fit in a signed long?
1935          if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
1936            Ty = Context.LongTy;
1937          else if (AllowUnsigned)
1938            Ty = Context.UnsignedLongTy;
1939          Width = LongSize;
1940        }
1941      }
1942
1943      // Finally, check long long if needed.
1944      if (Ty.isNull()) {
1945        unsigned LongLongSize = Context.Target.getLongLongWidth();
1946
1947        // Does it fit in a unsigned long long?
1948        if (ResultVal.isIntN(LongLongSize)) {
1949          // Does it fit in a signed long long?
1950          if (!Literal.isUnsigned && ResultVal[LongLongSize-1] == 0)
1951            Ty = Context.LongLongTy;
1952          else if (AllowUnsigned)
1953            Ty = Context.UnsignedLongLongTy;
1954          Width = LongLongSize;
1955        }
1956      }
1957
1958      // If we still couldn't decide a type, we probably have something that
1959      // does not fit in a signed long long, but has no U suffix.
1960      if (Ty.isNull()) {
1961        Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
1962        Ty = Context.UnsignedLongLongTy;
1963        Width = Context.Target.getLongLongWidth();
1964      }
1965
1966      if (ResultVal.getBitWidth() != Width)
1967        ResultVal.trunc(Width);
1968    }
1969    Res = new (Context) IntegerLiteral(ResultVal, Ty, Tok.getLocation());
1970  }
1971
1972  // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
1973  if (Literal.isImaginary)
1974    Res = new (Context) ImaginaryLiteral(Res,
1975                                        Context.getComplexType(Res->getType()));
1976
1977  return Owned(Res);
1978}
1979
1980Action::OwningExprResult Sema::ActOnParenExpr(SourceLocation L,
1981                                              SourceLocation R, ExprArg Val) {
1982  Expr *E = Val.takeAs<Expr>();
1983  assert((E != 0) && "ActOnParenExpr() missing expr");
1984  return Owned(new (Context) ParenExpr(L, R, E));
1985}
1986
1987/// The UsualUnaryConversions() function is *not* called by this routine.
1988/// See C99 6.3.2.1p[2-4] for more details.
1989bool Sema::CheckSizeOfAlignOfOperand(QualType exprType,
1990                                     SourceLocation OpLoc,
1991                                     const SourceRange &ExprRange,
1992                                     bool isSizeof) {
1993  if (exprType->isDependentType())
1994    return false;
1995
1996  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1997  //   the result is the size of the referenced type."
1998  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1999  //   result shall be the alignment of the referenced type."
2000  if (const ReferenceType *Ref = exprType->getAs<ReferenceType>())
2001    exprType = Ref->getPointeeType();
2002
2003  // C99 6.5.3.4p1:
2004  if (exprType->isFunctionType()) {
2005    // alignof(function) is allowed as an extension.
2006    if (isSizeof)
2007      Diag(OpLoc, diag::ext_sizeof_function_type) << ExprRange;
2008    return false;
2009  }
2010
2011  // Allow sizeof(void)/alignof(void) as an extension.
2012  if (exprType->isVoidType()) {
2013    Diag(OpLoc, diag::ext_sizeof_void_type)
2014      << (isSizeof ? "sizeof" : "__alignof") << ExprRange;
2015    return false;
2016  }
2017
2018  if (RequireCompleteType(OpLoc, exprType,
2019                          PDiag(diag::err_sizeof_alignof_incomplete_type)
2020                          << int(!isSizeof) << ExprRange))
2021    return true;
2022
2023  // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2024  if (LangOpts.ObjCNonFragileABI && exprType->isObjCObjectType()) {
2025    Diag(OpLoc, diag::err_sizeof_nonfragile_interface)
2026      << exprType << isSizeof << ExprRange;
2027    return true;
2028  }
2029
2030  if (Context.hasSameUnqualifiedType(exprType, Context.OverloadTy)) {
2031    Diag(OpLoc, diag::err_sizeof_alignof_overloaded_function_type)
2032      << !isSizeof << ExprRange;
2033    return true;
2034  }
2035
2036  return false;
2037}
2038
2039bool Sema::CheckAlignOfExpr(Expr *E, SourceLocation OpLoc,
2040                            const SourceRange &ExprRange) {
2041  E = E->IgnoreParens();
2042
2043  // alignof decl is always ok.
2044  if (isa<DeclRefExpr>(E))
2045    return false;
2046
2047  // Cannot know anything else if the expression is dependent.
2048  if (E->isTypeDependent())
2049    return false;
2050
2051  if (E->getBitField()) {
2052    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 1 << ExprRange;
2053    return true;
2054  }
2055
2056  // Alignment of a field access is always okay, so long as it isn't a
2057  // bit-field.
2058  if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
2059    if (isa<FieldDecl>(ME->getMemberDecl()))
2060      return false;
2061
2062  return CheckSizeOfAlignOfOperand(E->getType(), OpLoc, ExprRange, false);
2063}
2064
2065/// \brief Build a sizeof or alignof expression given a type operand.
2066Action::OwningExprResult
2067Sema::CreateSizeOfAlignOfExpr(TypeSourceInfo *TInfo,
2068                              SourceLocation OpLoc,
2069                              bool isSizeOf, SourceRange R) {
2070  if (!TInfo)
2071    return ExprError();
2072
2073  QualType T = TInfo->getType();
2074
2075  if (!T->isDependentType() &&
2076      CheckSizeOfAlignOfOperand(T, OpLoc, R, isSizeOf))
2077    return ExprError();
2078
2079  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2080  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, TInfo,
2081                                               Context.getSizeType(), OpLoc,
2082                                               R.getEnd()));
2083}
2084
2085/// \brief Build a sizeof or alignof expression given an expression
2086/// operand.
2087Action::OwningExprResult
2088Sema::CreateSizeOfAlignOfExpr(Expr *E, SourceLocation OpLoc,
2089                              bool isSizeOf, SourceRange R) {
2090  // Verify that the operand is valid.
2091  bool isInvalid = false;
2092  if (E->isTypeDependent()) {
2093    // Delay type-checking for type-dependent expressions.
2094  } else if (!isSizeOf) {
2095    isInvalid = CheckAlignOfExpr(E, OpLoc, R);
2096  } else if (E->getBitField()) {  // C99 6.5.3.4p1.
2097    Diag(OpLoc, diag::err_sizeof_alignof_bitfield) << 0;
2098    isInvalid = true;
2099  } else {
2100    isInvalid = CheckSizeOfAlignOfOperand(E->getType(), OpLoc, R, true);
2101  }
2102
2103  if (isInvalid)
2104    return ExprError();
2105
2106  // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
2107  return Owned(new (Context) SizeOfAlignOfExpr(isSizeOf, E,
2108                                               Context.getSizeType(), OpLoc,
2109                                               R.getEnd()));
2110}
2111
2112/// ActOnSizeOfAlignOfExpr - Handle @c sizeof(type) and @c sizeof @c expr and
2113/// the same for @c alignof and @c __alignof
2114/// Note that the ArgRange is invalid if isType is false.
2115Action::OwningExprResult
2116Sema::ActOnSizeOfAlignOfExpr(SourceLocation OpLoc, bool isSizeof, bool isType,
2117                             void *TyOrEx, const SourceRange &ArgRange) {
2118  // If error parsing type, ignore.
2119  if (TyOrEx == 0) return ExprError();
2120
2121  if (isType) {
2122    TypeSourceInfo *TInfo;
2123    (void) GetTypeFromParser(TyOrEx, &TInfo);
2124    return CreateSizeOfAlignOfExpr(TInfo, OpLoc, isSizeof, ArgRange);
2125  }
2126
2127  Expr *ArgEx = (Expr *)TyOrEx;
2128  Action::OwningExprResult Result
2129    = CreateSizeOfAlignOfExpr(ArgEx, OpLoc, isSizeof, ArgEx->getSourceRange());
2130
2131  if (Result.isInvalid())
2132    DeleteExpr(ArgEx);
2133
2134  return move(Result);
2135}
2136
2137QualType Sema::CheckRealImagOperand(Expr *&V, SourceLocation Loc, bool isReal) {
2138  if (V->isTypeDependent())
2139    return Context.DependentTy;
2140
2141  // These operators return the element type of a complex type.
2142  if (const ComplexType *CT = V->getType()->getAs<ComplexType>())
2143    return CT->getElementType();
2144
2145  // Otherwise they pass through real integer and floating point types here.
2146  if (V->getType()->isArithmeticType())
2147    return V->getType();
2148
2149  // Reject anything else.
2150  Diag(Loc, diag::err_realimag_invalid_type) << V->getType()
2151    << (isReal ? "__real" : "__imag");
2152  return QualType();
2153}
2154
2155
2156
2157Action::OwningExprResult
2158Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
2159                          tok::TokenKind Kind, ExprArg Input) {
2160  UnaryOperator::Opcode Opc;
2161  switch (Kind) {
2162  default: assert(0 && "Unknown unary op!");
2163  case tok::plusplus:   Opc = UnaryOperator::PostInc; break;
2164  case tok::minusminus: Opc = UnaryOperator::PostDec; break;
2165  }
2166
2167  return BuildUnaryOp(S, OpLoc, Opc, move(Input));
2168}
2169
2170Action::OwningExprResult
2171Sema::ActOnArraySubscriptExpr(Scope *S, ExprArg Base, SourceLocation LLoc,
2172                              ExprArg Idx, SourceLocation RLoc) {
2173  // Since this might be a postfix expression, get rid of ParenListExprs.
2174  Base = MaybeConvertParenListExprToParenExpr(S, move(Base));
2175
2176  Expr *LHSExp = static_cast<Expr*>(Base.get()),
2177       *RHSExp = static_cast<Expr*>(Idx.get());
2178
2179  if (getLangOptions().CPlusPlus &&
2180      (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
2181    Base.release();
2182    Idx.release();
2183    return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2184                                                  Context.DependentTy, RLoc));
2185  }
2186
2187  if (getLangOptions().CPlusPlus &&
2188      (LHSExp->getType()->isRecordType() ||
2189       LHSExp->getType()->isEnumeralType() ||
2190       RHSExp->getType()->isRecordType() ||
2191       RHSExp->getType()->isEnumeralType())) {
2192    return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, move(Base),move(Idx));
2193  }
2194
2195  return CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
2196}
2197
2198
2199Action::OwningExprResult
2200Sema::CreateBuiltinArraySubscriptExpr(ExprArg Base, SourceLocation LLoc,
2201                                     ExprArg Idx, SourceLocation RLoc) {
2202  Expr *LHSExp = static_cast<Expr*>(Base.get());
2203  Expr *RHSExp = static_cast<Expr*>(Idx.get());
2204
2205  // Perform default conversions.
2206  if (!LHSExp->getType()->getAs<VectorType>())
2207      DefaultFunctionArrayLvalueConversion(LHSExp);
2208  DefaultFunctionArrayLvalueConversion(RHSExp);
2209
2210  QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
2211
2212  // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
2213  // to the expression *((e1)+(e2)). This means the array "Base" may actually be
2214  // in the subscript position. As a result, we need to derive the array base
2215  // and index from the expression types.
2216  Expr *BaseExpr, *IndexExpr;
2217  QualType ResultType;
2218  if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
2219    BaseExpr = LHSExp;
2220    IndexExpr = RHSExp;
2221    ResultType = Context.DependentTy;
2222  } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
2223    BaseExpr = LHSExp;
2224    IndexExpr = RHSExp;
2225    ResultType = PTy->getPointeeType();
2226  } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
2227     // Handle the uncommon case of "123[Ptr]".
2228    BaseExpr = RHSExp;
2229    IndexExpr = LHSExp;
2230    ResultType = PTy->getPointeeType();
2231  } else if (const ObjCObjectPointerType *PTy =
2232               LHSTy->getAs<ObjCObjectPointerType>()) {
2233    BaseExpr = LHSExp;
2234    IndexExpr = RHSExp;
2235    ResultType = PTy->getPointeeType();
2236  } else if (const ObjCObjectPointerType *PTy =
2237               RHSTy->getAs<ObjCObjectPointerType>()) {
2238     // Handle the uncommon case of "123[Ptr]".
2239    BaseExpr = RHSExp;
2240    IndexExpr = LHSExp;
2241    ResultType = PTy->getPointeeType();
2242  } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
2243    BaseExpr = LHSExp;    // vectors: V[123]
2244    IndexExpr = RHSExp;
2245
2246    // FIXME: need to deal with const...
2247    ResultType = VTy->getElementType();
2248  } else if (LHSTy->isArrayType()) {
2249    // If we see an array that wasn't promoted by
2250    // DefaultFunctionArrayLvalueConversion, it must be an array that
2251    // wasn't promoted because of the C90 rule that doesn't
2252    // allow promoting non-lvalue arrays.  Warn, then
2253    // force the promotion here.
2254    Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2255        LHSExp->getSourceRange();
2256    ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
2257                      CastExpr::CK_ArrayToPointerDecay);
2258    LHSTy = LHSExp->getType();
2259
2260    BaseExpr = LHSExp;
2261    IndexExpr = RHSExp;
2262    ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
2263  } else if (RHSTy->isArrayType()) {
2264    // Same as previous, except for 123[f().a] case
2265    Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
2266        RHSExp->getSourceRange();
2267    ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
2268                      CastExpr::CK_ArrayToPointerDecay);
2269    RHSTy = RHSExp->getType();
2270
2271    BaseExpr = RHSExp;
2272    IndexExpr = LHSExp;
2273    ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
2274  } else {
2275    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
2276       << LHSExp->getSourceRange() << RHSExp->getSourceRange());
2277  }
2278  // C99 6.5.2.1p1
2279  if (!(IndexExpr->getType()->isIntegerType() &&
2280        IndexExpr->getType()->isScalarType()) && !IndexExpr->isTypeDependent())
2281    return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
2282                     << IndexExpr->getSourceRange());
2283
2284  if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
2285       IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
2286         && !IndexExpr->isTypeDependent())
2287    Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
2288
2289  // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
2290  // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
2291  // type. Note that Functions are not objects, and that (in C99 parlance)
2292  // incomplete types are not object types.
2293  if (ResultType->isFunctionType()) {
2294    Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
2295      << ResultType << BaseExpr->getSourceRange();
2296    return ExprError();
2297  }
2298
2299  if (!ResultType->isDependentType() &&
2300      RequireCompleteType(LLoc, ResultType,
2301                          PDiag(diag::err_subscript_incomplete_type)
2302                            << BaseExpr->getSourceRange()))
2303    return ExprError();
2304
2305  // Diagnose bad cases where we step over interface counts.
2306  if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
2307    Diag(LLoc, diag::err_subscript_nonfragile_interface)
2308      << ResultType << BaseExpr->getSourceRange();
2309    return ExprError();
2310  }
2311
2312  Base.release();
2313  Idx.release();
2314  return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
2315                                                ResultType, RLoc));
2316}
2317
2318QualType Sema::
2319CheckExtVectorComponent(QualType baseType, SourceLocation OpLoc,
2320                        const IdentifierInfo *CompName,
2321                        SourceLocation CompLoc) {
2322  // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
2323  // see FIXME there.
2324  //
2325  // FIXME: This logic can be greatly simplified by splitting it along
2326  // halving/not halving and reworking the component checking.
2327  const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
2328
2329  // The vector accessor can't exceed the number of elements.
2330  const char *compStr = CompName->getNameStart();
2331
2332  // This flag determines whether or not the component is one of the four
2333  // special names that indicate a subset of exactly half the elements are
2334  // to be selected.
2335  bool HalvingSwizzle = false;
2336
2337  // This flag determines whether or not CompName has an 's' char prefix,
2338  // indicating that it is a string of hex values to be used as vector indices.
2339  bool HexSwizzle = *compStr == 's' || *compStr == 'S';
2340
2341  // Check that we've found one of the special components, or that the component
2342  // names must come from the same set.
2343  if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
2344      !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
2345    HalvingSwizzle = true;
2346  } else if (vecType->getPointAccessorIdx(*compStr) != -1) {
2347    do
2348      compStr++;
2349    while (*compStr && vecType->getPointAccessorIdx(*compStr) != -1);
2350  } else if (HexSwizzle || vecType->getNumericAccessorIdx(*compStr) != -1) {
2351    do
2352      compStr++;
2353    while (*compStr && vecType->getNumericAccessorIdx(*compStr) != -1);
2354  }
2355
2356  if (!HalvingSwizzle && *compStr) {
2357    // We didn't get to the end of the string. This means the component names
2358    // didn't come from the same set *or* we encountered an illegal name.
2359    Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
2360      << std::string(compStr,compStr+1) << SourceRange(CompLoc);
2361    return QualType();
2362  }
2363
2364  // Ensure no component accessor exceeds the width of the vector type it
2365  // operates on.
2366  if (!HalvingSwizzle) {
2367    compStr = CompName->getNameStart();
2368
2369    if (HexSwizzle)
2370      compStr++;
2371
2372    while (*compStr) {
2373      if (!vecType->isAccessorWithinNumElements(*compStr++)) {
2374        Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
2375          << baseType << SourceRange(CompLoc);
2376        return QualType();
2377      }
2378    }
2379  }
2380
2381  // The component accessor looks fine - now we need to compute the actual type.
2382  // The vector type is implied by the component accessor. For example,
2383  // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
2384  // vec4.s0 is a float, vec4.s23 is a vec3, etc.
2385  // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
2386  unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
2387                                     : CompName->getLength();
2388  if (HexSwizzle)
2389    CompSize--;
2390
2391  if (CompSize == 1)
2392    return vecType->getElementType();
2393
2394  QualType VT = Context.getExtVectorType(vecType->getElementType(), CompSize);
2395  // Now look up the TypeDefDecl from the vector type. Without this,
2396  // diagostics look bad. We want extended vector types to appear built-in.
2397  for (unsigned i = 0, E = ExtVectorDecls.size(); i != E; ++i) {
2398    if (ExtVectorDecls[i]->getUnderlyingType() == VT)
2399      return Context.getTypedefType(ExtVectorDecls[i]);
2400  }
2401  return VT; // should never get here (a typedef type should always be found).
2402}
2403
2404static Decl *FindGetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
2405                                                IdentifierInfo *Member,
2406                                                const Selector &Sel,
2407                                                ASTContext &Context) {
2408
2409  if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
2410    return PD;
2411  if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
2412    return OMD;
2413
2414  for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
2415       E = PDecl->protocol_end(); I != E; ++I) {
2416    if (Decl *D = FindGetterNameDeclFromProtocolList(*I, Member, Sel,
2417                                                     Context))
2418      return D;
2419  }
2420  return 0;
2421}
2422
2423static Decl *FindGetterNameDecl(const ObjCObjectPointerType *QIdTy,
2424                                IdentifierInfo *Member,
2425                                const Selector &Sel,
2426                                ASTContext &Context) {
2427  // Check protocols on qualified interfaces.
2428  Decl *GDecl = 0;
2429  for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2430       E = QIdTy->qual_end(); I != E; ++I) {
2431    if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
2432      GDecl = PD;
2433      break;
2434    }
2435    // Also must look for a getter name which uses property syntax.
2436    if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
2437      GDecl = OMD;
2438      break;
2439    }
2440  }
2441  if (!GDecl) {
2442    for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
2443         E = QIdTy->qual_end(); I != E; ++I) {
2444      // Search in the protocol-qualifier list of current protocol.
2445      GDecl = FindGetterNameDeclFromProtocolList(*I, Member, Sel, Context);
2446      if (GDecl)
2447        return GDecl;
2448    }
2449  }
2450  return GDecl;
2451}
2452
2453Sema::OwningExprResult
2454Sema::ActOnDependentMemberExpr(ExprArg Base, QualType BaseType,
2455                               bool IsArrow, SourceLocation OpLoc,
2456                               const CXXScopeSpec &SS,
2457                               NamedDecl *FirstQualifierInScope,
2458                               DeclarationName Name, SourceLocation NameLoc,
2459                               const TemplateArgumentListInfo *TemplateArgs) {
2460  Expr *BaseExpr = Base.takeAs<Expr>();
2461
2462  // Even in dependent contexts, try to diagnose base expressions with
2463  // obviously wrong types, e.g.:
2464  //
2465  // T* t;
2466  // t.f;
2467  //
2468  // In Obj-C++, however, the above expression is valid, since it could be
2469  // accessing the 'f' property if T is an Obj-C interface. The extra check
2470  // allows this, while still reporting an error if T is a struct pointer.
2471  if (!IsArrow) {
2472    const PointerType *PT = BaseType->getAs<PointerType>();
2473    if (PT && (!getLangOptions().ObjC1 ||
2474               PT->getPointeeType()->isRecordType())) {
2475      assert(BaseExpr && "cannot happen with implicit member accesses");
2476      Diag(NameLoc, diag::err_typecheck_member_reference_struct_union)
2477        << BaseType << BaseExpr->getSourceRange();
2478      return ExprError();
2479    }
2480  }
2481
2482  assert(BaseType->isDependentType() || Name.isDependentName() ||
2483         isDependentScopeSpecifier(SS));
2484
2485  // Get the type being accessed in BaseType.  If this is an arrow, the BaseExpr
2486  // must have pointer type, and the accessed type is the pointee.
2487  return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
2488                                                   IsArrow, OpLoc,
2489                 static_cast<NestedNameSpecifier*>(SS.getScopeRep()),
2490                                                   SS.getRange(),
2491                                                   FirstQualifierInScope,
2492                                                   Name, NameLoc,
2493                                                   TemplateArgs));
2494}
2495
2496/// We know that the given qualified member reference points only to
2497/// declarations which do not belong to the static type of the base
2498/// expression.  Diagnose the problem.
2499static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
2500                                             Expr *BaseExpr,
2501                                             QualType BaseType,
2502                                             const CXXScopeSpec &SS,
2503                                             const LookupResult &R) {
2504  // If this is an implicit member access, use a different set of
2505  // diagnostics.
2506  if (!BaseExpr)
2507    return DiagnoseInstanceReference(SemaRef, SS, R);
2508
2509  SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_of_unrelated)
2510    << SS.getRange() << R.getRepresentativeDecl() << BaseType;
2511}
2512
2513// Check whether the declarations we found through a nested-name
2514// specifier in a member expression are actually members of the base
2515// type.  The restriction here is:
2516//
2517//   C++ [expr.ref]p2:
2518//     ... In these cases, the id-expression shall name a
2519//     member of the class or of one of its base classes.
2520//
2521// So it's perfectly legitimate for the nested-name specifier to name
2522// an unrelated class, and for us to find an overload set including
2523// decls from classes which are not superclasses, as long as the decl
2524// we actually pick through overload resolution is from a superclass.
2525bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
2526                                         QualType BaseType,
2527                                         const CXXScopeSpec &SS,
2528                                         const LookupResult &R) {
2529  const RecordType *BaseRT = BaseType->getAs<RecordType>();
2530  if (!BaseRT) {
2531    // We can't check this yet because the base type is still
2532    // dependent.
2533    assert(BaseType->isDependentType());
2534    return false;
2535  }
2536  CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
2537
2538  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2539    // If this is an implicit member reference and we find a
2540    // non-instance member, it's not an error.
2541    if (!BaseExpr && !(*I)->isCXXInstanceMember())
2542      return false;
2543
2544    // Note that we use the DC of the decl, not the underlying decl.
2545    CXXRecordDecl *RecordD = cast<CXXRecordDecl>((*I)->getDeclContext());
2546    while (RecordD->isAnonymousStructOrUnion())
2547      RecordD = cast<CXXRecordDecl>(RecordD->getParent());
2548
2549    llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
2550    MemberRecord.insert(RecordD->getCanonicalDecl());
2551
2552    if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
2553      return false;
2554  }
2555
2556  DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, R);
2557  return true;
2558}
2559
2560static bool
2561LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
2562                         SourceRange BaseRange, const RecordType *RTy,
2563                         SourceLocation OpLoc, CXXScopeSpec &SS,
2564                         bool HasTemplateArgs) {
2565  RecordDecl *RDecl = RTy->getDecl();
2566  if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
2567                              SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
2568                                    << BaseRange))
2569    return true;
2570
2571  if (HasTemplateArgs) {
2572    // LookupTemplateName doesn't expect these both to exist simultaneously.
2573    QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
2574
2575    bool MOUS;
2576    SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
2577    return false;
2578  }
2579
2580  DeclContext *DC = RDecl;
2581  if (SS.isSet()) {
2582    // If the member name was a qualified-id, look into the
2583    // nested-name-specifier.
2584    DC = SemaRef.computeDeclContext(SS, false);
2585
2586    if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
2587      SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
2588        << SS.getRange() << DC;
2589      return true;
2590    }
2591
2592    assert(DC && "Cannot handle non-computable dependent contexts in lookup");
2593
2594    if (!isa<TypeDecl>(DC)) {
2595      SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
2596        << DC << SS.getRange();
2597      return true;
2598    }
2599  }
2600
2601  // The record definition is complete, now look up the member.
2602  SemaRef.LookupQualifiedName(R, DC);
2603
2604  if (!R.empty())
2605    return false;
2606
2607  // We didn't find anything with the given name, so try to correct
2608  // for typos.
2609  DeclarationName Name = R.getLookupName();
2610  if (SemaRef.CorrectTypo(R, 0, &SS, DC, false, Sema::CTC_MemberLookup) &&
2611      !R.empty() &&
2612      (isa<ValueDecl>(*R.begin()) || isa<FunctionTemplateDecl>(*R.begin()))) {
2613    SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
2614      << Name << DC << R.getLookupName() << SS.getRange()
2615      << FixItHint::CreateReplacement(R.getNameLoc(),
2616                                      R.getLookupName().getAsString());
2617    if (NamedDecl *ND = R.getAsSingle<NamedDecl>())
2618      SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
2619        << ND->getDeclName();
2620    return false;
2621  } else {
2622    R.clear();
2623    R.setLookupName(Name);
2624  }
2625
2626  return false;
2627}
2628
2629Sema::OwningExprResult
2630Sema::BuildMemberReferenceExpr(ExprArg BaseArg, QualType BaseType,
2631                               SourceLocation OpLoc, bool IsArrow,
2632                               CXXScopeSpec &SS,
2633                               NamedDecl *FirstQualifierInScope,
2634                               DeclarationName Name, SourceLocation NameLoc,
2635                               const TemplateArgumentListInfo *TemplateArgs) {
2636  Expr *Base = BaseArg.takeAs<Expr>();
2637
2638  if (BaseType->isDependentType() ||
2639      (SS.isSet() && isDependentScopeSpecifier(SS)))
2640    return ActOnDependentMemberExpr(ExprArg(*this, Base), BaseType,
2641                                    IsArrow, OpLoc,
2642                                    SS, FirstQualifierInScope,
2643                                    Name, NameLoc,
2644                                    TemplateArgs);
2645
2646  LookupResult R(*this, Name, NameLoc, LookupMemberName);
2647
2648  // Implicit member accesses.
2649  if (!Base) {
2650    QualType RecordTy = BaseType;
2651    if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
2652    if (LookupMemberExprInRecord(*this, R, SourceRange(),
2653                                 RecordTy->getAs<RecordType>(),
2654                                 OpLoc, SS, TemplateArgs != 0))
2655      return ExprError();
2656
2657  // Explicit member accesses.
2658  } else {
2659    OwningExprResult Result =
2660      LookupMemberExpr(R, Base, IsArrow, OpLoc,
2661                       SS, /*ObjCImpDecl*/ DeclPtrTy(), TemplateArgs != 0);
2662
2663    if (Result.isInvalid()) {
2664      Owned(Base);
2665      return ExprError();
2666    }
2667
2668    if (Result.get())
2669      return move(Result);
2670
2671    // LookupMemberExpr can modify Base, and thus change BaseType
2672    BaseType = Base->getType();
2673  }
2674
2675  return BuildMemberReferenceExpr(ExprArg(*this, Base), BaseType,
2676                                  OpLoc, IsArrow, SS, FirstQualifierInScope,
2677                                  R, TemplateArgs);
2678}
2679
2680Sema::OwningExprResult
2681Sema::BuildMemberReferenceExpr(ExprArg Base, QualType BaseExprType,
2682                               SourceLocation OpLoc, bool IsArrow,
2683                               const CXXScopeSpec &SS,
2684                               NamedDecl *FirstQualifierInScope,
2685                               LookupResult &R,
2686                         const TemplateArgumentListInfo *TemplateArgs,
2687                               bool SuppressQualifierCheck) {
2688  Expr *BaseExpr = Base.takeAs<Expr>();
2689  QualType BaseType = BaseExprType;
2690  if (IsArrow) {
2691    assert(BaseType->isPointerType());
2692    BaseType = BaseType->getAs<PointerType>()->getPointeeType();
2693  }
2694  R.setBaseObjectType(BaseType);
2695
2696  NestedNameSpecifier *Qualifier =
2697    static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2698  DeclarationName MemberName = R.getLookupName();
2699  SourceLocation MemberLoc = R.getNameLoc();
2700
2701  if (R.isAmbiguous())
2702    return ExprError();
2703
2704  if (R.empty()) {
2705    // Rederive where we looked up.
2706    DeclContext *DC = (SS.isSet()
2707                       ? computeDeclContext(SS, false)
2708                       : BaseType->getAs<RecordType>()->getDecl());
2709
2710    Diag(R.getNameLoc(), diag::err_no_member)
2711      << MemberName << DC
2712      << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
2713    return ExprError();
2714  }
2715
2716  // Diagnose lookups that find only declarations from a non-base
2717  // type.  This is possible for either qualified lookups (which may
2718  // have been qualified with an unrelated type) or implicit member
2719  // expressions (which were found with unqualified lookup and thus
2720  // may have come from an enclosing scope).  Note that it's okay for
2721  // lookup to find declarations from a non-base type as long as those
2722  // aren't the ones picked by overload resolution.
2723  if ((SS.isSet() || !BaseExpr ||
2724       (isa<CXXThisExpr>(BaseExpr) &&
2725        cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
2726      !SuppressQualifierCheck &&
2727      CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
2728    return ExprError();
2729
2730  // Construct an unresolved result if we in fact got an unresolved
2731  // result.
2732  if (R.isOverloadedResult() || R.isUnresolvableResult()) {
2733    bool Dependent =
2734      BaseExprType->isDependentType() ||
2735      R.isUnresolvableResult() ||
2736      OverloadExpr::ComputeDependence(R.begin(), R.end(), TemplateArgs);
2737
2738    // Suppress any lookup-related diagnostics; we'll do these when we
2739    // pick a member.
2740    R.suppressDiagnostics();
2741
2742    UnresolvedMemberExpr *MemExpr
2743      = UnresolvedMemberExpr::Create(Context, Dependent,
2744                                     R.isUnresolvableResult(),
2745                                     BaseExpr, BaseExprType,
2746                                     IsArrow, OpLoc,
2747                                     Qualifier, SS.getRange(),
2748                                     MemberName, MemberLoc,
2749                                     TemplateArgs, R.begin(), R.end());
2750
2751    return Owned(MemExpr);
2752  }
2753
2754  assert(R.isSingleResult());
2755  DeclAccessPair FoundDecl = R.begin().getPair();
2756  NamedDecl *MemberDecl = R.getFoundDecl();
2757
2758  // FIXME: diagnose the presence of template arguments now.
2759
2760  // If the decl being referenced had an error, return an error for this
2761  // sub-expr without emitting another error, in order to avoid cascading
2762  // error cases.
2763  if (MemberDecl->isInvalidDecl())
2764    return ExprError();
2765
2766  // Handle the implicit-member-access case.
2767  if (!BaseExpr) {
2768    // If this is not an instance member, convert to a non-member access.
2769    if (!MemberDecl->isCXXInstanceMember())
2770      return BuildDeclarationNameExpr(SS, R.getNameLoc(), MemberDecl);
2771
2772    SourceLocation Loc = R.getNameLoc();
2773    if (SS.getRange().isValid())
2774      Loc = SS.getRange().getBegin();
2775    BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
2776  }
2777
2778  bool ShouldCheckUse = true;
2779  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
2780    // Don't diagnose the use of a virtual member function unless it's
2781    // explicitly qualified.
2782    if (MD->isVirtual() && !SS.isSet())
2783      ShouldCheckUse = false;
2784  }
2785
2786  // Check the use of this member.
2787  if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
2788    Owned(BaseExpr);
2789    return ExprError();
2790  }
2791
2792  if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) {
2793    // We may have found a field within an anonymous union or struct
2794    // (C++ [class.union]).
2795    if (cast<RecordDecl>(FD->getDeclContext())->isAnonymousStructOrUnion() &&
2796        !BaseType->getAs<RecordType>()->getDecl()->isAnonymousStructOrUnion())
2797      return BuildAnonymousStructUnionMemberReference(MemberLoc, FD,
2798                                                      BaseExpr, OpLoc);
2799
2800    // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
2801    QualType MemberType = FD->getType();
2802    if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>())
2803      MemberType = Ref->getPointeeType();
2804    else {
2805      Qualifiers BaseQuals = BaseType.getQualifiers();
2806      BaseQuals.removeObjCGCAttr();
2807      if (FD->isMutable()) BaseQuals.removeConst();
2808
2809      Qualifiers MemberQuals
2810        = Context.getCanonicalType(MemberType).getQualifiers();
2811
2812      Qualifiers Combined = BaseQuals + MemberQuals;
2813      if (Combined != MemberQuals)
2814        MemberType = Context.getQualifiedType(MemberType, Combined);
2815    }
2816
2817    MarkDeclarationReferenced(MemberLoc, FD);
2818    if (PerformObjectMemberConversion(BaseExpr, Qualifier, FoundDecl, FD))
2819      return ExprError();
2820    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2821                                 FD, FoundDecl, MemberLoc, MemberType));
2822  }
2823
2824  if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
2825    MarkDeclarationReferenced(MemberLoc, Var);
2826    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2827                                 Var, FoundDecl, MemberLoc,
2828                                 Var->getType().getNonReferenceType()));
2829  }
2830
2831  if (FunctionDecl *MemberFn = dyn_cast<FunctionDecl>(MemberDecl)) {
2832    MarkDeclarationReferenced(MemberLoc, MemberDecl);
2833    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2834                                 MemberFn, FoundDecl, MemberLoc,
2835                                 MemberFn->getType()));
2836  }
2837
2838  if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
2839    MarkDeclarationReferenced(MemberLoc, MemberDecl);
2840    return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
2841                                 Enum, FoundDecl, MemberLoc, Enum->getType()));
2842  }
2843
2844  Owned(BaseExpr);
2845
2846  // We found something that we didn't expect. Complain.
2847  if (isa<TypeDecl>(MemberDecl))
2848    Diag(MemberLoc,diag::err_typecheck_member_reference_type)
2849      << MemberName << BaseType << int(IsArrow);
2850  else
2851    Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
2852      << MemberName << BaseType << int(IsArrow);
2853
2854  Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
2855    << MemberName;
2856  R.suppressDiagnostics();
2857  return ExprError();
2858}
2859
2860/// Look up the given member of the given non-type-dependent
2861/// expression.  This can return in one of two ways:
2862///  * If it returns a sentinel null-but-valid result, the caller will
2863///    assume that lookup was performed and the results written into
2864///    the provided structure.  It will take over from there.
2865///  * Otherwise, the returned expression will be produced in place of
2866///    an ordinary member expression.
2867///
2868/// The ObjCImpDecl bit is a gross hack that will need to be properly
2869/// fixed for ObjC++.
2870Sema::OwningExprResult
2871Sema::LookupMemberExpr(LookupResult &R, Expr *&BaseExpr,
2872                       bool &IsArrow, SourceLocation OpLoc,
2873                       CXXScopeSpec &SS,
2874                       DeclPtrTy ObjCImpDecl, bool HasTemplateArgs) {
2875  assert(BaseExpr && "no base expression");
2876
2877  // Perform default conversions.
2878  DefaultFunctionArrayConversion(BaseExpr);
2879
2880  QualType BaseType = BaseExpr->getType();
2881  assert(!BaseType->isDependentType());
2882
2883  DeclarationName MemberName = R.getLookupName();
2884  SourceLocation MemberLoc = R.getNameLoc();
2885
2886  // If the user is trying to apply -> or . to a function pointer
2887  // type, it's probably because they forgot parentheses to call that
2888  // function. Suggest the addition of those parentheses, build the
2889  // call, and continue on.
2890  if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
2891    if (const FunctionProtoType *Fun
2892          = Ptr->getPointeeType()->getAs<FunctionProtoType>()) {
2893      QualType ResultTy = Fun->getResultType();
2894      if (Fun->getNumArgs() == 0 &&
2895          ((!IsArrow && ResultTy->isRecordType()) ||
2896           (IsArrow && ResultTy->isPointerType() &&
2897            ResultTy->getAs<PointerType>()->getPointeeType()
2898                                                          ->isRecordType()))) {
2899        SourceLocation Loc = PP.getLocForEndOfToken(BaseExpr->getLocEnd());
2900        Diag(Loc, diag::err_member_reference_needs_call)
2901          << QualType(Fun, 0)
2902          << FixItHint::CreateInsertion(Loc, "()");
2903
2904        OwningExprResult NewBase
2905          = ActOnCallExpr(0, ExprArg(*this, BaseExpr), Loc,
2906                          MultiExprArg(*this, 0, 0), 0, Loc);
2907        BaseExpr = 0;
2908        if (NewBase.isInvalid())
2909          return ExprError();
2910
2911        BaseExpr = NewBase.takeAs<Expr>();
2912        DefaultFunctionArrayConversion(BaseExpr);
2913        BaseType = BaseExpr->getType();
2914      }
2915    }
2916  }
2917
2918  // If this is an Objective-C pseudo-builtin and a definition is provided then
2919  // use that.
2920  if (BaseType->isObjCIdType()) {
2921    if (IsArrow) {
2922      // Handle the following exceptional case PObj->isa.
2923      if (const ObjCObjectPointerType *OPT =
2924          BaseType->getAs<ObjCObjectPointerType>()) {
2925        if (OPT->getObjectType()->isObjCId() &&
2926            MemberName.getAsIdentifierInfo()->isStr("isa"))
2927          return Owned(new (Context) ObjCIsaExpr(BaseExpr, true, MemberLoc,
2928                                                 Context.getObjCClassType()));
2929      }
2930    }
2931    // We have an 'id' type. Rather than fall through, we check if this
2932    // is a reference to 'isa'.
2933    if (BaseType != Context.ObjCIdRedefinitionType) {
2934      BaseType = Context.ObjCIdRedefinitionType;
2935      ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2936    }
2937  }
2938
2939  // If this is an Objective-C pseudo-builtin and a definition is provided then
2940  // use that.
2941  if (Context.isObjCSelType(BaseType)) {
2942    // We have an 'SEL' type. Rather than fall through, we check if this
2943    // is a reference to 'sel_id'.
2944    if (BaseType != Context.ObjCSelRedefinitionType) {
2945      BaseType = Context.ObjCSelRedefinitionType;
2946      ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
2947    }
2948  }
2949
2950  assert(!BaseType.isNull() && "no type for member expression");
2951
2952  // Handle properties on ObjC 'Class' types.
2953  if (!IsArrow && BaseType->isObjCClassType()) {
2954    // Also must look for a getter name which uses property syntax.
2955    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
2956    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
2957    if (ObjCMethodDecl *MD = getCurMethodDecl()) {
2958      ObjCInterfaceDecl *IFace = MD->getClassInterface();
2959      ObjCMethodDecl *Getter;
2960      // FIXME: need to also look locally in the implementation.
2961      if ((Getter = IFace->lookupClassMethod(Sel))) {
2962        // Check the use of this method.
2963        if (DiagnoseUseOfDecl(Getter, MemberLoc))
2964          return ExprError();
2965      }
2966      // If we found a getter then this may be a valid dot-reference, we
2967      // will look for the matching setter, in case it is needed.
2968      Selector SetterSel =
2969      SelectorTable::constructSetterName(PP.getIdentifierTable(),
2970                                         PP.getSelectorTable(), Member);
2971      ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
2972      if (!Setter) {
2973        // If this reference is in an @implementation, also check for 'private'
2974        // methods.
2975        Setter = IFace->lookupPrivateInstanceMethod(SetterSel);
2976      }
2977      // Look through local category implementations associated with the class.
2978      if (!Setter)
2979        Setter = IFace->getCategoryClassMethod(SetterSel);
2980
2981      if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
2982        return ExprError();
2983
2984      if (Getter || Setter) {
2985        QualType PType;
2986
2987        if (Getter)
2988          PType = Getter->getResultType();
2989        else
2990          // Get the expression type from Setter's incoming parameter.
2991          PType = (*(Setter->param_end() -1))->getType();
2992        // FIXME: we must check that the setter has property type.
2993        return Owned(new (Context) ObjCImplicitSetterGetterRefExpr(Getter,
2994                                                  PType,
2995                                                  Setter, MemberLoc, BaseExpr));
2996      }
2997      return ExprError(Diag(MemberLoc, diag::err_property_not_found)
2998                       << MemberName << BaseType);
2999    }
3000  }
3001
3002  if (BaseType->isObjCClassType() &&
3003      BaseType != Context.ObjCClassRedefinitionType) {
3004    BaseType = Context.ObjCClassRedefinitionType;
3005    ImpCastExprToType(BaseExpr, BaseType, CastExpr::CK_BitCast);
3006  }
3007
3008  if (IsArrow) {
3009    if (const PointerType *PT = BaseType->getAs<PointerType>())
3010      BaseType = PT->getPointeeType();
3011    else if (BaseType->isObjCObjectPointerType())
3012      ;
3013    else if (BaseType->isRecordType()) {
3014      // Recover from arrow accesses to records, e.g.:
3015      //   struct MyRecord foo;
3016      //   foo->bar
3017      // This is actually well-formed in C++ if MyRecord has an
3018      // overloaded operator->, but that should have been dealt with
3019      // by now.
3020      Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3021        << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3022        << FixItHint::CreateReplacement(OpLoc, ".");
3023      IsArrow = false;
3024    } else {
3025      Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
3026        << BaseType << BaseExpr->getSourceRange();
3027      return ExprError();
3028    }
3029  } else {
3030    // Recover from dot accesses to pointers, e.g.:
3031    //   type *foo;
3032    //   foo.bar
3033    // This is actually well-formed in two cases:
3034    //   - 'type' is an Objective C type
3035    //   - 'bar' is a pseudo-destructor name which happens to refer to
3036    //     the appropriate pointer type
3037    if (MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
3038      const PointerType *PT = BaseType->getAs<PointerType>();
3039      if (PT && PT->getPointeeType()->isRecordType()) {
3040        Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
3041          << BaseType << int(IsArrow) << BaseExpr->getSourceRange()
3042          << FixItHint::CreateReplacement(OpLoc, "->");
3043        BaseType = PT->getPointeeType();
3044        IsArrow = true;
3045      }
3046    }
3047  }
3048
3049  // Handle field access to simple records.
3050  if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
3051    if (LookupMemberExprInRecord(*this, R, BaseExpr->getSourceRange(),
3052                                 RTy, OpLoc, SS, HasTemplateArgs))
3053      return ExprError();
3054    return Owned((Expr*) 0);
3055  }
3056
3057  // Handle access to Objective-C instance variables, such as "Obj->ivar" and
3058  // (*Obj).ivar.
3059  if ((IsArrow && BaseType->isObjCObjectPointerType()) ||
3060      (!IsArrow && BaseType->isObjCObjectType())) {
3061    const ObjCObjectPointerType *OPT = BaseType->getAs<ObjCObjectPointerType>();
3062    ObjCInterfaceDecl *IDecl =
3063      OPT ? OPT->getInterfaceDecl()
3064          : BaseType->getAs<ObjCObjectType>()->getInterface();
3065    if (IDecl) {
3066      IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3067
3068      ObjCInterfaceDecl *ClassDeclared;
3069      ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
3070
3071      if (!IV) {
3072        // Attempt to correct for typos in ivar names.
3073        LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
3074                         LookupMemberName);
3075        if (CorrectTypo(Res, 0, 0, IDecl, false, CTC_MemberLookup) &&
3076            (IV = Res.getAsSingle<ObjCIvarDecl>())) {
3077          Diag(R.getNameLoc(),
3078               diag::err_typecheck_member_reference_ivar_suggest)
3079            << IDecl->getDeclName() << MemberName << IV->getDeclName()
3080            << FixItHint::CreateReplacement(R.getNameLoc(),
3081                                            IV->getNameAsString());
3082          Diag(IV->getLocation(), diag::note_previous_decl)
3083            << IV->getDeclName();
3084        } else {
3085          Res.clear();
3086          Res.setLookupName(Member);
3087        }
3088      }
3089
3090      if (IV) {
3091        // If the decl being referenced had an error, return an error for this
3092        // sub-expr without emitting another error, in order to avoid cascading
3093        // error cases.
3094        if (IV->isInvalidDecl())
3095          return ExprError();
3096
3097        // Check whether we can reference this field.
3098        if (DiagnoseUseOfDecl(IV, MemberLoc))
3099          return ExprError();
3100        if (IV->getAccessControl() != ObjCIvarDecl::Public &&
3101            IV->getAccessControl() != ObjCIvarDecl::Package) {
3102          ObjCInterfaceDecl *ClassOfMethodDecl = 0;
3103          if (ObjCMethodDecl *MD = getCurMethodDecl())
3104            ClassOfMethodDecl =  MD->getClassInterface();
3105          else if (ObjCImpDecl && getCurFunctionDecl()) {
3106            // Case of a c-function declared inside an objc implementation.
3107            // FIXME: For a c-style function nested inside an objc implementation
3108            // class, there is no implementation context available, so we pass
3109            // down the context as argument to this routine. Ideally, this context
3110            // need be passed down in the AST node and somehow calculated from the
3111            // AST for a function decl.
3112            Decl *ImplDecl = ObjCImpDecl.getAs<Decl>();
3113            if (ObjCImplementationDecl *IMPD =
3114                dyn_cast<ObjCImplementationDecl>(ImplDecl))
3115              ClassOfMethodDecl = IMPD->getClassInterface();
3116            else if (ObjCCategoryImplDecl* CatImplClass =
3117                        dyn_cast<ObjCCategoryImplDecl>(ImplDecl))
3118              ClassOfMethodDecl = CatImplClass->getClassInterface();
3119          }
3120
3121          if (IV->getAccessControl() == ObjCIvarDecl::Private) {
3122            if (ClassDeclared != IDecl ||
3123                ClassOfMethodDecl != ClassDeclared)
3124              Diag(MemberLoc, diag::error_private_ivar_access)
3125                << IV->getDeclName();
3126          } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
3127            // @protected
3128            Diag(MemberLoc, diag::error_protected_ivar_access)
3129              << IV->getDeclName();
3130        }
3131
3132        return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
3133                                                   MemberLoc, BaseExpr,
3134                                                   IsArrow));
3135      }
3136      return ExprError(Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
3137                         << IDecl->getDeclName() << MemberName
3138                         << BaseExpr->getSourceRange());
3139    }
3140  }
3141  // Handle properties on 'id' and qualified "id".
3142  if (!IsArrow && (BaseType->isObjCIdType() ||
3143                   BaseType->isObjCQualifiedIdType())) {
3144    const ObjCObjectPointerType *QIdTy = BaseType->getAs<ObjCObjectPointerType>();
3145    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3146
3147    // Check protocols on qualified interfaces.
3148    Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
3149    if (Decl *PMDecl = FindGetterNameDecl(QIdTy, Member, Sel, Context)) {
3150      if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
3151        // Check the use of this declaration
3152        if (DiagnoseUseOfDecl(PD, MemberLoc))
3153          return ExprError();
3154
3155        return Owned(new (Context) ObjCPropertyRefExpr(PD, PD->getType(),
3156                                                       MemberLoc, BaseExpr));
3157      }
3158      if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
3159        // Check the use of this method.
3160        if (DiagnoseUseOfDecl(OMD, MemberLoc))
3161          return ExprError();
3162
3163        return Owned(ObjCMessageExpr::Create(Context,
3164                                     OMD->getResultType().getNonReferenceType(),
3165                                             OpLoc, BaseExpr, Sel,
3166                                             OMD, NULL, 0, MemberLoc));
3167      }
3168    }
3169
3170    return ExprError(Diag(MemberLoc, diag::err_property_not_found)
3171                       << MemberName << BaseType);
3172  }
3173
3174  // Handle Objective-C property access, which is "Obj.property" where Obj is a
3175  // pointer to a (potentially qualified) interface type.
3176  if (!IsArrow)
3177    if (const ObjCObjectPointerType *OPT =
3178          BaseType->getAsObjCInterfacePointerType())
3179      return HandleExprPropertyRefExpr(OPT, BaseExpr, MemberName, MemberLoc);
3180
3181  // Handle the following exceptional case (*Obj).isa.
3182  if (!IsArrow &&
3183      BaseType->isObjCObjectType() &&
3184      BaseType->getAs<ObjCObjectType>()->isObjCId() &&
3185      MemberName.getAsIdentifierInfo()->isStr("isa"))
3186    return Owned(new (Context) ObjCIsaExpr(BaseExpr, false, MemberLoc,
3187                                           Context.getObjCClassType()));
3188
3189  // Handle 'field access' to vectors, such as 'V.xx'.
3190  if (BaseType->isExtVectorType()) {
3191    IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
3192    QualType ret = CheckExtVectorComponent(BaseType, OpLoc, Member, MemberLoc);
3193    if (ret.isNull())
3194      return ExprError();
3195    return Owned(new (Context) ExtVectorElementExpr(ret, BaseExpr, *Member,
3196                                                    MemberLoc));
3197  }
3198
3199  Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
3200    << BaseType << BaseExpr->getSourceRange();
3201
3202  return ExprError();
3203}
3204
3205/// The main callback when the parser finds something like
3206///   expression . [nested-name-specifier] identifier
3207///   expression -> [nested-name-specifier] identifier
3208/// where 'identifier' encompasses a fairly broad spectrum of
3209/// possibilities, including destructor and operator references.
3210///
3211/// \param OpKind either tok::arrow or tok::period
3212/// \param HasTrailingLParen whether the next token is '(', which
3213///   is used to diagnose mis-uses of special members that can
3214///   only be called
3215/// \param ObjCImpDecl the current ObjC @implementation decl;
3216///   this is an ugly hack around the fact that ObjC @implementations
3217///   aren't properly put in the context chain
3218Sema::OwningExprResult Sema::ActOnMemberAccessExpr(Scope *S, ExprArg BaseArg,
3219                                                   SourceLocation OpLoc,
3220                                                   tok::TokenKind OpKind,
3221                                                   CXXScopeSpec &SS,
3222                                                   UnqualifiedId &Id,
3223                                                   DeclPtrTy ObjCImpDecl,
3224                                                   bool HasTrailingLParen) {
3225  if (SS.isSet() && SS.isInvalid())
3226    return ExprError();
3227
3228  TemplateArgumentListInfo TemplateArgsBuffer;
3229
3230  // Decompose the name into its component parts.
3231  DeclarationName Name;
3232  SourceLocation NameLoc;
3233  const TemplateArgumentListInfo *TemplateArgs;
3234  DecomposeUnqualifiedId(*this, Id, TemplateArgsBuffer,
3235                         Name, NameLoc, TemplateArgs);
3236
3237  bool IsArrow = (OpKind == tok::arrow);
3238
3239  NamedDecl *FirstQualifierInScope
3240    = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
3241                       static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
3242
3243  // This is a postfix expression, so get rid of ParenListExprs.
3244  BaseArg = MaybeConvertParenListExprToParenExpr(S, move(BaseArg));
3245
3246  Expr *Base = BaseArg.takeAs<Expr>();
3247  OwningExprResult Result(*this);
3248  if (Base->getType()->isDependentType() || Name.isDependentName() ||
3249      isDependentScopeSpecifier(SS)) {
3250    Result = ActOnDependentMemberExpr(ExprArg(*this, Base), Base->getType(),
3251                                      IsArrow, OpLoc,
3252                                      SS, FirstQualifierInScope,
3253                                      Name, NameLoc,
3254                                      TemplateArgs);
3255  } else {
3256    LookupResult R(*this, Name, NameLoc, LookupMemberName);
3257    Result = LookupMemberExpr(R, Base, IsArrow, OpLoc,
3258                              SS, ObjCImpDecl, TemplateArgs != 0);
3259
3260    if (Result.isInvalid()) {
3261      Owned(Base);
3262      return ExprError();
3263    }
3264
3265    if (Result.get()) {
3266      // The only way a reference to a destructor can be used is to
3267      // immediately call it, which falls into this case.  If the
3268      // next token is not a '(', produce a diagnostic and build the
3269      // call now.
3270      if (!HasTrailingLParen &&
3271          Id.getKind() == UnqualifiedId::IK_DestructorName)
3272        return DiagnoseDtorReference(NameLoc, move(Result));
3273
3274      return move(Result);
3275    }
3276
3277    Result = BuildMemberReferenceExpr(ExprArg(*this, Base), Base->getType(),
3278                                      OpLoc, IsArrow, SS, FirstQualifierInScope,
3279                                      R, TemplateArgs);
3280  }
3281
3282  return move(Result);
3283}
3284
3285Sema::OwningExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
3286                                                    FunctionDecl *FD,
3287                                                    ParmVarDecl *Param) {
3288  if (Param->hasUnparsedDefaultArg()) {
3289    Diag (CallLoc,
3290          diag::err_use_of_default_argument_to_function_declared_later) <<
3291      FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
3292    Diag(UnparsedDefaultArgLocs[Param],
3293          diag::note_default_argument_declared_here);
3294  } else {
3295    if (Param->hasUninstantiatedDefaultArg()) {
3296      Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
3297
3298      // Instantiate the expression.
3299      MultiLevelTemplateArgumentList ArgList
3300        = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
3301
3302      InstantiatingTemplate Inst(*this, CallLoc, Param,
3303                                 ArgList.getInnermost().getFlatArgumentList(),
3304                                 ArgList.getInnermost().flat_size());
3305
3306      OwningExprResult Result = SubstExpr(UninstExpr, ArgList);
3307      if (Result.isInvalid())
3308        return ExprError();
3309
3310      // Check the expression as an initializer for the parameter.
3311      InitializedEntity Entity
3312        = InitializedEntity::InitializeParameter(Param);
3313      InitializationKind Kind
3314        = InitializationKind::CreateCopy(Param->getLocation(),
3315               /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3316      Expr *ResultE = Result.takeAs<Expr>();
3317
3318      InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3319      Result = InitSeq.Perform(*this, Entity, Kind,
3320                               MultiExprArg(*this, (void**)&ResultE, 1));
3321      if (Result.isInvalid())
3322        return ExprError();
3323
3324      // Build the default argument expression.
3325      return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3326                                             Result.takeAs<Expr>()));
3327    }
3328
3329    // If the default expression creates temporaries, we need to
3330    // push them to the current stack of expression temporaries so they'll
3331    // be properly destroyed.
3332    // FIXME: We should really be rebuilding the default argument with new
3333    // bound temporaries; see the comment in PR5810.
3334    for (unsigned i = 0, e = Param->getNumDefaultArgTemporaries(); i != e; ++i)
3335      ExprTemporaries.push_back(Param->getDefaultArgTemporary(i));
3336  }
3337
3338  // We already type-checked the argument, so we know it works.
3339  return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
3340}
3341
3342/// ConvertArgumentsForCall - Converts the arguments specified in
3343/// Args/NumArgs to the parameter types of the function FDecl with
3344/// function prototype Proto. Call is the call expression itself, and
3345/// Fn is the function expression. For a C++ member function, this
3346/// routine does not attempt to convert the object argument. Returns
3347/// true if the call is ill-formed.
3348bool
3349Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
3350                              FunctionDecl *FDecl,
3351                              const FunctionProtoType *Proto,
3352                              Expr **Args, unsigned NumArgs,
3353                              SourceLocation RParenLoc) {
3354  // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
3355  // assignment, to the types of the corresponding parameter, ...
3356  unsigned NumArgsInProto = Proto->getNumArgs();
3357  bool Invalid = false;
3358
3359  // If too few arguments are available (and we don't have default
3360  // arguments for the remaining parameters), don't make the call.
3361  if (NumArgs < NumArgsInProto) {
3362    if (!FDecl || NumArgs < FDecl->getMinRequiredArguments())
3363      return Diag(RParenLoc, diag::err_typecheck_call_too_few_args)
3364        << Fn->getType()->isBlockPointerType()
3365        << NumArgsInProto << NumArgs << Fn->getSourceRange();
3366    Call->setNumArgs(Context, NumArgsInProto);
3367  }
3368
3369  // If too many are passed and not variadic, error on the extras and drop
3370  // them.
3371  if (NumArgs > NumArgsInProto) {
3372    if (!Proto->isVariadic()) {
3373      Diag(Args[NumArgsInProto]->getLocStart(),
3374           diag::err_typecheck_call_too_many_args)
3375        << Fn->getType()->isBlockPointerType()
3376        << NumArgsInProto << NumArgs << Fn->getSourceRange()
3377        << SourceRange(Args[NumArgsInProto]->getLocStart(),
3378                       Args[NumArgs-1]->getLocEnd());
3379      // This deletes the extra arguments.
3380      Call->setNumArgs(Context, NumArgsInProto);
3381      return true;
3382    }
3383  }
3384  llvm::SmallVector<Expr *, 8> AllArgs;
3385  VariadicCallType CallType =
3386    Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3387  if (Fn->getType()->isBlockPointerType())
3388    CallType = VariadicBlock; // Block
3389  else if (isa<MemberExpr>(Fn))
3390    CallType = VariadicMethod;
3391  Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
3392                                   Proto, 0, Args, NumArgs, AllArgs, CallType);
3393  if (Invalid)
3394    return true;
3395  unsigned TotalNumArgs = AllArgs.size();
3396  for (unsigned i = 0; i < TotalNumArgs; ++i)
3397    Call->setArg(i, AllArgs[i]);
3398
3399  return false;
3400}
3401
3402bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3403                                  FunctionDecl *FDecl,
3404                                  const FunctionProtoType *Proto,
3405                                  unsigned FirstProtoArg,
3406                                  Expr **Args, unsigned NumArgs,
3407                                  llvm::SmallVector<Expr *, 8> &AllArgs,
3408                                  VariadicCallType CallType) {
3409  unsigned NumArgsInProto = Proto->getNumArgs();
3410  unsigned NumArgsToCheck = NumArgs;
3411  bool Invalid = false;
3412  if (NumArgs != NumArgsInProto)
3413    // Use default arguments for missing arguments
3414    NumArgsToCheck = NumArgsInProto;
3415  unsigned ArgIx = 0;
3416  // Continue to check argument types (even if we have too few/many args).
3417  for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
3418    QualType ProtoArgType = Proto->getArgType(i);
3419
3420    Expr *Arg;
3421    if (ArgIx < NumArgs) {
3422      Arg = Args[ArgIx++];
3423
3424      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3425                              ProtoArgType,
3426                              PDiag(diag::err_call_incomplete_argument)
3427                              << Arg->getSourceRange()))
3428        return true;
3429
3430      // Pass the argument
3431      ParmVarDecl *Param = 0;
3432      if (FDecl && i < FDecl->getNumParams())
3433        Param = FDecl->getParamDecl(i);
3434
3435
3436      InitializedEntity Entity =
3437        Param? InitializedEntity::InitializeParameter(Param)
3438             : InitializedEntity::InitializeParameter(ProtoArgType);
3439      OwningExprResult ArgE = PerformCopyInitialization(Entity,
3440                                                        SourceLocation(),
3441                                                        Owned(Arg));
3442      if (ArgE.isInvalid())
3443        return true;
3444
3445      Arg = ArgE.takeAs<Expr>();
3446    } else {
3447      ParmVarDecl *Param = FDecl->getParamDecl(i);
3448
3449      OwningExprResult ArgExpr =
3450        BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
3451      if (ArgExpr.isInvalid())
3452        return true;
3453
3454      Arg = ArgExpr.takeAs<Expr>();
3455    }
3456    AllArgs.push_back(Arg);
3457  }
3458
3459  // If this is a variadic call, handle args passed through "...".
3460  if (CallType != VariadicDoesNotApply) {
3461    // Promote the arguments (C99 6.5.2.2p7).
3462    for (unsigned i = ArgIx; i != NumArgs; ++i) {
3463      Expr *Arg = Args[i];
3464      Invalid |= DefaultVariadicArgumentPromotion(Arg, CallType, FDecl);
3465      AllArgs.push_back(Arg);
3466    }
3467  }
3468  return Invalid;
3469}
3470
3471/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
3472/// This provides the location of the left/right parens and a list of comma
3473/// locations.
3474Action::OwningExprResult
3475Sema::ActOnCallExpr(Scope *S, ExprArg fn, SourceLocation LParenLoc,
3476                    MultiExprArg args,
3477                    SourceLocation *CommaLocs, SourceLocation RParenLoc) {
3478  unsigned NumArgs = args.size();
3479
3480  // Since this might be a postfix expression, get rid of ParenListExprs.
3481  fn = MaybeConvertParenListExprToParenExpr(S, move(fn));
3482
3483  Expr *Fn = fn.takeAs<Expr>();
3484  Expr **Args = reinterpret_cast<Expr**>(args.release());
3485  assert(Fn && "no function call expression");
3486
3487  if (getLangOptions().CPlusPlus) {
3488    // If this is a pseudo-destructor expression, build the call immediately.
3489    if (isa<CXXPseudoDestructorExpr>(Fn)) {
3490      if (NumArgs > 0) {
3491        // Pseudo-destructor calls should not have any arguments.
3492        Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
3493          << FixItHint::CreateRemoval(
3494                                    SourceRange(Args[0]->getLocStart(),
3495                                                Args[NumArgs-1]->getLocEnd()));
3496
3497        for (unsigned I = 0; I != NumArgs; ++I)
3498          Args[I]->Destroy(Context);
3499
3500        NumArgs = 0;
3501      }
3502
3503      return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
3504                                          RParenLoc));
3505    }
3506
3507    // Determine whether this is a dependent call inside a C++ template,
3508    // in which case we won't do any semantic analysis now.
3509    // FIXME: Will need to cache the results of name lookup (including ADL) in
3510    // Fn.
3511    bool Dependent = false;
3512    if (Fn->isTypeDependent())
3513      Dependent = true;
3514    else if (Expr::hasAnyTypeDependentArguments(Args, NumArgs))
3515      Dependent = true;
3516
3517    if (Dependent)
3518      return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3519                                          Context.DependentTy, RParenLoc));
3520
3521    // Determine whether this is a call to an object (C++ [over.call.object]).
3522    if (Fn->getType()->isRecordType())
3523      return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
3524                                                CommaLocs, RParenLoc));
3525
3526    Expr *NakedFn = Fn->IgnoreParens();
3527
3528    // Determine whether this is a call to an unresolved member function.
3529    if (UnresolvedMemberExpr *MemE = dyn_cast<UnresolvedMemberExpr>(NakedFn)) {
3530      // If lookup was unresolved but not dependent (i.e. didn't find
3531      // an unresolved using declaration), it has to be an overloaded
3532      // function set, which means it must contain either multiple
3533      // declarations (all methods or method templates) or a single
3534      // method template.
3535      assert((MemE->getNumDecls() > 1) ||
3536             isa<FunctionTemplateDecl>(
3537                                 (*MemE->decls_begin())->getUnderlyingDecl()));
3538      (void)MemE;
3539
3540      return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3541                                       CommaLocs, RParenLoc);
3542    }
3543
3544    // Determine whether this is a call to a member function.
3545    if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(NakedFn)) {
3546      NamedDecl *MemDecl = MemExpr->getMemberDecl();
3547      if (isa<CXXMethodDecl>(MemDecl))
3548        return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
3549                                         CommaLocs, RParenLoc);
3550    }
3551
3552    // Determine whether this is a call to a pointer-to-member function.
3553    if (BinaryOperator *BO = dyn_cast<BinaryOperator>(NakedFn)) {
3554      if (BO->getOpcode() == BinaryOperator::PtrMemD ||
3555          BO->getOpcode() == BinaryOperator::PtrMemI) {
3556        if (const FunctionProtoType *FPT
3557                                = BO->getType()->getAs<FunctionProtoType>()) {
3558          QualType ResultTy = FPT->getResultType().getNonReferenceType();
3559
3560          ExprOwningPtr<CXXMemberCallExpr>
3561            TheCall(this, new (Context) CXXMemberCallExpr(Context, BO, Args,
3562                                                          NumArgs, ResultTy,
3563                                                          RParenLoc));
3564
3565          if (CheckCallReturnType(FPT->getResultType(),
3566                                  BO->getRHS()->getSourceRange().getBegin(),
3567                                  TheCall.get(), 0))
3568            return ExprError();
3569
3570          if (ConvertArgumentsForCall(&*TheCall, BO, 0, FPT, Args, NumArgs,
3571                                      RParenLoc))
3572            return ExprError();
3573
3574          return Owned(MaybeBindToTemporary(TheCall.release()).release());
3575        }
3576        return ExprError(Diag(Fn->getLocStart(),
3577                              diag::err_typecheck_call_not_function)
3578                              << Fn->getType() << Fn->getSourceRange());
3579      }
3580    }
3581  }
3582
3583  // If we're directly calling a function, get the appropriate declaration.
3584  // Also, in C++, keep track of whether we should perform argument-dependent
3585  // lookup and whether there were any explicitly-specified template arguments.
3586
3587  Expr *NakedFn = Fn->IgnoreParens();
3588  if (isa<UnresolvedLookupExpr>(NakedFn)) {
3589    UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(NakedFn);
3590    return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3591                                   CommaLocs, RParenLoc);
3592  }
3593
3594  NamedDecl *NDecl = 0;
3595  if (isa<DeclRefExpr>(NakedFn))
3596    NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
3597
3598  return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc);
3599}
3600
3601/// BuildResolvedCallExpr - Build a call to a resolved expression,
3602/// i.e. an expression not of \p OverloadTy.  The expression should
3603/// unary-convert to an expression of function-pointer or
3604/// block-pointer type.
3605///
3606/// \param NDecl the declaration being called, if available
3607Sema::OwningExprResult
3608Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3609                            SourceLocation LParenLoc,
3610                            Expr **Args, unsigned NumArgs,
3611                            SourceLocation RParenLoc) {
3612  FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3613
3614  // Promote the function operand.
3615  UsualUnaryConversions(Fn);
3616
3617  // Make the call expr early, before semantic checks.  This guarantees cleanup
3618  // of arguments and function on error.
3619  ExprOwningPtr<CallExpr> TheCall(this, new (Context) CallExpr(Context, Fn,
3620                                                               Args, NumArgs,
3621                                                               Context.BoolTy,
3622                                                               RParenLoc));
3623
3624  const FunctionType *FuncT;
3625  if (!Fn->getType()->isBlockPointerType()) {
3626    // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3627    // have type pointer to function".
3628    const PointerType *PT = Fn->getType()->getAs<PointerType>();
3629    if (PT == 0)
3630      return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3631        << Fn->getType() << Fn->getSourceRange());
3632    FuncT = PT->getPointeeType()->getAs<FunctionType>();
3633  } else { // This is a block call.
3634    FuncT = Fn->getType()->getAs<BlockPointerType>()->getPointeeType()->
3635                getAs<FunctionType>();
3636  }
3637  if (FuncT == 0)
3638    return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3639      << Fn->getType() << Fn->getSourceRange());
3640
3641  // Check for a valid return type
3642  if (CheckCallReturnType(FuncT->getResultType(),
3643                          Fn->getSourceRange().getBegin(), TheCall.get(),
3644                          FDecl))
3645    return ExprError();
3646
3647  // We know the result type of the call, set it.
3648  TheCall->setType(FuncT->getResultType().getNonReferenceType());
3649
3650  if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
3651    if (ConvertArgumentsForCall(&*TheCall, Fn, FDecl, Proto, Args, NumArgs,
3652                                RParenLoc))
3653      return ExprError();
3654  } else {
3655    assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
3656
3657    if (FDecl) {
3658      // Check if we have too few/too many template arguments, based
3659      // on our knowledge of the function definition.
3660      const FunctionDecl *Def = 0;
3661      if (FDecl->getBody(Def) && NumArgs != Def->param_size()) {
3662        const FunctionProtoType *Proto =
3663            Def->getType()->getAs<FunctionProtoType>();
3664        if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size())) {
3665          Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3666            << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
3667        }
3668      }
3669    }
3670
3671    // Promote the arguments (C99 6.5.2.2p6).
3672    for (unsigned i = 0; i != NumArgs; i++) {
3673      Expr *Arg = Args[i];
3674      DefaultArgumentPromotion(Arg);
3675      if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3676                              Arg->getType(),
3677                              PDiag(diag::err_call_incomplete_argument)
3678                                << Arg->getSourceRange()))
3679        return ExprError();
3680      TheCall->setArg(i, Arg);
3681    }
3682  }
3683
3684  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3685    if (!Method->isStatic())
3686      return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3687        << Fn->getSourceRange());
3688
3689  // Check for sentinels
3690  if (NDecl)
3691    DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
3692
3693  // Do special checking on direct calls to functions.
3694  if (FDecl) {
3695    if (CheckFunctionCall(FDecl, TheCall.get()))
3696      return ExprError();
3697
3698    if (unsigned BuiltinID = FDecl->getBuiltinID())
3699      return CheckBuiltinFunctionCall(BuiltinID, TheCall.take());
3700  } else if (NDecl) {
3701    if (CheckBlockCall(NDecl, TheCall.get()))
3702      return ExprError();
3703  }
3704
3705  return MaybeBindToTemporary(TheCall.take());
3706}
3707
3708Action::OwningExprResult
3709Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, TypeTy *Ty,
3710                           SourceLocation RParenLoc, ExprArg InitExpr) {
3711  assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
3712  // FIXME: put back this assert when initializers are worked out.
3713  //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
3714
3715  TypeSourceInfo *TInfo;
3716  QualType literalType = GetTypeFromParser(Ty, &TInfo);
3717  if (!TInfo)
3718    TInfo = Context.getTrivialTypeSourceInfo(literalType);
3719
3720  return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, move(InitExpr));
3721}
3722
3723Action::OwningExprResult
3724Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
3725                               SourceLocation RParenLoc, ExprArg InitExpr) {
3726  QualType literalType = TInfo->getType();
3727  Expr *literalExpr = static_cast<Expr*>(InitExpr.get());
3728
3729  if (literalType->isArrayType()) {
3730    if (literalType->isVariableArrayType())
3731      return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
3732        << SourceRange(LParenLoc, literalExpr->getSourceRange().getEnd()));
3733  } else if (!literalType->isDependentType() &&
3734             RequireCompleteType(LParenLoc, literalType,
3735                      PDiag(diag::err_typecheck_decl_incomplete_type)
3736                        << SourceRange(LParenLoc,
3737                                       literalExpr->getSourceRange().getEnd())))
3738    return ExprError();
3739
3740  InitializedEntity Entity
3741    = InitializedEntity::InitializeTemporary(literalType);
3742  InitializationKind Kind
3743    = InitializationKind::CreateCast(SourceRange(LParenLoc, RParenLoc),
3744                                     /*IsCStyleCast=*/true);
3745  InitializationSequence InitSeq(*this, Entity, Kind, &literalExpr, 1);
3746  OwningExprResult Result = InitSeq.Perform(*this, Entity, Kind,
3747                                   MultiExprArg(*this, (void**)&literalExpr, 1),
3748                                            &literalType);
3749  if (Result.isInvalid())
3750    return ExprError();
3751  InitExpr.release();
3752  literalExpr = static_cast<Expr*>(Result.get());
3753
3754  bool isFileScope = getCurFunctionOrMethodDecl() == 0;
3755  if (isFileScope) { // 6.5.2.5p3
3756    if (CheckForConstantInitializer(literalExpr, literalType))
3757      return ExprError();
3758  }
3759
3760  Result.release();
3761
3762  return Owned(new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
3763                                                 literalExpr, isFileScope));
3764}
3765
3766Action::OwningExprResult
3767Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg initlist,
3768                    SourceLocation RBraceLoc) {
3769  unsigned NumInit = initlist.size();
3770  Expr **InitList = reinterpret_cast<Expr**>(initlist.release());
3771
3772  // Semantic analysis for initializers is done by ActOnDeclarator() and
3773  // CheckInitializer() - it requires knowledge of the object being intialized.
3774
3775  InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3776                                               NumInit, RBraceLoc);
3777  E->setType(Context.VoidTy); // FIXME: just a place holder for now.
3778  return Owned(E);
3779}
3780
3781static CastExpr::CastKind getScalarCastKind(ASTContext &Context,
3782                                            QualType SrcTy, QualType DestTy) {
3783  if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
3784    return CastExpr::CK_NoOp;
3785
3786  if (SrcTy->hasPointerRepresentation()) {
3787    if (DestTy->hasPointerRepresentation())
3788      return DestTy->isObjCObjectPointerType() ?
3789                CastExpr::CK_AnyPointerToObjCPointerCast :
3790                CastExpr::CK_BitCast;
3791    if (DestTy->isIntegerType())
3792      return CastExpr::CK_PointerToIntegral;
3793  }
3794
3795  if (SrcTy->isIntegerType()) {
3796    if (DestTy->isIntegerType())
3797      return CastExpr::CK_IntegralCast;
3798    if (DestTy->hasPointerRepresentation())
3799      return CastExpr::CK_IntegralToPointer;
3800    if (DestTy->isRealFloatingType())
3801      return CastExpr::CK_IntegralToFloating;
3802  }
3803
3804  if (SrcTy->isRealFloatingType()) {
3805    if (DestTy->isRealFloatingType())
3806      return CastExpr::CK_FloatingCast;
3807    if (DestTy->isIntegerType())
3808      return CastExpr::CK_FloatingToIntegral;
3809  }
3810
3811  // FIXME: Assert here.
3812  // assert(false && "Unhandled cast combination!");
3813  return CastExpr::CK_Unknown;
3814}
3815
3816/// CheckCastTypes - Check type constraints for casting between types.
3817bool Sema::CheckCastTypes(SourceRange TyR, QualType castType, Expr *&castExpr,
3818                          CastExpr::CastKind& Kind,
3819                          CXXBaseSpecifierArray &BasePath,
3820                          bool FunctionalStyle) {
3821  if (getLangOptions().CPlusPlus)
3822    return CXXCheckCStyleCast(TyR, castType, castExpr, Kind, BasePath,
3823                              FunctionalStyle);
3824
3825  DefaultFunctionArrayLvalueConversion(castExpr);
3826
3827  // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
3828  // type needs to be scalar.
3829  if (castType->isVoidType()) {
3830    // Cast to void allows any expr type.
3831    Kind = CastExpr::CK_ToVoid;
3832    return false;
3833  }
3834
3835  if (!castType->isScalarType() && !castType->isVectorType()) {
3836    if (Context.hasSameUnqualifiedType(castType, castExpr->getType()) &&
3837        (castType->isStructureType() || castType->isUnionType())) {
3838      // GCC struct/union extension: allow cast to self.
3839      // FIXME: Check that the cast destination type is complete.
3840      Diag(TyR.getBegin(), diag::ext_typecheck_cast_nonscalar)
3841        << castType << castExpr->getSourceRange();
3842      Kind = CastExpr::CK_NoOp;
3843      return false;
3844    }
3845
3846    if (castType->isUnionType()) {
3847      // GCC cast to union extension
3848      RecordDecl *RD = castType->getAs<RecordType>()->getDecl();
3849      RecordDecl::field_iterator Field, FieldEnd;
3850      for (Field = RD->field_begin(), FieldEnd = RD->field_end();
3851           Field != FieldEnd; ++Field) {
3852        if (Context.hasSameUnqualifiedType(Field->getType(),
3853                                           castExpr->getType())) {
3854          Diag(TyR.getBegin(), diag::ext_typecheck_cast_to_union)
3855            << castExpr->getSourceRange();
3856          break;
3857        }
3858      }
3859      if (Field == FieldEnd)
3860        return Diag(TyR.getBegin(), diag::err_typecheck_cast_to_union_no_type)
3861          << castExpr->getType() << castExpr->getSourceRange();
3862      Kind = CastExpr::CK_ToUnion;
3863      return false;
3864    }
3865
3866    // Reject any other conversions to non-scalar types.
3867    return Diag(TyR.getBegin(), diag::err_typecheck_cond_expect_scalar)
3868      << castType << castExpr->getSourceRange();
3869  }
3870
3871  if (!castExpr->getType()->isScalarType() &&
3872      !castExpr->getType()->isVectorType()) {
3873    return Diag(castExpr->getLocStart(),
3874                diag::err_typecheck_expect_scalar_operand)
3875      << castExpr->getType() << castExpr->getSourceRange();
3876  }
3877
3878  if (castType->isExtVectorType())
3879    return CheckExtVectorCast(TyR, castType, castExpr, Kind);
3880
3881  if (castType->isVectorType())
3882    return CheckVectorCast(TyR, castType, castExpr->getType(), Kind);
3883  if (castExpr->getType()->isVectorType())
3884    return CheckVectorCast(TyR, castExpr->getType(), castType, Kind);
3885
3886  if (isa<ObjCSelectorExpr>(castExpr))
3887    return Diag(castExpr->getLocStart(), diag::err_cast_selector_expr);
3888
3889  if (!castType->isArithmeticType()) {
3890    QualType castExprType = castExpr->getType();
3891    if (!castExprType->isIntegralType(Context) &&
3892        castExprType->isArithmeticType())
3893      return Diag(castExpr->getLocStart(),
3894                  diag::err_cast_pointer_from_non_pointer_int)
3895        << castExprType << castExpr->getSourceRange();
3896  } else if (!castExpr->getType()->isArithmeticType()) {
3897    if (!castType->isIntegralType(Context) && castType->isArithmeticType())
3898      return Diag(castExpr->getLocStart(),
3899                  diag::err_cast_pointer_to_non_pointer_int)
3900        << castType << castExpr->getSourceRange();
3901  }
3902
3903  Kind = getScalarCastKind(Context, castExpr->getType(), castType);
3904  return false;
3905}
3906
3907bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
3908                           CastExpr::CastKind &Kind) {
3909  assert(VectorTy->isVectorType() && "Not a vector type!");
3910
3911  if (Ty->isVectorType() || Ty->isIntegerType()) {
3912    if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
3913      return Diag(R.getBegin(),
3914                  Ty->isVectorType() ?
3915                  diag::err_invalid_conversion_between_vectors :
3916                  diag::err_invalid_conversion_between_vector_and_integer)
3917        << VectorTy << Ty << R;
3918  } else
3919    return Diag(R.getBegin(),
3920                diag::err_invalid_conversion_between_vector_and_scalar)
3921      << VectorTy << Ty << R;
3922
3923  Kind = CastExpr::CK_BitCast;
3924  return false;
3925}
3926
3927bool Sema::CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *&CastExpr,
3928                              CastExpr::CastKind &Kind) {
3929  assert(DestTy->isExtVectorType() && "Not an extended vector type!");
3930
3931  QualType SrcTy = CastExpr->getType();
3932
3933  // If SrcTy is a VectorType, the total size must match to explicitly cast to
3934  // an ExtVectorType.
3935  if (SrcTy->isVectorType()) {
3936    if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy))
3937      return Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
3938        << DestTy << SrcTy << R;
3939    Kind = CastExpr::CK_BitCast;
3940    return false;
3941  }
3942
3943  // All non-pointer scalars can be cast to ExtVector type.  The appropriate
3944  // conversion will take place first from scalar to elt type, and then
3945  // splat from elt type to vector.
3946  if (SrcTy->isPointerType())
3947    return Diag(R.getBegin(),
3948                diag::err_invalid_conversion_between_vector_and_scalar)
3949      << DestTy << SrcTy << R;
3950
3951  QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
3952  ImpCastExprToType(CastExpr, DestElemTy,
3953                    getScalarCastKind(Context, SrcTy, DestElemTy));
3954
3955  Kind = CastExpr::CK_VectorSplat;
3956  return false;
3957}
3958
3959Action::OwningExprResult
3960Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc, TypeTy *Ty,
3961                    SourceLocation RParenLoc, ExprArg Op) {
3962  assert((Ty != 0) && (Op.get() != 0) &&
3963         "ActOnCastExpr(): missing type or expr");
3964
3965  TypeSourceInfo *castTInfo;
3966  QualType castType = GetTypeFromParser(Ty, &castTInfo);
3967  if (!castTInfo)
3968    castTInfo = Context.getTrivialTypeSourceInfo(castType);
3969
3970  // If the Expr being casted is a ParenListExpr, handle it specially.
3971  Expr *castExpr = (Expr *)Op.get();
3972  if (isa<ParenListExpr>(castExpr))
3973    return ActOnCastOfParenListExpr(S, LParenLoc, RParenLoc, move(Op),
3974                                    castTInfo);
3975
3976  return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, move(Op));
3977}
3978
3979Action::OwningExprResult
3980Sema::BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty,
3981                          SourceLocation RParenLoc, ExprArg Op) {
3982  Expr *castExpr = static_cast<Expr*>(Op.get());
3983
3984  CastExpr::CastKind Kind = CastExpr::CK_Unknown;
3985  CXXBaseSpecifierArray BasePath;
3986  if (CheckCastTypes(SourceRange(LParenLoc, RParenLoc), Ty->getType(), castExpr,
3987                     Kind, BasePath))
3988    return ExprError();
3989
3990  Op.release();
3991  return Owned(new (Context) CStyleCastExpr(Ty->getType().getNonReferenceType(),
3992                                            Kind, castExpr, BasePath, Ty,
3993                                            LParenLoc, RParenLoc));
3994}
3995
3996/// This is not an AltiVec-style cast, so turn the ParenListExpr into a sequence
3997/// of comma binary operators.
3998Action::OwningExprResult
3999Sema::MaybeConvertParenListExprToParenExpr(Scope *S, ExprArg EA) {
4000  Expr *expr = EA.takeAs<Expr>();
4001  ParenListExpr *E = dyn_cast<ParenListExpr>(expr);
4002  if (!E)
4003    return Owned(expr);
4004
4005  OwningExprResult Result(*this, E->getExpr(0));
4006
4007  for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
4008    Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, move(Result),
4009                        Owned(E->getExpr(i)));
4010
4011  return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), move(Result));
4012}
4013
4014Action::OwningExprResult
4015Sema::ActOnCastOfParenListExpr(Scope *S, SourceLocation LParenLoc,
4016                               SourceLocation RParenLoc, ExprArg Op,
4017                               TypeSourceInfo *TInfo) {
4018  ParenListExpr *PE = (ParenListExpr *)Op.get();
4019  QualType Ty = TInfo->getType();
4020  bool isAltiVecLiteral = false;
4021
4022  // Check for an altivec literal,
4023  // i.e. all the elements are integer constants.
4024  if (getLangOptions().AltiVec && Ty->isVectorType()) {
4025    if (PE->getNumExprs() == 0) {
4026      Diag(PE->getExprLoc(), diag::err_altivec_empty_initializer);
4027      return ExprError();
4028    }
4029    if (PE->getNumExprs() == 1) {
4030      if (!PE->getExpr(0)->getType()->isVectorType())
4031        isAltiVecLiteral = true;
4032    }
4033    else
4034      isAltiVecLiteral = true;
4035  }
4036
4037  // If this is an altivec initializer, '(' type ')' '(' init, ..., init ')'
4038  // then handle it as such.
4039  if (isAltiVecLiteral) {
4040    llvm::SmallVector<Expr *, 8> initExprs;
4041    for (unsigned i = 0, e = PE->getNumExprs(); i != e; ++i)
4042      initExprs.push_back(PE->getExpr(i));
4043
4044    // FIXME: This means that pretty-printing the final AST will produce curly
4045    // braces instead of the original commas.
4046    Op.release();
4047    InitListExpr *E = new (Context) InitListExpr(Context, LParenLoc,
4048                                                 &initExprs[0],
4049                                                 initExprs.size(), RParenLoc);
4050    E->setType(Ty);
4051    return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, Owned(E));
4052  } else {
4053    // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4054    // sequence of BinOp comma operators.
4055    Op = MaybeConvertParenListExprToParenExpr(S, move(Op));
4056    return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, move(Op));
4057  }
4058}
4059
4060Action::OwningExprResult Sema::ActOnParenOrParenListExpr(SourceLocation L,
4061                                                  SourceLocation R,
4062                                                  MultiExprArg Val,
4063                                                  TypeTy *TypeOfCast) {
4064  unsigned nexprs = Val.size();
4065  Expr **exprs = reinterpret_cast<Expr**>(Val.release());
4066  assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
4067  Expr *expr;
4068  if (nexprs == 1 && TypeOfCast && !TypeIsVectorType(TypeOfCast))
4069    expr = new (Context) ParenExpr(L, R, exprs[0]);
4070  else
4071    expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
4072  return Owned(expr);
4073}
4074
4075/// Note that lhs is not null here, even if this is the gnu "x ?: y" extension.
4076/// In that case, lhs = cond.
4077/// C99 6.5.15
4078QualType Sema::CheckConditionalOperands(Expr *&Cond, Expr *&LHS, Expr *&RHS,
4079                                        SourceLocation QuestionLoc) {
4080  // C++ is sufficiently different to merit its own checker.
4081  if (getLangOptions().CPlusPlus)
4082    return CXXCheckConditionalOperands(Cond, LHS, RHS, QuestionLoc);
4083
4084  UsualUnaryConversions(Cond);
4085  UsualUnaryConversions(LHS);
4086  UsualUnaryConversions(RHS);
4087  QualType CondTy = Cond->getType();
4088  QualType LHSTy = LHS->getType();
4089  QualType RHSTy = RHS->getType();
4090
4091  // first, check the condition.
4092  if (!CondTy->isScalarType()) { // C99 6.5.15p2
4093    Diag(Cond->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4094      << CondTy;
4095    return QualType();
4096  }
4097
4098  // Now check the two expressions.
4099  if (LHSTy->isVectorType() || RHSTy->isVectorType())
4100    return CheckVectorOperands(QuestionLoc, LHS, RHS);
4101
4102  // If both operands have arithmetic type, do the usual arithmetic conversions
4103  // to find a common type: C99 6.5.15p3,5.
4104  if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4105    UsualArithmeticConversions(LHS, RHS);
4106    return LHS->getType();
4107  }
4108
4109  // If both operands are the same structure or union type, the result is that
4110  // type.
4111  if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) {    // C99 6.5.15p3
4112    if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
4113      if (LHSRT->getDecl() == RHSRT->getDecl())
4114        // "If both the operands have structure or union type, the result has
4115        // that type."  This implies that CV qualifiers are dropped.
4116        return LHSTy.getUnqualifiedType();
4117    // FIXME: Type of conditional expression must be complete in C mode.
4118  }
4119
4120  // C99 6.5.15p5: "If both operands have void type, the result has void type."
4121  // The following || allows only one side to be void (a GCC-ism).
4122  if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
4123    if (!LHSTy->isVoidType())
4124      Diag(RHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4125        << RHS->getSourceRange();
4126    if (!RHSTy->isVoidType())
4127      Diag(LHS->getLocStart(), diag::ext_typecheck_cond_one_void)
4128        << LHS->getSourceRange();
4129    ImpCastExprToType(LHS, Context.VoidTy, CastExpr::CK_ToVoid);
4130    ImpCastExprToType(RHS, Context.VoidTy, CastExpr::CK_ToVoid);
4131    return Context.VoidTy;
4132  }
4133  // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4134  // the type of the other operand."
4135  if ((LHSTy->isAnyPointerType() || LHSTy->isBlockPointerType()) &&
4136      RHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4137    // promote the null to a pointer.
4138    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_Unknown);
4139    return LHSTy;
4140  }
4141  if ((RHSTy->isAnyPointerType() || RHSTy->isBlockPointerType()) &&
4142      LHS->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
4143    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_Unknown);
4144    return RHSTy;
4145  }
4146
4147  // All objective-c pointer type analysis is done here.
4148  QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4149                                                        QuestionLoc);
4150  if (!compositeType.isNull())
4151    return compositeType;
4152
4153
4154  // Handle block pointer types.
4155  if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType()) {
4156    if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4157      if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4158        QualType destType = Context.getPointerType(Context.VoidTy);
4159        ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4160        ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4161        return destType;
4162      }
4163      Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4164      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4165      return QualType();
4166    }
4167    // We have 2 block pointer types.
4168    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4169      // Two identical block pointer types are always compatible.
4170      return LHSTy;
4171    }
4172    // The block pointer types aren't identical, continue checking.
4173    QualType lhptee = LHSTy->getAs<BlockPointerType>()->getPointeeType();
4174    QualType rhptee = RHSTy->getAs<BlockPointerType>()->getPointeeType();
4175
4176    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4177                                    rhptee.getUnqualifiedType())) {
4178      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4179      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4180      // In this situation, we assume void* type. No especially good
4181      // reason, but this is what gcc does, and we do have to pick
4182      // to get a consistent AST.
4183      QualType incompatTy = Context.getPointerType(Context.VoidTy);
4184      ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4185      ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4186      return incompatTy;
4187    }
4188    // The block pointer types are compatible.
4189    ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4190    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4191    return LHSTy;
4192  }
4193
4194  // Check constraints for C object pointers types (C99 6.5.15p3,6).
4195  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4196    // get the "pointed to" types
4197    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4198    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4199
4200    // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4201    if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4202      // Figure out necessary qualifiers (C99 6.5.15p6)
4203      QualType destPointee
4204        = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4205      QualType destType = Context.getPointerType(destPointee);
4206      // Add qualifiers if necessary.
4207      ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4208      // Promote to void*.
4209      ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4210      return destType;
4211    }
4212    if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4213      QualType destPointee
4214        = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4215      QualType destType = Context.getPointerType(destPointee);
4216      // Add qualifiers if necessary.
4217      ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4218      // Promote to void*.
4219      ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4220      return destType;
4221    }
4222
4223    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4224      // Two identical pointer types are always compatible.
4225      return LHSTy;
4226    }
4227    if (!Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4228                                    rhptee.getUnqualifiedType())) {
4229      Diag(QuestionLoc, diag::warn_typecheck_cond_incompatible_pointers)
4230        << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4231      // In this situation, we assume void* type. No especially good
4232      // reason, but this is what gcc does, and we do have to pick
4233      // to get a consistent AST.
4234      QualType incompatTy = Context.getPointerType(Context.VoidTy);
4235      ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4236      ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4237      return incompatTy;
4238    }
4239    // The pointer types are compatible.
4240    // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4241    // differently qualified versions of compatible types, the result type is
4242    // a pointer to an appropriately qualified version of the *composite*
4243    // type.
4244    // FIXME: Need to calculate the composite type.
4245    // FIXME: Need to add qualifiers
4246    ImpCastExprToType(LHS, LHSTy, CastExpr::CK_BitCast);
4247    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4248    return LHSTy;
4249  }
4250
4251  // GCC compatibility: soften pointer/integer mismatch.
4252  if (RHSTy->isPointerType() && LHSTy->isIntegerType()) {
4253    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4254      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4255    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_IntegralToPointer);
4256    return RHSTy;
4257  }
4258  if (LHSTy->isPointerType() && RHSTy->isIntegerType()) {
4259    Diag(QuestionLoc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4260      << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4261    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_IntegralToPointer);
4262    return LHSTy;
4263  }
4264
4265  // Otherwise, the operands are not compatible.
4266  Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
4267    << LHSTy << RHSTy << LHS->getSourceRange() << RHS->getSourceRange();
4268  return QualType();
4269}
4270
4271/// FindCompositeObjCPointerType - Helper method to find composite type of
4272/// two objective-c pointer types of the two input expressions.
4273QualType Sema::FindCompositeObjCPointerType(Expr *&LHS, Expr *&RHS,
4274                                        SourceLocation QuestionLoc) {
4275  QualType LHSTy = LHS->getType();
4276  QualType RHSTy = RHS->getType();
4277
4278  // Handle things like Class and struct objc_class*.  Here we case the result
4279  // to the pseudo-builtin, because that will be implicitly cast back to the
4280  // redefinition type if an attempt is made to access its fields.
4281  if (LHSTy->isObjCClassType() &&
4282      (RHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4283    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4284    return LHSTy;
4285  }
4286  if (RHSTy->isObjCClassType() &&
4287      (LHSTy.getDesugaredType() == Context.ObjCClassRedefinitionType)) {
4288    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4289    return RHSTy;
4290  }
4291  // And the same for struct objc_object* / id
4292  if (LHSTy->isObjCIdType() &&
4293      (RHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4294    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4295    return LHSTy;
4296  }
4297  if (RHSTy->isObjCIdType() &&
4298      (LHSTy.getDesugaredType() == Context.ObjCIdRedefinitionType)) {
4299    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4300    return RHSTy;
4301  }
4302  // And the same for struct objc_selector* / SEL
4303  if (Context.isObjCSelType(LHSTy) &&
4304      (RHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4305    ImpCastExprToType(RHS, LHSTy, CastExpr::CK_BitCast);
4306    return LHSTy;
4307  }
4308  if (Context.isObjCSelType(RHSTy) &&
4309      (LHSTy.getDesugaredType() == Context.ObjCSelRedefinitionType)) {
4310    ImpCastExprToType(LHS, RHSTy, CastExpr::CK_BitCast);
4311    return RHSTy;
4312  }
4313  // Check constraints for Objective-C object pointers types.
4314  if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
4315
4316    if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4317      // Two identical object pointer types are always compatible.
4318      return LHSTy;
4319    }
4320    const ObjCObjectPointerType *LHSOPT = LHSTy->getAs<ObjCObjectPointerType>();
4321    const ObjCObjectPointerType *RHSOPT = RHSTy->getAs<ObjCObjectPointerType>();
4322    QualType compositeType = LHSTy;
4323
4324    // If both operands are interfaces and either operand can be
4325    // assigned to the other, use that type as the composite
4326    // type. This allows
4327    //   xxx ? (A*) a : (B*) b
4328    // where B is a subclass of A.
4329    //
4330    // Additionally, as for assignment, if either type is 'id'
4331    // allow silent coercion. Finally, if the types are
4332    // incompatible then make sure to use 'id' as the composite
4333    // type so the result is acceptable for sending messages to.
4334
4335    // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4336    // It could return the composite type.
4337    if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4338      compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4339    } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4340      compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4341    } else if ((LHSTy->isObjCQualifiedIdType() ||
4342                RHSTy->isObjCQualifiedIdType()) &&
4343               Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4344      // Need to handle "id<xx>" explicitly.
4345      // GCC allows qualified id and any Objective-C type to devolve to
4346      // id. Currently localizing to here until clear this should be
4347      // part of ObjCQualifiedIdTypesAreCompatible.
4348      compositeType = Context.getObjCIdType();
4349    } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4350      compositeType = Context.getObjCIdType();
4351    } else if (!(compositeType =
4352                 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4353      ;
4354    else {
4355      Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4356      << LHSTy << RHSTy
4357      << LHS->getSourceRange() << RHS->getSourceRange();
4358      QualType incompatTy = Context.getObjCIdType();
4359      ImpCastExprToType(LHS, incompatTy, CastExpr::CK_BitCast);
4360      ImpCastExprToType(RHS, incompatTy, CastExpr::CK_BitCast);
4361      return incompatTy;
4362    }
4363    // The object pointer types are compatible.
4364    ImpCastExprToType(LHS, compositeType, CastExpr::CK_BitCast);
4365    ImpCastExprToType(RHS, compositeType, CastExpr::CK_BitCast);
4366    return compositeType;
4367  }
4368  // Check Objective-C object pointer types and 'void *'
4369  if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
4370    QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4371    QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4372    QualType destPointee
4373    = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4374    QualType destType = Context.getPointerType(destPointee);
4375    // Add qualifiers if necessary.
4376    ImpCastExprToType(LHS, destType, CastExpr::CK_NoOp);
4377    // Promote to void*.
4378    ImpCastExprToType(RHS, destType, CastExpr::CK_BitCast);
4379    return destType;
4380  }
4381  if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
4382    QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4383    QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4384    QualType destPointee
4385    = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4386    QualType destType = Context.getPointerType(destPointee);
4387    // Add qualifiers if necessary.
4388    ImpCastExprToType(RHS, destType, CastExpr::CK_NoOp);
4389    // Promote to void*.
4390    ImpCastExprToType(LHS, destType, CastExpr::CK_BitCast);
4391    return destType;
4392  }
4393  return QualType();
4394}
4395
4396/// ActOnConditionalOp - Parse a ?: operation.  Note that 'LHS' may be null
4397/// in the case of a the GNU conditional expr extension.
4398Action::OwningExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
4399                                                  SourceLocation ColonLoc,
4400                                                  ExprArg Cond, ExprArg LHS,
4401                                                  ExprArg RHS) {
4402  Expr *CondExpr = (Expr *) Cond.get();
4403  Expr *LHSExpr = (Expr *) LHS.get(), *RHSExpr = (Expr *) RHS.get();
4404
4405  // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4406  // was the condition.
4407  bool isLHSNull = LHSExpr == 0;
4408  if (isLHSNull)
4409    LHSExpr = CondExpr;
4410
4411  QualType result = CheckConditionalOperands(CondExpr, LHSExpr,
4412                                             RHSExpr, QuestionLoc);
4413  if (result.isNull())
4414    return ExprError();
4415
4416  Cond.release();
4417  LHS.release();
4418  RHS.release();
4419  return Owned(new (Context) ConditionalOperator(CondExpr, QuestionLoc,
4420                                                 isLHSNull ? 0 : LHSExpr,
4421                                                 ColonLoc, RHSExpr, result));
4422}
4423
4424// CheckPointerTypesForAssignment - This is a very tricky routine (despite
4425// being closely modeled after the C99 spec:-). The odd characteristic of this
4426// routine is it effectively iqnores the qualifiers on the top level pointee.
4427// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
4428// FIXME: add a couple examples in this comment.
4429Sema::AssignConvertType
4430Sema::CheckPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4431  QualType lhptee, rhptee;
4432
4433  if ((lhsType->isObjCClassType() &&
4434       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4435     (rhsType->isObjCClassType() &&
4436       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4437      return Compatible;
4438  }
4439
4440  // get the "pointed to" type (ignoring qualifiers at the top level)
4441  lhptee = lhsType->getAs<PointerType>()->getPointeeType();
4442  rhptee = rhsType->getAs<PointerType>()->getPointeeType();
4443
4444  // make sure we operate on the canonical type
4445  lhptee = Context.getCanonicalType(lhptee);
4446  rhptee = Context.getCanonicalType(rhptee);
4447
4448  AssignConvertType ConvTy = Compatible;
4449
4450  // C99 6.5.16.1p1: This following citation is common to constraints
4451  // 3 & 4 (below). ...and the type *pointed to* by the left has all the
4452  // qualifiers of the type *pointed to* by the right;
4453  // FIXME: Handle ExtQualType
4454  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4455    ConvTy = CompatiblePointerDiscardsQualifiers;
4456
4457  // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
4458  // incomplete type and the other is a pointer to a qualified or unqualified
4459  // version of void...
4460  if (lhptee->isVoidType()) {
4461    if (rhptee->isIncompleteOrObjectType())
4462      return ConvTy;
4463
4464    // As an extension, we allow cast to/from void* to function pointer.
4465    assert(rhptee->isFunctionType());
4466    return FunctionVoidPointer;
4467  }
4468
4469  if (rhptee->isVoidType()) {
4470    if (lhptee->isIncompleteOrObjectType())
4471      return ConvTy;
4472
4473    // As an extension, we allow cast to/from void* to function pointer.
4474    assert(lhptee->isFunctionType());
4475    return FunctionVoidPointer;
4476  }
4477  // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
4478  // unqualified versions of compatible types, ...
4479  lhptee = lhptee.getUnqualifiedType();
4480  rhptee = rhptee.getUnqualifiedType();
4481  if (!Context.typesAreCompatible(lhptee, rhptee)) {
4482    // Check if the pointee types are compatible ignoring the sign.
4483    // We explicitly check for char so that we catch "char" vs
4484    // "unsigned char" on systems where "char" is unsigned.
4485    if (lhptee->isCharType())
4486      lhptee = Context.UnsignedCharTy;
4487    else if (lhptee->isSignedIntegerType())
4488      lhptee = Context.getCorrespondingUnsignedType(lhptee);
4489
4490    if (rhptee->isCharType())
4491      rhptee = Context.UnsignedCharTy;
4492    else if (rhptee->isSignedIntegerType())
4493      rhptee = Context.getCorrespondingUnsignedType(rhptee);
4494
4495    if (lhptee == rhptee) {
4496      // Types are compatible ignoring the sign. Qualifier incompatibility
4497      // takes priority over sign incompatibility because the sign
4498      // warning can be disabled.
4499      if (ConvTy != Compatible)
4500        return ConvTy;
4501      return IncompatiblePointerSign;
4502    }
4503
4504    // If we are a multi-level pointer, it's possible that our issue is simply
4505    // one of qualification - e.g. char ** -> const char ** is not allowed. If
4506    // the eventual target type is the same and the pointers have the same
4507    // level of indirection, this must be the issue.
4508    if (lhptee->isPointerType() && rhptee->isPointerType()) {
4509      do {
4510        lhptee = lhptee->getAs<PointerType>()->getPointeeType();
4511        rhptee = rhptee->getAs<PointerType>()->getPointeeType();
4512
4513        lhptee = Context.getCanonicalType(lhptee);
4514        rhptee = Context.getCanonicalType(rhptee);
4515      } while (lhptee->isPointerType() && rhptee->isPointerType());
4516
4517      if (Context.hasSameUnqualifiedType(lhptee, rhptee))
4518        return IncompatibleNestedPointerQualifiers;
4519    }
4520
4521    // General pointer incompatibility takes priority over qualifiers.
4522    return IncompatiblePointer;
4523  }
4524  return ConvTy;
4525}
4526
4527/// CheckBlockPointerTypesForAssignment - This routine determines whether two
4528/// block pointer types are compatible or whether a block and normal pointer
4529/// are compatible. It is more restrict than comparing two function pointer
4530// types.
4531Sema::AssignConvertType
4532Sema::CheckBlockPointerTypesForAssignment(QualType lhsType,
4533                                          QualType rhsType) {
4534  QualType lhptee, rhptee;
4535
4536  // get the "pointed to" type (ignoring qualifiers at the top level)
4537  lhptee = lhsType->getAs<BlockPointerType>()->getPointeeType();
4538  rhptee = rhsType->getAs<BlockPointerType>()->getPointeeType();
4539
4540  // make sure we operate on the canonical type
4541  lhptee = Context.getCanonicalType(lhptee);
4542  rhptee = Context.getCanonicalType(rhptee);
4543
4544  AssignConvertType ConvTy = Compatible;
4545
4546  // For blocks we enforce that qualifiers are identical.
4547  if (lhptee.getLocalCVRQualifiers() != rhptee.getLocalCVRQualifiers())
4548    ConvTy = CompatiblePointerDiscardsQualifiers;
4549
4550  if (!getLangOptions().CPlusPlus) {
4551    if (!Context.typesAreBlockPointerCompatible(lhsType, rhsType))
4552      return IncompatibleBlockPointer;
4553  }
4554  else if (!Context.typesAreCompatible(lhptee, rhptee))
4555    return IncompatibleBlockPointer;
4556  return ConvTy;
4557}
4558
4559/// CheckObjCPointerTypesForAssignment - Compares two objective-c pointer types
4560/// for assignment compatibility.
4561Sema::AssignConvertType
4562Sema::CheckObjCPointerTypesForAssignment(QualType lhsType, QualType rhsType) {
4563  if (lhsType->isObjCBuiltinType()) {
4564    // Class is not compatible with ObjC object pointers.
4565    if (lhsType->isObjCClassType() && !rhsType->isObjCBuiltinType() &&
4566        !rhsType->isObjCQualifiedClassType())
4567      return IncompatiblePointer;
4568    return Compatible;
4569  }
4570  if (rhsType->isObjCBuiltinType()) {
4571    // Class is not compatible with ObjC object pointers.
4572    if (rhsType->isObjCClassType() && !lhsType->isObjCBuiltinType() &&
4573        !lhsType->isObjCQualifiedClassType())
4574      return IncompatiblePointer;
4575    return Compatible;
4576  }
4577  QualType lhptee =
4578  lhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4579  QualType rhptee =
4580  rhsType->getAs<ObjCObjectPointerType>()->getPointeeType();
4581  // make sure we operate on the canonical type
4582  lhptee = Context.getCanonicalType(lhptee);
4583  rhptee = Context.getCanonicalType(rhptee);
4584  if (!lhptee.isAtLeastAsQualifiedAs(rhptee))
4585    return CompatiblePointerDiscardsQualifiers;
4586
4587  if (Context.typesAreCompatible(lhsType, rhsType))
4588    return Compatible;
4589  if (lhsType->isObjCQualifiedIdType() || rhsType->isObjCQualifiedIdType())
4590    return IncompatibleObjCQualifiedId;
4591  return IncompatiblePointer;
4592}
4593
4594/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
4595/// has code to accommodate several GCC extensions when type checking
4596/// pointers. Here are some objectionable examples that GCC considers warnings:
4597///
4598///  int a, *pint;
4599///  short *pshort;
4600///  struct foo *pfoo;
4601///
4602///  pint = pshort; // warning: assignment from incompatible pointer type
4603///  a = pint; // warning: assignment makes integer from pointer without a cast
4604///  pint = a; // warning: assignment makes pointer from integer without a cast
4605///  pint = pfoo; // warning: assignment from incompatible pointer type
4606///
4607/// As a result, the code for dealing with pointers is more complex than the
4608/// C99 spec dictates.
4609///
4610Sema::AssignConvertType
4611Sema::CheckAssignmentConstraints(QualType lhsType, QualType rhsType) {
4612  // Get canonical types.  We're not formatting these types, just comparing
4613  // them.
4614  lhsType = Context.getCanonicalType(lhsType).getUnqualifiedType();
4615  rhsType = Context.getCanonicalType(rhsType).getUnqualifiedType();
4616
4617  if (lhsType == rhsType)
4618    return Compatible; // Common case: fast path an exact match.
4619
4620  if ((lhsType->isObjCClassType() &&
4621       (rhsType.getDesugaredType() == Context.ObjCClassRedefinitionType)) ||
4622     (rhsType->isObjCClassType() &&
4623       (lhsType.getDesugaredType() == Context.ObjCClassRedefinitionType))) {
4624      return Compatible;
4625  }
4626
4627  // If the left-hand side is a reference type, then we are in a
4628  // (rare!) case where we've allowed the use of references in C,
4629  // e.g., as a parameter type in a built-in function. In this case,
4630  // just make sure that the type referenced is compatible with the
4631  // right-hand side type. The caller is responsible for adjusting
4632  // lhsType so that the resulting expression does not have reference
4633  // type.
4634  if (const ReferenceType *lhsTypeRef = lhsType->getAs<ReferenceType>()) {
4635    if (Context.typesAreCompatible(lhsTypeRef->getPointeeType(), rhsType))
4636      return Compatible;
4637    return Incompatible;
4638  }
4639  // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
4640  // to the same ExtVector type.
4641  if (lhsType->isExtVectorType()) {
4642    if (rhsType->isExtVectorType())
4643      return lhsType == rhsType ? Compatible : Incompatible;
4644    if (rhsType->isArithmeticType())
4645      return Compatible;
4646  }
4647
4648  if (lhsType->isVectorType() || rhsType->isVectorType()) {
4649    // If we are allowing lax vector conversions, and LHS and RHS are both
4650    // vectors, the total size only needs to be the same. This is a bitcast;
4651    // no bits are changed but the result type is different.
4652    if (getLangOptions().LaxVectorConversions &&
4653        lhsType->isVectorType() && rhsType->isVectorType()) {
4654      if (Context.getTypeSize(lhsType) == Context.getTypeSize(rhsType))
4655        return IncompatibleVectors;
4656    }
4657    return Incompatible;
4658  }
4659
4660  if (lhsType->isArithmeticType() && rhsType->isArithmeticType() &&
4661      !(getLangOptions().CPlusPlus && lhsType->isEnumeralType()))
4662    return Compatible;
4663
4664  if (isa<PointerType>(lhsType)) {
4665    if (rhsType->isIntegerType())
4666      return IntToPointer;
4667
4668    if (isa<PointerType>(rhsType))
4669      return CheckPointerTypesForAssignment(lhsType, rhsType);
4670
4671    // In general, C pointers are not compatible with ObjC object pointers.
4672    if (isa<ObjCObjectPointerType>(rhsType)) {
4673      if (lhsType->isVoidPointerType()) // an exception to the rule.
4674        return Compatible;
4675      return IncompatiblePointer;
4676    }
4677    if (rhsType->getAs<BlockPointerType>()) {
4678      if (lhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4679        return Compatible;
4680
4681      // Treat block pointers as objects.
4682      if (getLangOptions().ObjC1 && lhsType->isObjCIdType())
4683        return Compatible;
4684    }
4685    return Incompatible;
4686  }
4687
4688  if (isa<BlockPointerType>(lhsType)) {
4689    if (rhsType->isIntegerType())
4690      return IntToBlockPointer;
4691
4692    // Treat block pointers as objects.
4693    if (getLangOptions().ObjC1 && rhsType->isObjCIdType())
4694      return Compatible;
4695
4696    if (rhsType->isBlockPointerType())
4697      return CheckBlockPointerTypesForAssignment(lhsType, rhsType);
4698
4699    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
4700      if (RHSPT->getPointeeType()->isVoidType())
4701        return Compatible;
4702    }
4703    return Incompatible;
4704  }
4705
4706  if (isa<ObjCObjectPointerType>(lhsType)) {
4707    if (rhsType->isIntegerType())
4708      return IntToPointer;
4709
4710    // In general, C pointers are not compatible with ObjC object pointers.
4711    if (isa<PointerType>(rhsType)) {
4712      if (rhsType->isVoidPointerType()) // an exception to the rule.
4713        return Compatible;
4714      return IncompatiblePointer;
4715    }
4716    if (rhsType->isObjCObjectPointerType()) {
4717      return CheckObjCPointerTypesForAssignment(lhsType, rhsType);
4718    }
4719    if (const PointerType *RHSPT = rhsType->getAs<PointerType>()) {
4720      if (RHSPT->getPointeeType()->isVoidType())
4721        return Compatible;
4722    }
4723    // Treat block pointers as objects.
4724    if (rhsType->isBlockPointerType())
4725      return Compatible;
4726    return Incompatible;
4727  }
4728  if (isa<PointerType>(rhsType)) {
4729    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4730    if (lhsType == Context.BoolTy)
4731      return Compatible;
4732
4733    if (lhsType->isIntegerType())
4734      return PointerToInt;
4735
4736    if (isa<PointerType>(lhsType))
4737      return CheckPointerTypesForAssignment(lhsType, rhsType);
4738
4739    if (isa<BlockPointerType>(lhsType) &&
4740        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4741      return Compatible;
4742    return Incompatible;
4743  }
4744  if (isa<ObjCObjectPointerType>(rhsType)) {
4745    // C99 6.5.16.1p1: the left operand is _Bool and the right is a pointer.
4746    if (lhsType == Context.BoolTy)
4747      return Compatible;
4748
4749    if (lhsType->isIntegerType())
4750      return PointerToInt;
4751
4752    // In general, C pointers are not compatible with ObjC object pointers.
4753    if (isa<PointerType>(lhsType)) {
4754      if (lhsType->isVoidPointerType()) // an exception to the rule.
4755        return Compatible;
4756      return IncompatiblePointer;
4757    }
4758    if (isa<BlockPointerType>(lhsType) &&
4759        rhsType->getAs<PointerType>()->getPointeeType()->isVoidType())
4760      return Compatible;
4761    return Incompatible;
4762  }
4763
4764  if (isa<TagType>(lhsType) && isa<TagType>(rhsType)) {
4765    if (Context.typesAreCompatible(lhsType, rhsType))
4766      return Compatible;
4767  }
4768  return Incompatible;
4769}
4770
4771/// \brief Constructs a transparent union from an expression that is
4772/// used to initialize the transparent union.
4773static void ConstructTransparentUnion(ASTContext &C, Expr *&E,
4774                                      QualType UnionType, FieldDecl *Field) {
4775  // Build an initializer list that designates the appropriate member
4776  // of the transparent union.
4777  InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
4778                                                   &E, 1,
4779                                                   SourceLocation());
4780  Initializer->setType(UnionType);
4781  Initializer->setInitializedFieldInUnion(Field);
4782
4783  // Build a compound literal constructing a value of the transparent
4784  // union type from this initializer list.
4785  TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
4786  E = new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
4787                                  Initializer, false);
4788}
4789
4790Sema::AssignConvertType
4791Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType, Expr *&rExpr) {
4792  QualType FromType = rExpr->getType();
4793
4794  // If the ArgType is a Union type, we want to handle a potential
4795  // transparent_union GCC extension.
4796  const RecordType *UT = ArgType->getAsUnionType();
4797  if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
4798    return Incompatible;
4799
4800  // The field to initialize within the transparent union.
4801  RecordDecl *UD = UT->getDecl();
4802  FieldDecl *InitField = 0;
4803  // It's compatible if the expression matches any of the fields.
4804  for (RecordDecl::field_iterator it = UD->field_begin(),
4805         itend = UD->field_end();
4806       it != itend; ++it) {
4807    if (it->getType()->isPointerType()) {
4808      // If the transparent union contains a pointer type, we allow:
4809      // 1) void pointer
4810      // 2) null pointer constant
4811      if (FromType->isPointerType())
4812        if (FromType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
4813          ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_BitCast);
4814          InitField = *it;
4815          break;
4816        }
4817
4818      if (rExpr->isNullPointerConstant(Context,
4819                                       Expr::NPC_ValueDependentIsNull)) {
4820        ImpCastExprToType(rExpr, it->getType(), CastExpr::CK_IntegralToPointer);
4821        InitField = *it;
4822        break;
4823      }
4824    }
4825
4826    if (CheckAssignmentConstraints(it->getType(), rExpr->getType())
4827          == Compatible) {
4828      InitField = *it;
4829      break;
4830    }
4831  }
4832
4833  if (!InitField)
4834    return Incompatible;
4835
4836  ConstructTransparentUnion(Context, rExpr, ArgType, InitField);
4837  return Compatible;
4838}
4839
4840Sema::AssignConvertType
4841Sema::CheckSingleAssignmentConstraints(QualType lhsType, Expr *&rExpr) {
4842  if (getLangOptions().CPlusPlus) {
4843    if (!lhsType->isRecordType()) {
4844      // C++ 5.17p3: If the left operand is not of class type, the
4845      // expression is implicitly converted (C++ 4) to the
4846      // cv-unqualified type of the left operand.
4847      if (PerformImplicitConversion(rExpr, lhsType.getUnqualifiedType(),
4848                                    AA_Assigning))
4849        return Incompatible;
4850      return Compatible;
4851    }
4852
4853    // FIXME: Currently, we fall through and treat C++ classes like C
4854    // structures.
4855  }
4856
4857  // C99 6.5.16.1p1: the left operand is a pointer and the right is
4858  // a null pointer constant.
4859  if ((lhsType->isPointerType() ||
4860       lhsType->isObjCObjectPointerType() ||
4861       lhsType->isBlockPointerType())
4862      && rExpr->isNullPointerConstant(Context,
4863                                      Expr::NPC_ValueDependentIsNull)) {
4864    ImpCastExprToType(rExpr, lhsType, CastExpr::CK_Unknown);
4865    return Compatible;
4866  }
4867
4868  // This check seems unnatural, however it is necessary to ensure the proper
4869  // conversion of functions/arrays. If the conversion were done for all
4870  // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
4871  // expressions that surpress this implicit conversion (&, sizeof).
4872  //
4873  // Suppress this for references: C++ 8.5.3p5.
4874  if (!lhsType->isReferenceType())
4875    DefaultFunctionArrayLvalueConversion(rExpr);
4876
4877  Sema::AssignConvertType result =
4878    CheckAssignmentConstraints(lhsType, rExpr->getType());
4879
4880  // C99 6.5.16.1p2: The value of the right operand is converted to the
4881  // type of the assignment expression.
4882  // CheckAssignmentConstraints allows the left-hand side to be a reference,
4883  // so that we can use references in built-in functions even in C.
4884  // The getNonReferenceType() call makes sure that the resulting expression
4885  // does not have reference type.
4886  if (result != Incompatible && rExpr->getType() != lhsType)
4887    ImpCastExprToType(rExpr, lhsType.getNonReferenceType(),
4888                      CastExpr::CK_Unknown);
4889  return result;
4890}
4891
4892QualType Sema::InvalidOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4893  Diag(Loc, diag::err_typecheck_invalid_operands)
4894    << lex->getType() << rex->getType()
4895    << lex->getSourceRange() << rex->getSourceRange();
4896  return QualType();
4897}
4898
4899QualType Sema::CheckVectorOperands(SourceLocation Loc, Expr *&lex, Expr *&rex) {
4900  // For conversion purposes, we ignore any qualifiers.
4901  // For example, "const float" and "float" are equivalent.
4902  QualType lhsType =
4903    Context.getCanonicalType(lex->getType()).getUnqualifiedType();
4904  QualType rhsType =
4905    Context.getCanonicalType(rex->getType()).getUnqualifiedType();
4906
4907  // If the vector types are identical, return.
4908  if (lhsType == rhsType)
4909    return lhsType;
4910
4911  // Handle the case of a vector & extvector type of the same size and element
4912  // type.  It would be nice if we only had one vector type someday.
4913  if (getLangOptions().LaxVectorConversions) {
4914    // FIXME: Should we warn here?
4915    if (const VectorType *LV = lhsType->getAs<VectorType>()) {
4916      if (const VectorType *RV = rhsType->getAs<VectorType>())
4917        if (LV->getElementType() == RV->getElementType() &&
4918            LV->getNumElements() == RV->getNumElements()) {
4919          if (lhsType->isExtVectorType()) {
4920            ImpCastExprToType(rex, lhsType, CastExpr::CK_BitCast);
4921            return lhsType;
4922          }
4923
4924          ImpCastExprToType(lex, rhsType, CastExpr::CK_BitCast);
4925          return rhsType;
4926        }
4927    }
4928  }
4929
4930  // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
4931  // swap back (so that we don't reverse the inputs to a subtract, for instance.
4932  bool swapped = false;
4933  if (rhsType->isExtVectorType()) {
4934    swapped = true;
4935    std::swap(rex, lex);
4936    std::swap(rhsType, lhsType);
4937  }
4938
4939  // Handle the case of an ext vector and scalar.
4940  if (const ExtVectorType *LV = lhsType->getAs<ExtVectorType>()) {
4941    QualType EltTy = LV->getElementType();
4942    if (EltTy->isIntegralType(Context) && rhsType->isIntegralType(Context)) {
4943      if (Context.getIntegerTypeOrder(EltTy, rhsType) >= 0) {
4944        ImpCastExprToType(rex, lhsType, CastExpr::CK_IntegralCast);
4945        if (swapped) std::swap(rex, lex);
4946        return lhsType;
4947      }
4948    }
4949    if (EltTy->isRealFloatingType() && rhsType->isScalarType() &&
4950        rhsType->isRealFloatingType()) {
4951      if (Context.getFloatingTypeOrder(EltTy, rhsType) >= 0) {
4952        ImpCastExprToType(rex, lhsType, CastExpr::CK_FloatingCast);
4953        if (swapped) std::swap(rex, lex);
4954        return lhsType;
4955      }
4956    }
4957  }
4958
4959  // Vectors of different size or scalar and non-ext-vector are errors.
4960  Diag(Loc, diag::err_typecheck_vector_not_convertable)
4961    << lex->getType() << rex->getType()
4962    << lex->getSourceRange() << rex->getSourceRange();
4963  return QualType();
4964}
4965
4966QualType Sema::CheckMultiplyDivideOperands(
4967  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign, bool isDiv) {
4968  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
4969    return CheckVectorOperands(Loc, lex, rex);
4970
4971  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4972
4973  if (!lex->getType()->isArithmeticType() ||
4974      !rex->getType()->isArithmeticType())
4975    return InvalidOperands(Loc, lex, rex);
4976
4977  // Check for division by zero.
4978  if (isDiv &&
4979      rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
4980    DiagRuntimeBehavior(Loc, PDiag(diag::warn_division_by_zero)
4981                                     << rex->getSourceRange());
4982
4983  return compType;
4984}
4985
4986QualType Sema::CheckRemainderOperands(
4987  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
4988  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
4989    if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
4990      return CheckVectorOperands(Loc, lex, rex);
4991    return InvalidOperands(Loc, lex, rex);
4992  }
4993
4994  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
4995
4996  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
4997    return InvalidOperands(Loc, lex, rex);
4998
4999  // Check for remainder by zero.
5000  if (rex->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
5001    DiagRuntimeBehavior(Loc, PDiag(diag::warn_remainder_by_zero)
5002                                 << rex->getSourceRange());
5003
5004  return compType;
5005}
5006
5007QualType Sema::CheckAdditionOperands( // C99 6.5.6
5008  Expr *&lex, Expr *&rex, SourceLocation Loc, QualType* CompLHSTy) {
5009  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5010    QualType compType = CheckVectorOperands(Loc, lex, rex);
5011    if (CompLHSTy) *CompLHSTy = compType;
5012    return compType;
5013  }
5014
5015  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
5016
5017  // handle the common case first (both operands are arithmetic).
5018  if (lex->getType()->isArithmeticType() &&
5019      rex->getType()->isArithmeticType()) {
5020    if (CompLHSTy) *CompLHSTy = compType;
5021    return compType;
5022  }
5023
5024  // Put any potential pointer into PExp
5025  Expr* PExp = lex, *IExp = rex;
5026  if (IExp->getType()->isAnyPointerType())
5027    std::swap(PExp, IExp);
5028
5029  if (PExp->getType()->isAnyPointerType()) {
5030
5031    if (IExp->getType()->isIntegerType()) {
5032      QualType PointeeTy = PExp->getType()->getPointeeType();
5033
5034      // Check for arithmetic on pointers to incomplete types.
5035      if (PointeeTy->isVoidType()) {
5036        if (getLangOptions().CPlusPlus) {
5037          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5038            << lex->getSourceRange() << rex->getSourceRange();
5039          return QualType();
5040        }
5041
5042        // GNU extension: arithmetic on pointer to void
5043        Diag(Loc, diag::ext_gnu_void_ptr)
5044          << lex->getSourceRange() << rex->getSourceRange();
5045      } else if (PointeeTy->isFunctionType()) {
5046        if (getLangOptions().CPlusPlus) {
5047          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5048            << lex->getType() << lex->getSourceRange();
5049          return QualType();
5050        }
5051
5052        // GNU extension: arithmetic on pointer to function
5053        Diag(Loc, diag::ext_gnu_ptr_func_arith)
5054          << lex->getType() << lex->getSourceRange();
5055      } else {
5056        // Check if we require a complete type.
5057        if (((PExp->getType()->isPointerType() &&
5058              !PExp->getType()->isDependentType()) ||
5059              PExp->getType()->isObjCObjectPointerType()) &&
5060             RequireCompleteType(Loc, PointeeTy,
5061                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5062                             << PExp->getSourceRange()
5063                             << PExp->getType()))
5064          return QualType();
5065      }
5066      // Diagnose bad cases where we step over interface counts.
5067      if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
5068        Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5069          << PointeeTy << PExp->getSourceRange();
5070        return QualType();
5071      }
5072
5073      if (CompLHSTy) {
5074        QualType LHSTy = Context.isPromotableBitField(lex);
5075        if (LHSTy.isNull()) {
5076          LHSTy = lex->getType();
5077          if (LHSTy->isPromotableIntegerType())
5078            LHSTy = Context.getPromotedIntegerType(LHSTy);
5079        }
5080        *CompLHSTy = LHSTy;
5081      }
5082      return PExp->getType();
5083    }
5084  }
5085
5086  return InvalidOperands(Loc, lex, rex);
5087}
5088
5089// C99 6.5.6
5090QualType Sema::CheckSubtractionOperands(Expr *&lex, Expr *&rex,
5091                                        SourceLocation Loc, QualType* CompLHSTy) {
5092  if (lex->getType()->isVectorType() || rex->getType()->isVectorType()) {
5093    QualType compType = CheckVectorOperands(Loc, lex, rex);
5094    if (CompLHSTy) *CompLHSTy = compType;
5095    return compType;
5096  }
5097
5098  QualType compType = UsualArithmeticConversions(lex, rex, CompLHSTy);
5099
5100  // Enforce type constraints: C99 6.5.6p3.
5101
5102  // Handle the common case first (both operands are arithmetic).
5103  if (lex->getType()->isArithmeticType()
5104      && rex->getType()->isArithmeticType()) {
5105    if (CompLHSTy) *CompLHSTy = compType;
5106    return compType;
5107  }
5108
5109  // Either ptr - int   or   ptr - ptr.
5110  if (lex->getType()->isAnyPointerType()) {
5111    QualType lpointee = lex->getType()->getPointeeType();
5112
5113    // The LHS must be an completely-defined object type.
5114
5115    bool ComplainAboutVoid = false;
5116    Expr *ComplainAboutFunc = 0;
5117    if (lpointee->isVoidType()) {
5118      if (getLangOptions().CPlusPlus) {
5119        Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5120          << lex->getSourceRange() << rex->getSourceRange();
5121        return QualType();
5122      }
5123
5124      // GNU C extension: arithmetic on pointer to void
5125      ComplainAboutVoid = true;
5126    } else if (lpointee->isFunctionType()) {
5127      if (getLangOptions().CPlusPlus) {
5128        Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5129          << lex->getType() << lex->getSourceRange();
5130        return QualType();
5131      }
5132
5133      // GNU C extension: arithmetic on pointer to function
5134      ComplainAboutFunc = lex;
5135    } else if (!lpointee->isDependentType() &&
5136               RequireCompleteType(Loc, lpointee,
5137                                   PDiag(diag::err_typecheck_sub_ptr_object)
5138                                     << lex->getSourceRange()
5139                                     << lex->getType()))
5140      return QualType();
5141
5142    // Diagnose bad cases where we step over interface counts.
5143    if (lpointee->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
5144      Diag(Loc, diag::err_arithmetic_nonfragile_interface)
5145        << lpointee << lex->getSourceRange();
5146      return QualType();
5147    }
5148
5149    // The result type of a pointer-int computation is the pointer type.
5150    if (rex->getType()->isIntegerType()) {
5151      if (ComplainAboutVoid)
5152        Diag(Loc, diag::ext_gnu_void_ptr)
5153          << lex->getSourceRange() << rex->getSourceRange();
5154      if (ComplainAboutFunc)
5155        Diag(Loc, diag::ext_gnu_ptr_func_arith)
5156          << ComplainAboutFunc->getType()
5157          << ComplainAboutFunc->getSourceRange();
5158
5159      if (CompLHSTy) *CompLHSTy = lex->getType();
5160      return lex->getType();
5161    }
5162
5163    // Handle pointer-pointer subtractions.
5164    if (const PointerType *RHSPTy = rex->getType()->getAs<PointerType>()) {
5165      QualType rpointee = RHSPTy->getPointeeType();
5166
5167      // RHS must be a completely-type object type.
5168      // Handle the GNU void* extension.
5169      if (rpointee->isVoidType()) {
5170        if (getLangOptions().CPlusPlus) {
5171          Diag(Loc, diag::err_typecheck_pointer_arith_void_type)
5172            << lex->getSourceRange() << rex->getSourceRange();
5173          return QualType();
5174        }
5175
5176        ComplainAboutVoid = true;
5177      } else if (rpointee->isFunctionType()) {
5178        if (getLangOptions().CPlusPlus) {
5179          Diag(Loc, diag::err_typecheck_pointer_arith_function_type)
5180            << rex->getType() << rex->getSourceRange();
5181          return QualType();
5182        }
5183
5184        // GNU extension: arithmetic on pointer to function
5185        if (!ComplainAboutFunc)
5186          ComplainAboutFunc = rex;
5187      } else if (!rpointee->isDependentType() &&
5188                 RequireCompleteType(Loc, rpointee,
5189                                     PDiag(diag::err_typecheck_sub_ptr_object)
5190                                       << rex->getSourceRange()
5191                                       << rex->getType()))
5192        return QualType();
5193
5194      if (getLangOptions().CPlusPlus) {
5195        // Pointee types must be the same: C++ [expr.add]
5196        if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
5197          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5198            << lex->getType() << rex->getType()
5199            << lex->getSourceRange() << rex->getSourceRange();
5200          return QualType();
5201        }
5202      } else {
5203        // Pointee types must be compatible C99 6.5.6p3
5204        if (!Context.typesAreCompatible(
5205                Context.getCanonicalType(lpointee).getUnqualifiedType(),
5206                Context.getCanonicalType(rpointee).getUnqualifiedType())) {
5207          Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
5208            << lex->getType() << rex->getType()
5209            << lex->getSourceRange() << rex->getSourceRange();
5210          return QualType();
5211        }
5212      }
5213
5214      if (ComplainAboutVoid)
5215        Diag(Loc, diag::ext_gnu_void_ptr)
5216          << lex->getSourceRange() << rex->getSourceRange();
5217      if (ComplainAboutFunc)
5218        Diag(Loc, diag::ext_gnu_ptr_func_arith)
5219          << ComplainAboutFunc->getType()
5220          << ComplainAboutFunc->getSourceRange();
5221
5222      if (CompLHSTy) *CompLHSTy = lex->getType();
5223      return Context.getPointerDiffType();
5224    }
5225  }
5226
5227  return InvalidOperands(Loc, lex, rex);
5228}
5229
5230// C99 6.5.7
5231QualType Sema::CheckShiftOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
5232                                  bool isCompAssign) {
5233  // C99 6.5.7p2: Each of the operands shall have integer type.
5234  if (!lex->getType()->isIntegerType() || !rex->getType()->isIntegerType())
5235    return InvalidOperands(Loc, lex, rex);
5236
5237  // Vector shifts promote their scalar inputs to vector type.
5238  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5239    return CheckVectorOperands(Loc, lex, rex);
5240
5241  // Shifts don't perform usual arithmetic conversions, they just do integer
5242  // promotions on each operand. C99 6.5.7p3
5243  QualType LHSTy = Context.isPromotableBitField(lex);
5244  if (LHSTy.isNull()) {
5245    LHSTy = lex->getType();
5246    if (LHSTy->isPromotableIntegerType())
5247      LHSTy = Context.getPromotedIntegerType(LHSTy);
5248  }
5249  if (!isCompAssign)
5250    ImpCastExprToType(lex, LHSTy, CastExpr::CK_IntegralCast);
5251
5252  UsualUnaryConversions(rex);
5253
5254  // Sanity-check shift operands
5255  llvm::APSInt Right;
5256  // Check right/shifter operand
5257  if (!rex->isValueDependent() &&
5258      rex->isIntegerConstantExpr(Right, Context)) {
5259    if (Right.isNegative())
5260      Diag(Loc, diag::warn_shift_negative) << rex->getSourceRange();
5261    else {
5262      llvm::APInt LeftBits(Right.getBitWidth(),
5263                          Context.getTypeSize(lex->getType()));
5264      if (Right.uge(LeftBits))
5265        Diag(Loc, diag::warn_shift_gt_typewidth) << rex->getSourceRange();
5266    }
5267  }
5268
5269  // "The type of the result is that of the promoted left operand."
5270  return LHSTy;
5271}
5272
5273// C99 6.5.8, C++ [expr.rel]
5274QualType Sema::CheckCompareOperands(Expr *&lex, Expr *&rex, SourceLocation Loc,
5275                                    unsigned OpaqueOpc, bool isRelational) {
5276  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)OpaqueOpc;
5277
5278  // Handle vector comparisons separately.
5279  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5280    return CheckVectorCompareOperands(lex, rex, Loc, isRelational);
5281
5282  QualType lType = lex->getType();
5283  QualType rType = rex->getType();
5284
5285  if (!lType->hasFloatingRepresentation() &&
5286      !(lType->isBlockPointerType() && isRelational)) {
5287    // For non-floating point types, check for self-comparisons of the form
5288    // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
5289    // often indicate logic errors in the program.
5290    // NOTE: Don't warn about comparisons of enum constants. These can arise
5291    //  from macro expansions, and are usually quite deliberate.
5292    Expr *LHSStripped = lex->IgnoreParens();
5293    Expr *RHSStripped = rex->IgnoreParens();
5294    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped))
5295      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
5296        if (DRL->getDecl() == DRR->getDecl() &&
5297            !isa<EnumConstantDecl>(DRL->getDecl())) {
5298          DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5299                              << 0 // self-
5300                              << (Opc == BinaryOperator::EQ
5301                                  || Opc == BinaryOperator::LE
5302                                  || Opc == BinaryOperator::GE));
5303        } else if (lType->isArrayType() && rType->isArrayType() &&
5304                   !DRL->getDecl()->getType()->isReferenceType() &&
5305                   !DRR->getDecl()->getType()->isReferenceType()) {
5306            // what is it always going to eval to?
5307            char always_evals_to;
5308            switch(Opc) {
5309            case BinaryOperator::EQ: // e.g. array1 == array2
5310              always_evals_to = 0; // false
5311              break;
5312            case BinaryOperator::NE: // e.g. array1 != array2
5313              always_evals_to = 1; // true
5314              break;
5315            default:
5316              // best we can say is 'a constant'
5317              always_evals_to = 2; // e.g. array1 <= array2
5318              break;
5319            }
5320            DiagRuntimeBehavior(Loc, PDiag(diag::warn_comparison_always)
5321                                << 1 // array
5322                                << always_evals_to);
5323        }
5324      }
5325
5326    if (isa<CastExpr>(LHSStripped))
5327      LHSStripped = LHSStripped->IgnoreParenCasts();
5328    if (isa<CastExpr>(RHSStripped))
5329      RHSStripped = RHSStripped->IgnoreParenCasts();
5330
5331    // Warn about comparisons against a string constant (unless the other
5332    // operand is null), the user probably wants strcmp.
5333    Expr *literalString = 0;
5334    Expr *literalStringStripped = 0;
5335    if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
5336        !RHSStripped->isNullPointerConstant(Context,
5337                                            Expr::NPC_ValueDependentIsNull)) {
5338      literalString = lex;
5339      literalStringStripped = LHSStripped;
5340    } else if ((isa<StringLiteral>(RHSStripped) ||
5341                isa<ObjCEncodeExpr>(RHSStripped)) &&
5342               !LHSStripped->isNullPointerConstant(Context,
5343                                            Expr::NPC_ValueDependentIsNull)) {
5344      literalString = rex;
5345      literalStringStripped = RHSStripped;
5346    }
5347
5348    if (literalString) {
5349      std::string resultComparison;
5350      switch (Opc) {
5351      case BinaryOperator::LT: resultComparison = ") < 0"; break;
5352      case BinaryOperator::GT: resultComparison = ") > 0"; break;
5353      case BinaryOperator::LE: resultComparison = ") <= 0"; break;
5354      case BinaryOperator::GE: resultComparison = ") >= 0"; break;
5355      case BinaryOperator::EQ: resultComparison = ") == 0"; break;
5356      case BinaryOperator::NE: resultComparison = ") != 0"; break;
5357      default: assert(false && "Invalid comparison operator");
5358      }
5359
5360      DiagRuntimeBehavior(Loc,
5361        PDiag(diag::warn_stringcompare)
5362          << isa<ObjCEncodeExpr>(literalStringStripped)
5363          << literalString->getSourceRange());
5364    }
5365  }
5366
5367  // C99 6.5.8p3 / C99 6.5.9p4
5368  if (lex->getType()->isArithmeticType() && rex->getType()->isArithmeticType())
5369    UsualArithmeticConversions(lex, rex);
5370  else {
5371    UsualUnaryConversions(lex);
5372    UsualUnaryConversions(rex);
5373  }
5374
5375  lType = lex->getType();
5376  rType = rex->getType();
5377
5378  // The result of comparisons is 'bool' in C++, 'int' in C.
5379  QualType ResultTy = getLangOptions().CPlusPlus ? Context.BoolTy:Context.IntTy;
5380
5381  if (isRelational) {
5382    if (lType->isRealType() && rType->isRealType())
5383      return ResultTy;
5384  } else {
5385    // Check for comparisons of floating point operands using != and ==.
5386    if (lType->hasFloatingRepresentation())
5387      CheckFloatComparison(Loc,lex,rex);
5388
5389    if (lType->isArithmeticType() && rType->isArithmeticType())
5390      return ResultTy;
5391  }
5392
5393  bool LHSIsNull = lex->isNullPointerConstant(Context,
5394                                              Expr::NPC_ValueDependentIsNull);
5395  bool RHSIsNull = rex->isNullPointerConstant(Context,
5396                                              Expr::NPC_ValueDependentIsNull);
5397
5398  // All of the following pointer-related warnings are GCC extensions, except
5399  // when handling null pointer constants.
5400  if (lType->isPointerType() && rType->isPointerType()) { // C99 6.5.8p2
5401    QualType LCanPointeeTy =
5402      Context.getCanonicalType(lType->getAs<PointerType>()->getPointeeType());
5403    QualType RCanPointeeTy =
5404      Context.getCanonicalType(rType->getAs<PointerType>()->getPointeeType());
5405
5406    if (getLangOptions().CPlusPlus) {
5407      if (LCanPointeeTy == RCanPointeeTy)
5408        return ResultTy;
5409      if (!isRelational &&
5410          (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5411        // Valid unless comparison between non-null pointer and function pointer
5412        // This is a gcc extension compatibility comparison.
5413        // In a SFINAE context, we treat this as a hard error to maintain
5414        // conformance with the C++ standard.
5415        if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5416            && !LHSIsNull && !RHSIsNull) {
5417          Diag(Loc,
5418               isSFINAEContext()?
5419                   diag::err_typecheck_comparison_of_fptr_to_void
5420                 : diag::ext_typecheck_comparison_of_fptr_to_void)
5421            << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5422
5423          if (isSFINAEContext())
5424            return QualType();
5425
5426          ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5427          return ResultTy;
5428        }
5429      }
5430      // C++ [expr.rel]p2:
5431      //   [...] Pointer conversions (4.10) and qualification
5432      //   conversions (4.4) are performed on pointer operands (or on
5433      //   a pointer operand and a null pointer constant) to bring
5434      //   them to their composite pointer type. [...]
5435      //
5436      // C++ [expr.eq]p1 uses the same notion for (in)equality
5437      // comparisons of pointers.
5438      bool NonStandardCompositeType = false;
5439      QualType T = FindCompositePointerType(Loc, lex, rex,
5440                              isSFINAEContext()? 0 : &NonStandardCompositeType);
5441      if (T.isNull()) {
5442        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5443          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5444        return QualType();
5445      } else if (NonStandardCompositeType) {
5446        Diag(Loc,
5447             diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
5448          << lType << rType << T
5449          << lex->getSourceRange() << rex->getSourceRange();
5450      }
5451
5452      ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5453      ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
5454      return ResultTy;
5455    }
5456    // C99 6.5.9p2 and C99 6.5.8p2
5457    if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
5458                                   RCanPointeeTy.getUnqualifiedType())) {
5459      // Valid unless a relational comparison of function pointers
5460      if (isRelational && LCanPointeeTy->isFunctionType()) {
5461        Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
5462          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5463      }
5464    } else if (!isRelational &&
5465               (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
5466      // Valid unless comparison between non-null pointer and function pointer
5467      if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
5468          && !LHSIsNull && !RHSIsNull) {
5469        Diag(Loc, diag::ext_typecheck_comparison_of_fptr_to_void)
5470          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5471      }
5472    } else {
5473      // Invalid
5474      Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5475        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5476    }
5477    if (LCanPointeeTy != RCanPointeeTy)
5478      ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5479    return ResultTy;
5480  }
5481
5482  if (getLangOptions().CPlusPlus) {
5483    // Comparison of pointers with null pointer constants and equality
5484    // comparisons of member pointers to null pointer constants.
5485    if (RHSIsNull &&
5486        (lType->isPointerType() ||
5487         (!isRelational && lType->isMemberPointerType()))) {
5488      ImpCastExprToType(rex, lType, CastExpr::CK_NullToMemberPointer);
5489      return ResultTy;
5490    }
5491    if (LHSIsNull &&
5492        (rType->isPointerType() ||
5493         (!isRelational && rType->isMemberPointerType()))) {
5494      ImpCastExprToType(lex, rType, CastExpr::CK_NullToMemberPointer);
5495      return ResultTy;
5496    }
5497
5498    // Comparison of member pointers.
5499    if (!isRelational &&
5500        lType->isMemberPointerType() && rType->isMemberPointerType()) {
5501      // C++ [expr.eq]p2:
5502      //   In addition, pointers to members can be compared, or a pointer to
5503      //   member and a null pointer constant. Pointer to member conversions
5504      //   (4.11) and qualification conversions (4.4) are performed to bring
5505      //   them to a common type. If one operand is a null pointer constant,
5506      //   the common type is the type of the other operand. Otherwise, the
5507      //   common type is a pointer to member type similar (4.4) to the type
5508      //   of one of the operands, with a cv-qualification signature (4.4)
5509      //   that is the union of the cv-qualification signatures of the operand
5510      //   types.
5511      bool NonStandardCompositeType = false;
5512      QualType T = FindCompositePointerType(Loc, lex, rex,
5513                              isSFINAEContext()? 0 : &NonStandardCompositeType);
5514      if (T.isNull()) {
5515        Diag(Loc, diag::err_typecheck_comparison_of_distinct_pointers)
5516          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5517        return QualType();
5518      } else if (NonStandardCompositeType) {
5519        Diag(Loc,
5520             diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
5521          << lType << rType << T
5522          << lex->getSourceRange() << rex->getSourceRange();
5523      }
5524
5525      ImpCastExprToType(lex, T, CastExpr::CK_BitCast);
5526      ImpCastExprToType(rex, T, CastExpr::CK_BitCast);
5527      return ResultTy;
5528    }
5529
5530    // Comparison of nullptr_t with itself.
5531    if (lType->isNullPtrType() && rType->isNullPtrType())
5532      return ResultTy;
5533  }
5534
5535  // Handle block pointer types.
5536  if (!isRelational && lType->isBlockPointerType() && rType->isBlockPointerType()) {
5537    QualType lpointee = lType->getAs<BlockPointerType>()->getPointeeType();
5538    QualType rpointee = rType->getAs<BlockPointerType>()->getPointeeType();
5539
5540    if (!LHSIsNull && !RHSIsNull &&
5541        !Context.typesAreCompatible(lpointee, rpointee)) {
5542      Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5543        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5544    }
5545    ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5546    return ResultTy;
5547  }
5548  // Allow block pointers to be compared with null pointer constants.
5549  if (!isRelational
5550      && ((lType->isBlockPointerType() && rType->isPointerType())
5551          || (lType->isPointerType() && rType->isBlockPointerType()))) {
5552    if (!LHSIsNull && !RHSIsNull) {
5553      if (!((rType->isPointerType() && rType->getAs<PointerType>()
5554             ->getPointeeType()->isVoidType())
5555            || (lType->isPointerType() && lType->getAs<PointerType>()
5556                ->getPointeeType()->isVoidType())))
5557        Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
5558          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5559    }
5560    ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5561    return ResultTy;
5562  }
5563
5564  if ((lType->isObjCObjectPointerType() || rType->isObjCObjectPointerType())) {
5565    if (lType->isPointerType() || rType->isPointerType()) {
5566      const PointerType *LPT = lType->getAs<PointerType>();
5567      const PointerType *RPT = rType->getAs<PointerType>();
5568      bool LPtrToVoid = LPT ?
5569        Context.getCanonicalType(LPT->getPointeeType())->isVoidType() : false;
5570      bool RPtrToVoid = RPT ?
5571        Context.getCanonicalType(RPT->getPointeeType())->isVoidType() : false;
5572
5573      if (!LPtrToVoid && !RPtrToVoid &&
5574          !Context.typesAreCompatible(lType, rType)) {
5575        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5576          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5577      }
5578      ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5579      return ResultTy;
5580    }
5581    if (lType->isObjCObjectPointerType() && rType->isObjCObjectPointerType()) {
5582      if (!Context.areComparableObjCPointerTypes(lType, rType))
5583        Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers)
5584          << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5585      ImpCastExprToType(rex, lType, CastExpr::CK_BitCast);
5586      return ResultTy;
5587    }
5588  }
5589  if ((lType->isAnyPointerType() && rType->isIntegerType()) ||
5590      (lType->isIntegerType() && rType->isAnyPointerType())) {
5591    unsigned DiagID = 0;
5592    bool isError = false;
5593    if ((LHSIsNull && lType->isIntegerType()) ||
5594        (RHSIsNull && rType->isIntegerType())) {
5595      if (isRelational && !getLangOptions().CPlusPlus)
5596        DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
5597    } else if (isRelational && !getLangOptions().CPlusPlus)
5598      DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
5599    else if (getLangOptions().CPlusPlus) {
5600      DiagID = diag::err_typecheck_comparison_of_pointer_integer;
5601      isError = true;
5602    } else
5603      DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
5604
5605    if (DiagID) {
5606      Diag(Loc, DiagID)
5607        << lType << rType << lex->getSourceRange() << rex->getSourceRange();
5608      if (isError)
5609        return QualType();
5610    }
5611
5612    if (lType->isIntegerType())
5613      ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
5614    else
5615      ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
5616    return ResultTy;
5617  }
5618
5619  // Handle block pointers.
5620  if (!isRelational && RHSIsNull
5621      && lType->isBlockPointerType() && rType->isIntegerType()) {
5622    ImpCastExprToType(rex, lType, CastExpr::CK_IntegralToPointer);
5623    return ResultTy;
5624  }
5625  if (!isRelational && LHSIsNull
5626      && lType->isIntegerType() && rType->isBlockPointerType()) {
5627    ImpCastExprToType(lex, rType, CastExpr::CK_IntegralToPointer);
5628    return ResultTy;
5629  }
5630  return InvalidOperands(Loc, lex, rex);
5631}
5632
5633/// CheckVectorCompareOperands - vector comparisons are a clang extension that
5634/// operates on extended vector types.  Instead of producing an IntTy result,
5635/// like a scalar comparison, a vector comparison produces a vector of integer
5636/// types.
5637QualType Sema::CheckVectorCompareOperands(Expr *&lex, Expr *&rex,
5638                                          SourceLocation Loc,
5639                                          bool isRelational) {
5640  // Check to make sure we're operating on vectors of the same type and width,
5641  // Allowing one side to be a scalar of element type.
5642  QualType vType = CheckVectorOperands(Loc, lex, rex);
5643  if (vType.isNull())
5644    return vType;
5645
5646  QualType lType = lex->getType();
5647  QualType rType = rex->getType();
5648
5649  // For non-floating point types, check for self-comparisons of the form
5650  // x == x, x != x, x < x, etc.  These always evaluate to a constant, and
5651  // often indicate logic errors in the program.
5652  if (!lType->hasFloatingRepresentation()) {
5653    if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(lex->IgnoreParens()))
5654      if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(rex->IgnoreParens()))
5655        if (DRL->getDecl() == DRR->getDecl())
5656          DiagRuntimeBehavior(Loc,
5657                              PDiag(diag::warn_comparison_always)
5658                                << 0 // self-
5659                                << 2 // "a constant"
5660                              );
5661  }
5662
5663  // Check for comparisons of floating point operands using != and ==.
5664  if (!isRelational && lType->hasFloatingRepresentation()) {
5665    assert (rType->hasFloatingRepresentation());
5666    CheckFloatComparison(Loc,lex,rex);
5667  }
5668
5669  // Return the type for the comparison, which is the same as vector type for
5670  // integer vectors, or an integer type of identical size and number of
5671  // elements for floating point vectors.
5672  if (lType->isIntegerType())
5673    return lType;
5674
5675  const VectorType *VTy = lType->getAs<VectorType>();
5676  unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
5677  if (TypeSize == Context.getTypeSize(Context.IntTy))
5678    return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
5679  if (TypeSize == Context.getTypeSize(Context.LongTy))
5680    return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
5681
5682  assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
5683         "Unhandled vector element size in vector compare");
5684  return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
5685}
5686
5687inline QualType Sema::CheckBitwiseOperands(
5688  Expr *&lex, Expr *&rex, SourceLocation Loc, bool isCompAssign) {
5689  if (lex->getType()->isVectorType() || rex->getType()->isVectorType())
5690    return CheckVectorOperands(Loc, lex, rex);
5691
5692  QualType compType = UsualArithmeticConversions(lex, rex, isCompAssign);
5693
5694  if (lex->getType()->isIntegerType() && rex->getType()->isIntegerType())
5695    return compType;
5696  return InvalidOperands(Loc, lex, rex);
5697}
5698
5699inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
5700  Expr *&lex, Expr *&rex, SourceLocation Loc) {
5701  if (!Context.getLangOptions().CPlusPlus) {
5702    UsualUnaryConversions(lex);
5703    UsualUnaryConversions(rex);
5704
5705    if (!lex->getType()->isScalarType() || !rex->getType()->isScalarType())
5706      return InvalidOperands(Loc, lex, rex);
5707
5708    return Context.IntTy;
5709  }
5710
5711  // The following is safe because we only use this method for
5712  // non-overloadable operands.
5713
5714  // C++ [expr.log.and]p1
5715  // C++ [expr.log.or]p1
5716  // The operands are both contextually converted to type bool.
5717  if (PerformContextuallyConvertToBool(lex) ||
5718      PerformContextuallyConvertToBool(rex))
5719    return InvalidOperands(Loc, lex, rex);
5720
5721  // C++ [expr.log.and]p2
5722  // C++ [expr.log.or]p2
5723  // The result is a bool.
5724  return Context.BoolTy;
5725}
5726
5727/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
5728/// is a read-only property; return true if so. A readonly property expression
5729/// depends on various declarations and thus must be treated specially.
5730///
5731static bool IsReadonlyProperty(Expr *E, Sema &S) {
5732  if (E->getStmtClass() == Expr::ObjCPropertyRefExprClass) {
5733    const ObjCPropertyRefExpr* PropExpr = cast<ObjCPropertyRefExpr>(E);
5734    if (ObjCPropertyDecl *PDecl = PropExpr->getProperty()) {
5735      QualType BaseType = PropExpr->getBase()->getType();
5736      if (const ObjCObjectPointerType *OPT =
5737            BaseType->getAsObjCInterfacePointerType())
5738        if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
5739          if (S.isPropertyReadonly(PDecl, IFace))
5740            return true;
5741    }
5742  }
5743  return false;
5744}
5745
5746/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue.  If not,
5747/// emit an error and return true.  If so, return false.
5748static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
5749  SourceLocation OrigLoc = Loc;
5750  Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
5751                                                              &Loc);
5752  if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
5753    IsLV = Expr::MLV_ReadonlyProperty;
5754  if (IsLV == Expr::MLV_Valid)
5755    return false;
5756
5757  unsigned Diag = 0;
5758  bool NeedType = false;
5759  switch (IsLV) { // C99 6.5.16p2
5760  case Expr::MLV_ConstQualified: Diag = diag::err_typecheck_assign_const; break;
5761  case Expr::MLV_ArrayType:
5762    Diag = diag::err_typecheck_array_not_modifiable_lvalue;
5763    NeedType = true;
5764    break;
5765  case Expr::MLV_NotObjectType:
5766    Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
5767    NeedType = true;
5768    break;
5769  case Expr::MLV_LValueCast:
5770    Diag = diag::err_typecheck_lvalue_casts_not_supported;
5771    break;
5772  case Expr::MLV_Valid:
5773    llvm_unreachable("did not take early return for MLV_Valid");
5774  case Expr::MLV_InvalidExpression:
5775  case Expr::MLV_MemberFunction:
5776  case Expr::MLV_ClassTemporary:
5777    Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
5778    break;
5779  case Expr::MLV_IncompleteType:
5780  case Expr::MLV_IncompleteVoidType:
5781    return S.RequireCompleteType(Loc, E->getType(),
5782              S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
5783                  << E->getSourceRange());
5784  case Expr::MLV_DuplicateVectorComponents:
5785    Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
5786    break;
5787  case Expr::MLV_NotBlockQualified:
5788    Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
5789    break;
5790  case Expr::MLV_ReadonlyProperty:
5791    Diag = diag::error_readonly_property_assignment;
5792    break;
5793  case Expr::MLV_NoSetterProperty:
5794    Diag = diag::error_nosetter_property_assignment;
5795    break;
5796  case Expr::MLV_SubObjCPropertySetting:
5797    Diag = diag::error_no_subobject_property_setting;
5798    break;
5799  }
5800
5801  SourceRange Assign;
5802  if (Loc != OrigLoc)
5803    Assign = SourceRange(OrigLoc, OrigLoc);
5804  if (NeedType)
5805    S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
5806  else
5807    S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
5808  return true;
5809}
5810
5811
5812
5813// C99 6.5.16.1
5814QualType Sema::CheckAssignmentOperands(Expr *LHS, Expr *&RHS,
5815                                       SourceLocation Loc,
5816                                       QualType CompoundType) {
5817  // Verify that LHS is a modifiable lvalue, and emit error if not.
5818  if (CheckForModifiableLvalue(LHS, Loc, *this))
5819    return QualType();
5820
5821  QualType LHSType = LHS->getType();
5822  QualType RHSType = CompoundType.isNull() ? RHS->getType() : CompoundType;
5823  AssignConvertType ConvTy;
5824  if (CompoundType.isNull()) {
5825    QualType LHSTy(LHSType);
5826    // Simple assignment "x = y".
5827    if (const ObjCImplicitSetterGetterRefExpr *OISGE =
5828        dyn_cast<ObjCImplicitSetterGetterRefExpr>(LHS)) {
5829      // If using property-dot syntax notation for assignment, and there is a
5830      // setter, RHS expression is being passed to the setter argument. So,
5831      // type conversion (and comparison) is RHS to setter's argument type.
5832      if (const ObjCMethodDecl *SetterMD = OISGE->getSetterMethod()) {
5833        ObjCMethodDecl::param_iterator P = SetterMD->param_begin();
5834        LHSTy = (*P)->getType();
5835      }
5836    }
5837
5838    ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
5839    // Special case of NSObject attributes on c-style pointer types.
5840    if (ConvTy == IncompatiblePointer &&
5841        ((Context.isObjCNSObjectType(LHSType) &&
5842          RHSType->isObjCObjectPointerType()) ||
5843         (Context.isObjCNSObjectType(RHSType) &&
5844          LHSType->isObjCObjectPointerType())))
5845      ConvTy = Compatible;
5846
5847    // If the RHS is a unary plus or minus, check to see if they = and + are
5848    // right next to each other.  If so, the user may have typo'd "x =+ 4"
5849    // instead of "x += 4".
5850    Expr *RHSCheck = RHS;
5851    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
5852      RHSCheck = ICE->getSubExpr();
5853    if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
5854      if ((UO->getOpcode() == UnaryOperator::Plus ||
5855           UO->getOpcode() == UnaryOperator::Minus) &&
5856          Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
5857          // Only if the two operators are exactly adjacent.
5858          Loc.getFileLocWithOffset(1) == UO->getOperatorLoc() &&
5859          // And there is a space or other character before the subexpr of the
5860          // unary +/-.  We don't want to warn on "x=-1".
5861          Loc.getFileLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
5862          UO->getSubExpr()->getLocStart().isFileID()) {
5863        Diag(Loc, diag::warn_not_compound_assign)
5864          << (UO->getOpcode() == UnaryOperator::Plus ? "+" : "-")
5865          << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
5866      }
5867    }
5868  } else {
5869    // Compound assignment "x += y"
5870    ConvTy = CheckAssignmentConstraints(LHSType, RHSType);
5871  }
5872
5873  if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
5874                               RHS, AA_Assigning))
5875    return QualType();
5876
5877  // C99 6.5.16p3: The type of an assignment expression is the type of the
5878  // left operand unless the left operand has qualified type, in which case
5879  // it is the unqualified version of the type of the left operand.
5880  // C99 6.5.16.1p2: In simple assignment, the value of the right operand
5881  // is converted to the type of the assignment expression (above).
5882  // C++ 5.17p1: the type of the assignment expression is that of its left
5883  // operand.
5884  return LHSType.getUnqualifiedType();
5885}
5886
5887// C99 6.5.17
5888QualType Sema::CheckCommaOperands(Expr *LHS, Expr *&RHS, SourceLocation Loc) {
5889  DiagnoseUnusedExprResult(LHS);
5890
5891  // Comma performs lvalue conversion (C99 6.3.2.1), but not unary conversions.
5892  // C++ does not perform this conversion (C++ [expr.comma]p1).
5893  if (!getLangOptions().CPlusPlus)
5894    DefaultFunctionArrayLvalueConversion(RHS);
5895
5896  // FIXME: Check that RHS type is complete in C mode (it's legal for it to be
5897  // incomplete in C++).
5898
5899  return RHS->getType();
5900}
5901
5902/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
5903/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
5904QualType Sema::CheckIncrementDecrementOperand(Expr *Op, SourceLocation OpLoc,
5905                                              bool isInc, bool isPrefix) {
5906  if (Op->isTypeDependent())
5907    return Context.DependentTy;
5908
5909  QualType ResType = Op->getType();
5910  assert(!ResType.isNull() && "no type for increment/decrement expression");
5911
5912  if (getLangOptions().CPlusPlus && ResType->isBooleanType()) {
5913    // Decrement of bool is not allowed.
5914    if (!isInc) {
5915      Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
5916      return QualType();
5917    }
5918    // Increment of bool sets it to true, but is deprecated.
5919    Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
5920  } else if (ResType->isRealType()) {
5921    // OK!
5922  } else if (ResType->isAnyPointerType()) {
5923    QualType PointeeTy = ResType->getPointeeType();
5924
5925    // C99 6.5.2.4p2, 6.5.6p2
5926    if (PointeeTy->isVoidType()) {
5927      if (getLangOptions().CPlusPlus) {
5928        Diag(OpLoc, diag::err_typecheck_pointer_arith_void_type)
5929          << Op->getSourceRange();
5930        return QualType();
5931      }
5932
5933      // Pointer to void is a GNU extension in C.
5934      Diag(OpLoc, diag::ext_gnu_void_ptr) << Op->getSourceRange();
5935    } else if (PointeeTy->isFunctionType()) {
5936      if (getLangOptions().CPlusPlus) {
5937        Diag(OpLoc, diag::err_typecheck_pointer_arith_function_type)
5938          << Op->getType() << Op->getSourceRange();
5939        return QualType();
5940      }
5941
5942      Diag(OpLoc, diag::ext_gnu_ptr_func_arith)
5943        << ResType << Op->getSourceRange();
5944    } else if (RequireCompleteType(OpLoc, PointeeTy,
5945                           PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5946                             << Op->getSourceRange()
5947                             << ResType))
5948      return QualType();
5949    // Diagnose bad cases where we step over interface counts.
5950    else if (PointeeTy->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
5951      Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5952        << PointeeTy << Op->getSourceRange();
5953      return QualType();
5954    }
5955  } else if (ResType->isAnyComplexType()) {
5956    // C99 does not support ++/-- on complex types, we allow as an extension.
5957    Diag(OpLoc, diag::ext_integer_increment_complex)
5958      << ResType << Op->getSourceRange();
5959  } else {
5960    Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
5961      << ResType << int(isInc) << Op->getSourceRange();
5962    return QualType();
5963  }
5964  // At this point, we know we have a real, complex or pointer type.
5965  // Now make sure the operand is a modifiable lvalue.
5966  if (CheckForModifiableLvalue(Op, OpLoc, *this))
5967    return QualType();
5968  // In C++, a prefix increment is the same type as the operand. Otherwise
5969  // (in C or with postfix), the increment is the unqualified type of the
5970  // operand.
5971  return isPrefix && getLangOptions().CPlusPlus
5972    ? ResType : ResType.getUnqualifiedType();
5973}
5974
5975/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
5976/// This routine allows us to typecheck complex/recursive expressions
5977/// where the declaration is needed for type checking. We only need to
5978/// handle cases when the expression references a function designator
5979/// or is an lvalue. Here are some examples:
5980///  - &(x) => x
5981///  - &*****f => f for f a function designator.
5982///  - &s.xx => s
5983///  - &s.zz[1].yy -> s, if zz is an array
5984///  - *(x + 1) -> x, if x is an array
5985///  - &"123"[2] -> 0
5986///  - & __real__ x -> x
5987static NamedDecl *getPrimaryDecl(Expr *E) {
5988  switch (E->getStmtClass()) {
5989  case Stmt::DeclRefExprClass:
5990    return cast<DeclRefExpr>(E)->getDecl();
5991  case Stmt::MemberExprClass:
5992    // If this is an arrow operator, the address is an offset from
5993    // the base's value, so the object the base refers to is
5994    // irrelevant.
5995    if (cast<MemberExpr>(E)->isArrow())
5996      return 0;
5997    // Otherwise, the expression refers to a part of the base
5998    return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
5999  case Stmt::ArraySubscriptExprClass: {
6000    // FIXME: This code shouldn't be necessary!  We should catch the implicit
6001    // promotion of register arrays earlier.
6002    Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
6003    if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
6004      if (ICE->getSubExpr()->getType()->isArrayType())
6005        return getPrimaryDecl(ICE->getSubExpr());
6006    }
6007    return 0;
6008  }
6009  case Stmt::UnaryOperatorClass: {
6010    UnaryOperator *UO = cast<UnaryOperator>(E);
6011
6012    switch(UO->getOpcode()) {
6013    case UnaryOperator::Real:
6014    case UnaryOperator::Imag:
6015    case UnaryOperator::Extension:
6016      return getPrimaryDecl(UO->getSubExpr());
6017    default:
6018      return 0;
6019    }
6020  }
6021  case Stmt::ParenExprClass:
6022    return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
6023  case Stmt::ImplicitCastExprClass:
6024    // If the result of an implicit cast is an l-value, we care about
6025    // the sub-expression; otherwise, the result here doesn't matter.
6026    return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
6027  default:
6028    return 0;
6029  }
6030}
6031
6032/// CheckAddressOfOperand - The operand of & must be either a function
6033/// designator or an lvalue designating an object. If it is an lvalue, the
6034/// object cannot be declared with storage class register or be a bit field.
6035/// Note: The usual conversions are *not* applied to the operand of the &
6036/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
6037/// In C++, the operand might be an overloaded function name, in which case
6038/// we allow the '&' but retain the overloaded-function type.
6039QualType Sema::CheckAddressOfOperand(Expr *op, SourceLocation OpLoc) {
6040  // Make sure to ignore parentheses in subsequent checks
6041  op = op->IgnoreParens();
6042
6043  if (op->isTypeDependent())
6044    return Context.DependentTy;
6045
6046  if (getLangOptions().C99) {
6047    // Implement C99-only parts of addressof rules.
6048    if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
6049      if (uOp->getOpcode() == UnaryOperator::Deref)
6050        // Per C99 6.5.3.2, the address of a deref always returns a valid result
6051        // (assuming the deref expression is valid).
6052        return uOp->getSubExpr()->getType();
6053    }
6054    // Technically, there should be a check for array subscript
6055    // expressions here, but the result of one is always an lvalue anyway.
6056  }
6057  NamedDecl *dcl = getPrimaryDecl(op);
6058  Expr::isLvalueResult lval = op->isLvalue(Context);
6059
6060  MemberExpr *ME = dyn_cast<MemberExpr>(op);
6061  if (lval == Expr::LV_MemberFunction && ME &&
6062      isa<CXXMethodDecl>(ME->getMemberDecl())) {
6063    ValueDecl *dcl = cast<MemberExpr>(op)->getMemberDecl();
6064    // &f where f is a member of the current object, or &o.f, or &p->f
6065    // All these are not allowed, and we need to catch them before the dcl
6066    // branch of the if, below.
6067    Diag(OpLoc, diag::err_unqualified_pointer_member_function)
6068        << dcl;
6069    // FIXME: Improve this diagnostic and provide a fixit.
6070
6071    // Now recover by acting as if the function had been accessed qualified.
6072    return Context.getMemberPointerType(op->getType(),
6073                Context.getTypeDeclType(cast<RecordDecl>(dcl->getDeclContext()))
6074                       .getTypePtr());
6075  }
6076
6077  if (lval == Expr::LV_ClassTemporary) {
6078    Diag(OpLoc, isSFINAEContext()? diag::err_typecheck_addrof_class_temporary
6079                                 : diag::ext_typecheck_addrof_class_temporary)
6080      << op->getType() << op->getSourceRange();
6081    if (isSFINAEContext())
6082      return QualType();
6083  } else if (isa<ObjCSelectorExpr>(op))
6084    return Context.getPointerType(op->getType());
6085  else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
6086    // C99 6.5.3.2p1
6087    // The operand must be either an l-value or a function designator
6088    if (!op->getType()->isFunctionType()) {
6089      // FIXME: emit more specific diag...
6090      Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
6091        << op->getSourceRange();
6092      return QualType();
6093    }
6094  } else if (op->getBitField()) { // C99 6.5.3.2p1
6095    // The operand cannot be a bit-field
6096    Diag(OpLoc, diag::err_typecheck_address_of)
6097      << "bit-field" << op->getSourceRange();
6098        return QualType();
6099  } else if (op->refersToVectorElement()) {
6100    // The operand cannot be an element of a vector
6101    Diag(OpLoc, diag::err_typecheck_address_of)
6102      << "vector element" << op->getSourceRange();
6103    return QualType();
6104  } else if (isa<ObjCPropertyRefExpr>(op)) {
6105    // cannot take address of a property expression.
6106    Diag(OpLoc, diag::err_typecheck_address_of)
6107      << "property expression" << op->getSourceRange();
6108    return QualType();
6109  } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(op)) {
6110    // FIXME: Can LHS ever be null here?
6111    if (!CheckAddressOfOperand(CO->getTrueExpr(), OpLoc).isNull())
6112      return CheckAddressOfOperand(CO->getFalseExpr(), OpLoc);
6113  } else if (isa<UnresolvedLookupExpr>(op)) {
6114    return Context.OverloadTy;
6115  } else if (dcl) { // C99 6.5.3.2p1
6116    // We have an lvalue with a decl. Make sure the decl is not declared
6117    // with the register storage-class specifier.
6118    if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
6119      if (vd->getStorageClass() == VarDecl::Register) {
6120        Diag(OpLoc, diag::err_typecheck_address_of)
6121          << "register variable" << op->getSourceRange();
6122        return QualType();
6123      }
6124    } else if (isa<FunctionTemplateDecl>(dcl)) {
6125      return Context.OverloadTy;
6126    } else if (FieldDecl *FD = dyn_cast<FieldDecl>(dcl)) {
6127      // Okay: we can take the address of a field.
6128      // Could be a pointer to member, though, if there is an explicit
6129      // scope qualifier for the class.
6130      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
6131        DeclContext *Ctx = dcl->getDeclContext();
6132        if (Ctx && Ctx->isRecord()) {
6133          if (FD->getType()->isReferenceType()) {
6134            Diag(OpLoc,
6135                 diag::err_cannot_form_pointer_to_member_of_reference_type)
6136              << FD->getDeclName() << FD->getType();
6137            return QualType();
6138          }
6139
6140          return Context.getMemberPointerType(op->getType(),
6141                Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
6142        }
6143      }
6144    } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(dcl)) {
6145      // Okay: we can take the address of a function.
6146      // As above.
6147      if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier() &&
6148          MD->isInstance())
6149        return Context.getMemberPointerType(op->getType(),
6150              Context.getTypeDeclType(MD->getParent()).getTypePtr());
6151    } else if (!isa<FunctionDecl>(dcl))
6152      assert(0 && "Unknown/unexpected decl type");
6153  }
6154
6155  if (lval == Expr::LV_IncompleteVoidType) {
6156    // Taking the address of a void variable is technically illegal, but we
6157    // allow it in cases which are otherwise valid.
6158    // Example: "extern void x; void* y = &x;".
6159    Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
6160  }
6161
6162  // If the operand has type "type", the result has type "pointer to type".
6163  return Context.getPointerType(op->getType());
6164}
6165
6166/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
6167QualType Sema::CheckIndirectionOperand(Expr *Op, SourceLocation OpLoc) {
6168  if (Op->isTypeDependent())
6169    return Context.DependentTy;
6170
6171  UsualUnaryConversions(Op);
6172  QualType OpTy = Op->getType();
6173  QualType Result;
6174
6175  // Note that per both C89 and C99, indirection is always legal, even if OpTy
6176  // is an incomplete type or void.  It would be possible to warn about
6177  // dereferencing a void pointer, but it's completely well-defined, and such a
6178  // warning is unlikely to catch any mistakes.
6179  if (const PointerType *PT = OpTy->getAs<PointerType>())
6180    Result = PT->getPointeeType();
6181  else if (const ObjCObjectPointerType *OPT =
6182             OpTy->getAs<ObjCObjectPointerType>())
6183    Result = OPT->getPointeeType();
6184
6185  if (Result.isNull()) {
6186    Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
6187      << OpTy << Op->getSourceRange();
6188    return QualType();
6189  }
6190
6191  return Result;
6192}
6193
6194static inline BinaryOperator::Opcode ConvertTokenKindToBinaryOpcode(
6195  tok::TokenKind Kind) {
6196  BinaryOperator::Opcode Opc;
6197  switch (Kind) {
6198  default: assert(0 && "Unknown binop!");
6199  case tok::periodstar:           Opc = BinaryOperator::PtrMemD; break;
6200  case tok::arrowstar:            Opc = BinaryOperator::PtrMemI; break;
6201  case tok::star:                 Opc = BinaryOperator::Mul; break;
6202  case tok::slash:                Opc = BinaryOperator::Div; break;
6203  case tok::percent:              Opc = BinaryOperator::Rem; break;
6204  case tok::plus:                 Opc = BinaryOperator::Add; break;
6205  case tok::minus:                Opc = BinaryOperator::Sub; break;
6206  case tok::lessless:             Opc = BinaryOperator::Shl; break;
6207  case tok::greatergreater:       Opc = BinaryOperator::Shr; break;
6208  case tok::lessequal:            Opc = BinaryOperator::LE; break;
6209  case tok::less:                 Opc = BinaryOperator::LT; break;
6210  case tok::greaterequal:         Opc = BinaryOperator::GE; break;
6211  case tok::greater:              Opc = BinaryOperator::GT; break;
6212  case tok::exclaimequal:         Opc = BinaryOperator::NE; break;
6213  case tok::equalequal:           Opc = BinaryOperator::EQ; break;
6214  case tok::amp:                  Opc = BinaryOperator::And; break;
6215  case tok::caret:                Opc = BinaryOperator::Xor; break;
6216  case tok::pipe:                 Opc = BinaryOperator::Or; break;
6217  case tok::ampamp:               Opc = BinaryOperator::LAnd; break;
6218  case tok::pipepipe:             Opc = BinaryOperator::LOr; break;
6219  case tok::equal:                Opc = BinaryOperator::Assign; break;
6220  case tok::starequal:            Opc = BinaryOperator::MulAssign; break;
6221  case tok::slashequal:           Opc = BinaryOperator::DivAssign; break;
6222  case tok::percentequal:         Opc = BinaryOperator::RemAssign; break;
6223  case tok::plusequal:            Opc = BinaryOperator::AddAssign; break;
6224  case tok::minusequal:           Opc = BinaryOperator::SubAssign; break;
6225  case tok::lesslessequal:        Opc = BinaryOperator::ShlAssign; break;
6226  case tok::greatergreaterequal:  Opc = BinaryOperator::ShrAssign; break;
6227  case tok::ampequal:             Opc = BinaryOperator::AndAssign; break;
6228  case tok::caretequal:           Opc = BinaryOperator::XorAssign; break;
6229  case tok::pipeequal:            Opc = BinaryOperator::OrAssign; break;
6230  case tok::comma:                Opc = BinaryOperator::Comma; break;
6231  }
6232  return Opc;
6233}
6234
6235static inline UnaryOperator::Opcode ConvertTokenKindToUnaryOpcode(
6236  tok::TokenKind Kind) {
6237  UnaryOperator::Opcode Opc;
6238  switch (Kind) {
6239  default: assert(0 && "Unknown unary op!");
6240  case tok::plusplus:     Opc = UnaryOperator::PreInc; break;
6241  case tok::minusminus:   Opc = UnaryOperator::PreDec; break;
6242  case tok::amp:          Opc = UnaryOperator::AddrOf; break;
6243  case tok::star:         Opc = UnaryOperator::Deref; break;
6244  case tok::plus:         Opc = UnaryOperator::Plus; break;
6245  case tok::minus:        Opc = UnaryOperator::Minus; break;
6246  case tok::tilde:        Opc = UnaryOperator::Not; break;
6247  case tok::exclaim:      Opc = UnaryOperator::LNot; break;
6248  case tok::kw___real:    Opc = UnaryOperator::Real; break;
6249  case tok::kw___imag:    Opc = UnaryOperator::Imag; break;
6250  case tok::kw___extension__: Opc = UnaryOperator::Extension; break;
6251  }
6252  return Opc;
6253}
6254
6255/// CreateBuiltinBinOp - Creates a new built-in binary operation with
6256/// operator @p Opc at location @c TokLoc. This routine only supports
6257/// built-in operations; ActOnBinOp handles overloaded operators.
6258Action::OwningExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
6259                                                  unsigned Op,
6260                                                  Expr *lhs, Expr *rhs) {
6261  QualType ResultTy;     // Result type of the binary operator.
6262  BinaryOperator::Opcode Opc = (BinaryOperator::Opcode)Op;
6263  // The following two variables are used for compound assignment operators
6264  QualType CompLHSTy;    // Type of LHS after promotions for computation
6265  QualType CompResultTy; // Type of computation result
6266
6267  switch (Opc) {
6268  case BinaryOperator::Assign:
6269    ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, QualType());
6270    break;
6271  case BinaryOperator::PtrMemD:
6272  case BinaryOperator::PtrMemI:
6273    ResultTy = CheckPointerToMemberOperands(lhs, rhs, OpLoc,
6274                                            Opc == BinaryOperator::PtrMemI);
6275    break;
6276  case BinaryOperator::Mul:
6277  case BinaryOperator::Div:
6278    ResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, false,
6279                                           Opc == BinaryOperator::Div);
6280    break;
6281  case BinaryOperator::Rem:
6282    ResultTy = CheckRemainderOperands(lhs, rhs, OpLoc);
6283    break;
6284  case BinaryOperator::Add:
6285    ResultTy = CheckAdditionOperands(lhs, rhs, OpLoc);
6286    break;
6287  case BinaryOperator::Sub:
6288    ResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc);
6289    break;
6290  case BinaryOperator::Shl:
6291  case BinaryOperator::Shr:
6292    ResultTy = CheckShiftOperands(lhs, rhs, OpLoc);
6293    break;
6294  case BinaryOperator::LE:
6295  case BinaryOperator::LT:
6296  case BinaryOperator::GE:
6297  case BinaryOperator::GT:
6298    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, true);
6299    break;
6300  case BinaryOperator::EQ:
6301  case BinaryOperator::NE:
6302    ResultTy = CheckCompareOperands(lhs, rhs, OpLoc, Opc, false);
6303    break;
6304  case BinaryOperator::And:
6305  case BinaryOperator::Xor:
6306  case BinaryOperator::Or:
6307    ResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc);
6308    break;
6309  case BinaryOperator::LAnd:
6310  case BinaryOperator::LOr:
6311    ResultTy = CheckLogicalOperands(lhs, rhs, OpLoc);
6312    break;
6313  case BinaryOperator::MulAssign:
6314  case BinaryOperator::DivAssign:
6315    CompResultTy = CheckMultiplyDivideOperands(lhs, rhs, OpLoc, true,
6316                                              Opc == BinaryOperator::DivAssign);
6317    CompLHSTy = CompResultTy;
6318    if (!CompResultTy.isNull())
6319      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6320    break;
6321  case BinaryOperator::RemAssign:
6322    CompResultTy = CheckRemainderOperands(lhs, rhs, OpLoc, true);
6323    CompLHSTy = CompResultTy;
6324    if (!CompResultTy.isNull())
6325      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6326    break;
6327  case BinaryOperator::AddAssign:
6328    CompResultTy = CheckAdditionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6329    if (!CompResultTy.isNull())
6330      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6331    break;
6332  case BinaryOperator::SubAssign:
6333    CompResultTy = CheckSubtractionOperands(lhs, rhs, OpLoc, &CompLHSTy);
6334    if (!CompResultTy.isNull())
6335      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6336    break;
6337  case BinaryOperator::ShlAssign:
6338  case BinaryOperator::ShrAssign:
6339    CompResultTy = CheckShiftOperands(lhs, rhs, OpLoc, true);
6340    CompLHSTy = CompResultTy;
6341    if (!CompResultTy.isNull())
6342      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6343    break;
6344  case BinaryOperator::AndAssign:
6345  case BinaryOperator::XorAssign:
6346  case BinaryOperator::OrAssign:
6347    CompResultTy = CheckBitwiseOperands(lhs, rhs, OpLoc, true);
6348    CompLHSTy = CompResultTy;
6349    if (!CompResultTy.isNull())
6350      ResultTy = CheckAssignmentOperands(lhs, rhs, OpLoc, CompResultTy);
6351    break;
6352  case BinaryOperator::Comma:
6353    ResultTy = CheckCommaOperands(lhs, rhs, OpLoc);
6354    break;
6355  }
6356  if (ResultTy.isNull())
6357    return ExprError();
6358  if (CompResultTy.isNull())
6359    return Owned(new (Context) BinaryOperator(lhs, rhs, Opc, ResultTy, OpLoc));
6360  else
6361    return Owned(new (Context) CompoundAssignOperator(lhs, rhs, Opc, ResultTy,
6362                                                      CompLHSTy, CompResultTy,
6363                                                      OpLoc));
6364}
6365
6366/// SuggestParentheses - Emit a diagnostic together with a fixit hint that wraps
6367/// ParenRange in parentheses.
6368static void SuggestParentheses(Sema &Self, SourceLocation Loc,
6369                               const PartialDiagnostic &PD,
6370                               const PartialDiagnostic &FirstNote,
6371                               SourceRange FirstParenRange,
6372                               const PartialDiagnostic &SecondNote,
6373                               SourceRange SecondParenRange) {
6374  Self.Diag(Loc, PD);
6375
6376  if (!FirstNote.getDiagID())
6377    return;
6378
6379  SourceLocation EndLoc = Self.PP.getLocForEndOfToken(FirstParenRange.getEnd());
6380  if (!FirstParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6381    // We can't display the parentheses, so just return.
6382    return;
6383  }
6384
6385  Self.Diag(Loc, FirstNote)
6386    << FixItHint::CreateInsertion(FirstParenRange.getBegin(), "(")
6387    << FixItHint::CreateInsertion(EndLoc, ")");
6388
6389  if (!SecondNote.getDiagID())
6390    return;
6391
6392  EndLoc = Self.PP.getLocForEndOfToken(SecondParenRange.getEnd());
6393  if (!SecondParenRange.getEnd().isFileID() || EndLoc.isInvalid()) {
6394    // We can't display the parentheses, so just dig the
6395    // warning/error and return.
6396    Self.Diag(Loc, SecondNote);
6397    return;
6398  }
6399
6400  Self.Diag(Loc, SecondNote)
6401    << FixItHint::CreateInsertion(SecondParenRange.getBegin(), "(")
6402    << FixItHint::CreateInsertion(EndLoc, ")");
6403}
6404
6405/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
6406/// operators are mixed in a way that suggests that the programmer forgot that
6407/// comparison operators have higher precedence. The most typical example of
6408/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
6409static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6410                                      SourceLocation OpLoc,Expr *lhs,Expr *rhs){
6411  typedef BinaryOperator BinOp;
6412  BinOp::Opcode lhsopc = static_cast<BinOp::Opcode>(-1),
6413                rhsopc = static_cast<BinOp::Opcode>(-1);
6414  if (BinOp *BO = dyn_cast<BinOp>(lhs))
6415    lhsopc = BO->getOpcode();
6416  if (BinOp *BO = dyn_cast<BinOp>(rhs))
6417    rhsopc = BO->getOpcode();
6418
6419  // Subs are not binary operators.
6420  if (lhsopc == -1 && rhsopc == -1)
6421    return;
6422
6423  // Bitwise operations are sometimes used as eager logical ops.
6424  // Don't diagnose this.
6425  if ((BinOp::isComparisonOp(lhsopc) || BinOp::isBitwiseOp(lhsopc)) &&
6426      (BinOp::isComparisonOp(rhsopc) || BinOp::isBitwiseOp(rhsopc)))
6427    return;
6428
6429  if (BinOp::isComparisonOp(lhsopc))
6430    SuggestParentheses(Self, OpLoc,
6431      Self.PDiag(diag::warn_precedence_bitwise_rel)
6432          << SourceRange(lhs->getLocStart(), OpLoc)
6433          << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(lhsopc),
6434      Self.PDiag(diag::note_precedence_bitwise_first)
6435          << BinOp::getOpcodeStr(Opc),
6436      SourceRange(cast<BinOp>(lhs)->getRHS()->getLocStart(), rhs->getLocEnd()),
6437      Self.PDiag(diag::note_precedence_bitwise_silence)
6438          << BinOp::getOpcodeStr(lhsopc),
6439                       lhs->getSourceRange());
6440  else if (BinOp::isComparisonOp(rhsopc))
6441    SuggestParentheses(Self, OpLoc,
6442      Self.PDiag(diag::warn_precedence_bitwise_rel)
6443          << SourceRange(OpLoc, rhs->getLocEnd())
6444          << BinOp::getOpcodeStr(Opc) << BinOp::getOpcodeStr(rhsopc),
6445      Self.PDiag(diag::note_precedence_bitwise_first)
6446        << BinOp::getOpcodeStr(Opc),
6447      SourceRange(lhs->getLocEnd(), cast<BinOp>(rhs)->getLHS()->getLocStart()),
6448      Self.PDiag(diag::note_precedence_bitwise_silence)
6449        << BinOp::getOpcodeStr(rhsopc),
6450                       rhs->getSourceRange());
6451}
6452
6453/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
6454/// precedence. This currently diagnoses only "arg1 'bitwise' arg2 'eq' arg3".
6455/// But it could also warn about arg1 && arg2 || arg3, as GCC 4.3+ does.
6456static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperator::Opcode Opc,
6457                                    SourceLocation OpLoc, Expr *lhs, Expr *rhs){
6458  if (BinaryOperator::isBitwiseOp(Opc))
6459    DiagnoseBitwisePrecedence(Self, Opc, OpLoc, lhs, rhs);
6460}
6461
6462// Binary Operators.  'Tok' is the token for the operator.
6463Action::OwningExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
6464                                          tok::TokenKind Kind,
6465                                          ExprArg LHS, ExprArg RHS) {
6466  BinaryOperator::Opcode Opc = ConvertTokenKindToBinaryOpcode(Kind);
6467  Expr *lhs = LHS.takeAs<Expr>(), *rhs = RHS.takeAs<Expr>();
6468
6469  assert((lhs != 0) && "ActOnBinOp(): missing left expression");
6470  assert((rhs != 0) && "ActOnBinOp(): missing right expression");
6471
6472  // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
6473  DiagnoseBinOpPrecedence(*this, Opc, TokLoc, lhs, rhs);
6474
6475  return BuildBinOp(S, TokLoc, Opc, lhs, rhs);
6476}
6477
6478Action::OwningExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
6479                                          BinaryOperator::Opcode Opc,
6480                                          Expr *lhs, Expr *rhs) {
6481  if (getLangOptions().CPlusPlus &&
6482      (lhs->getType()->isOverloadableType() ||
6483       rhs->getType()->isOverloadableType())) {
6484    // Find all of the overloaded operators visible from this
6485    // point. We perform both an operator-name lookup from the local
6486    // scope and an argument-dependent lookup based on the types of
6487    // the arguments.
6488    UnresolvedSet<16> Functions;
6489    OverloadedOperatorKind OverOp = BinaryOperator::getOverloadedOperator(Opc);
6490    if (S && OverOp != OO_None)
6491      LookupOverloadedOperatorName(OverOp, S, lhs->getType(), rhs->getType(),
6492                                   Functions);
6493
6494    // Build the (potentially-overloaded, potentially-dependent)
6495    // binary operation.
6496    return CreateOverloadedBinOp(OpLoc, Opc, Functions, lhs, rhs);
6497  }
6498
6499  // Build a built-in binary operation.
6500  return CreateBuiltinBinOp(OpLoc, Opc, lhs, rhs);
6501}
6502
6503Action::OwningExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
6504                                                    unsigned OpcIn,
6505                                                    ExprArg InputArg) {
6506  UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6507
6508  // FIXME: Input is modified below, but InputArg is not updated appropriately.
6509  Expr *Input = (Expr *)InputArg.get();
6510  QualType resultType;
6511  switch (Opc) {
6512  case UnaryOperator::OffsetOf:
6513    assert(false && "Invalid unary operator");
6514    break;
6515
6516  case UnaryOperator::PreInc:
6517  case UnaryOperator::PreDec:
6518  case UnaryOperator::PostInc:
6519  case UnaryOperator::PostDec:
6520    resultType = CheckIncrementDecrementOperand(Input, OpLoc,
6521                                                Opc == UnaryOperator::PreInc ||
6522                                                Opc == UnaryOperator::PostInc,
6523                                                Opc == UnaryOperator::PreInc ||
6524                                                Opc == UnaryOperator::PreDec);
6525    break;
6526  case UnaryOperator::AddrOf:
6527    resultType = CheckAddressOfOperand(Input, OpLoc);
6528    break;
6529  case UnaryOperator::Deref:
6530    DefaultFunctionArrayLvalueConversion(Input);
6531    resultType = CheckIndirectionOperand(Input, OpLoc);
6532    break;
6533  case UnaryOperator::Plus:
6534  case UnaryOperator::Minus:
6535    UsualUnaryConversions(Input);
6536    resultType = Input->getType();
6537    if (resultType->isDependentType())
6538      break;
6539    if (resultType->isArithmeticType() || // C99 6.5.3.3p1
6540        resultType->isVectorType())
6541      break;
6542    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
6543             resultType->isEnumeralType())
6544      break;
6545    else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
6546             Opc == UnaryOperator::Plus &&
6547             resultType->isPointerType())
6548      break;
6549
6550    return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6551      << resultType << Input->getSourceRange());
6552  case UnaryOperator::Not: // bitwise complement
6553    UsualUnaryConversions(Input);
6554    resultType = Input->getType();
6555    if (resultType->isDependentType())
6556      break;
6557    // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
6558    if (resultType->isComplexType() || resultType->isComplexIntegerType())
6559      // C99 does not support '~' for complex conjugation.
6560      Diag(OpLoc, diag::ext_integer_complement_complex)
6561        << resultType << Input->getSourceRange();
6562    else if (!resultType->isIntegerType())
6563      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6564        << resultType << Input->getSourceRange());
6565    break;
6566  case UnaryOperator::LNot: // logical negation
6567    // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
6568    DefaultFunctionArrayLvalueConversion(Input);
6569    resultType = Input->getType();
6570    if (resultType->isDependentType())
6571      break;
6572    if (!resultType->isScalarType()) // C99 6.5.3.3p1
6573      return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
6574        << resultType << Input->getSourceRange());
6575    // LNot always has type int. C99 6.5.3.3p5.
6576    // In C++, it's bool. C++ 5.3.1p8
6577    resultType = getLangOptions().CPlusPlus ? Context.BoolTy : Context.IntTy;
6578    break;
6579  case UnaryOperator::Real:
6580  case UnaryOperator::Imag:
6581    resultType = CheckRealImagOperand(Input, OpLoc, Opc == UnaryOperator::Real);
6582    break;
6583  case UnaryOperator::Extension:
6584    resultType = Input->getType();
6585    break;
6586  }
6587  if (resultType.isNull())
6588    return ExprError();
6589
6590  InputArg.release();
6591  return Owned(new (Context) UnaryOperator(Input, Opc, resultType, OpLoc));
6592}
6593
6594Action::OwningExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
6595                                            UnaryOperator::Opcode Opc,
6596                                            ExprArg input) {
6597  Expr *Input = (Expr*)input.get();
6598  if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
6599      Opc != UnaryOperator::Extension) {
6600    // Find all of the overloaded operators visible from this
6601    // point. We perform both an operator-name lookup from the local
6602    // scope and an argument-dependent lookup based on the types of
6603    // the arguments.
6604    UnresolvedSet<16> Functions;
6605    OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
6606    if (S && OverOp != OO_None)
6607      LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
6608                                   Functions);
6609
6610    return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, move(input));
6611  }
6612
6613  return CreateBuiltinUnaryOp(OpLoc, Opc, move(input));
6614}
6615
6616// Unary Operators.  'Tok' is the token for the operator.
6617Action::OwningExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
6618                                            tok::TokenKind Op, ExprArg input) {
6619  return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), move(input));
6620}
6621
6622/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
6623Sema::OwningExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc,
6624                                            SourceLocation LabLoc,
6625                                            IdentifierInfo *LabelII) {
6626  // Look up the record for this label identifier.
6627  LabelStmt *&LabelDecl = getLabelMap()[LabelII];
6628
6629  // If we haven't seen this label yet, create a forward reference. It
6630  // will be validated and/or cleaned up in ActOnFinishFunctionBody.
6631  if (LabelDecl == 0)
6632    LabelDecl = new (Context) LabelStmt(LabLoc, LabelII, 0);
6633
6634  // Create the AST node.  The address of a label always has type 'void*'.
6635  return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, LabelDecl,
6636                                       Context.getPointerType(Context.VoidTy)));
6637}
6638
6639Sema::OwningExprResult
6640Sema::ActOnStmtExpr(SourceLocation LPLoc, StmtArg substmt,
6641                    SourceLocation RPLoc) { // "({..})"
6642  Stmt *SubStmt = static_cast<Stmt*>(substmt.get());
6643  assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
6644  CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
6645
6646  bool isFileScope
6647    = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
6648  if (isFileScope)
6649    return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
6650
6651  // FIXME: there are a variety of strange constraints to enforce here, for
6652  // example, it is not possible to goto into a stmt expression apparently.
6653  // More semantic analysis is needed.
6654
6655  // If there are sub stmts in the compound stmt, take the type of the last one
6656  // as the type of the stmtexpr.
6657  QualType Ty = Context.VoidTy;
6658
6659  if (!Compound->body_empty()) {
6660    Stmt *LastStmt = Compound->body_back();
6661    // If LastStmt is a label, skip down through into the body.
6662    while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt))
6663      LastStmt = Label->getSubStmt();
6664
6665    if (Expr *LastExpr = dyn_cast<Expr>(LastStmt))
6666      Ty = LastExpr->getType();
6667  }
6668
6669  // FIXME: Check that expression type is complete/non-abstract; statement
6670  // expressions are not lvalues.
6671
6672  substmt.release();
6673  return Owned(new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc));
6674}
6675
6676Sema::OwningExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
6677                                                  TypeSourceInfo *TInfo,
6678                                                  OffsetOfComponent *CompPtr,
6679                                                  unsigned NumComponents,
6680                                                  SourceLocation RParenLoc) {
6681  QualType ArgTy = TInfo->getType();
6682  bool Dependent = ArgTy->isDependentType();
6683  SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
6684
6685  // We must have at least one component that refers to the type, and the first
6686  // one is known to be a field designator.  Verify that the ArgTy represents
6687  // a struct/union/class.
6688  if (!Dependent && !ArgTy->isRecordType())
6689    return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
6690                       << ArgTy << TypeRange);
6691
6692  // Type must be complete per C99 7.17p3 because a declaring a variable
6693  // with an incomplete type would be ill-formed.
6694  if (!Dependent
6695      && RequireCompleteType(BuiltinLoc, ArgTy,
6696                             PDiag(diag::err_offsetof_incomplete_type)
6697                               << TypeRange))
6698    return ExprError();
6699
6700  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6701  // GCC extension, diagnose them.
6702  // FIXME: This diagnostic isn't actually visible because the location is in
6703  // a system header!
6704  if (NumComponents != 1)
6705    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6706      << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
6707
6708  bool DidWarnAboutNonPOD = false;
6709  QualType CurrentType = ArgTy;
6710  typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
6711  llvm::SmallVector<OffsetOfNode, 4> Comps;
6712  llvm::SmallVector<Expr*, 4> Exprs;
6713  for (unsigned i = 0; i != NumComponents; ++i) {
6714    const OffsetOfComponent &OC = CompPtr[i];
6715    if (OC.isBrackets) {
6716      // Offset of an array sub-field.  TODO: Should we allow vector elements?
6717      if (!CurrentType->isDependentType()) {
6718        const ArrayType *AT = Context.getAsArrayType(CurrentType);
6719        if(!AT)
6720          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6721                           << CurrentType);
6722        CurrentType = AT->getElementType();
6723      } else
6724        CurrentType = Context.DependentTy;
6725
6726      // The expression must be an integral expression.
6727      // FIXME: An integral constant expression?
6728      Expr *Idx = static_cast<Expr*>(OC.U.E);
6729      if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
6730          !Idx->getType()->isIntegerType())
6731        return ExprError(Diag(Idx->getLocStart(),
6732                              diag::err_typecheck_subscript_not_integer)
6733                         << Idx->getSourceRange());
6734
6735      // Record this array index.
6736      Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
6737      Exprs.push_back(Idx);
6738      continue;
6739    }
6740
6741    // Offset of a field.
6742    if (CurrentType->isDependentType()) {
6743      // We have the offset of a field, but we can't look into the dependent
6744      // type. Just record the identifier of the field.
6745      Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
6746      CurrentType = Context.DependentTy;
6747      continue;
6748    }
6749
6750    // We need to have a complete type to look into.
6751    if (RequireCompleteType(OC.LocStart, CurrentType,
6752                            diag::err_offsetof_incomplete_type))
6753      return ExprError();
6754
6755    // Look for the designated field.
6756    const RecordType *RC = CurrentType->getAs<RecordType>();
6757    if (!RC)
6758      return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6759                       << CurrentType);
6760    RecordDecl *RD = RC->getDecl();
6761
6762    // C++ [lib.support.types]p5:
6763    //   The macro offsetof accepts a restricted set of type arguments in this
6764    //   International Standard. type shall be a POD structure or a POD union
6765    //   (clause 9).
6766    if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6767      if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6768          DiagRuntimeBehavior(BuiltinLoc,
6769                              PDiag(diag::warn_offsetof_non_pod_type)
6770                              << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6771                              << CurrentType))
6772        DidWarnAboutNonPOD = true;
6773    }
6774
6775    // Look for the field.
6776    LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6777    LookupQualifiedName(R, RD);
6778    FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6779    if (!MemberDecl)
6780      return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6781                       << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
6782                                                              OC.LocEnd));
6783
6784    // C99 7.17p3:
6785    //   (If the specified member is a bit-field, the behavior is undefined.)
6786    //
6787    // We diagnose this as an error.
6788    if (MemberDecl->getBitWidth()) {
6789      Diag(OC.LocEnd, diag::err_offsetof_bitfield)
6790        << MemberDecl->getDeclName()
6791        << SourceRange(BuiltinLoc, RParenLoc);
6792      Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
6793      return ExprError();
6794    }
6795
6796    // If the member was found in a base class, introduce OffsetOfNodes for
6797    // the base class indirections.
6798    CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
6799                       /*DetectVirtual=*/false);
6800    if (IsDerivedFrom(CurrentType,
6801                      Context.getTypeDeclType(MemberDecl->getParent()),
6802                      Paths)) {
6803      CXXBasePath &Path = Paths.front();
6804      for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
6805           B != BEnd; ++B)
6806        Comps.push_back(OffsetOfNode(B->Base));
6807    }
6808
6809    if (cast<RecordDecl>(MemberDecl->getDeclContext())->
6810                                                isAnonymousStructOrUnion()) {
6811      llvm::SmallVector<FieldDecl*, 4> Path;
6812      BuildAnonymousStructUnionMemberPath(MemberDecl, Path);
6813      unsigned n = Path.size();
6814      for (int j = n - 1; j > -1; --j)
6815        Comps.push_back(OffsetOfNode(OC.LocStart, Path[j], OC.LocEnd));
6816    } else {
6817      Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
6818    }
6819    CurrentType = MemberDecl->getType().getNonReferenceType();
6820  }
6821
6822  return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
6823                                    TInfo, Comps.data(), Comps.size(),
6824                                    Exprs.data(), Exprs.size(), RParenLoc));
6825}
6826
6827Sema::OwningExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
6828                                                  SourceLocation BuiltinLoc,
6829                                                  SourceLocation TypeLoc,
6830                                                  TypeTy *argty,
6831                                                  OffsetOfComponent *CompPtr,
6832                                                  unsigned NumComponents,
6833                                                  SourceLocation RPLoc) {
6834
6835  TypeSourceInfo *ArgTInfo;
6836  QualType ArgTy = GetTypeFromParser(argty, &ArgTInfo);
6837  if (ArgTy.isNull())
6838    return ExprError();
6839
6840  if (getLangOptions().CPlusPlus) {
6841    if (!ArgTInfo)
6842      ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
6843
6844    return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
6845                                RPLoc);
6846  }
6847
6848  // FIXME: The code below is marked for death, once we have proper CodeGen
6849  // support for non-constant OffsetOf expressions.
6850
6851  bool Dependent = ArgTy->isDependentType();
6852
6853  // We must have at least one component that refers to the type, and the first
6854  // one is known to be a field designator.  Verify that the ArgTy represents
6855  // a struct/union/class.
6856  if (!Dependent && !ArgTy->isRecordType())
6857    return ExprError(Diag(TypeLoc, diag::err_offsetof_record_type) << ArgTy);
6858
6859  // FIXME: Type must be complete per C99 7.17p3 because a declaring a variable
6860  // with an incomplete type would be illegal.
6861
6862  // Otherwise, create a null pointer as the base, and iteratively process
6863  // the offsetof designators.
6864  QualType ArgTyPtr = Context.getPointerType(ArgTy);
6865  Expr* Res = new (Context) ImplicitValueInitExpr(ArgTyPtr);
6866  Res = new (Context) UnaryOperator(Res, UnaryOperator::Deref,
6867                                    ArgTy, SourceLocation());
6868
6869  // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
6870  // GCC extension, diagnose them.
6871  // FIXME: This diagnostic isn't actually visible because the location is in
6872  // a system header!
6873  if (NumComponents != 1)
6874    Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
6875    << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
6876
6877  if (!Dependent) {
6878    bool DidWarnAboutNonPOD = false;
6879
6880    if (RequireCompleteType(TypeLoc, Res->getType(),
6881                            diag::err_offsetof_incomplete_type))
6882      return ExprError();
6883
6884    // FIXME: Dependent case loses a lot of information here. And probably
6885    // leaks like a sieve.
6886    for (unsigned i = 0; i != NumComponents; ++i) {
6887      const OffsetOfComponent &OC = CompPtr[i];
6888      if (OC.isBrackets) {
6889        // Offset of an array sub-field.  TODO: Should we allow vector elements?
6890        const ArrayType *AT = Context.getAsArrayType(Res->getType());
6891        if (!AT) {
6892          Res->Destroy(Context);
6893          return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
6894                           << Res->getType());
6895        }
6896
6897        // FIXME: C++: Verify that operator[] isn't overloaded.
6898
6899        // Promote the array so it looks more like a normal array subscript
6900        // expression.
6901        DefaultFunctionArrayLvalueConversion(Res);
6902
6903        // C99 6.5.2.1p1
6904        Expr *Idx = static_cast<Expr*>(OC.U.E);
6905        // FIXME: Leaks Res
6906        if (!Idx->isTypeDependent() && !Idx->getType()->isIntegerType())
6907          return ExprError(Diag(Idx->getLocStart(),
6908                                diag::err_typecheck_subscript_not_integer)
6909                           << Idx->getSourceRange());
6910
6911        Res = new (Context) ArraySubscriptExpr(Res, Idx, AT->getElementType(),
6912                                               OC.LocEnd);
6913        continue;
6914      }
6915
6916      const RecordType *RC = Res->getType()->getAs<RecordType>();
6917      if (!RC) {
6918        Res->Destroy(Context);
6919        return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
6920                         << Res->getType());
6921      }
6922
6923      // Get the decl corresponding to this.
6924      RecordDecl *RD = RC->getDecl();
6925      if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
6926        if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
6927            DiagRuntimeBehavior(BuiltinLoc,
6928                                PDiag(diag::warn_offsetof_non_pod_type)
6929                                << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
6930                                << Res->getType()))
6931          DidWarnAboutNonPOD = true;
6932      }
6933
6934      LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
6935      LookupQualifiedName(R, RD);
6936
6937      FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
6938      // FIXME: Leaks Res
6939      if (!MemberDecl)
6940        return ExprError(Diag(BuiltinLoc, diag::err_no_member)
6941                         << OC.U.IdentInfo << RD << SourceRange(OC.LocStart, OC.LocEnd));
6942
6943      // C99 7.17p3:
6944      //   (If the specified member is a bit-field, the behavior is undefined.)
6945      //
6946      // We diagnose this as an error.
6947      if (MemberDecl->getBitWidth()) {
6948        Diag(OC.LocEnd, diag::err_offsetof_bitfield)
6949          << MemberDecl->getDeclName()
6950          << SourceRange(BuiltinLoc, RPLoc);
6951        Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
6952        return ExprError();
6953      }
6954
6955      // FIXME: C++: Verify that MemberDecl isn't a static field.
6956      // FIXME: Verify that MemberDecl isn't a bitfield.
6957      if (cast<RecordDecl>(MemberDecl->getDeclContext())->isAnonymousStructOrUnion()) {
6958        Res = BuildAnonymousStructUnionMemberReference(
6959                                                       OC.LocEnd, MemberDecl, Res, OC.LocEnd).takeAs<Expr>();
6960      } else {
6961        PerformObjectMemberConversion(Res, /*Qualifier=*/0,
6962                                      *R.begin(), MemberDecl);
6963        // MemberDecl->getType() doesn't get the right qualifiers, but it
6964        // doesn't matter here.
6965        Res = new (Context) MemberExpr(Res, false, MemberDecl, OC.LocEnd,
6966                                       MemberDecl->getType().getNonReferenceType());
6967      }
6968    }
6969  }
6970
6971  return Owned(new (Context) UnaryOperator(Res, UnaryOperator::OffsetOf,
6972                                           Context.getSizeType(), BuiltinLoc));
6973}
6974
6975
6976Sema::OwningExprResult Sema::ActOnTypesCompatibleExpr(SourceLocation BuiltinLoc,
6977                                                      TypeTy *arg1,TypeTy *arg2,
6978                                                      SourceLocation RPLoc) {
6979  // FIXME: Preserve type source info.
6980  QualType argT1 = GetTypeFromParser(arg1);
6981  QualType argT2 = GetTypeFromParser(arg2);
6982
6983  assert((!argT1.isNull() && !argT2.isNull()) && "Missing type argument(s)");
6984
6985  if (getLangOptions().CPlusPlus) {
6986    Diag(BuiltinLoc, diag::err_types_compatible_p_in_cplusplus)
6987      << SourceRange(BuiltinLoc, RPLoc);
6988    return ExprError();
6989  }
6990
6991  return Owned(new (Context) TypesCompatibleExpr(Context.IntTy, BuiltinLoc,
6992                                                 argT1, argT2, RPLoc));
6993}
6994
6995Sema::OwningExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
6996                                             ExprArg cond,
6997                                             ExprArg expr1, ExprArg expr2,
6998                                             SourceLocation RPLoc) {
6999  Expr *CondExpr = static_cast<Expr*>(cond.get());
7000  Expr *LHSExpr = static_cast<Expr*>(expr1.get());
7001  Expr *RHSExpr = static_cast<Expr*>(expr2.get());
7002
7003  assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
7004
7005  QualType resType;
7006  bool ValueDependent = false;
7007  if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
7008    resType = Context.DependentTy;
7009    ValueDependent = true;
7010  } else {
7011    // The conditional expression is required to be a constant expression.
7012    llvm::APSInt condEval(32);
7013    SourceLocation ExpLoc;
7014    if (!CondExpr->isIntegerConstantExpr(condEval, Context, &ExpLoc))
7015      return ExprError(Diag(ExpLoc,
7016                       diag::err_typecheck_choose_expr_requires_constant)
7017        << CondExpr->getSourceRange());
7018
7019    // If the condition is > zero, then the AST type is the same as the LSHExpr.
7020    resType = condEval.getZExtValue() ? LHSExpr->getType() : RHSExpr->getType();
7021    ValueDependent = condEval.getZExtValue() ? LHSExpr->isValueDependent()
7022                                             : RHSExpr->isValueDependent();
7023  }
7024
7025  cond.release(); expr1.release(); expr2.release();
7026  return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
7027                                        resType, RPLoc,
7028                                        resType->isDependentType(),
7029                                        ValueDependent));
7030}
7031
7032//===----------------------------------------------------------------------===//
7033// Clang Extensions.
7034//===----------------------------------------------------------------------===//
7035
7036/// ActOnBlockStart - This callback is invoked when a block literal is started.
7037void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *BlockScope) {
7038  BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
7039  PushBlockScope(BlockScope, Block);
7040  CurContext->addDecl(Block);
7041  PushDeclContext(BlockScope, Block);
7042}
7043
7044void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
7045  assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
7046  BlockScopeInfo *CurBlock = getCurBlock();
7047
7048  TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
7049  CurBlock->TheDecl->setSignatureAsWritten(Sig);
7050  QualType T = Sig->getType();
7051
7052  bool isVariadic;
7053  QualType RetTy;
7054  if (const FunctionType *Fn = T->getAs<FunctionType>()) {
7055    CurBlock->FunctionType = T;
7056    RetTy = Fn->getResultType();
7057    isVariadic =
7058      !isa<FunctionProtoType>(Fn) || cast<FunctionProtoType>(Fn)->isVariadic();
7059  } else {
7060    RetTy = T;
7061    isVariadic = false;
7062  }
7063
7064  CurBlock->TheDecl->setIsVariadic(isVariadic);
7065
7066  // Don't allow returning an array by value.
7067  if (RetTy->isArrayType()) {
7068    Diag(ParamInfo.getSourceRange().getBegin(), diag::err_block_returns_array);
7069    return;
7070  }
7071
7072  // Don't allow returning a objc interface by value.
7073  if (RetTy->isObjCObjectType()) {
7074    Diag(ParamInfo.getSourceRange().getBegin(),
7075         diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
7076    return;
7077  }
7078
7079  // Context.DependentTy is used as a placeholder for a missing block
7080  // return type.  TODO:  what should we do with declarators like:
7081  //   ^ * { ... }
7082  // If the answer is "apply template argument deduction"....
7083  if (RetTy != Context.DependentTy)
7084    CurBlock->ReturnType = RetTy;
7085
7086  // Push block parameters from the declarator if we had them.
7087  llvm::SmallVector<ParmVarDecl*, 8> Params;
7088  if (isa<FunctionProtoType>(T)) {
7089    FunctionProtoTypeLoc TL = cast<FunctionProtoTypeLoc>(Sig->getTypeLoc());
7090    for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
7091      ParmVarDecl *Param = TL.getArg(I);
7092      if (Param->getIdentifier() == 0 &&
7093          !Param->isImplicit() &&
7094          !Param->isInvalidDecl() &&
7095          !getLangOptions().CPlusPlus)
7096        Diag(Param->getLocation(), diag::err_parameter_name_omitted);
7097      Params.push_back(Param);
7098    }
7099
7100  // Fake up parameter variables if we have a typedef, like
7101  //   ^ fntype { ... }
7102  } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
7103    for (FunctionProtoType::arg_type_iterator
7104           I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
7105      ParmVarDecl *Param =
7106        BuildParmVarDeclForTypedef(CurBlock->TheDecl,
7107                                   ParamInfo.getSourceRange().getBegin(),
7108                                   *I);
7109      Params.push_back(Param);
7110    }
7111  }
7112
7113  // Set the parameters on the block decl.
7114  if (!Params.empty())
7115    CurBlock->TheDecl->setParams(Params.data(), Params.size());
7116
7117  // Finally we can process decl attributes.
7118  ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
7119
7120  if (!isVariadic && CurBlock->TheDecl->getAttr<SentinelAttr>()) {
7121    Diag(ParamInfo.getAttributes()->getLoc(),
7122         diag::warn_attribute_sentinel_not_variadic) << 1;
7123    // FIXME: remove the attribute.
7124  }
7125
7126  // Put the parameter variables in scope.  We can bail out immediately
7127  // if we don't have any.
7128  if (Params.empty())
7129    return;
7130
7131  bool ShouldCheckShadow =
7132    Diags.getDiagnosticLevel(diag::warn_decl_shadow) != Diagnostic::Ignored;
7133
7134  for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
7135         E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
7136    (*AI)->setOwningFunction(CurBlock->TheDecl);
7137
7138    // If this has an identifier, add it to the scope stack.
7139    if ((*AI)->getIdentifier()) {
7140      if (ShouldCheckShadow)
7141        CheckShadow(CurBlock->TheScope, *AI);
7142
7143      PushOnScopeChains(*AI, CurBlock->TheScope);
7144    }
7145  }
7146}
7147
7148/// ActOnBlockError - If there is an error parsing a block, this callback
7149/// is invoked to pop the information about the block from the action impl.
7150void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
7151  // Pop off CurBlock, handle nested blocks.
7152  PopDeclContext();
7153  PopFunctionOrBlockScope();
7154  // FIXME: Delete the ParmVarDecl objects as well???
7155}
7156
7157/// ActOnBlockStmtExpr - This is called when the body of a block statement
7158/// literal was successfully completed.  ^(int x){...}
7159Sema::OwningExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
7160                                                StmtArg body, Scope *CurScope) {
7161  // If blocks are disabled, emit an error.
7162  if (!LangOpts.Blocks)
7163    Diag(CaretLoc, diag::err_blocks_disable);
7164
7165  BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
7166
7167  PopDeclContext();
7168
7169  QualType RetTy = Context.VoidTy;
7170  if (!BSI->ReturnType.isNull())
7171    RetTy = BSI->ReturnType;
7172
7173  bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
7174  QualType BlockTy;
7175
7176  // If the user wrote a function type in some form, try to use that.
7177  if (!BSI->FunctionType.isNull()) {
7178    const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
7179
7180    FunctionType::ExtInfo Ext = FTy->getExtInfo();
7181    if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
7182
7183    // Turn protoless block types into nullary block types.
7184    if (isa<FunctionNoProtoType>(FTy)) {
7185      BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7186                                        false, false, 0, 0, Ext);
7187
7188    // Otherwise, if we don't need to change anything about the function type,
7189    // preserve its sugar structure.
7190    } else if (FTy->getResultType() == RetTy &&
7191               (!NoReturn || FTy->getNoReturnAttr())) {
7192      BlockTy = BSI->FunctionType;
7193
7194    // Otherwise, make the minimal modifications to the function type.
7195    } else {
7196      const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
7197      BlockTy = Context.getFunctionType(RetTy,
7198                                        FPT->arg_type_begin(),
7199                                        FPT->getNumArgs(),
7200                                        FPT->isVariadic(),
7201                                        /*quals*/ 0,
7202                                        FPT->hasExceptionSpec(),
7203                                        FPT->hasAnyExceptionSpec(),
7204                                        FPT->getNumExceptions(),
7205                                        FPT->exception_begin(),
7206                                        Ext);
7207    }
7208
7209  // If we don't have a function type, just build one from nothing.
7210  } else {
7211    BlockTy = Context.getFunctionType(RetTy, 0, 0, false, 0,
7212                                      false, false, 0, 0,
7213                             FunctionType::ExtInfo(NoReturn, 0, CC_Default));
7214  }
7215
7216  // FIXME: Check that return/parameter types are complete/non-abstract
7217  DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
7218                           BSI->TheDecl->param_end());
7219  BlockTy = Context.getBlockPointerType(BlockTy);
7220
7221  // If needed, diagnose invalid gotos and switches in the block.
7222  if (FunctionNeedsScopeChecking() && !hasAnyErrorsInThisFunction())
7223    DiagnoseInvalidJumps(static_cast<CompoundStmt*>(body.get()));
7224
7225  BSI->TheDecl->setBody(body.takeAs<CompoundStmt>());
7226
7227  bool Good = true;
7228  // Check goto/label use.
7229  for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
7230         I = BSI->LabelMap.begin(), E = BSI->LabelMap.end(); I != E; ++I) {
7231    LabelStmt *L = I->second;
7232
7233    // Verify that we have no forward references left.  If so, there was a goto
7234    // or address of a label taken, but no definition of it.
7235    if (L->getSubStmt() != 0)
7236      continue;
7237
7238    // Emit error.
7239    Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
7240    Good = false;
7241  }
7242  if (!Good) {
7243    PopFunctionOrBlockScope();
7244    return ExprError();
7245  }
7246
7247  // Issue any analysis-based warnings.
7248  const sema::AnalysisBasedWarnings::Policy &WP =
7249    AnalysisWarnings.getDefaultPolicy();
7250  AnalysisWarnings.IssueWarnings(WP, BSI->TheDecl, BlockTy);
7251
7252  Expr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy,
7253                                         BSI->hasBlockDeclRefExprs);
7254  PopFunctionOrBlockScope();
7255  return Owned(Result);
7256}
7257
7258Sema::OwningExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
7259                                        ExprArg expr, TypeTy *type,
7260                                        SourceLocation RPLoc) {
7261  QualType T = GetTypeFromParser(type);
7262  Expr *E = static_cast<Expr*>(expr.get());
7263  Expr *OrigExpr = E;
7264
7265  InitBuiltinVaListType();
7266
7267  // Get the va_list type
7268  QualType VaListType = Context.getBuiltinVaListType();
7269  if (VaListType->isArrayType()) {
7270    // Deal with implicit array decay; for example, on x86-64,
7271    // va_list is an array, but it's supposed to decay to
7272    // a pointer for va_arg.
7273    VaListType = Context.getArrayDecayedType(VaListType);
7274    // Make sure the input expression also decays appropriately.
7275    UsualUnaryConversions(E);
7276  } else {
7277    // Otherwise, the va_list argument must be an l-value because
7278    // it is modified by va_arg.
7279    if (!E->isTypeDependent() &&
7280        CheckForModifiableLvalue(E, BuiltinLoc, *this))
7281      return ExprError();
7282  }
7283
7284  if (!E->isTypeDependent() &&
7285      !Context.hasSameType(VaListType, E->getType())) {
7286    return ExprError(Diag(E->getLocStart(),
7287                         diag::err_first_argument_to_va_arg_not_of_type_va_list)
7288      << OrigExpr->getType() << E->getSourceRange());
7289  }
7290
7291  // FIXME: Check that type is complete/non-abstract
7292  // FIXME: Warn if a non-POD type is passed in.
7293
7294  expr.release();
7295  return Owned(new (Context) VAArgExpr(BuiltinLoc, E, T.getNonReferenceType(),
7296                                       RPLoc));
7297}
7298
7299Sema::OwningExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
7300  // The type of __null will be int or long, depending on the size of
7301  // pointers on the target.
7302  QualType Ty;
7303  if (Context.Target.getPointerWidth(0) == Context.Target.getIntWidth())
7304    Ty = Context.IntTy;
7305  else
7306    Ty = Context.LongTy;
7307
7308  return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
7309}
7310
7311static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
7312                                           Expr *SrcExpr, FixItHint &Hint) {
7313  if (!SemaRef.getLangOptions().ObjC1)
7314    return;
7315
7316  const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
7317  if (!PT)
7318    return;
7319
7320  // Check if the destination is of type 'id'.
7321  if (!PT->isObjCIdType()) {
7322    // Check if the destination is the 'NSString' interface.
7323    const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
7324    if (!ID || !ID->getIdentifier()->isStr("NSString"))
7325      return;
7326  }
7327
7328  // Strip off any parens and casts.
7329  StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr->IgnoreParenCasts());
7330  if (!SL || SL->isWide())
7331    return;
7332
7333  Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
7334}
7335
7336bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
7337                                    SourceLocation Loc,
7338                                    QualType DstType, QualType SrcType,
7339                                    Expr *SrcExpr, AssignmentAction Action,
7340                                    bool *Complained) {
7341  if (Complained)
7342    *Complained = false;
7343
7344  // Decode the result (notice that AST's are still created for extensions).
7345  bool isInvalid = false;
7346  unsigned DiagKind;
7347  FixItHint Hint;
7348
7349  switch (ConvTy) {
7350  default: assert(0 && "Unknown conversion type");
7351  case Compatible: return false;
7352  case PointerToInt:
7353    DiagKind = diag::ext_typecheck_convert_pointer_int;
7354    break;
7355  case IntToPointer:
7356    DiagKind = diag::ext_typecheck_convert_int_pointer;
7357    break;
7358  case IncompatiblePointer:
7359    MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
7360    DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
7361    break;
7362  case IncompatiblePointerSign:
7363    DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
7364    break;
7365  case FunctionVoidPointer:
7366    DiagKind = diag::ext_typecheck_convert_pointer_void_func;
7367    break;
7368  case CompatiblePointerDiscardsQualifiers:
7369    // If the qualifiers lost were because we were applying the
7370    // (deprecated) C++ conversion from a string literal to a char*
7371    // (or wchar_t*), then there was no error (C++ 4.2p2).  FIXME:
7372    // Ideally, this check would be performed in
7373    // CheckPointerTypesForAssignment. However, that would require a
7374    // bit of refactoring (so that the second argument is an
7375    // expression, rather than a type), which should be done as part
7376    // of a larger effort to fix CheckPointerTypesForAssignment for
7377    // C++ semantics.
7378    if (getLangOptions().CPlusPlus &&
7379        IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
7380      return false;
7381    DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
7382    break;
7383  case IncompatibleNestedPointerQualifiers:
7384    DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
7385    break;
7386  case IntToBlockPointer:
7387    DiagKind = diag::err_int_to_block_pointer;
7388    break;
7389  case IncompatibleBlockPointer:
7390    DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
7391    break;
7392  case IncompatibleObjCQualifiedId:
7393    // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
7394    // it can give a more specific diagnostic.
7395    DiagKind = diag::warn_incompatible_qualified_id;
7396    break;
7397  case IncompatibleVectors:
7398    DiagKind = diag::warn_incompatible_vectors;
7399    break;
7400  case Incompatible:
7401    DiagKind = diag::err_typecheck_convert_incompatible;
7402    isInvalid = true;
7403    break;
7404  }
7405
7406  QualType FirstType, SecondType;
7407  switch (Action) {
7408  case AA_Assigning:
7409  case AA_Initializing:
7410    // The destination type comes first.
7411    FirstType = DstType;
7412    SecondType = SrcType;
7413    break;
7414
7415  case AA_Returning:
7416  case AA_Passing:
7417  case AA_Converting:
7418  case AA_Sending:
7419  case AA_Casting:
7420    // The source type comes first.
7421    FirstType = SrcType;
7422    SecondType = DstType;
7423    break;
7424  }
7425
7426  Diag(Loc, DiagKind) << FirstType << SecondType << Action
7427    << SrcExpr->getSourceRange() << Hint;
7428  if (Complained)
7429    *Complained = true;
7430  return isInvalid;
7431}
7432
7433bool Sema::VerifyIntegerConstantExpression(const Expr *E, llvm::APSInt *Result){
7434  llvm::APSInt ICEResult;
7435  if (E->isIntegerConstantExpr(ICEResult, Context)) {
7436    if (Result)
7437      *Result = ICEResult;
7438    return false;
7439  }
7440
7441  Expr::EvalResult EvalResult;
7442
7443  if (!E->Evaluate(EvalResult, Context) || !EvalResult.Val.isInt() ||
7444      EvalResult.HasSideEffects) {
7445    Diag(E->getExprLoc(), diag::err_expr_not_ice) << E->getSourceRange();
7446
7447    if (EvalResult.Diag) {
7448      // We only show the note if it's not the usual "invalid subexpression"
7449      // or if it's actually in a subexpression.
7450      if (EvalResult.Diag != diag::note_invalid_subexpr_in_ice ||
7451          E->IgnoreParens() != EvalResult.DiagExpr->IgnoreParens())
7452        Diag(EvalResult.DiagLoc, EvalResult.Diag);
7453    }
7454
7455    return true;
7456  }
7457
7458  Diag(E->getExprLoc(), diag::ext_expr_not_ice) <<
7459    E->getSourceRange();
7460
7461  if (EvalResult.Diag &&
7462      Diags.getDiagnosticLevel(diag::ext_expr_not_ice) != Diagnostic::Ignored)
7463    Diag(EvalResult.DiagLoc, EvalResult.Diag);
7464
7465  if (Result)
7466    *Result = EvalResult.Val.getInt();
7467  return false;
7468}
7469
7470void
7471Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext) {
7472  ExprEvalContexts.push_back(
7473        ExpressionEvaluationContextRecord(NewContext, ExprTemporaries.size()));
7474}
7475
7476void
7477Sema::PopExpressionEvaluationContext() {
7478  // Pop the current expression evaluation context off the stack.
7479  ExpressionEvaluationContextRecord Rec = ExprEvalContexts.back();
7480  ExprEvalContexts.pop_back();
7481
7482  if (Rec.Context == PotentiallyPotentiallyEvaluated) {
7483    if (Rec.PotentiallyReferenced) {
7484      // Mark any remaining declarations in the current position of the stack
7485      // as "referenced". If they were not meant to be referenced, semantic
7486      // analysis would have eliminated them (e.g., in ActOnCXXTypeId).
7487      for (PotentiallyReferencedDecls::iterator
7488             I = Rec.PotentiallyReferenced->begin(),
7489             IEnd = Rec.PotentiallyReferenced->end();
7490           I != IEnd; ++I)
7491        MarkDeclarationReferenced(I->first, I->second);
7492    }
7493
7494    if (Rec.PotentiallyDiagnosed) {
7495      // Emit any pending diagnostics.
7496      for (PotentiallyEmittedDiagnostics::iterator
7497                I = Rec.PotentiallyDiagnosed->begin(),
7498             IEnd = Rec.PotentiallyDiagnosed->end();
7499           I != IEnd; ++I)
7500        Diag(I->first, I->second);
7501    }
7502  }
7503
7504  // When are coming out of an unevaluated context, clear out any
7505  // temporaries that we may have created as part of the evaluation of
7506  // the expression in that context: they aren't relevant because they
7507  // will never be constructed.
7508  if (Rec.Context == Unevaluated &&
7509      ExprTemporaries.size() > Rec.NumTemporaries)
7510    ExprTemporaries.erase(ExprTemporaries.begin() + Rec.NumTemporaries,
7511                          ExprTemporaries.end());
7512
7513  // Destroy the popped expression evaluation record.
7514  Rec.Destroy();
7515}
7516
7517/// \brief Note that the given declaration was referenced in the source code.
7518///
7519/// This routine should be invoke whenever a given declaration is referenced
7520/// in the source code, and where that reference occurred. If this declaration
7521/// reference means that the the declaration is used (C++ [basic.def.odr]p2,
7522/// C99 6.9p3), then the declaration will be marked as used.
7523///
7524/// \param Loc the location where the declaration was referenced.
7525///
7526/// \param D the declaration that has been referenced by the source code.
7527void Sema::MarkDeclarationReferenced(SourceLocation Loc, Decl *D) {
7528  assert(D && "No declaration?");
7529
7530  if (D->isUsed(false))
7531    return;
7532
7533  // Mark a parameter or variable declaration "used", regardless of whether we're in a
7534  // template or not. The reason for this is that unevaluated expressions
7535  // (e.g. (void)sizeof()) constitute a use for warning purposes (-Wunused-variables and
7536  // -Wunused-parameters)
7537  if (isa<ParmVarDecl>(D) ||
7538      (isa<VarDecl>(D) && D->getDeclContext()->isFunctionOrMethod())) {
7539    D->setUsed(true);
7540    return;
7541  }
7542
7543  if (!isa<VarDecl>(D) && !isa<FunctionDecl>(D))
7544    return;
7545
7546  // Do not mark anything as "used" within a dependent context; wait for
7547  // an instantiation.
7548  if (CurContext->isDependentContext())
7549    return;
7550
7551  switch (ExprEvalContexts.back().Context) {
7552    case Unevaluated:
7553      // We are in an expression that is not potentially evaluated; do nothing.
7554      return;
7555
7556    case PotentiallyEvaluated:
7557      // We are in a potentially-evaluated expression, so this declaration is
7558      // "used"; handle this below.
7559      break;
7560
7561    case PotentiallyPotentiallyEvaluated:
7562      // We are in an expression that may be potentially evaluated; queue this
7563      // declaration reference until we know whether the expression is
7564      // potentially evaluated.
7565      ExprEvalContexts.back().addReferencedDecl(Loc, D);
7566      return;
7567  }
7568
7569  // Note that this declaration has been used.
7570  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
7571    unsigned TypeQuals;
7572    if (Constructor->isImplicit() && Constructor->isDefaultConstructor()) {
7573        if (!Constructor->isUsed(false))
7574          DefineImplicitDefaultConstructor(Loc, Constructor);
7575    } else if (Constructor->isImplicit() &&
7576               Constructor->isCopyConstructor(TypeQuals)) {
7577      if (!Constructor->isUsed(false))
7578        DefineImplicitCopyConstructor(Loc, Constructor, TypeQuals);
7579    }
7580
7581    MarkVTableUsed(Loc, Constructor->getParent());
7582  } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
7583    if (Destructor->isImplicit() && !Destructor->isUsed(false))
7584      DefineImplicitDestructor(Loc, Destructor);
7585    if (Destructor->isVirtual())
7586      MarkVTableUsed(Loc, Destructor->getParent());
7587  } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) {
7588    if (MethodDecl->isImplicit() && MethodDecl->isOverloadedOperator() &&
7589        MethodDecl->getOverloadedOperator() == OO_Equal) {
7590      if (!MethodDecl->isUsed(false))
7591        DefineImplicitCopyAssignment(Loc, MethodDecl);
7592    } else if (MethodDecl->isVirtual())
7593      MarkVTableUsed(Loc, MethodDecl->getParent());
7594  }
7595  if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
7596    // Implicit instantiation of function templates and member functions of
7597    // class templates.
7598    if (Function->isImplicitlyInstantiable()) {
7599      bool AlreadyInstantiated = false;
7600      if (FunctionTemplateSpecializationInfo *SpecInfo
7601                                = Function->getTemplateSpecializationInfo()) {
7602        if (SpecInfo->getPointOfInstantiation().isInvalid())
7603          SpecInfo->setPointOfInstantiation(Loc);
7604        else if (SpecInfo->getTemplateSpecializationKind()
7605                   == TSK_ImplicitInstantiation)
7606          AlreadyInstantiated = true;
7607      } else if (MemberSpecializationInfo *MSInfo
7608                                  = Function->getMemberSpecializationInfo()) {
7609        if (MSInfo->getPointOfInstantiation().isInvalid())
7610          MSInfo->setPointOfInstantiation(Loc);
7611        else if (MSInfo->getTemplateSpecializationKind()
7612                   == TSK_ImplicitInstantiation)
7613          AlreadyInstantiated = true;
7614      }
7615
7616      if (!AlreadyInstantiated) {
7617        if (isa<CXXRecordDecl>(Function->getDeclContext()) &&
7618            cast<CXXRecordDecl>(Function->getDeclContext())->isLocalClass())
7619          PendingLocalImplicitInstantiations.push_back(std::make_pair(Function,
7620                                                                      Loc));
7621        else
7622          PendingImplicitInstantiations.push_back(std::make_pair(Function,
7623                                                                 Loc));
7624      }
7625    }
7626
7627    // FIXME: keep track of references to static functions
7628    Function->setUsed(true);
7629
7630    return;
7631  }
7632
7633  if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
7634    // Implicit instantiation of static data members of class templates.
7635    if (Var->isStaticDataMember() &&
7636        Var->getInstantiatedFromStaticDataMember()) {
7637      MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
7638      assert(MSInfo && "Missing member specialization information?");
7639      if (MSInfo->getPointOfInstantiation().isInvalid() &&
7640          MSInfo->getTemplateSpecializationKind()== TSK_ImplicitInstantiation) {
7641        MSInfo->setPointOfInstantiation(Loc);
7642        PendingImplicitInstantiations.push_back(std::make_pair(Var, Loc));
7643      }
7644    }
7645
7646    // FIXME: keep track of references to static data?
7647
7648    D->setUsed(true);
7649    return;
7650  }
7651}
7652
7653namespace {
7654  // Mark all of the declarations referenced
7655  // FIXME: Not fully implemented yet! We need to have a better understanding
7656  // of when we're entering
7657  class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
7658    Sema &S;
7659    SourceLocation Loc;
7660
7661  public:
7662    typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
7663
7664    MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
7665
7666    bool TraverseTemplateArgument(const TemplateArgument &Arg);
7667    bool TraverseRecordType(RecordType *T);
7668  };
7669}
7670
7671bool MarkReferencedDecls::TraverseTemplateArgument(
7672  const TemplateArgument &Arg) {
7673  if (Arg.getKind() == TemplateArgument::Declaration) {
7674    S.MarkDeclarationReferenced(Loc, Arg.getAsDecl());
7675  }
7676
7677  return Inherited::TraverseTemplateArgument(Arg);
7678}
7679
7680bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
7681  if (ClassTemplateSpecializationDecl *Spec
7682                  = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
7683    const TemplateArgumentList &Args = Spec->getTemplateArgs();
7684    return TraverseTemplateArguments(Args.getFlatArgumentList(),
7685                                     Args.flat_size());
7686  }
7687
7688  return true;
7689}
7690
7691void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
7692  MarkReferencedDecls Marker(*this, Loc);
7693  Marker.TraverseType(Context.getCanonicalType(T));
7694}
7695
7696/// \brief Emit a diagnostic that describes an effect on the run-time behavior
7697/// of the program being compiled.
7698///
7699/// This routine emits the given diagnostic when the code currently being
7700/// type-checked is "potentially evaluated", meaning that there is a
7701/// possibility that the code will actually be executable. Code in sizeof()
7702/// expressions, code used only during overload resolution, etc., are not
7703/// potentially evaluated. This routine will suppress such diagnostics or,
7704/// in the absolutely nutty case of potentially potentially evaluated
7705/// expressions (C++ typeid), queue the diagnostic to potentially emit it
7706/// later.
7707///
7708/// This routine should be used for all diagnostics that describe the run-time
7709/// behavior of a program, such as passing a non-POD value through an ellipsis.
7710/// Failure to do so will likely result in spurious diagnostics or failures
7711/// during overload resolution or within sizeof/alignof/typeof/typeid.
7712bool Sema::DiagRuntimeBehavior(SourceLocation Loc,
7713                               const PartialDiagnostic &PD) {
7714  switch (ExprEvalContexts.back().Context ) {
7715  case Unevaluated:
7716    // The argument will never be evaluated, so don't complain.
7717    break;
7718
7719  case PotentiallyEvaluated:
7720    Diag(Loc, PD);
7721    return true;
7722
7723  case PotentiallyPotentiallyEvaluated:
7724    ExprEvalContexts.back().addDiagnostic(Loc, PD);
7725    break;
7726  }
7727
7728  return false;
7729}
7730
7731bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
7732                               CallExpr *CE, FunctionDecl *FD) {
7733  if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
7734    return false;
7735
7736  PartialDiagnostic Note =
7737    FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
7738    << FD->getDeclName() : PDiag();
7739  SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
7740
7741  if (RequireCompleteType(Loc, ReturnType,
7742                          FD ?
7743                          PDiag(diag::err_call_function_incomplete_return)
7744                            << CE->getSourceRange() << FD->getDeclName() :
7745                          PDiag(diag::err_call_incomplete_return)
7746                            << CE->getSourceRange(),
7747                          std::make_pair(NoteLoc, Note)))
7748    return true;
7749
7750  return false;
7751}
7752
7753// Diagnose the common s/=/==/ typo.  Note that adding parentheses
7754// will prevent this condition from triggering, which is what we want.
7755void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
7756  SourceLocation Loc;
7757
7758  unsigned diagnostic = diag::warn_condition_is_assignment;
7759
7760  if (isa<BinaryOperator>(E)) {
7761    BinaryOperator *Op = cast<BinaryOperator>(E);
7762    if (Op->getOpcode() != BinaryOperator::Assign)
7763      return;
7764
7765    // Greylist some idioms by putting them into a warning subcategory.
7766    if (ObjCMessageExpr *ME
7767          = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
7768      Selector Sel = ME->getSelector();
7769
7770      // self = [<foo> init...]
7771      if (isSelfExpr(Op->getLHS())
7772          && Sel.getIdentifierInfoForSlot(0)->getName().startswith("init"))
7773        diagnostic = diag::warn_condition_is_idiomatic_assignment;
7774
7775      // <foo> = [<bar> nextObject]
7776      else if (Sel.isUnarySelector() &&
7777               Sel.getIdentifierInfoForSlot(0)->getName() == "nextObject")
7778        diagnostic = diag::warn_condition_is_idiomatic_assignment;
7779    }
7780
7781    Loc = Op->getOperatorLoc();
7782  } else if (isa<CXXOperatorCallExpr>(E)) {
7783    CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(E);
7784    if (Op->getOperator() != OO_Equal)
7785      return;
7786
7787    Loc = Op->getOperatorLoc();
7788  } else {
7789    // Not an assignment.
7790    return;
7791  }
7792
7793  SourceLocation Open = E->getSourceRange().getBegin();
7794  SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
7795
7796  Diag(Loc, diagnostic) << E->getSourceRange();
7797  Diag(Loc, diag::note_condition_assign_to_comparison)
7798    << FixItHint::CreateReplacement(Loc, "==");
7799  Diag(Loc, diag::note_condition_assign_silence)
7800    << FixItHint::CreateInsertion(Open, "(")
7801    << FixItHint::CreateInsertion(Close, ")");
7802}
7803
7804bool Sema::CheckBooleanCondition(Expr *&E, SourceLocation Loc) {
7805  DiagnoseAssignmentAsCondition(E);
7806
7807  if (!E->isTypeDependent()) {
7808    DefaultFunctionArrayLvalueConversion(E);
7809
7810    QualType T = E->getType();
7811
7812    if (getLangOptions().CPlusPlus) {
7813      if (CheckCXXBooleanCondition(E)) // C++ 6.4p4
7814        return true;
7815    } else if (!T->isScalarType()) { // C99 6.8.4.1p1
7816      Diag(Loc, diag::err_typecheck_statement_requires_scalar)
7817        << T << E->getSourceRange();
7818      return true;
7819    }
7820  }
7821
7822  return false;
7823}
7824
7825Sema::OwningExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
7826                                                   ExprArg SubExpr) {
7827  Expr *Sub = SubExpr.takeAs<Expr>();
7828  if (!Sub)
7829    return ExprError();
7830
7831  if (CheckBooleanCondition(Sub, Loc)) {
7832    Sub->Destroy(Context);
7833    return ExprError();
7834  }
7835
7836  return Owned(Sub);
7837}
7838