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