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