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