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