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