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